CircuitPython HC-SR04 Driver

Documentation Status Release Version CI Build Status License: MIT

_images/hcsr04.jpg

The HC-SR04 is an inexpensive solution for measuring distances using microcontrollers. This library provides a simple driver for controlling these sensors from CircuitPython, Adafruit’s port of MicroPython.

Installation

This driver depends on CircuitPython and is designed for use with an HC-SR04 ultrasonic range sensor. You’ll also need to ensure all dependencies are available on the CircuitPython filesystem. This is easily achieved by downloading the Adafruit library and driver bundle.

Warning

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

Note

If you want to use an HC-SR04 with MicroPython, I recommend checking out this library.

Quick Start

You’ll need to dedicate two pins to communicating with the HC-SR04. The sensor communicates in a very rudimentary manner, so it doesn’t matter which pins you choose, as long as they’re digital IO pins (pins that start with “D” are digital).

There are two ways of instantiating a HCSR04 object: with or without using a context manager.

Note

It is technically possible to communicate with the HC-SR04 using only one wire since the trigger and echo signals aren’t ever active at the same time. Once I have a chance to determine a safe way to do this, I plan to add this as a feature to the library.

See also

Adafruit’s guide on Lifetime and ContextManagers
Gives more info on using context managers with CircuitPython drivers.
board

A list of pins available on your device. To view this list, first get a REPL (the guide linked was written for the pyboard, but it still works), then input the following:

import board
dir(board)

Without a Context Manager

In the example below, we create the HCSR04 object directly, get the distance every 2 seconds, then de-initialize the device.

from hcsr04 import HCSR04
sonar = HCSR04(trig, echo)
try:
    while True:
        print(sonar.dist_cm())
        sleep(2)
except KeyboardInterrupt:
    pass
sonar.deinit()

With a Context Manager

In the example below, we use a context manager (the with statement) to create the HCSR04 instance, again get the distance every 2 seconds, but then the context manager handles de-initializing the device for us.

from hcsr04 import HCSR04
with HCSR04(trig, echo) as sonar:
    try:
        while True:
            print(sonar.dist_cm())
            sleep(2)
    except KeyboardInterrupt:
        pass

API Reference

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 air at 343.2 meters per second

Warning

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

  • Author(s): Mike Mabey
class hcsr04.HCSR04(trig_pin, echo_pin)[source]

Control a HC-SR04 ultrasonic range sensor.

Example use:

with HCSR04(trig, echo) as sonar:
    try:
        while True:
            print(sonar.dist_cm())
            sleep(2)
    except KeyboardInterrupt:
        pass
Parameters:
  • trig_pin (str or microcontroller.Pin) – The pin on the microcontroller that’s connected to the Trig pin on the HC-SR04.
  • echo_pin (str or microcontroller.Pin) – The pin on the microcontroller that’s connected to the Echo pin on the HC-SR04.
deinit()[source]

De-initialize the trigger and echo pins.

dist_cm()[source]

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, the return value will be -1. 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
hcsr04.test(trig, echo, delay=2)[source]

Create and get distances from an HCSR04 object.

This is meant to be helpful when first setting up the HC-SR04. It will get a distance every delay seconds and print it to standard out.

Parameters:
  • trig (str or microcontroller.Pin) – The pin on the microcontroller that’s connected to the Trig pin on the HC-SR04.
  • echo (str or microcontroller.Pin) – The pin on the microcontroller that’s connected to the Echo pin on the HC-SR04.
  • delay (int or float) – Seconds to wait between triggers.
Return type:

None

Contributing

Contributions are welcome! Please read our Code of Conduct before contributing to help this project stay welcoming.

License

This project is licensed under the MIT License.