Contents
- Project Description
- 1. Introduction
- 2. Main Functions
- 3. Hardware Requirements
- 4. Software Environment
- 5. File Structure
- 6. Description of Key Documents
- 7. Core Ideas of Software Design
- 8. Instructions for Use
- 9. Sample Program
- 10. Notes
- 11. Version Record
- 12. Contact the Developer
- 13. Licensing Agreement
- Appendix 1: Project Source Code Download
- Appendix II: Reference Materials for hardware Modules
- Version Record

Project Description
1. Introduction
1.1 Project Background
Traditional security alarm systems mostly feature single functions or fixed-threshold detection, lacking intelligent multi-sensor fusion detection capabilities. This project is based on the GraftPort-RP2040 development board, and integrates MQ series electrochemical gas sensor modules, the PT334-based flame sensor module and LED alarm indicator to implement an integrated "smoke-flame dual detection - intelligent alarm" system, addressing the issue of single detection mode in traditional security systems. Meanwhile, it incorporates MicroPython 's lightweight task scheduling and exception handling mechanism to ensure stable system operation.
1.2 Overview of the Main Functions of the Project
This project is developed based on MicroPython, whose core function is to detect the environmental status in real time via the MQ series electrochemical gas sensor module and the PT334-based flame sensor module, and trigger an LED alarm when any sensor detects an abnormality; the system checks the status of the sensors every 5 seconds, and automatically turns off the alarm when both sensors return to normal, realizing intelligent alarm management.
1.3 Applicable Scenarios or Application Area
- Home Security: Real-time monitoring of smoke and flame in areas such as kitchens and bedrooms to prevent fires;
- Industrial Safety: Applied for fire early warning and safety monitoring in scenarios such as factories and warehouses;
- Teaching Demo: For
MicroPythontask scheduling, digital input detection,PWMcontrol and other knowledge points in practical teaching; - Smart Home: Integrated into smart home systems to provide fire early warning functionality.
2. Main Functions
- Dual Safety Detection: Adopt MQ series electrochemical gas sensor modules to detect smoke, and PT334-based flame sensor modules to detect flames, achieving dual safety protection;
- Intelligent Alarm Management: Automatically check the status of sensors every 5 seconds, trigger an alarm immediately when an abnormality occurs, and automatically turn off the alarm once the status returns to normal;
- Real-time Status Monitoring: Sensor data is read every 200 milliseconds to ensure real-time detection performance;
- Visual alarm indication: clear alarm status indication is provided via
LEDlights; - Automatic Status Recovery: When the environment returns to normal, the system will automatically turn off the alarm without manual intervention;
- Debugging Support: Supports debugging information output to facilitate development and troubleshooting.
3. Hardware Requirements
3.1 Hardware Required
The project is based on the GraftPort-RP2040 development board as the main controller:

The other required modules include:

- GraftSense-MQ Series Electrochemical Gas Sensor Module: (digital output; a low level indicates smoke is detected);
- GraftSense - PT334-based Flame Sensor Module:(Digital Output, Low Level Indicates Flame Detected);
- GraftSense - High-Power Single-Die LED Module Based on OC7140:(
PWMControlled, Brightness Adjustment Supported); - GraftSense - Based on SY7656 Lithium Battery Charge-Discharge Module:(for connecting polymer lithium batteries, outputting 5V voltage, equipped with a
Type-Ccharging port); - Onboard buttons: By default, the fixed pins of the development board (Pin 18, pull-up input) are used, and no additional wiring is required.
- Onboard
LED: By default, it uses the fixed pin (Pin 25) of the development board, and no additional wiring is required.
3.2 Hardware Connection
MQ series electrochemical gas sensor module: connect the digital output pin to the AIN2 input pin of the development board;

Flame sensor module based on PT334: connect the digital output pin to the AIN1 input pin of the development board;
High-power single-die LED module based on OC7140: connected to the DIO0 output pin of the development board.
Lithium Battery Charge-Discharge Module: BAT interface connects to the lithium battery, and the OUT interface supplies power to the main control board via a PH2.0-2P connection cable.



3.3 Structural Assembly
First, use M3 plastic pillars to fix each module and the main control board to the bottom plate of the housing (M3 screw holes are pre-drilled on both the main control board and the housing):


Next, secure the periphery of the housing with M3 plastic pillars, then screw in M3 screws at the corresponding positions to complete the assembly:

3.4 Notes
When the main control board is not connected to an external watchdog module, the RUN DIP switch 2 must be turned on:

The lithium battery charge-discharge module supports power level display, and you can charge it via the Type-C interface below:

4. Software Environment
- Core Firmware:
MicroPython v1.23.0(adaptation required forGraftPort-RP2040, with support formachine.Pin/I2C/Timermodules and soft timer scheduling); - Development IDE:
PyCharm(used for code writing, uploading and debugging, supportsMicroPython REPLinteraction, and requires the installation of theMicroPythonplugin); - Auxiliary Tools:
Python 3.12+(optional, for running local helper scripts such as firmware flashing scripts);mpy-cross v1.23.0(used to. pyfiles compile to. mpyto reduce the memory usage of the development board, optional);mpremote v0.11.0+(replacesThonnyfor file upload, supports command-line operations, optional);
- Dependency Modules: No additional third-party libraries are required; all drivers (including but not limited to
passive_buzzer_driver.py) are custom-implemented and provided along with the project files.
5. File Structure
fire_gas_alarm
├─ .flake8
├─ LICENSE
├─ README.md
├─ tools
│ ├─ dependency_analyzer.py
│ ├─ mpy_compiler.py
│ ├─ mpy_uploader.py
│ └─ README.md
├─ firmware
│ ├─ board.py
│ ├─ boot.py
│ ├─ conf.py
│ ├─ main.py
│ ├─ tasks
│ │ ├─ maintenance.py
│ │ ├─ sensor_task.py
│ │ └─ __init__.py
│ ├─ libs
│ │ ├─ __init__.py
│ │ └─ scheduler
│ └─ drivers
│ ├─ __init__.py
│ ├─ mqx_driver
│ ├─ led_single_driver
│ └─ flame_driver
├─ examples
└─ docs6. Description of Key Documents
main.py: the project entry point, whose core logic includes:- Power on with a 3-second delay (wait for hardware to stabilize), initialize the onboard
LED, flame sensor module based on PT334,MQ-2sensor, and buttons (including interrupt registration); - Hardware initialization: flame sensor module based on PT334,
MQ-2sensor, alarmLED; - Create
sensor_taskinstance (pass in hardware driver and configuration parameters), and encapsulate it as a scheduler task (with a period of 200ms); - Initialize
Scheduler(software timer with a scheduling period of 10ms), add tasks, start scheduling, and enter an infinite loop; - Define
fire_callbackinterrupt callback (task start/stop switching),fatal_hangblocking function (fatal error handling).
- Power on with a 3-second delay (wait for hardware to stabilize), initialize the onboard
tasks/sensor_task.py: Core business task. Key logic of theGasFireAlarmTaskclass:init: Initialize the hardware instance;tick: Executed once every 200ms, the process is "read sensor status → determine whether to trigger an alarm → controlLEDalarm";
tasks/maintenance.py: System maintenance module, key functions:task_idle_callbackTriggered when the scheduler is idle; if the detected memory usage is lower thanGC_THRESHOLD_BYTES(100000 bytes by default), it will executegc.collect ();task_err_callback: Triggered when an exception is thrown by a task, it prints the full traceback (preferentially viasys.print_exception), then delays forERROR_REPEAT_DELAY_S(1 second by default) to prevent screen flooding;- Supports reading configuration from
conf.py, uses default values when no configuration is available to ensure compatibility.
drivers/xxx_driver: hardware driver modules, all adopting the "instantiation + method call" pattern, only expose hardware-related control interfaces while shielding underlying details:flame_driver:FlameSensorclass reads the flame status via a digital pin, and theis_flame_detectedmethod returns the detection status;mqx_driver:The MQXclass reads the smoke status via a digital pin, and usescomp_pin.value ()to obtain the digital output (0 indicates smoke is detected);led_single_driver:The PowerLEDclass controls the brightness ofPWM-controlledLEDsand provides methods includingon,off, andset_brightness.
board.py: a board-level pin mapping module that defines theBOARDSdictionary (including the fixed pins of GraftPort-RP2040 and the mapping ofI2C/DIOinterfaces), and provides interfaces such asget_fixed_pinandget_dio_pinsto realize the decoupling of board-level configuration and business logic; when expanding to other development boards later, you only need to addBOARDSsub-items.conf.py: user configuration file. The parameters that require manual definition by the user include:ENABLE_DEBUG(debug print switch),AUTO_START(whether the task starts automatically); the system will use default values if these parameters are not defined.
7. Core Ideas of Software Design

- System Hierarchy Concept: Adopt a "four-tier architecture" to achieve decoupling and reuse
- Hardware Driver Layer (
drivers/): responsible for the low-level control of hardware; for example, a flame sensor driver only concerns itself with "how to obtain the flame status"; - Task Logic Layer (
tasks/): Implements business logic based on the driver layer, for example,GasFireAlarmTaskjudges alarm conditions by calling sensor status; - Scheduling Control Layer (
libs/scheduler.py): provides generic task management capabilities, supporting task addition, pause and resume; - Entry Layer (
main.py): responsible for "assembling" all layers, initializing hardware → creating tasks → starting scheduling. - Core Mechanism: Ensuring System Stability and User Experience
- Task scheduling mechanism: Implemented based on a soft timer, with a scheduling cycle of 10ms and a core task cycle of 200ms; the task execution timing is determined via "counter accumulation";
- Intelligent Alarm Mechanism: Adopts the strategy of "dual-sensor verification + periodic inspection" to improve alarm accuracy and reduce false alarms;
- Fault tolerance mechanism: All critical operations are wrapped with
try-exceptto prevent system crash caused by a single module failure.
Task Execution Process: The task execution process is as follows:

8. Instructions for Use
8.1 Hardware Connection
Connect the main control board, each sensor module and the battery according to the connection method specified in the "hardware requirements";
8.2 Run the Project (Using PyCharm + MicroPython Plugin)
Open PyCharm and install the corresponding MicroPython plugin.

In the plugin, select Target Device (Target Device) as RP2040, and enable Auto-detect device path (Auto-detect device path).

Set Project/firmware as the project root directory.

Modify the runtime configuration:

- Check Allow multiple instances (
Allow multiple instances) - Select Store as Project File (
Store as project file) - Click OK to save the configuration.
Click the IDE green triangle button in the upper right corner to run, and you can start uploading the firmware and executing the project.

8.3 Modification of Running Configuration
You can configure conf.py, modify or add parameters as needed, for example:
# conf.py example configuration
I2C_INIT_MAX_ATTEMPTS = 3 # Maximum number of sensor initialization retries
I2C_INIT_RETRY_DELAY_S = 0.5 # Interval between retries (seconds)
ENABLE_DEBUG = True # Whether to enable debug printing
AUTO_START = True # Whether to run tasks automatically at startup8.4 Functional Testing
- Sensor Calibration: Calibrate the flame sensor and gas sensor under normal ambient conditions
- Flame sensor: manually turn the to
LED3red indicator lights up, then turn the back slightly until the redLED3indicator just goes out under normal ambient conditions. - Gas sensor: Use a screwdriver to turn the variable resistor until
LED2red indicator lights up, then turn the back slightly until the redLED2indicator just turns off under normal ambient conditions.
- Flame sensor: manually turn the to
- Flame Detection: Use a lighter to test the flame sensor at a safe distance and check whether the
LEDgives an alarm;
- Gas detection: Test with items such as alcohol swabs
MQ-2sensor, and check whether theLEDgives an alarm; - Automatic recovery: Remove the fire source and gas source, and observe for 5 seconds
whether theLED is automatically turned off.
The terminal output is as follows:

8.5 Debugging and Troubleshooting
- If the function malfunctions, ensure that
ENABLE_DEBUG = True, and then check the debug information in the terminal; - If the sensor fails to initialize, check the hardware connections, power supply and pin configuration;
- If the
LEDdoes not light up, check thePWMconfiguration and the driver circuit.
9. Sample Program
There are no other reference sample codes for this project, you can directly make modifications in the firmware folder.
10. Notes
- Sensor-related:
- The flame sensor shall be protected from direct strong light to avoid affecting the detection accuracy;
MQ-2sensor requires a warm-up period, and its readings may be unstable immediately after power-on.
- Hardware Connection Related:
- Pay attention to the operating voltage and signal level of the sensor to ensure compatibility with the main control board;
LEDmodules require appropriate current-limiting resistors to avoid damage caused by overcurrent.
- Software Version Related:
MicroPython v1.23.0 or later version must be used;- Debug printing consumes a certain amount of memory, so it is recommended to disable it in formal use scenarios.
- Function Usage Related:
- The task cycle (200ms) is not recommended to be set too small, otherwise it may increase the system load;
- The alarm logic can adjust the sensor judgment conditions according to actual requirements.
11. Version Record
- v1.0.0 (2025-11-03): Initial version completed by Hou Junhan, with basic functions implemented and documentation prepared:
- Support flame sensor detection
- Supports
MQ-2gas sensor detection - Implement
LEDalarm control - Implement intelligent alarm logic
12. Contact the Developer
If you have any questions or need assistance, please contact the developer via the following channels :
📧 Email: 10696531183@qq.com
💻 GitHub: https://github.com/FreakStudioCN
13. Licensing Agreement
In this project, except for machine and other MicroPython official modules (MIT License), all driver and extension codes written by the author are released under the Creative Commons Attribution-NonCommercial 4.0 International (CC BY-NC 4.0) Licensing Agreement.
You are free to:
- Share — copy, distribute the work in any medium or in any form
- Derivative Works — to modify, transform, or create based on the Work
Only the following conditions shall be complied with:
- Attribution — You must give appropriate credit, provide a link to the Licensing Agreement, and indicate if changes were made to the original work. You may do so in any reasonable manner, but not in any way that suggests the licensor endorses you or your use.
- Non-commercial Use — You may not use this work for commercial purposes.
- Proper Citation Method — You may clearly indicate the source in code comments, documentation, demo videos or project descriptions.
Copyright © FreakStudio. All rights reserved.
Appendix 1: Project Source Code Download
https://github.com/FreakStudioCN/GraftPort_MicroPython_Labs/tree/main/fire_gas_alarm
Appendix II: Reference Materials for hardware Modules
GraftSense-MQ Series Electrochemical Gas Sensor Module
GraftSense - PT334-based Flame Sensor Module
GraftSense - High-power Single-chip LED Module Based on OC7140
GraftSense - Based on SY7656 Lithium Battery Charge-Discharge Module
GraftPort - Raspberry Pi Pico Expansion Board (Open Edition Template Files)
Version Record
Document Version | Date of Revision | Modifier | Revised Content |
V1.0.0 | 2025-11-03 | Hou Junhan | Draft the initial version of the document. |
V1.1.0 | 2026-01-04 | Li Zisheng | Final version. |