import time
from machine import ADC, Pin, I2C
from lcd_api import LcdApi
from i2c_lcd import I2cLcd
i = 0
# TEMP SENSOR SETUP
TEMP_PIN = 26
tempSensor = ADC(TEMP_PIN)
#LCD SCREEN SETUP
I2C_ADDR = 0x27 #39 Decimal
I2C_NUM_ROWS = 2
I2C_NUM_COLS = 16
sda = Pin(0)
slc = Pin(1)
i2c = I2C(0, sda=sda, scl=slc, freq=400000)
lcd = I2cLcd(i2c, I2C_ADDR, I2C_NUM_ROWS, I2C_NUM_COLS)
# FAN SETUP
FAN_ACTIVATE_TEMP = 30 #Temperature at which fan comes on
# MOTION SENSOR
motion_detected = False
motion_in_progress = False
# Define the PIR sensor input pin
pir_pin = Pin(16, Pin.IN)
led_pin = Pin(15,Pin.OUT,value=0)
# Callback function to handle motion detection. This function
# will be called when the motion sensor detects movement
def pir_interrupt(pin):
global motion_detected
if pin.value() == 1: # Rising edge (motion detected)
motion_detected = True
led_pin.value(1) # Turn on the LED
else: # Falling edge (motion stopped)
motion_detected = False
led_pin.value(0) # Turn off the LED
#register callback for pir pin IRQ
pir_pin.irq(trigger=(Pin.IRQ_RISING | Pin.IRQ_FALLING), handler=pir_interrupt)
time.sleep(0.1) # Wait for USB to become ready
#function to read temp sensor and convert to celsius
def getTemp():
adc_value = tempSensor.read_u16()
volt = (3.3/65535) * adc_value
degC = (100*volt) - 50
return round(degC,1)
def isFanActivateTemp(temp):
return temp >= FAN_ACTIVATE_TEMP
def getLightDisplayMsg(isOn):
if isOn :
return "Light: ON"
else :
return "Light:OFF"
#get display message for LCD
def getDisplayMsg(degC,lightOn):
if isFanActivateTemp(degC):
fansState = "ON"
else:
fansState = "OFF"
return "Fan :" + fansState + " " + str(degC) + "C" + "\n" + getLightDisplayMsg(lightOn)
#Main loop
while True:
#measure temp/display only when i resets to 0
if i == 0:
degC = getTemp()
#TODO FAN LOGIC
displayMsg = getDisplayMsg(degC,motion_in_progress)
lcd.clear()
lcd.putstr(displayMsg)
print(degC)
if motion_detected and not motion_in_progress:
print("Motion detected!")
motion_in_progress = True # Set the flag to indicate motion detected
lcd.clear()
displayMsg = getDisplayMsg(degC,True)
lcd.putstr(displayMsg)
elif not motion_detected and motion_in_progress:
print("Motion stopped")
motion_in_progress = False # Reset the flag
lcd.clear()
displayMsg = getDisplayMsg(degC,False)
lcd.putstr(displayMsg)
if i == 100:
i = 0
else:
i = i+1
time.sleep(0.1)
# Temp Sensor wiring
# VCC -> 3v3 Power
# GND -> GND Ground
# OUT -> GP26 Data
# LCD -> PICO wiring
# GND -> GND1 Ground
# VCC -> VBUS 5v power
# SDA -> GP0 Data
# SCL -> GP1 Clock