import time
from machine import I2C, Pin, ADC
from lcd_api import LcdApi
from pico_i2c_lcd import I2cLcd
lightPin = Pin(12, Pin.OUT)
fanPin = Pin(13, Pin.OUT)
fanButton = Pin(14, Pin.IN)
lightButton = Pin(15, Pin.IN)
buzzPin = Pin(16, Pin.OUT)
potPin = ADC(Pin(26))
ldrPin = ADC(Pin(28))
#to use push buttons as toggle switches
fanOldstate = 1
fanNewstate = 0
lightOldstate = 1
lightNewstate = 0
fanStatus = False
lightStatus = False
fanOverride = False
lightOverride = False
#limits for auto features
ldrThreshold = 80
potThreshold = 30
buzzThreshold = 60
I2C_ADDR = 39 #[39] is the register address for this lcd.
i2c = I2C(0, sda=machine.Pin(0), scl=machine.Pin(1), freq=400000)
lcd = I2cLcd(i2c, I2C_ADDR, 2, 16)
#function for beeping the buzzer
def beepBuzzer(iterations):
for i in range(iterations):
buzzPin.on()
time.sleep_ms(100)
buzzPin.off()
time.sleep_ms(100)
while True:
potReading = potPin.read_u16() * (100/65535)
ldrReading = ldrPin.read_u16() * (100/65535)
#Manual control of the Fan.
fanNewstate = fanButton.value()
if fanOldstate == 0 and fanNewstate == 1:
fanOverride = not fanOverride
if fanOverride:
fanStatus = not fanStatus
fanPin.value(fanStatus)
fanOldstate = fanNewstate
time.sleep(0.05)
#Manual control of the Light.
lightNewstate = lightButton.value()
if lightOldstate == 0 and lightNewstate == 1:
lightOverride = not lightOverride
if lightOverride:
lightStatus = not lightStatus
lightPin.value(lightStatus)
lightOldstate = lightNewstate
time.sleep(0.05)
#Auto control of the light using LDR
if not lightOverride:
if ldrReading >= ldrThreshold:
lightStatus = True
else:
lightStatus = False
lightPin.value(lightStatus)
#Auto control of fan based on pot readings
if not fanOverride:
if potReading >= potThreshold:
fanStatus = True
else:
fanStatus = False
fanPin.value(fanStatus)
#Feedback buzzer thingy
oldPotReading = potReading
newPotReading = potPin.read_u16() * (100/65535)
if oldPotReading < buzzThreshold and newPotReading >= buzzThreshold:
beepBuzzer(3)
newPotReading = oldPotReading
time.sleep(0.05)
formatted_temperature = "{:.1f}".format(potReading)
string_temperature = str("T=" + formatted_temperature + "C")
formatted_light = "{:.1f}".format(ldrReading)
string_light = str("L=" + formatted_light)
#lcd display programming
if fanStatus == True:
fan = "Fan=ON"
lcd.move_to(15,1)
lcd.putstr(" ")
else:
fan = "Fan=OFF"
if lightStatus == True:
light = "Lite=ON"
lcd.move_to(7,1)
lcd.putstr(" ")
else:
light = "Lite=OFF"
lcd.move_to(0,0)
lcd.putstr(string_temperature)
lcd.move_to(10,0)
lcd.putstr(string_light)
lcd.move_to(0,1)
lcd.putstr(fan)
lcd.move_to(8,1)
lcd.putstr(light)
time.sleep(0.1)Fan Button
Light Button
Fan
Light