from machine import Pin, I2C, ADC
import time
import ssd1306
import dht
import ds1307
import nec
from machine import Pin
# ------------------ 硬件初始化 ------------------
i2c = I2C(0, scl=Pin(22), sda=Pin(21)) # OLED + DS1307 共用I2C总线
oled = ssd1306.SSD1306_I2C(128, 64, i2c)
rtc = ds1307.DS1307(i2c)
# rtc.datetime((2025, 6, 3, 2, 15, 30, 0, 0)) # 初始化时间(只用一次)
dht_sensor = dht.DHT22(Pin(4)) # DHT22 温湿度
mq2 = ADC(Pin(36)) # MQ2 气体传感器
mq2.atten(ADC.ATTN_11DB) # 设置ADC范围为 0~3.6V
pir = Pin(14, Pin.IN) # PIR 人体感应
relay = Pin(5, Pin.OUT) # 继电器控制风扇
# ------------------ 红外遥控相关 ------------------
threshold = 2000 # 初始阈值
ir_pin = Pin(13, Pin.IN) # 红外接收器接在 GPIO13
def ir_callback(data, addr, ext):
global threshold
if data == 0x2A: # 遥控器按键 "1"
threshold += 100
print("增加阈值, 当前值: ", threshold)
elif data == 0xA8: # 按键 "2"
threshold -= 100
print("降低阈值, 当前值: ", threshold)
else:
print("收到未知按键: ", hex(data))
ir = nec.IR_RX(ir_pin, ir_callback)
# ------------------ 显示姓名、学号、时间 ------------------
def display_page_1():
for _ in range(3):
dt = rtc.datetime()
time_str = "{:02d}:{:02d}:{:02d}".format(dt[4], dt[5], dt[6])
oled.fill(0)
oled.text("name: jjjrrr", 0, 0)
oled.text("sno: 20251234", 0, 10)
oled.text("time:", 0, 25)
oled.text(time_str, 0, 40)
oled.show()
time.sleep(1)
# ------------------ 显示传感器信息 ------------------
def display_page_2(temp, hum, gas, motion, thr):
oled.fill(0)
oled.text("Temp: {:.1f}C".format(temp), 0, 0)
oled.text("Humi: {:.1f}%".format(hum), 0, 10)
oled.text("Gas: {}".format(gas), 0, 20)
oled.text("Motion: {}".format("Yes" if motion else "No"), 0, 30)
oled.text("Thr: {}".format(thr), 0, 50)
oled.show()
time.sleep(2)
# ------------------ 主程序循环 ------------------
def main():
display_page_1()
while True:
try:
dht_sensor.measure()
temp = dht_sensor.temperature()
hum = dht_sensor.humidity()
except:
temp = 0
hum = 0
gas_value = mq2.read()
motion = pir.value()
# 控制风扇
if gas_value > threshold:
relay.value(1)
else:
relay.value(0)
display_page_2(temp, hum, gas_value, motion, threshold)
main()