' Space Finder detection PIC code
'(c) 2002-2003 OMNISOFT
DEFINE OSC 20
A VAR BYTE
U VAR WORD
D VAR WORD 'measured distance of sound reflection
LD VAR WORD 'last distance measured
C VAR BYTE 'the number of distnace readings obtained
P VAR WORD 'value of var pot resistor (used to set threshold if car detected or not)
TRISA = 0
CMCON = 7
High PORTB.3 'turn off RED led
High PORTB.4 'turn off Green led
C = 0
LD = 0
Scan:
Pot PORTA.0, 255, P 'get pot reading (this is a variable resistor used to set the "threshold" distance = car present if distance is less then this value)
P = P * 10
GoSub Send40 'send a 40khz burst of ultrasonic signal
Low PORTB.7 'turn off receiving sensor so wont false trigger too soon
Pause 5 '5ms
High PORTB.7 'turn on receiving sensor
For D = 1 TO 2500 'start measuring how long it takes for sound reflection to be detected (D = ~ time)
A = PORTB.6 'see if reflected sound was detected
IF A > 0 Then 'if heard, then report and check distance (in value of D)
SerOut2 PORTB.2, 32, [DEC D, 10, 13] 'report to external serial terminal the measured distance
Goto Check 'no calc if car present or not based on measured distance and pot value
EndIF
Next D
Check:
If ABS(D - LD) < 100 then 'if difference between last detected distance and this detect is less then 50, then reading is stable
C = C + 1 'increment reading count
if C > 2 then 'if got 3 readings of roughly the same value, then
IF D < P Then 'if distance is less then pot value - there is a car present in spot
High PORTB.4 'turn off green leds
Low PORTB.3 'turn on red leds
SerOut2 PORTB.2, 32, ["CAR (P=",dec P,")",10,13] 'report that there is a car present
Else 'since reflection distance is greater then pot value = no car present in spot
Low PORTB.4 'turn on green leds
High PORTB.3 'turn off red leds
if D > 2500 then 'if distance overflow, then timeout (car windshield probably deflecting audio signal away from receiver)
SerOut2 PORTB.2, 32, ["TIMEOUT (P=",dec P,")",10,13]
else 'distance is greater then pot, so no car
SerOut2 PORTB.2, 32, ["NO-CAR (P=",dec P,")",10,13]
endif
EndIF
endif
else
C = 0
endif
LD = D 'last distance = current distance
Pause 500 'wait .5 seconds
GoTo scan 'retake another measurement
Send40:
'sends 40khz pulse for .5ms
'the NOP statements were inserted to produce a perfect 40khz signal at 50% duty cycle
For U = 1 TO 20
High PORTA.6
For A = 1 TO 5
@ NOP
Next A
@ NOP
@ NOP
@ NOP
Low PORTA.6
For A=1 TO 1
@ NOP
Next A
@ NOP
@ NOP
Next U
Return