Example Code for micro:bit-Ultrasonic Obstacle Avoidance
Last revision 2025/12/19
This article provides detailed instructions and example code for implementing ultrasonic obstacle avoidance using micro:bit and Maqueen V5 robot car, including hardware and software setup, wiring, and programming tips.
Hardware Preparation
- Maqueen V5 Robot Car: 1 (Purchase Link: https://www.dfrobot.com/product-2937.html)
- micro:bit Mainboard: 1
- 3 AA Batteries: 1 set
- Ultrasonic Sensor (H-SR04): 1 (Purchase Link: https://www.dfrobot.com/product-1033.html)
Software Preparation
- MakeCode Platform: https://makecode.microbit.org/
- Maqueen Library: Load via MakeCode Extensions (search for "dfrobot" and select "Maqueen")
Wiring Diagram
Insert the ultrasonic sensor into the ultrasonic interface at the front of the car. Both the front and rear rows of interfaces can be used, and there is no functional difference, as shown in the figure:

The situation when the ultrasonic sensor is inserted properly is shown in the figure:

Other Preparation Work
- Ensure the micro:bit mainboard is properly plugged into Maqueen V5.
- Install the batteries correctly.
- Turn on the power switch.
- Insert the ultrasonic sensor into the front interface.
Sample Code
Example 1: Ultrasonic Obstacle Avoidance
After downloading the program, the car will automatically detect whether there are obstacles in the front. If so, it will automatically turn to avoid the obstacles.

Example 2: Assembly Line Robot
Function Description:
Place obstacles on the map as shown in the following figure.
After the program is downloaded, place the car on the black line. The car will travel along the black line. When encountering an obstacle in the front, the car will turn around and then continue to trace the line. This repeats all the time.
If the battery power is different and when the turning angle and speed are not appropriate, the speed of the motor and the pause time can be adjusted to improve the effect.
Note: If the detection distance of 10 cm in the program is too short and causes a collision, the distance value can be appropriately increased, such as 15cm-20 cm.

Result
- Example 1: Car avoids obstacles detected by the ultrasonic sensor.
- Example 2: Car follows the line and turns around when encountering obstacles.
Was this article helpful?
