You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
spydian/lib/ultrasonic.py

47 lines
1.3 KiB
Python

7 years ago
import RPi.GPIO as GPIO
import time
GPIO.setmode(GPIO.BOARD)
7 years ago
class Sensor(object):
def init(self, TRIG, ECHO):
self.TRIGGER = TRIG
self.ECHO = ECHO
self.lastValues = [1, 1, 1, 1, 1, 1, 1, 1, 1, 1]
GPIO.setup(self.TRIGGER, GPIO.OUT)
GPIO.setup(self.ECHO, GPIO.IN)
GPIO.output(self.TRIGGER, False)
7 years ago
print('Waiting for Sensor to settle')
time.sleep(2)
def echo(self):
GPIO.output(self.TRIGGER, True)
time.sleep(0.00001)
GPIO.output(self.TRIGGER, False)
abs_start = time.time()
7 years ago
while GPIO.input(self.ECHO) == 0 and (time.time() - abs_start) < 0.02:
# print(time.time()-abs_start)
7 years ago
pass
pulse_start = time.time()
7 years ago
while GPIO.input(self.ECHO) == 1 and (time.time() - abs_start) < 0.02:
# print(time.time()-abs_start)
7 years ago
pass
pulse_end = time.time()
7 years ago
pulse_duration = pulse_end - pulse_start
7 years ago
distance = pulse_duration * 17150
distance = round(distance, 2)
7 years ago
self.lastValues.append(distance)
self.lastValues = self.lastValues[1:]
distance = round((sum(self.lastValues)) / (len(self.lastValues)), 2)
# print(self.lastValues)
# print("Distance: {}".format(distance))
7 years ago
return distance
def clean(self):
GPIO.cleanup()