GuyCarver-MicroPython/lib/SR04Distance.py

80 wiersze
1.8 KiB
Python

2017-11-04 21:43:37 +00:00
from pyb import Pin, Timer, udelay
2018-02-28 23:03:42 +00:00
# WARNING: Should place a 1k resistor on the echo pin.
2017-11-04 21:43:37 +00:00
2018-02-18 14:11:30 +00:00
class sr04distance(object):
2018-02-28 23:03:42 +00:00
"""Driver for SR05 sonic distance sensor. """
2017-11-04 21:43:37 +00:00
2018-02-28 23:03:42 +00:00
# _MAXINCHES = const(20) #maximum range of SR04.
2017-11-04 21:43:37 +00:00
2018-02-28 23:03:42 +00:00
def __init__( self, tpin, epin, timer = 2 ) :
'''tpin = Timer pin.
epin = Echo pin.
timer = Timer #.
'''
2017-11-04 21:43:37 +00:00
if type(tpin) == str:
self._tpin = Pin(tpin, Pin.OUT_PP, Pin.PULL_NONE)
elif type(tpin) == Pin:
self._tpin = tpin
else:
raise Exception("trigger pin must be pin name or pyb.Pin configured for output.")
self._tpin.low()
if type(epin) == str:
self._epin = Pin(epin, Pin.IN, Pin.PULL_NONE)
elif type(epin) == Pin:
self._epin = epin
else:
raise Exception("echo pin must be pin name or pyb.Pin configured for input.")
# Create a microseconds counter.
2018-02-28 23:03:42 +00:00
self._micros = Timer(timer, prescaler = 83, period = 0x3fffffff)
2017-11-04 21:43:37 +00:00
def __del__( self ) :
self._micros.deinit()
@property
2018-02-28 23:03:42 +00:00
def counter( self ) :
return self._micros.counter()
2017-11-04 21:43:37 +00:00
@counter.setter
2018-02-28 23:03:42 +00:00
def counter( self, value ) :
self._micros.counter(value)
2017-11-04 21:43:37 +00:00
@property
def centimeters( self ) :
2018-02-28 23:03:42 +00:00
'''Get # of centimeters distance sensor is reporting.'''
2017-11-04 21:43:37 +00:00
start = 0
end = 0
self.counter = 0
#Send 10us pulse.
self._tpin.high()
udelay(10)
self._tpin.low()
while not self._epin.value():
start = self.counter
j = 0
# Wait 'till the pulse is gone.
while self._epin.value() and j < 1000:
j += 1
end = self.counter
# Calc the duration of the recieved pulse, divide the result by
# 2 (round-trip) and divide it by 29 (the speed of sound is
# 340 m/s and that is 29 us/cm).
2018-02-28 23:03:42 +00:00
return (end - start) / 58.0
2017-11-04 21:43:37 +00:00
@property
2018-02-28 23:03:42 +00:00
def inches( self ) :
#Get distance in inches.
return self.centimeters * 0.3937
2017-11-04 21:43:37 +00:00