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

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.

DFR0989-microbit Connection 1

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.

DFR0989-microbit Connection 2

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.

DFR0989-Mind+ code

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.

DFR0989-MakeCode code

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?

TOP