Example Code for micro:bit-Ultrasonic Obstacle-avoiding

Last revision 2026/01/14

This article explores the use of micro:bit in conjunction with an ultrasonic sensor for obstacle avoidance in Maqueen Lite robots. It includes detailed hardware and software preparation instructions, wiring diagrams, and sample code. The ultrasonic sensor detects obstacles within 30cm and instructs the Maqueen to turn left or right to avoid the obstacle, enhancing the robot's navigation capabilities.

Hardware Preparation

  • Maqueen Lite x1
  • micro:bit V1/V2 x1
  • MicroUSB cable x1
  • H-SR04 Ultrasonic Sensor x1

Software Preparation

  • Programming Platform: makecode
  • Libraries: maqueen, neopixel

Wiring Diagram

Plug the ultrasonic sensor into the corresponding port in the front side of the Maqueen car as the following picture:

Other Preparation Work

  1. Load MakeCode Graphical Library for Maqueen as described in the previous example.
  2. Prepare an H-SR04 Ultrasonic Sensor.

Sample Code

Effect: the ultrasonic sensor detects the distance between the Maqueen and obstacle ahead, if it is smaller than 30cm, Maqueen randomly turns left or right to avoid the obstacle.

Code URL: https://makecode.microbit.org/_V0yFaqJ4EEkD

Code File: maqueen9.hex

Code Screenshot:

Result

Power on Maqueen and it starts to move forward. When an obstacle is detected about 30cm ahead, Maqueen randomly turns left or right to avoid the obstacle and then continues to move forward.

Was this article helpful?

TOP