-
Notifications
You must be signed in to change notification settings - Fork 1
/
ultrasonic.py
41 lines (29 loc) · 938 Bytes
/
ultrasonic.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
import RPi.GPIO as gpio
import time
class Ultrasonic:
__trig = 19
__echo = 26
latestValidUltrasonicDistance = 0
def __init__(self):
gpio.setmode(gpio.BCM)
gpio.setwarnings(False)
gpio.setup(self.__trig, gpio.OUT)
gpio.setup(self.__echo, gpio.IN)
gpio.output(self.__trig, False)
print ("WAITING FOR SENSOR")
time.sleep(2)
def sense(self):
gpio.output(self.__trig, True)
time.sleep(0.00001)
gpio.output(self.__trig, False)
while gpio.input(self.__echo) == 0: start = time.time()
while gpio.input(self.__echo) == 1: end = time.time()
duration = end - start
distance = duration * 17150
distance = round(distance, 2)
print("FRONT DISTANCE: " + str(distance) + " CM")
return distance
def cleanup(self):
gpio.cleanup()
def __del__(self):
gpio.cleanup()