adafruit_hcsr04

A CircuitPython library for the HC-SR04 ultrasonic range sensor.

The HC-SR04 functions by sending an ultrasonic signal, which is reflected by many materials, and then sensing when the signal returns to the sensor. Knowing that sound travels through dry air at 343.2 meters per second (at 20 °C), it’s pretty straightforward to calculate how far away the object is by timing how long the signal took to go round-trip and do some simple arithmetic, which is handled for you by this library.

Warning

The HC-SR04 uses 5V logic, so you will have to use a level shifter or simple voltage divider between it and your CircuitPython board (which uses 3.3V logic)

  • Authors:
    • Mike Mabey
    • Jerry Needell - modified to add timeout while waiting for echo (2/26/2018)
    • ladyada - compatible with distance property standard, renaming, Pi compat
class adafruit_hcsr04.HCSR04(trigger_pin, echo_pin, *, timeout=0.1)[source]

Control a HC-SR04 ultrasonic range sensor.

Example use:

import time
import board

import adafruit_hcsr04

sonar = adafruit_hcsr04.HCSR04(trigger_pin=board.D2, echo_pin=board.D3)


while True:
    try:
        print((sonar.distance,))
    except RuntimeError:
        print("Retrying!")
        pass
    time.sleep(0.1)
Parameters:
  • trigger_pin – The pin on the microcontroller that’s connected to the Trig pin on the HC-SR04.
  • echo_pin (microcontroller.Pin) – The pin on the microcontroller that’s connected to the Echo pin on the HC-SR04.
  • timeout (float) – Max seconds to wait for a response from the sensor before assuming it isn’t going to answer. Should not be set to less than 0.05 seconds!
deinit()[source]

De-initialize the trigger and echo pins.

distance

Return the distance measured by the sensor in cm.

This is the function that will be called most often in user code. The distance is calculated by timing a pulse from the sensor, indicating how long between when the sensor sent out an ultrasonic signal and when it bounced back and was received again.

If no signal is received, we’ll throw a RuntimeError exception. This means either the sensor was moving too fast to be pointing in the right direction to pick up the ultrasonic signal when it bounced back (less likely), or the object off of which the signal bounced is too far away for the sensor to handle. In my experience, the sensor can detect objects over 460 cm away.

Returns:Distance in centimeters.
Return type:float