forked from manugeorge04/Swarm-Robotics
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathUltrasoundSensor.py
More file actions
44 lines (30 loc) · 950 Bytes
/
UltrasoundSensor.py
File metadata and controls
44 lines (30 loc) · 950 Bytes
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
try:
GPIO.setmode(GPIO.BCM)
GPIO.setwarnings(False)
TRIG = 3
ECHO = 4
maxTime = 0.04
while True:
GPIO.setup(TRIG,GPIO.OUT)
GPIO.setup(ECHO,GPIO.IN)
GPIO.output(TRIG,False)
time.sleep(0.01)
GPIO.output(TRIG,True)
time.sleep(0.00001)
GPIO.output(TRIG,False)
pulse_start = time.time()
timeout = pulse_start + maxTime
while GPIO.input(ECHO) == 0 and pulse_start < timeout:
pulse_start = time.time()
pulse_end = time.time()
timeout = pulse_end + maxTime
while GPIO.input(ECHO) == 1 and pulse_end < timeout:
pulse_end = time.time()
pulse_duration = pulse_end - pulse_start
distance = pulse_duration * 17000
distance = round(distance, 2)
print(distance)
except:
GPIO.cleanup()