MicroPython Driver for HC-SR04 Ultrasonic Distance Sensor

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.

HC-SR04P distance sensor, micro-bit and the target board used in the development in this driver.
Fig 2 HC-SR04P ultrasonic distance sensor with the micro:bit and the target board used during the development of this driver.

HC-SR04P ultrasonic distance sensor.
Fig 3 HC-SR04P ultrasonic distance sensor.

US-100 distance sensor, micro-bit and the target board used in the development in this driver.
Fig 4 US-100 ultrasonic distance sensor with the micro:bit and the target board used during the development of this driver.

US-100 hooked up to the micro:bit.
Fig 5 US-100 ultrasonic distance sensor hooked up to the micro:bit.