RCWL-1601 3V Ultrasonic Sensor
ElecFreaks Motor Bit
MakeCode Extensions:
Sonar Extension:
MotorBit Extension:
Code Part 1:
"Sonar" extension enables the use of multiple sensors
with a single Microbit
Code Part 2:
If left sensor triggered- turns right, display "R"
If right sensor triggered- turns left, display "L"
If neither sensor triggered- goes forward, displays "F"
From Google Gemini:
Connecting multiple ultrasonic sensors (like the HC-SR04) to a Micro:bit is an awesome way to give a project "spatial awareness"—especially if you are building an obstacle-avoiding robot or a room-monitoring system.
Because each sensor typically requires two data pins (Trigger and Echo), adding multiple sensors requires a bit of pin management. Here is the straightforward guide to getting it done.
The Golden Rule: Watch Your Voltage
Standard HC-SR04 sensors require 5V to operate, but the Micro:bit only outputs 3.3V. If you plug a 5V sensor's "Echo" pin directly into a Micro:bit, you risk frying the board.
* The easy fix: Buy the HC-SR04P or RCWL-1601 models. These are specifically designed to run on 3.3V and can be connected directly to your Micro:bit without any extra components.
* The hard fix: If you only have standard 5V HC-SR04s, you must power them externally with 5V and use a voltage divider (using resistors) on the Echo pin to step the 5V signal down to 3.3V before it reaches the Micro:bit.
Step 1: The Hardware Setup
Because the Micro:bit only has three large, easily accessible GPIO pins (0, 1, and 2), you won't have enough room to easily clip on multiple sensors. You will need a Micro:bit Edge Connector Breakout Board to access the smaller pins (like P8, P13, P14, P15, etc.).
Note: You can use almost any of the standard digital pins on your breakout board, just avoid pins P3, P4, P6, P7, P9, and P10 if you are also using the LED matrix, as they are shared!
Step 2: The Software (MakeCode)
To read the sensors easily in Microsoft MakeCode, you should use the built-in Sonar extension.
1. Open MakeCode, click on Extensions (under the Advanced menu).
2. Search for sonar and add the official package.
3. In your code, create two variables (e.g., distance_left and distance_right).
4. Set up a forever loop to constantly update these variables.
The MakeCode Logic:
* set distance_left to [sonar ping trig P0 echo P1 unit cm]
* set distance_right to [sonar ping trig P2 echo P8 unit cm]
Now you can use if / else statements to act on the data. For example: If distance_left < 10 cm, turn right.
Possible improvement: Add a 3rd sensor in the middle, so that if it detects a wall, it backs up and turns