-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathultrasonic.py
More file actions
67 lines (56 loc) · 1.91 KB
/
ultrasonic.py
File metadata and controls
67 lines (56 loc) · 1.91 KB
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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
# Import required Python libraries
from math import *
import time
import RPi.GPIO as GPIO
GPIO.setwarnings(False)
GPIO.cleanup()
# Use BCM GPIO references
# instead of physical pin numbers
GPIO.setmode(GPIO.BCM)
ultrasonic1_pins = [7, 8]
ultrasonic2_pins = [15, 14]
ultrasonic3_pins = [21, 20]
ultrasonic4_pins = [5, 6]
def get_ultrasonic(ultrasonic_number):
try:
# Define GPIO to use on Pi
if ultrasonic_number == 1:
GPIO_TRIGGER = ultrasonic1_pins[0]
GPIO_ECHO = ultrasonic1_pins[1]
if ultrasonic_number == 2:
GPIO_TRIGGER = ultrasonic2_pins[0]
GPIO_ECHO = ultrasonic2_pins[1]
if ultrasonic_number == 3:
GPIO_TRIGGER = ultrasonic3_pins[0]
GPIO_ECHO = ultrasonic3_pins[1]
if ultrasonic_number == 4:
GPIO_TRIGGER = ultrasonic4_pins[0]
GPIO_ECHO = ultrasonic4_pins[1]
# Set pins as output and input
GPIO.setup(GPIO_TRIGGER, GPIO.OUT) # Trigger
GPIO.setup(GPIO_ECHO, GPIO.IN) # Echo
# Set trigger to False (Low)
GPIO.output(GPIO_TRIGGER, False)
# Allow module to settle
time.sleep(0.5)
# Send 10us pulse to trigger
GPIO.output(GPIO_TRIGGER, True)
time.sleep(0.00001)
GPIO.output(GPIO_TRIGGER, False)
start = time.time()
while GPIO.input(GPIO_ECHO) == 0:
start = time.time()
while GPIO.input(GPIO_ECHO) == 1:
stop = time.time()
# Calculate pulse length
elapsed = stop - start
# Distance pulse travelled in that time is time
# multiplied by the speed of sound (cm/s)
distance = elapsed * 34000
# That was the distance there and back so halve the value
distance = distance / 2
return round(distance, 2)
except KeyboardInterrupt:
GPIO.cleanup()
# Reset GPIO settings
GPIO.cleanup()