from machine import Pin, ADC
from utime import sleep
import math
from util import init_pins
sleep(0.1)
LED_START = 0
LED_COUNT = 2
NTC_ID = 27
PID_ID = 20
LIGHT_ID = 28
NTC = ADC(Pin(NTC_ID))
PID = Pin(PID_ID, Pin.IN, Pin.PULL_DOWN)
LIGHT = Pin(LIGHT_ID, Pin.IN, Pin.PULL_DOWN)
LEDS = init_pins(LED_START, LED_COUNT, Pin.OUT)
is_room_empty = True
def motion_interrupt(pin):
global is_room_empty
is_room_empty = False if is_room_empty else True
def read_temp(ntc):
BETA = 3950
R0 = 10000
R_SERIES = 10000
V_REF = 3.3
T0 = 298.15
analog_value = ntc.read_u16()
voltage = (analog_value / 65535) * V_REF
if voltage == V_REF:
return None
resistance = R_SERIES * voltage / (V_REF - voltage)
celsius = 1 / (1 / T0 + (1 / BETA) * math.log(resistance / R0)) - 273.15
return celsius
def main():
PID.irq(handler=motion_interrupt, trigger=Pin.IRQ_RISING)
print("Starting")
is_fan = False
while True:
if read_temp(NTC) >= 30 and not is_room_empty and not is_fan:
is_fan = True
print("Too hot, turning fans on.")
LEDS[1].on()
elif is_fan and read_temp(NTC) < 30:
is_fan = False
print("Turning fans off.")
LEDS[1].off()
elif is_room_empty and is_fan:
is_fan = False
print("No one in the room, fans off.")
LEDS[1].off()
if not LIGHT.value() and not is_room_empty:
LEDS[0].on()
else:
LEDS[0].off()
sleep(0.2)
if __name__ == "__main__":
main()