|
| 1 | +## |
| 2 | +# Ultrasonic library for MicroPython's pyboard. |
| 3 | +# Compatible with HC-SR04 and SRF04. |
| 4 | +# |
| 5 | +# Copyright 2014 - Sergio Conde Gómez <skgsergio@gmail.com> |
| 6 | +# |
| 7 | +# This program is free software: you can redistribute it and/or modify |
| 8 | +# it under the terms of the GNU General Public License as published by |
| 9 | +# the Free Software Foundation, either version 3 of the License, or |
| 10 | +# (at your option) any later version. |
| 11 | +# |
| 12 | +# This program is distributed in the hope that it will be useful, |
| 13 | +# but WITHOUT ANY WARRANTY; without even the implied warranty of |
| 14 | +# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the |
| 15 | +# GNU General Public License for more details. |
| 16 | +# |
| 17 | +# You should have received a copy of the GNU General Public License |
| 18 | +# along with this program. If not, see <http://www.gnu.org/licenses/>. |
| 19 | +## |
| 20 | + |
| 21 | +import pyb |
| 22 | + |
| 23 | +# Pin configuration. |
| 24 | +# WARNING: Do not use PA4-X5 or PA5-X6 as the echo pin without a 1k resistor. |
| 25 | + |
| 26 | +class Ultrasonic: |
| 27 | + def __init__(self, tPin, ePin): |
| 28 | + self.triggerPin = tPin |
| 29 | + self.echoPin = ePin |
| 30 | + |
| 31 | + # Init trigger pin (out) |
| 32 | + self.trigger = pyb.Pin(self.triggerPin) |
| 33 | + self.trigger.init(pyb.Pin.OUT_PP, pyb.Pin.PULL_NONE) |
| 34 | + self.trigger.low() |
| 35 | + |
| 36 | + # Init echo pin (in) |
| 37 | + self.echo = pyb.Pin(self.echoPin) |
| 38 | + self.echo.init(pyb.Pin.IN, pyb.Pin.PULL_NONE) |
| 39 | + |
| 40 | + def distance_in_inches(self): |
| 41 | + return (self.distance_in_cm() * 0.3937) |
| 42 | + |
| 43 | + def distance_in_cm(self): |
| 44 | + start = 0 |
| 45 | + end = 0 |
| 46 | + |
| 47 | + # Create a microseconds counter. |
| 48 | + micros = pyb.Timer(2, prescaler=83, period=0x3fffffff) |
| 49 | + micros.counter(0) |
| 50 | + |
| 51 | + # Send a 10us pulse. |
| 52 | + self.trigger.high() |
| 53 | + pyb.udelay(10) |
| 54 | + self.trigger.low() |
| 55 | + |
| 56 | + # Wait 'till whe pulse starts. |
| 57 | + while self.echo.value() == 0: |
| 58 | + start = micros.counter() |
| 59 | + |
| 60 | + # Wait 'till the pulse is gone. |
| 61 | + while self.echo.value() == 1: |
| 62 | + end = micros.counter() |
| 63 | + |
| 64 | + # Deinit the microseconds counter |
| 65 | + micros.deinit() |
| 66 | + |
| 67 | + # Calc the duration of the recieved pulse, divide the result by |
| 68 | + # 2 (round-trip) and divide it by 29 (the speed of sound is |
| 69 | + # 340 m/s and that is 29 us/cm). |
| 70 | + dist_in_cm = ((end - start) / 2) / 29 |
| 71 | + |
| 72 | + return dist_in_cm |
0 commit comments