MicroPython Driver for HC-SR04P Ultrasonic Distance Sensor

HC-SR04P Driver Code for micro:bit

Download as zip file

'''
HC-SR04P ultrasonic distance sensor
MicroPython driver for BBC micro:bit

******* IMPORTANT ********
This driver uses I2C mode.
As per RCWL-9610 datasheet.
**************************

AUTHOR: fredscave.com
DATE  : 2025/11
VERSION : 1.00
'''

from microbit import *
from micropython import const

_REG_COMMAND  = const(0xAE)
_REG_DISTANCE = const(0xAF)
_CMD_DISTANCE = const(0x01)
_ADDRESS      = const(0x57)

class HC_SR04P_I2C():

    # Returns the distance in cm.
    @property
    def Reading(self):
        # Send command to start measurement
        i2c.write(_ADDRESS, bytes([_REG_COMMAND]), True)
        i2c.write(_ADDRESS, bytes([_CMD_DISTANCE]))
        sleep(150)
        # Retrieve distance measurement
        i2c.write(_ADDRESS, bytes([_REG_DISTANCE]))
        buf = i2c.read(_ADDRESS, 3)
        d = buf[0] * 65536 + buf[1] * 256 + buf[2]
        return round(d/10000, 1)

          

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 connected to the micro-bit to use I2C.
Fig 2 HC-SR04P distance sensor connected to the micro-bit to use I2C.

M1 jumper on the rear of the board.
Fig 3A M1 jumper on the rear of the board.

M2 jumper on the rear of the board.
Fig 3B M2 jumper on the rear of the board.

In order to configure I2C mode the M1 jumper must not be connected and the M2 jumper must be connected with a blob of solder.