from machine import Pin, ADC, I2C
import dht
import ssd1306
import time
# 初始化传感器及设备
ps2_y = ADC(Pin(2))
ps2_y.atten(ADC.ATTN_11DB)
p15 = Pin(15, Pin.IN)
red_led = Pin(18, Pin.OUT)
yellow_led = Pin(25, Pin.OUT)
buzzer = Pin(23, Pin.OUT)
i2c = I2C(0, scl=Pin(22), sda=Pin(21))
oled = ssd1306.SSD1306_I2C(128, 64, i2c)
d = dht.DHT22(Pin(27))
# 阈值定义
smoke_threshold = 2000
temp_min, temp_max = 10, 30
humidity_min, humidity_max = 30, 70
while True:
# 读取数据
val_y = ps2_y.read()
light = p15.value()
try:
# 多次尝试读取温湿度数据,增加准确性
for _ in range(3):
time.sleep(1) # 每次尝试间隔1秒
d.measure()
temp = d.temperature()
humidity = d.humidity()
if temp is not None and humidity is not None:
break
else:
temp = 0
humidity = 0
except OSError:
temp = 0
humidity = 0
oled.fill(0)
red_alert = yellow_alert = False
display_text = "Normal Environment"
# 烟雾检测优先级最高
if light == 0 or val_y > smoke_threshold:
display_text = "Fire Danger!"
red_alert = True
else: # 烟雾正常时检查温湿度
if temp < temp_min or temp > temp_max or humidity < humidity_min or humidity > humidity_max:
display_text = "Not Suitable"
yellow_alert = True
# 设备控制
red_led.value(red_alert)
yellow_led.value(yellow_alert)
buzzer.value(red_alert or yellow_alert)
# 在OLED上显示状态信息
oled.text(display_text, 10, 10)
# 显示烟雾浓度、温度和湿度
oled.text(f"Smoke: {val_y}", 10, 25)
oled.text(f"Temp: {temp}°C", 10, 35)
oled.text(f"Humidity: {humidity}%", 10, 45)
oled.show()
print(f"烟雾: {val_y}, 温度: {temp}°C, 湿度: {humidity}%")
time.sleep(1)