How to use the MQ2 sensor with Microbit board | Gas Level monitoring system with MicroBit
Hello and welcome back. In this tutorial, we will learn how to use the MQ2 sensor with Micro:bit board. The MQ2 sensor can detect gases like LPG, smoke, carbon monoxide, and methane, making it useful for safety and environmental monitoring projects. I’ve also added a buzzer for alerts and an OLED display to show sensor readings in real time. This creates a simple gas-level detection system that demonstrates how the sensor works. In addition, this tutorial covers how to set up and program the OLED display with the microbit board. For coding, I used the MakeCode platform, which lets you create programs with block-based coding, JavaScript, or Python. If you’re a beginner, I recommend starting with the block coding. Then you can see the auto-generated Java and Python codes. You can use this tutorial to learn how to make LP gas and smoke detection systems. OK let’s go ahead.
- What is the MQ2 sensor – Click on me
- What is the OLED display – Click on me
OK, let’s do this project step by step. The required components are given below.
- Microbit board — Our store / Amazon
- MQ2 sensor x 1 — Our store / Amazon
- Buzzer x 1 — Our store / Amazon
- OLED display x 1 — Our store / Amazon
- Microbit sensor shield — Our store / Amazon
- Jumper wires — Our store / Amazon
- Keyestudio BBC Micro: bit starter kit — Click on me
Step 1
Firstly, identify these components.
Step 2
Secondly, connect the microbit board to the sensor shield.
Step 3
Thirdly, connect the mq2 sensor, buzzer, and OLED display to the sensor shield. For that, use the circuit diagram below.
Step 4
Now, connect the microbit board to the computer. After, let’s make a program for this project. For that, follow the instructions below.
- First, go to the Makecode website and create a new project as you like.
- Then, include the OLED extension. Afterward, copy and paste the following Python script into the Python tab. Now you can see the auto-generated code blocks. Otherwise, you can make this code along with code blocks.
- Python script — Download
value = 0
OLED12864_I2C.init(60)
OLED12864_I2C.show_string(2, 0, "GAS Level", 1)
OLED12864_I2C.show_string(1, 1, "Monitoring", 1)
def on_forever():
global value
value = pins.analog_read_pin(AnalogReadWritePin.P2)
OLED12864_I2C.show_string(5, 2, "" + str(value) + " ", 1)
if value >= 250:
pins.digital_write_pin(DigitalPin.P5, 1)
OLED12864_I2C.show_string(3, 3, "Warning!", 1)
basic.show_leds("""
. . # . .
. . # . .
. . # . .
. . . . .
. . # . .
""")
else:
pins.digital_write_pin(DigitalPin.P5, 0)
OLED12864_I2C.show_string(3, 3, " ", 1)
basic.clear_screen()
basic.forever(on_forever)
- Next, connect the microbit board to the Makecode platform. Finally, click the download button.
Step 5
Now, you can test this project with an LP gas source or smoke. I used a lighter for that.