Attribute VB_Name = "SonarExample"
'-------------------------------------------------------------------------------
Option Explicit

' This program demonstrates the operation of a Polaroid ultrasonic
' rangefinder. The rangefinder is sampled several times per second, and
' the range is sent to the Com1 serial port.

Private Const EchoPin As Byte = 15
Private Const InitPin As Byte = 16
'-------------------------------------------------------------------------------
Public Sub Main()

    Dim Tx As String, Range As Single, NoEcho As Boolean

    Call OpenSerialPort(1, 19200)

    Call InitializeRangefinder

    Do
        Call GetRange(Range, NoEcho)

        If (NoEcho) Then
            Tx = "No echo"
            Call PutLine(Tx)
        Else
            ' Display data.
            Tx = "Range = "
            Call PutStr(Tx)

            ' Convert to mm.
            Call PutL( CLng(Range * 1000.0) )

            Tx = " mm"
            Call PutLine(Tx)
        End If

        Call Delay(0.2)
    Loop

End Sub
'-------------------------------------------------------------------------------
Sub InitializeRangefinder()

    ' Configure I/O pins.
    Call PutPin(EchoPin, bxInputTristate)
    Call PutPin(InitPin, bxOutputLow)

End Sub
'-------------------------------------------------------------------------------
Sub GetRange( _
    ByRef Range As Single, _
    ByRef NoEcho As Boolean)

' This procedure returns the range measured by a Polaroid ultrasonic
' rangefinder. The range is in meters.
'
' If there is nothing detected by the device, NoEcho is set to true.
' Otherwise NoEcho is false.

    ' Speed of sound at room temperature (m/s).
    Const SpeedOfSound As Single = 344.0

    Dim EchoDelay As Single

    ' Trigger acoustic ping.
    Call PutPin(InitPin, bxOutputHigh)

    ' Wait for echo.
    Call RCtime(EchoPin, 0, EchoDelay)

    ' Get ready for the next cycle.
    Call PutPin(InitPin, bxOutputLow)

    ' If we don't receive an echo, RCtime overflows and returns 0.0.
    If (EchoDelay = 0.0) Then
        Range = 11.0
        NoEcho = True
    Else
        Range = (EchoDelay / 2.0) * SpeedOfSound
        NoEcho = False
    End If

End Sub
'-------------------------------------------------------------------------------
