And here's the code I used to test it:
io(po,12,0)
io(po,4,0)
c = 0
av = 0
esum2 = 0
dim hist(8)
dim er(8)
meter c, 0, 1023
wprint "<br>"
meter av, 0, 1023
wprint "<br>"
meter esum2, 0, 10
timer 500, [tick]
wait
[tick]
io(pi, 4)
io(po, 12, 1)
io(po, 12, 0)
delay 20
t = io(ai)
if t<1023 then
c = t
e = 0
else
e = 1
endif
io(po,4,0)
sum = 0
esum = 0
hist(8) = c
er(8) = e
for t=0 to 7
er(t) = er(t+1)
hist(t) = hist(t+1)
sum = sum+hist(t)
esum = esum+er(t)
next t
av = sum/8
esum2 = esum
waitThis is test code, meaning that it does more than just sample the sensor. This will make 2 samples per second, report the last readable results in the top meter, the average distance over the last 8 samples in the second meter, and the percentage of known errors in the bottom meter over the last 10 samples.
For a stripped down version to just do individual samples, the following will work:
' Initialization of pins
io(po,12,0)
io(po,4,0)
' Your code continues here
wait
[sample]
io(pi, 4)
io(po, 12, 1)
io(po, 12, 0)
delay 20
sample = io(ai)
io(po,4,0)
returnAnd again with comments:
' Initialization of pins
' Be sure we are not pulsing the sensor
io(po,12,0)
' Ground the capacitor to keep it discharged
io(po,4,0)
' Your code continues here
wait
' GOSUB here to sample the sensor. SAMPLE contains the result, 0-1022. 1023 = error.
[sample]
' Allow capacitor to float
io(pi, 4)
' Pulse the sensor to initiate a read
io(po, 12, 1)
io(po, 12, 0)
' Wait for the sensor to respond, allowing it to charge the capacitor
delay 20
' Read the state of charge of the capacitor
sample = io(ai)
' Start the capacitor discharging. Should allow about 100 milliseconds for discharge, maybe more.
io(po,4,0)
' All done! Here is where you might add statistical analysis and/or precise distance conversion to
' burn up some of that 100ms you need to waste.
returnNow remember, this returns state of charge of the capacitor which is NOT linear. The way to turn this into a fairly precise distance is to build a table of sampled values of known distances and do a simple interpolation. I'll get to that another time.
Reminder: The circuit diagram is pictured with a 330ohm resistor. That will limit you to about 4 feet but with fewer sensor errors. A 560ohm resistor gets to about 6 feet but with increasing sensor errors. Your choice.