Example Code for micro:bit-SR04 Ultrasonic Distance Sensor

Last revision 2026/01/14

This article guides users through the process of connecting and programming a micro:bit with the SR04 Ultrasonic Distance Sensor using the MakeCode platform, including necessary hardware and software setup, wiring instructions, and example code for accurate distance measurement.

Hardware Preparation

  • micro:bit V2,
  • MBT0042 expansion board,
  • SR04 ultrasonic module (not included, need to purchase independently),

Software Preparation

  1. Enter the MakeCode programming platform in browser: https://makecode.microbit.org/
  2. Create a new project and name it.
  3. Load in the program library of xia_mi board: click “setting”, and “expansion” in turn, then paste this link in the search box: https://github.com/DFRobot/pxt-DFRobot_xia_mi_Board.

Wiring Diagram

Insert the SR04 ultrasonic sensor into the interface (as shown in the figure below):

SR04 Ultrasonic Sensor

Sample Code

MakeCode Program Link: https://makecode.microbit.org/_0K01rcdXf0y1

SR04

Was this article helpful?

TOP