Attribute VB_Name = "RCtimeExample"
'-------------------------------------------------------------------------------
Option Explicit

' This program uses the RCtime system call to measure the resistance of
' a 50 kOhm potentiometer. The pot is part of an RC circuit attached to
' I/O pin 15 (see below). The measured resistance is output through the
' Com1 serial port.
'
'                   +5 V
'                    |
'                    C = 0.1 uF
'                    |
'  Pin 15 o---R1-----o
'            300     |
'            Ohm     RV = 50 kOhm
'                    |
'                   Gnd
'
'-------------------------------------------------------------------------------
Public Sub Main()

    Dim Tx As String, Resistance As Single

    Call OpenSerialPort(1, 19200)

    Do
        Call GetResistance(Resistance)

        ' Display data.
        Tx = "R = "
        Call PutStr(Tx)

        Call PutL(CLng(Resistance))

        Tx = " Ohms"
        Call PutLine(Tx)

        Call Delay(0.2)
    Loop

End Sub
'-------------------------------------------------------------------------------
Public Sub GetResistance( _
    ByRef Resistance As Single)

' Measures the resistance of a pot attached to an I/O pin.

    Const PotPin As Byte = 15
    Const DischargeTime As Single = 120.0E-6 ' Seconds
    Const Capacitance As Single = 0.1E-6     ' Farads
    Const TripVoltage As Single = 2.5        ' Volts
    Const InitialVoltage As Single = 5.0     ' Volts

    Dim TimeInterval As Single, K As Single

    ' Raise the pin and discharge the capacitor.
    Call PutPin(PotPin, bxOutputHigh)

    ' Wait for discharge.
    Call Delay(DischargeTime)

    ' Set the pin to input-tristate, then measure how long the pin stays
    ' at logic-high.
    Call RCtime(PotPin, 1, TimeInterval)

    K = 1.0 / (Capacitance * Log(InitialVoltage / TripVoltage))

    Resistance = TimeInterval * K

End Sub
'-------------------------------------------------------------------------------
