'-------------------------------------------------------------------------------
Option Explicit

' This module is for reading the output of an Analog Devices ADXL202
' 2-axis accelerometer.
'
' The following 4 values depend on calibration. 
Private Const CenterX As Single = 0.5
Private Const DeltaX As Single = 0.125
Private Const CenterY As Single = 0.5
Private Const DeltaY As Single = 0.125

Private Const PinX As Byte = 16
Private Const PinY As Byte = 17

Private Period As Single
'-------------------------------------------------------------------------------
Public Sub GetAccelerations( _
    ByRef Ax As Single, _
    ByRef Ay As Single)

' This procedure reads each axis of an ADXL202 accelerometer. Both components
' of a 2D acceleration vector are returned. Units are in gravities.
'
'      <------ Period ----->
'     +--------+            +----
'     |        |            |
'  ---+        +------------+
'      <--T1-->
'
' Acceleration = (T1/Period - 0.5)/0.125

    Dim T1X as single, T1Y As Single
    Dim SumX As Single, SumY As Single
    Dim i As Byte, T1 As Single
    Const Samples As Byte = 20

    SumX = 0.0
    SumY = 0.0
    For i = 1 to Samples
        Call PulseIn(PinX, 1, T1)
        SumX = SumX + T1

        Call PulseIn(PinY, 1, T1)
        SumY = SumY + T1
    Next

    T1X = SumX / CSng(Samples)
    Ax = ((T1X / Period) - CenterX) / DeltaX

    T1Y = SumY / CSng(Samples)
    Ay = ((T1Y / Period) - CenterY) / DeltaY

End Sub
'-------------------------------------------------------------------------------
Public Sub GetPeriod()

' This procedure determines the average period generated by the X axis
' channel of an ADXL202 accelerometer.
'
' The period is also denoted as T2 in Analog Devices documentation.
'
'      <------ Period ----->
'     +--------+            +----
'     |        |            |
'  ---+        +------------+
'      <--T1--> <--- T3 --->

    Dim SumT1 As Single, SumT3 As Single
    Dim T1 As Single, T3 As Single, i As Integer
    Dim AvgT1 As Single, AvgT3 As Single
    Const NSamples As Integer = 20

    SumT1 = 0.0
    SumT3 = 0.0
    For i = 1 to NSamples
        Call PulseIn(PinX, 1, T1)
        Call PulseIn(PinX, 0, T3)

        SumT1 = SumT1 + T1
        SumT3 = SumT3 + T3
    Next

    AvgT1 = SumT1 / CSng(NSamples)
    AvgT3 = SumT3 / CSng(NSamples)

    Period = AvgT1 + AvgT3

End Sub
'-------------------------------------------------------------------------------
