from machine import Pin,ADC,I2C,PWM
import dht
import time
import ssd1306
D = dht.DHT22(Pin(23))
i2c = I2C(scl=Pin(22),sda=Pin(21),freq=100000)
oled = ssd1306.SSD1306_I2C(128,64,i2c)
M = ADC(0,atten=ADC.ATTN_11DB)
while True:
try:
D.measure()
temp = D.temperature()
hum = D.humidity()
print(f"温度: {temp}°C, 湿度: {hum}%")
oled.text("Temp:{:02}c".format(temp),20,0)
oled.text("Humi:{:02}%".format(hum),20,20)
oled.show()
except Exception as e:
print("DHT11错误")
try:
val_read = M.read()
val = val_read
print(f"烟雾浓度: {val}ppm")
oled.text("Smog:{:02}ppm".format(val),20,40)
oled.show()
except Exception as e:
print("MQ-2错误")
Pin_16=Pin(16,Pin.OUT)
Pin_17=Pin(17,Pin.OUT)
Pin_18=Pin(18,Pin.OUT)
buzzer=PWM(Pin(19))
def beep(frequency=1000, duration=500):
buzzer.freq(frequency)
buzzer.duty(512)
time.sleep_ms(duration)
buzzer.duty(0)
if temp >= 40:
print("温度过高")
Pin_16.value(1)
beep(1000,500)
else:
Pin_16.value(0)
if hum >= 20:
print("湿度过高")
Pin_17.value(1)
beep(1000,500)
else:
Pin_17.value(0)
if val >= 3600:
print("烟雾警告")
Pin_18.value(1)
beep(1000,500)
else:
Pin_18.value(0)
buzzer.deinit()
time.sleep(5)