2.13 MQ Gas Sensor
The MQ gas sensor detects hazardous gases (e.g., methane, CO) by measuring changes in resistance. It outputs an analog value (0-4095), where higher values indicate higher gas concentrations.
Example Applications:
- Air quality monitoring
- Leak detection in industrial settings
- Smart safety alarms
2.13.1 Example Code for the MQ Gas Sensor
The MQ gas sensor outputs an analog value (typically between 0 and 4095) based on gas concentration. When no gas is detected, the sensor typically outputs its maximum value (around 4095). As gas is detected, this value reduces, with lower numbers indicating a higher gas intensity. In this example, we check if the gas level is below a threshold (4000) to trigger alerts, meaning we're looking for a drop in the reading from the 'no gas' baseline
- Hardware Setup:
- Connect the MQ gas sensor to analog pin
P0
or any pin which supports analog input.
- Connect the MQ gas sensor to analog pin
- Programming Steps (Block-Based):
- Gas Reading: Continuously read gas levels (
set GAS to read MQ_GAS on P0
). - Alert System:
- If gas < 4000:
- Display "GAS DETECTED" on screen
- Activate alert (
TTS Module Speak "WARNING! GAS LEAK DETECTED"
) - Turn all RGB LEDs RED (
lampNumber All (-1) displayColor RED
)
- Else:
- Display "CLEAR AIR" on screen
- Set all RGB LEDs to GREEN (
lampNumber All (-1) displayColor GREEN
)
- If gas < 4000:
- Gas Reading: Continuously read gas levels (
- Key Notes:
- The sensor's 12-bit analog input (0-4095) corresponds to gas concentration
- Threshold (4000) can be adjusted for sensitivity
- Visual (LED) and auditory (TTS) feedback for both safe/alert states
- Green LEDs indicate safe conditions, red indicates danger

Figure 2.13.1a: Gas detection logic with clear air indication