forked from RyanZotti/Self-Driving-Car
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrange_sensor.py
44 lines (34 loc) · 988 Bytes
/
range_sensor.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
import RPi.GPIO as GPIO
import time
import sys
# I got all code from here:
# http://www.modmypi.com/blog/hc-sr04-ultrasonic-range-sensor-on-the-raspberry-pi
def calculate_distance(ECHO,TRIG):
# Set output pin to low
GPIO.output(TRIG, False)
GPIO.output(TRIG, True)
time.sleep(0.00001)
GPIO.output(TRIG, False)
while GPIO.input(ECHO) == 0:
pulse_start = time.time()
while GPIO.input(ECHO) == 1:
pulse_end = time.time()
pulse_duration = pulse_end - pulse_start
distance = pulse_duration * 17150
distance = round(distance, 2)
return distance
if __name__ == '__main__':
GPIO.setmode(GPIO.BCM)
TRIG = 2
ECHO = 3
GPIO.setup(TRIG, GPIO.OUT)
GPIO.setup(ECHO, GPIO.IN)
while True:
try:
distance = calculate_distance(ECHO,TRIG)
print("Distance:", distance, "cm")
except KeyboardInterrupt:
sys.exit(0)
except:
pass
GPIO.cleanup()