##========================导入mq系列模块================##=
from machine import Pin, ADC
import time
from time import sleep
from mqx import MQX
from led_single_power import PowerLED
##=========================回调函数=======================
def mq_callback(voltage: float) -> None:
"""
当比较器引脚触发中断时调用该函数,打印当前电压值。
Args:
voltage (float): 电压值 (单位: V)。
Returns:
None: 无返回值。
Raises:
None: 本函数不抛出异常。
"""
state = comp.value()
if state == 1:
# 上升沿触发后的状态
comp_warning = 1
else:
# 下降沿触发后的状态
comp_warning = 0
print("[IRQ] Voltage: {:.3f} V".format(voltage))
# 上电延时3s
time.sleep(3)
##=====================配置mq传感器=======================
# 打印调试消息
print("Measuring Gas Concentration with MQ Series Gas Sensor Modules")
# LED (GPIO,PWM)
led = PowerLED(pin=19, pwm_freq=1000)
# Pico ADC0 (GPIO26)
adc = ADC(Pin(26))
# Comparator output (GPIO15, optional)
comp = Pin(15, Pin.IN)
comp_warning = None
mq = MQX(adc, comp, mq_callback, rl_ohm=10000, vref=3.3,)
# 选择内置多项式(MQ2、MQ4、MQ7)
mq.select_builtin("MQ2")
##================主函数================
def main():
print("===== MQ Sensor Test Program Started =====")
try:
while True:
# 读取电压
v = mq.read_voltage()
print("Voltage: {:.3f} V".format(v))
# 读取 ppm(5 次采样,间隔 200 ms)
ppm = mq.read_ppm(samples=5, delay_ms=200)
print("Gas concentration: {:.2f} ppm".format(ppm))
print("-" * 40)
# 主循环间隔
sleep(2)
except KeyboardInterrupt:
print("User interrupted, exiting program...")
finally:
mq.deinit()
print("Sensor resources released.")
if __name__ == "__main__":
main()