dir ANALOG_0 In
dir DIGITAL_10 in
dim cm,cm10 as Integer
dim math as Integer
dim text as string * 16
dim digit as string * 2
sub calc_distance
' from the datasheet the analog voltage is
' the inverse of distance, so distance can be calculated
' d = (1 / volts) then just scaled to suit the datasheet
' load ADC value in 16bit math variable.
' math = ADC_Read(0);
' math = ADRESH;
' math = (math * 255);
' math += ADRESL;
math = readad10( 0 )
' now invert it; (1 / volts) use (6050 / volts) for scaling, 6050 is a constant;
math = (6050 / math)
if (math >= 2) then
math = math - 2; ' fix linear error (-2)
end if
if (math < 10) then
math = 10; ' min limit at 10cm
end if
if (math > 80) then
math = 80; ' max limit at 80cm
end if
' convert from 0-99 to 2 decimal digits, 0-99cm
cm10=0;
do while (math >= 10)
cm10++
math = math - 10
loop
cm = math;
end sub
do forever
CLS
text = "Sharp 2Y0A21";
Locate(0,0)
Print text
text = "Distance:";
Locate(1,0)
Print text
text = "cm";
Locate(1,13)
Print text
wait 3 s
do forever
if cm10 <> abs(cm10) Then
locate 1,0
Print "Error reading "
else
'calc_distance; ' Call the "calc_distance" sub;
digit(1) = cm10 + 48; ' tens digit;
digit(2) = cm +48; ' unit digit;
locate 1, 10
Print digit; ' display on LCD from column 2, from character 10;
end if
wait 100 ms;
loop
loop