import time
import ntptime
import network
from machine import Pin, I2C, ADC, RTC
from ssd1306 import SSD1306_I2C
import dht
# ======================
# 1. 硬件初始化
# ======================
# OLED(I2C:SCL=GPIO22,SDA=GPIO21)
i2c = I2C(0, scl=Pin(22), sda=Pin(21))
oled = SSD1306_I2C(128, 64, i2c)
# 传感器 & 执行器
dht_sensor = dht.DHT22(Pin(4))
light_adc = ADC(Pin(34)) # 光照传感器 AO 引脚
light_adc.atten(ADC.ATTN_11DB) # 0-3.3V 范围
gas_adc = ADC(Pin(35)) # 气体传感器 AOUT 引脚
gas_adc.atten(ADC.ATTN_11DB)
relay = Pin(12, Pin.OUT) # 继电器 IN 引脚
buzzer = Pin(14, Pin.OUT) # 蜂鸣器正极引脚
# WiFi 配置(替换为实际热点信息)
WIFI_SSID = "your_WiFi_SSID"
WIFI_PASS = "your_WiFi_Password"
# 阈值(可通过红外修改,此处为初始值)
TEMP_THRESHOLD = 30 # 温度阈值(℃)
HUMI_THRESHOLD = 40 # 湿度阈值(%RH)
GAS_THRESHOLD = 800 # 气体 ADC 阈值(需校准)
# ======================
# 2. WiFi 连接 & 时间同步
# ======================
def connect_wifi():
"""连接 WiFi 热点,重试 5 次"""
wlan = network.WLAN(network.STA_IF)
wlan.active(True)
if wlan.isconnected():
return True
print("Connecting to WiFi...")
wlan.connect(WIFI_SSID, WIFI_PASS)
for _ in range(5):
if wlan.isconnected():
print("WiFi Connected:", wlan.ifconfig())
return True
time.sleep(2)
print("WiFi Connection Failed!")
return False
def sync_ntp_time():
"""同步 NTP 时间(转北京时间 UTC+8)"""
try:
ntptime.settime() # 获取 UTC 时间
rtc = RTC()
dt = rtc.datetime() # (year, mon, day, week, hour, min, sec, usec)
# 调整为北京时间(UTC+8)
hour = (dt[4] + 8) % 24
rtc.datetime((dt[0], dt[1], dt[2], dt[3], hour, dt[5], dt[6], dt[7]))
print("Time Synced:", rtc.datetime())
except Exception as e:
print("NTP Sync Failed:", e)
# ======================
# 3. 显示逻辑优化
# ======================
def show_boot_screen():
"""开机界面:动态显示时间 3 秒(每秒刷新)"""
oled.fill(0)
oled.text("Name: 李文庆", 0, 0)
oled.text("ID: 2026XXXX", 0, 10) # 替换为实际学号
start_time = time.time()
while time.time() - start_time < 3:
# 获取实时时间(已同步 NTP)
current_dt = time.localtime()
time_str = f"{current_dt[0]}-{current_dt[1]:02d}-{current_dt[2]:02d} " \
f"{current_dt[3]:02d}:{current_dt[4]:02d}:{current_dt[5]:02d}"
# 清除旧时间区域,避免重叠
oled.fill_rect(0, 20, 128, 16, 0) # 矩形清除(行 20-36)
oled.text(f"Time: {time_str}", 0, 20)
oled.show()
time.sleep(1) # 每秒更新一次
def show_sensor_data(temp, humi, light, gas):
"""传感器数据界面:显示 2 秒"""
oled.fill(0)
oled.text(f"Temp: {temp}°C", 0, 0)
oled.text(f"Humi: {humi}%", 0, 10)
oled.text(f"Light: {light}", 0, 20)
oled.text(f"Gas: {gas}", 0, 30)
oled.show()
time.sleep(2)
# ======================
# 4. 传感器 & 控制逻辑
# ======================
def read_sensors():
"""读取所有传感器数据"""
# DHT22 温湿度
dht_sensor.measure()
temp = dht_sensor.temperature()
humi = dht_sensor.humidity()
# 光照(ADC 原始值,0-1023)
light = light_adc.read()
# 气体(ADC 原始值,0-1023)
gas = gas_adc.read()
return temp, humi, light, gas
def control_devices(temp, humi, gas):
"""根据阈值控制继电器和蜂鸣器"""
# 继电器:温湿度超限(示例逻辑)
relay.value(1 if (temp > TEMP_THRESHOLD and humi < HUMI_THRESHOLD) else 0)
# 蜂鸣器:气体超限(示例逻辑)
buzzer.value(1 if gas > GAS_THRESHOLD else 0)
# ======================
# 5. 主程序
# ======================
if __name__ == "__main__":
# 步骤 1:连接 WiFi(必须,否则 NTP 失败)
if connect_wifi():
sync_ntp_time() # 同步时间
# 步骤 2:显示开机界面(动态时间)
show_boot_screen()
# 步骤 3:主循环(传感器 + 控制)
while True:
temp, humi, light, gas = read_sensors()
show_sensor_data(temp, humi, light, gas)
control_devices(temp, humi, gas)
time.sleep(1) # 主循环间隔