from machine import Pin, I2C, ADC
import ssd1306
import dht
import time
from time import localtime
# 硬件初始化
i2c = I2C(scl=Pin(22), sda=Pin(21))
display = ssd1306.SSD1306_I2C(128, 64, i2c)
dht_sensor = dht.DHT22(Pin(4))
light_sensor = ADC(Pin(34))
motion_sensor = Pin(35, Pin.IN)
led = Pin(23, Pin.OUT) # LED控制引脚
# 系统参数
STUDENT_NAME = "lixinqian"
STUDENT_ID = "2023103030189"
TEMP_THRESHOLD = 28.0 # 温度阈值(℃)
LIGHT_THRESHOLD = 1500 # 光照阈值
SCREEN_DURATION = [3000, 2000] # 两屏显示时长(ms)
# 时间同步(仿真环境用模拟时间)
def sync_time():
try:
# 真实硬件可用NTP,仿真环境手动设置
tm = (2025, 6, 6, 16,39, 0, 0, 0)
time.mktime(tm) # 设置系统时间
print("[仿真] 时间已设置")
except:
print("时间设置失败")
def ger_full_time():
now = localtime()
return f"{now[0]}-now[1]:02d}-now[2]:02d}-now[3]:02d}-now[4]:02d}-now[5]:02d}"
# 读取传感器数据
def read_sensors():
dht_sensor.measure()
return (
dht_sensor.temperature(),
dht_sensor.humidity(),
light_sensor.read(),
motion_sensor.value()
)
# 显示个人信息屏
def show_info_screen():
display.fill(0)
display.text(f"Name: {STUDENT_NAME}", 0, 10)
display.text(f"ID: {STUDENT_ID}", 0, 25)
display.text(f"Time: {get_formatted_time()}", 0, 45)
display.show()
# 显示传感器数据屏
def show_sensors_screen(temp, humidity, light, motion):
display.fill(0)
# 温度行(带超阈值提示)
temp_status = "[HOT]" if temp > TEMP_THRESHOLD else ""
display.text(f"Temp: {temp:.1f}C {temp_status}", 0, 0)
# 湿度行
display.text(f"Humidity: {humidity:.1f}%", 0, 15)
# 光照行(带低光提示)
light_status = "[DARK]" if light < LIGHT_THRESHOLD else ""
display.text(f"Light: {light} {light_status}", 0, 30)
# 运动检测行
display.text(f"Motion: {'YES' if motion else 'NO'}", 0, 45)
# 显示当前阈值
display.text(f"TH: {TEMP_THRESHOLD:.1f}C", 80, 0)
display.show()
# 获取格式化时间
def get_formatted_time():
now = localtime()
return f"{now[3]:02d}:{now[4]:02d}:{now[5]:02d}"
# 主程序初始化
sync_time()
led.off() # 初始关闭LED
current_screen = 0 # 0=信息屏,1=传感器屏
last_screen_switch = time.ticks_ms()
# 主循环
while True:
# 1. 读取传感器数据
temp, humidity, light, motion = read_sensors()
# 2. 控制LED(温度超阈值时点亮)
led.value(1 if temp > TEMP_THRESHOLD else 0)
# 3. 处理屏幕切换
current_time = time.ticks_ms()
if time.ticks_diff(current_time, last_screen_switch) >= SCREEN_DURATION[current_screen]:
current_screen = 1 - current_screen # 切换屏幕
last_screen_switch = current_time
display.fill(0)
# 4. 更新当前屏幕
if current_screen == 0:
show_info_screen()
else:
show_sensors_screen(temp, humidity, light, motion)
# 5. 短暂延迟(降低CPU占用)
time.sleep(0.1)