import network
import urequests
from machine import Pin, PWM, I2C, RTC
import dht
from time import sleep
from lcd_api import LcdApi
from i2c_lcd import I2cLcd
# Blynk Configuration
BLYNK_AUTH = "wASkvdw63BlxIE-74arhG3TjkzuhNbth"
# Wi-Fi Configuration
WIFI_SSID = "Wokwi-GUEST"
WIFI_PASSWORD = ""
# Pin Definitions
LDR_PIN = Pin(2, Pin.IN)
SERVO_PIN = PWM(Pin(4), freq=50)
DHT_PIN = Pin(15, Pin.IN)
dht_sensor = dht.DHT22(DHT_PIN)
# LCD Configuration
I2C_ADDR = 0x27
i2c = I2C(0, sda=Pin(21), scl=Pin(22))
lcd = I2cLcd(i2c, I2C_ADDR, 2, 16)
# RTC Configuration
rtc = RTC()
rtc.datetime((2024, 1, 1, 0, 0, 0, 0, 0)) # (year, month, day, weekday, hours, minutes, seconds, subseconds)
# Global Variables
lullaby_mode = 0
sleep_time = 20
# Wi-Fi Setup
def connect_wifi():
wlan = network.WLAN(network.STA_IF)
wlan.active(True)
wlan.connect(WIFI_SSID, WIFI_PASSWORD)
while not wlan.isconnected():
print("Connecting to Wi-Fi...")
sleep(1)
print("Wi-Fi Connected:", wlan.ifconfig())
# Send Blynk Notification
def send_blynk_notification(message):
url = f'http://blynk-cloud.com/{BLYNK_AUTH}/notify'
data = {"body": message}
try:
response = urequests.post(url, json=data)
response.close()
print(f"Notification sent: {message}")
except Exception as e:
print(f"Failed to send notification: {e}")
# Servo Control
def set_servo_angle(angle):
duty = int((angle / 180) * 1023 + 26) # Calculate duty cycle
SERVO_PIN.duty(duty)
# Periodic Updates
def my_timer_event():
current_time = rtc.datetime()
hour = current_time[4]
lcd.move_to(14, 0)
if lullaby_mode == 1 or not LDR_PIN.value() or hour == sleep_time:
lcd.putstr("ON")
for angle in range(90, 121, 1): # Sweep up
set_servo_angle(angle)
sleep(0.02)
for angle in range(120, 59, -1): # Sweep down
set_servo_angle(angle)
sleep(0.02)
for angle in range(60, 91, 1): # Reset to neutral
set_servo_angle(angle)
sleep(0.02)
else:
lcd.putstr("OFF")
set_servo_angle(90) # Neutral position
def my_timer_event2():
try:
dht_sensor.measure()
temperature = dht_sensor.temperature()
humidity = dht_sensor.humidity()
lcd.move_to(0, 1)
lcd.putstr("Temp: {:.1f}C".format(temperature))
lcd.move_to(0, 2)
lcd.putstr("Hum: {:.1f}%".format(humidity))
if temperature > 40:
send_blynk_notification("Room is too hot!")
elif temperature < 20:
send_blynk_notification("Room is too cold!")
elif humidity > 70:
send_blynk_notification("Room's humidity is too high!")
except Exception as e:
print(f"Error reading DHT sensor: {e}")
# Main Loop
def main():
connect_wifi()
# Initialize LCD
lcd.clear()
lcd.putstr("Lullaby mode:")
lcd.move_to(1, 3)
lcd.putstr("Sleep time: ")
lcd.move_to(13, 3)
lcd.putstr(str(sleep_time) + "h")
while True:
my_timer_event()
my_timer_event2()
sleep(1)
# Run Main Loop
if __name__ == "__main__":
main()