PDA

View Full Version : Ultrasonic distance sensor with PIC16F84A



MrRoboto
- 28th June 2009, 01:11
All

I used the code below to light a LED if the distance is less than 12 inches, the code runs , but for only 3 iterations, some time 4 iterations, I cannot seem to find out why, can anyone help.

I am using the parallax ping sonar sensor

Thanks



-----------------------------------
code
------------------------------------
SYMBOL Ping = 7


' -----[ Constants ]-------------------------------------------------------

SYMBOL Trigger = 1 ' 10 uS trigger pulse
SYMBOL Scale = 10 ' raw x 10.00 = uS

SYMBOL RawToIn = 889 ' 1 / 73.746 (with **)
SYMBOL RawToCm = 2257 ' 1 / 29.034 (with **)

SYMBOL IsHigh = 1 ' for PULSOUT
SYMBOL IsLow = 0


' -----[ Variables ]-------------------------------------------------------

SYMBOL rawDist = W1 ' raw measurement
SYMBOL inches = W2
SYMBOL cm = W3



' -----[ Initialization ]--------------------------------------------------

Reset:


' -----[ Program Code ]----------------------------------------------------

Main:

GOSUB Get_Sonar ' get sensor value



inches = rawDist ** RawToIn ' convert to inches
'cm = rawDist ** RawToCm ' convert to centimeters

if inches < 12 then pushd




'DEBUG CLS ' report
'DEBUG "Time (uS)..... ", #rawDist, CR
'DEBUG "Inches........ ", #inches, CR
'DEBUG "Centimeters... ", #cm

PAUSE 500
GOTO Main

end




' -----[ Subroutines ]-----------------------------------------------------

' This subroutine triggers the Ping sonar sensor and measures
' the echo pulse. The raw value from the sensor is converted to
' microseconds based on the Stamp module in use. This value is
' divided by two to remove the return trip -- the result value is
' the distance from the sensor to the target in microseconds.

Get_Sonar:
LOW Ping ' make trigger 0-1-0
PULSOUT Ping, Trigger ' activate sensor
PULSIN Ping, IsHigh, rawDist ' measure echo pulse
rawDist = rawDist * Scale ' convert to uS
rawDist = rawDist / 2 ' remove return trip
RETURN


pushd:
high 1 'high RB 1
pause 1000
LOW 1

PAUSE 500

HIGH 1
PAUSE 1000
LOW 1

PAUSE 500
return

Melanie
- 28th June 2009, 02:50
One problem is that your have a GOTO PUSHD...

if inches < 12 then pushd

... but your have a RETURN at the end of the PUSHD code.

Change your code to read...

if inches < 12 then GOSUB pushd

MrRoboto
- 29th June 2009, 01:13
Thank you, but thats not the problem, there must be something inherinant to the ultrasonic sensor that wont let it infinite loop without being reset or something,

Can anyone tell me why after four object detects it goes off based on the code I provided?

Melanie
- 29th June 2009, 09:01
If you have added the GOSUB, then your code is now good.

You could always check if RawDist=0 then light an Error LED, that way you can check if you are actually getting sensible results back from your Sensor.