Example Code for micro:bit-Onboard Button Control Relay
Last revision 2025/12/22
This article provides a comprehensive guide to controlling a relay using the onboard buttons of a micro:bit. It includes hardware preparation, wiring diagrams, and sample code compatible with both MakeCode and Mind+. The guide demonstrates how to configure the micro:bit to switch the relay state, enabling or disabling a connected pump. Beginner-friendly, it is perfect for hobbyists and educators looking to create interactive projects with micro:bit and relay modules.
Hardware Preparation
- micro:bit V2 (SKU: MBT0039)(or similar) ×1
- Amphibious Horizontal Submersible Pump (SKU: FIT0800) ×1
- IO Extender for micro:bit (SKU: MBT0008) ×1
- Relay Module with Transparent Case (SKU: DFR0989) ×1
- 3V DC Power ×1
- PH2.0 Wire ×1
- micro USB Cable ×1
Software Preparation
micro:bit can be programmed on both MakeCode and Mind+.
Wiring Diagram
Connection 1
NO and COM ports will be used in this connection. An external DC power source is required and should be selected according to the load voltage to be connected.

Description:
- Relay Module: D--to--Mainboard: P0
- Relay Module: VCC--to--Mainboard: 3V3
- Relay Module: GND--to--Mainboard: GND
- Relay Module: NO--to--Pump: Positive(Red wire)
- Relay Module: COM--to--3V DC power: Positive
- 3V DC power: Negative--to--Pump: Negative(Black wire)
Connection 2
This connection is simpler. The pump is directly connected to the OUT and power by VCC, no second power source required.
Note: since the micro:bit itself has weak load capacity, here the Relay VCC needs to be connected to the 5V of the micro:bit IO Extender and the power source should be connected to the extender external power interface.

Description:
- Relay Module: D--to--Mainboard: P0
- Relay Module: VCC--to--Mainboard: 5V
- Relay Module: GND--to--Mainboard: GND
- Relay Module: OUT+ --to--Pump: Positive(Red wire)
- Relay Module: OUT- --to--Pump: Negative(Black wire)
Sample Code
Mind+ Sample Code
The sample code below is suitable for the two connections above. It realizes the function of controlling the relay's ON/PFF through the button A and B on micro:bit. When button A pressed, P0 outputs high; Button B pressed, P0 outputs low.

MakeCode Sample Code
The sample code below is suitable for the two connections above. It realizes the function of controlling the relay's ON/PFF through the button A and B on micro:bit. When button A pressed, P0 outputs high; Button B pressed, P0 outputs low.

Result
Mind+ Result
When button A is pressed, the relay is in pull-in state and the pump starts working; when button B is pressed, the relay is in releasing state and the pump stops working.
MakeCode Result
When button A is pressed, the relay is in pull-in state and the pump starts working; when button B is pressed, the relay is in releasing state and the pump stops working.
Was this article helpful?
