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

45 lines
1.2 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, trigger, echo):
self.TRIGGER = trigger
self.ECHO = echo
self.lastValue = 0
self.lastValuesCount = 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:
7 years ago
pass
pulse_start = time.time()
7 years ago
while GPIO.input(self.ECHO) == 1 and (time.time() - abs_start) < 0.02:
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)
lastc = self.lastValuesCount
self.lastValue = (1/lastc) * distance + ((lastc-1)/lastc) * self.lastValue
distance = self.lastValue
7 years ago
return distance
@staticmethod
def cleanup():
GPIO.cleanup()