MicroPython Driver for HC-SR04 Ultrasonic Distance Sensor
Contents
Introduction
This a MicroPython driver written specifically for the BBC micro:bit that will work with the original HC‑SR04 sensor. Unfortunately the original HC‑SR04 board requires a 5V power supply making it inconvenient to use with the 3.3V micro:bit.
Recently, however, many 3.3V powered HC-SR04 variants have come to market. These include (but not limited to) the HC‑SR04P and US‑100 families of ultrasonic distance sensors.
NOTE: This webpage was written using the HC‑SR04P as the test sensor. Any of the other 3.3V variants such as the US‑100 can be directly substituted.
The HC-SR04P and US-100 distance sensors are discussed in some detail here.
FIG 1 - HC-SR04P board (2022 model): [Left] front view, [Right] rear view
The HC-SR04P boards are readily available in various forms.
Connecting the HC-SR04P
This driver uses the classical HC-SR04 interface. It's easy to hookup to the micro:bit.
| micro:bit | HC-SR04P |
|---|---|
| 3.3V | VCC |
| GND | GND |
| Pin 1 | Trig |
| Pin 2 | Echo |
Any two available digital pins on the micro:bit can be used. The above table shows the driver's default.
If these default pins aren't used then the actual digital pins in use must be given when declaring an instance of the driver class. This is explained in the following section.
Driver Overview
This driver is very simple. There is a single property which returns distance in cm.
Driver codeThe driver code can be:
- Copied from this webpage onto the clipboard then pasted into the MicroPython editor e.g. the Mu Editor. It should be saved as fc_hc_sr04.py - OR -
- Download as a zip file using the link. Unzip the file and save it as fc_hc_sr04.py into the default directory where the MicroPython editor e.g. Mu Editor saves python code files.
After saving the fc_hc_sr04.py file to the computer it should be copied to the small filesystem on the micro:bit. The examples on this page will not work if this step is omitted. Any MicroPython editor that recognises the micro:bit will have an option to do this.
The Mu Editor is recommended for its simplicity. It provides a Files button on the toolbar for just this purpose.
Class constructorThe driver is implemented as a class.The first thing to do is call the constructor of the HC_SR04 class to obtain a sensor object.
Syntax:
HC_SR04(Trig=pin1, Echo=pin2)
The Trig and Echo pins can be changed to
any available digital pins.
Example 1
from fc_hc_sr04 import *
# Declare a HC-SR04 sensor object using
# the default Trig and Echo pins.
sensor = HC_SR04()
Example 2
from fc_hc_sr04 import *
# Declare a HC-SR04 sensor object using
# different Trig and Echo pins.
sensor = HC_SR04(Trig=pin14, Echo=pin15)
This assumes that the file fc_hc_sr04.py has been successfully copied to the micro:bit's filesystem as described above.
Measuring Distance
It's a very simple process to read distance values from the sensor. The distance values have units of centimeters.
Syntax:
Reading
Property that returns the distance in cm.
A value of 0 will be returned in the
event of an error. This might occur
e.g. if the target or the sensor are
in rapid movement.
Example 1:
from fc_hc_sr04 import *
sensor = HC_SR04()
d = sensor.Reading
print('Distance:', d, 'cm')
Typical Output:
Distance: 44 cm
Example 2:
# Takes a distance measurement every
# 3 seconds in an endless loop.
from fc_hc_sr04 import *
sensor = HC_SR04()
while True:
d = sensor.Reading
print('Distance:', d, 'cm')
sleep(3000)
Typical Output:
Distance: 44 cm
Distance: 35 cm
Distance: 29 cm
Distance: 19 cm
Distance: 7 cm
Distance: 3 cm
Distance: 16 cm
Distance: 35 cm
Traceback (most recent call last):
File "main.py", line 10, in <module>
KeyboardInterrupt:
While Example 2 was running the sensor was continuously moved. The program was stopped by typing CTRL/C (Windows) in the REPL.
Enjoy!
HC-SR04 Driver Code for micro:bit
Download as zip file
'''
MicroPython driver for BBC micro:bit
This driver works with the following
ultrasonic distance sensors (and others):
HC-SR04
HC-SR04P
HY-SRF05
US-100
WARNING:
HC-SR04 and HY-SRF05 are 5V sensors.
Trig pin can be directly connected to micro:bit pin.
Echo pin must be connected to micro:bit through
a voltage divider or a logic level shifter that
converts the 5V to 3.3V.
HC-SR04P is a 3.3V to 5V powered sensor.
This sensor can be powered from the micro:bit
and be directly connected to micro:bit pins.
US-100 : To operate this sensor in HC_SR04 mode the
jumper on the back of the board must be removed.
This sensor is a 3.3V to 5V powered sensor.
AUTHOR: fredscave.com
DATE : 2025/10
VERSION : 2.00
'''
from microbit import *
import machine
import utime
class HC_SR04():
def __init__(self, Trig=pin1, Echo=pin2):
self.Trig = Trig
self.Echo = Echo
# Triggers the sensor and returns the distance in cm.
@property
def Reading(self):
# Pulse Trig pin for just longer than 10 uS
self.Trig.write_digital(1)
s = 0; s = 1 # Waste a small amount of time
self.Trig.write_digital(0)
# Read echo time
time = machine.time_pulse_us(self.Echo, 1, 1000000)
# Convert echo time to distance in cm
return round((0.034 * time)/2)
Images
Our sincere thanks goes to Frank, the local highly talented 'design and build' specialist, for the target board used in the development of this driver.
This target board will find use in the future development of drivers for other distance sensors; both ultrasonic and infrared based.