import time
from machine import Pin, ADC
from utime import sleep
import math
#------------------------------------------------------------#
#Definition of pin numbers
#------------------------------------------------------------#
Motion_pin = 15
Temp_pin = 26
Led_pin = 1
Button_pin = 0
BETA = 3950
#------------------------------------------------------------#
#Definition of pin directions
#------------------------------------------------------------#
Motion_Sensor = Pin(Motion_pin,Pin.IN, Pin.PULL_DOWN)
Temp_Sensor = ADC(Pin(Temp_pin))
Led = Pin(Led_pin, Pin.OUT)
Button = Pin(Button_pin, Pin.IN, Pin.PULL_DOWN)
#------------------------------------------------------------#
#Global variables definition
#------------------------------------------------------------#
ref_time = 0
ForcedMode = 0
#------------------------------------------------------------#
#Interrupt function
#------------------------------------------------------------#
def interrupt_fun(pin):
global ref_time, ForcedMode
current_time = time.ticks_ms()
diff = current_time - ref_time
if diff > 200:
ForcedMode = 1
ref_time = current_time
Button.irq(trigger = Pin.IRQ_FALLING, handler = interrupt_fun)
#------------------------------------------------------------#
#Main function
#------------------------------------------------------------#
def main():
while True:
global ForcedMode
motion_detect = Motion_Sensor.value()
temp_value = Temp_Sensor.read_u16()
celsius = 1 / (math.log(1 / (65535. / temp_value - 1)) / BETA + 1.0 / 298.15) - 273.15
#--------------------------- Case 1 ---------------------------------#
#Forced Mode happens if the button is pressed
#Door shall be forced open for one second
#Led shall be ON
#Print "Forced Mode, Door is Open"
if ForcedMode:
print("Forced Mode, Door is Open")
Led.value(1)
sleep(2)
ForcedMode = 0
#--------------------------- Case 2 ---------------------------------#
#Motion is detected and the temp. is in normal range which is below 40 c
#Door shall open for 2 seconds
#Led shall be ON
#Print "Motion is detected and Temp is good, Door is open"
if motion_detect and celsius < 40:
print("Motion is detected and Temp is good, Door is open")
Led.value(1)
sleep(1)
#--------------------------- Case 3 ---------------------------------#
#Motion is detected but the temp. is too high which is above 40 c
#Door shall close
#Led shall be OFF
#Print "Can't open the door, Temp is {celsius} too high"
elif motion_detect and celsius > 40:
print(f"Can't open the door, Temp is {celsius} too high")
Led.value(0)
sleep(1)
#--------------------------- Case 4 ---------------------------------#
#Motion is not detected
#Door is closed
#Led shall be OFF
#Print "Door is closed"
else:
print("Door is closed")
Led.value(0)
sleep(1)
if __name__ == "__main__":
main()