'-------------------------------------------------------------------------------
Option Explicit

'-------------------------------------------------------------------------------
Public Sub Main()

' This program exercises a servo by moving it back and forth through its
' position range, at about 1 cycle every 5 seconds.

    Const ServoPin As Byte = 17

    Const NSteps As Integer = 100

    ' This is to generate a refresh rate of roughly 50 Hz.
    Const RefreshPeriod As Single = 0.02

    Dim i As Integer, Position As Single

    Debug.Print
    Debug.Print "Servo Demonstration"
    Debug.Print

    Debug.Print "Center servo"

    For i = 1 To 50  ' For about 1 second.
        Call MoveServo(ServoPin, 0.5)
        Call Delay(RefreshPeriod)
    Next
	
    Do
        Debug.Print "Forward"

        For i = 0 To NSteps

            ' Nondimensionalize position.
            Position = CSng(i) / CSng(NSteps)

            Call MoveServo(ServoPin, Position)
            
            Call Delay(RefreshPeriod)
        Next

        Debug.Print "Reverse"

        For i = NSteps To 0 Step -1

            ' Nondimensionalize position.
            Position = CSng(i) / CSng(NSteps)

            Call MoveServo(ServoPin, Position)
            
            Call Delay(RefreshPeriod)
        Next
    Loop

End Sub
'-------------------------------------------------------------------------------
Public Sub MoveServo( _
    ByVal ServoPin As Byte, _
    ByVal Position As Single)

' Moves a servo by sending a single pulse. The position is a nondimensional
' value in range 0.0 to 1.0.

    Dim PulseWidth As Single

    ' Translate position to pulse width. Resulting range is 1.0 to 2.0 ms,
    ' centered at 1.5 ms.
    PulseWidth = 0.001 + (0.001 * Position)

    ' Generate a high-going pulse on the servo pin.
    Call PulseOut(ServoPin, PulseWidth, 1)

End Sub
'-------------------------------------------------------------------------------
