/ hcsr04.py
hcsr04.py
1 # The MIT License (MIT) 2 # 3 # Copyright (c) 2017 Mike Mabey 4 # 5 # Permission is hereby granted, free of charge, to any person obtaining a copy 6 # of this software and associated documentation files (the "Software"), to deal 7 # in the Software without restriction, including without limitation the rights 8 # to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 # copies of the Software, and to permit persons to whom the Software is 10 # furnished to do so, subject to the following conditions: 11 # 12 # The above copyright notice and this permission notice shall be included in 13 # all copies or substantial portions of the Software. 14 # 15 # THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 # IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 # FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 # AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 # LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 # OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN 21 # THE SOFTWARE. 22 """ 23 A CircuitPython library for the HC-SR04 ultrasonic range sensor. 24 25 The HC-SR04 functions by sending an ultrasonic signal, which is reflected by 26 many materials, and then sensing when the signal returns to the sensor. Knowing 27 that sound travels through dry air at `343.2 meters per second (at 20 °C) 28 <https://en.wikipedia.org/wiki/Speed_of_sound>`_, it's pretty straightforward 29 to calculate how far away the object is by timing how long the signal took to 30 go round-trip and do some simple arithmetic, which is handled for you by this 31 library. 32 33 .. warning:: 34 35 The HC-SR04 uses 5V logic, so you will have to use a `level shifter 36 <https://www.adafruit.com/product/2653?q=level%20shifter&>`_ between it 37 and your CircuitPython board (which uses 3.3V logic). 38 39 * Authors: 40 41 - Mike Mabey 42 - Jerry Needell - modified to add timeout while waiting for echo (2/26/2018) 43 """ 44 import board 45 from digitalio import DigitalInOut, DriveMode 46 from pulseio import PulseIn 47 import time 48 49 50 class HCSR04: 51 """Control a HC-SR04 ultrasonic range sensor. 52 53 Example use: 54 55 :: 56 57 with HCSR04(trig, echo) as sonar: 58 try: 59 while True: 60 print(sonar.dist_cm()) 61 sleep(2) 62 except KeyboardInterrupt: 63 pass 64 """ 65 def __init__(self, trig_pin, echo_pin, timeout_sec=.1): 66 """ 67 :param trig_pin: The pin on the microcontroller that's connected to the 68 ``Trig`` pin on the HC-SR04. 69 :type trig_pin: str or microcontroller.Pin 70 :param echo_pin: The pin on the microcontroller that's connected to the 71 ``Echo`` pin on the HC-SR04. 72 :type echo_pin: str or microcontroller.Pin 73 :param float timeout_sec: Max seconds to wait for a response from the 74 sensor before assuming it isn't going to answer. Should *not* be 75 set to less than 0.05 seconds! 76 """ 77 if isinstance(trig_pin, str): 78 trig_pin = getattr(board, trig_pin) 79 if isinstance(echo_pin, str): 80 echo_pin = getattr(board, echo_pin) 81 self.dist_cm = self._dist_two_wire 82 self.timeout_sec = timeout_sec 83 84 self.trig = DigitalInOut(trig_pin) 85 self.trig.switch_to_output(value=False, drive_mode=DriveMode.PUSH_PULL) 86 87 self.echo = PulseIn(echo_pin) 88 self.echo.pause() 89 self.echo.clear() 90 91 def __enter__(self): 92 """Allows for use in context managers.""" 93 return self 94 95 def __exit__(self, exc_type, exc_val, exc_tb): 96 """Automatically de-initialize after a context manager.""" 97 self.deinit() 98 99 def deinit(self): 100 """De-initialize the trigger and echo pins.""" 101 self.trig.deinit() 102 self.echo.deinit() 103 104 def dist_cm(self): 105 """Return the distance measured by the sensor in cm. 106 107 This is the function that will be called most often in user code. The 108 distance is calculated by timing a pulse from the sensor, indicating 109 how long between when the sensor sent out an ultrasonic signal and when 110 it bounced back and was received again. 111 112 If no signal is received, the return value will be ``-1``. This means 113 either the sensor was moving too fast to be pointing in the right 114 direction to pick up the ultrasonic signal when it bounced back (less 115 likely), or the object off of which the signal bounced is too far away 116 for the sensor to handle. In my experience, the sensor can detect 117 objects over 460 cm away. 118 119 :return: Distance in centimeters. 120 :rtype: float 121 """ 122 # This method only exists to make it easier to document. See either 123 # _dist_one_wire or _dist_two_wire for the actual implementation. One 124 # of those two methods will be assigned to be used in place of this 125 # method on instantiation. 126 pass 127 128 def _dist_two_wire(self): 129 self.echo.clear() # Discard any previous pulse values 130 self.trig.value = 1 # Set trig high 131 time.sleep(0.00001) # 10 micro seconds 10/1000/1000 132 self.trig.value = 0 # Set trig low 133 timeout = time.monotonic() 134 self.echo.resume() 135 while len(self.echo) == 0: 136 # Wait for a pulse 137 if (time.monotonic() - timeout) > self.timeout_sec: 138 self.echo.pause() 139 return -1 140 self.echo.pause() 141 if self.echo[0] == 65535: 142 return -1 143 144 return (self.echo[0] / 2) / (291 / 10) 145 146 147 def test(trig, echo, delay=2): 148 """Create and get distances from an :class:`HCSR04` object. 149 150 This is meant to be helpful when first setting up the HC-SR04. It will get 151 a distance every ``delay`` seconds and print it to standard out. 152 153 :param trig: The pin on the microcontroller that's connected to the 154 ``Trig`` pin on the HC-SR04. 155 :type trig: str or microcontroller.Pin 156 :param echo: The pin on the microcontroller that's connected to the 157 ``Echo`` pin on the HC-SR04. 158 :type echo: str or microcontroller.Pin 159 :param delay: Seconds to wait between triggers. 160 :type delay: int or float 161 :rtype: None 162 """ 163 with HCSR04(trig, echo) as sonar: 164 try: 165 while True: 166 print(sonar.dist_cm()) 167 time.sleep(delay) 168 except KeyboardInterrupt: 169 pass