from machine import Pin
from neopixel import NeoPixel
from machine import ADC
from machine import SoftI2C
from ssd1306 import SSD1306_I2C
import time
import onewire
import ds18x20
# 初始化OLED显示屏
i2c=SoftI2C(sda=Pin(12),scl=Pin(13))
oled=SSD1306_I2C(128,64,i2c)
# 初始化电压传感器
adc = ADC(Pin(34))
# 初始化人体红外传感器
pir = Pin(14, Pin.IN)
# 初始化温度传感器18b20
# 这里假设温度传感器连接到了GPIO 32
temp_sensor =ds18x20.DS18X20(onewire.OneWire(Pin(32)))
adc.atten(ADC.ATTN_11DB)
# 初始化光照传感器
# 这里假设光照传感器连接到了GPIO 33
light_sensor = ADC(Pin(15))
# 检测温度
def check_temperature():
roms=temp_sensor.scan
temp_sensor.covert_temp()
time.sleep(1)
return temp_sensor.read_temp(roms)
# 检测光照
def check_light():
light_reading = light_sensor.read()
return light_reading
# 显示界面
def display(screen, line1, line2):
screen.fill(0)
screen.text(line1, 0, 0)
screen.text(line2, 0, 10)
screen.show()
# 主程序
def main():
display(oled, "Smart home", "lock:off")
door_locked = True
light_on = False
ac_on = False
time.sleep(5)
door_locked = False
while True:
# 检测ADC电压
voltage = adc.read() * 3.3 / 4095
if voltage >= 0.5 and door_locked:
display(oled, "Smart home", "lock:on")
door_locked = False
if not door_locked:
# 3秒后显示室内情况
time.sleep(3)
if pir.value() == 1:
people = "Y"
else:
people = "N"
temp = check_temperature()
light = check_light()
display(oled, "people:" + people, "tem:" + str(temp))
display(oled, "light:" + str(light), "", "people:" + people, "tem:" + str(temp), "light:" + str(light))
if temp > 30 and not ac_on:
# 开冷空调
ac_on = True
# your code for turning on the air conditioner
elif temp < 10 and not ac_on:
# 开热空调
ac_on = True
# your code for turning on the heater
elif temp >= 10 and temp <= 30 and ac_on:
# 关闭空调
ac_on = False
# your code for turning off the air conditioner
if light < 2500 and not light_on:
# 打开灯光
light_on = True
# your code for turning on the lights
elif light >= 2500 and light_on:
# 关闭灯光
light_on = False
# your code for turning off the lights
if __name__ == "__main__":
main()