import time
from machine import Pin, PWM, ADC, I2C
import dht
from pico_i2c_lcd import I2cLcd
import blynklib
import network
# Wi-Fi credentials
WIFI_SSID = "Wokwi-GUEST"
WIFI_PASSWORD = ""
BLYNK_AUTH_TOKEN = "abA2nFHLVHS5FrLRrwAMN1OUMr2t_2fu"
# Initialize Wi-Fi
wlan = network.WLAN(network.STA_IF)
wlan.active(True)
wlan.connect(WIFI_SSID, WIFI_PASSWORD)
print('Waiting for Wi-Fi connection...')
max_wait = 10
while max_wait > 0:
if wlan.status() < 0 or wlan.status() >= 3:
break
max_wait -= 1
time.sleep(1)
if wlan.status() != 3:
raise RuntimeError('Wi-Fi connection failed')
else:
print('Wi-Fi connected.')
print('IP Address:', wlan.ifconfig()[0])
# Initialize Blynk
print("Connecting to Blynk...")
blynk = blynklib.Blynk(BLYNK_AUTH_TOKEN, server="blynk.cloud", port=80, insecure=True)
print("Blynk connected!")
# Initialize LCD (I2C, 20x4)
i2c = I2C(0, sda=Pin(4), scl=Pin(5))
lcd = I2cLcd(i2c, 0x27, 4, 20)
# Initialize DHT22 Sensor
dht_sensor = dht.DHT22(Pin(16))
# Initialize LDR (Light Sensor)
ldr = ADC(Pin(26))
# Initialize PIR Motion Sensor
pir = Pin(27, Pin.IN)
# Initialize Servo Motors
servo_door = PWM(Pin(14)) # Servo for door
servo_curtain = PWM(Pin(17)) # Servo for curtain
servo_scan = PWM(Pin(13)) # Servo for scanning
servo_door.freq(50)
servo_curtain.freq(50)
servo_scan.freq(50)
# Function to control standard servo motor
def control_servo(servo, angle):
try:
# Map angle to duty cycle based on provided values
duty_cycle_map = {
0: 1638,
45: 3276,
90: 4915,
135: 6554,
180: 8192
}
duty = duty_cycle_map.get(angle, int((angle / 180) * (8192 - 1638) + 1638))
servo.duty_u16(duty)
print(f"Servo moved to {angle}° with duty cycle {duty}")
time.sleep(1) # Adjust delay based on servo motor speed
except Exception as e:
print(f"Error controlling servo: {e}")
# Function to read DHT22 sensor
def read_dht22():
try:
dht_sensor.measure()
temp = dht_sensor.temperature()
hum = dht_sensor.humidity()
return temp, hum
except Exception as e:
print("Error reading DHT22:", e)
return None, None
# Function to read LDR
def read_ldr():
try:
light_level_raw = ldr.read_u16()
light_level = round((light_level_raw / 65535) * 100, 2)
return light_level
except Exception as e:
print("Error reading LDR:", e)
return None
# Main Loop
while True:
try:
blynk.run() # Process Blynk events
# Read sensors
temp, hum = read_dht22() # Read temperature and humidity
light_level = read_ldr() # Read light intensity
motion_detected = pir.value() # Check for motion detection
# Send sensor data to Blynk
if temp is not None and hum is not None:
blynk.virtual_write(0, temp) # Send temperature to Blynk
blynk.virtual_write(1, hum) # Send humidity to Blynk
if light_level is not None:
blynk.virtual_write(2, light_level) # Send light level to Blynk
blynk.virtual_write(4, motion_detected) # Send motion status to Blynk
# Display sensor data on LCD
lcd.clear()
lcd.putstr(f"Temp: {temp}C Hum: {hum}%")
lcd.move_to(0, 1)
lcd.putstr(f"Light: {light_level}%")
lcd.move_to(0, 2)
lcd.putstr(f"Motion: {'Yes' if motion_detected else 'No'}")
# Automated Actions
# 1. High Temperature Alert
if temp is not None and temp > 40:
print("ALERT: High temperature detected!")
lcd.move_to(0, 3)
lcd.putstr("ALERT: High Temp!")
blynk.log_event("high_temp")
time.sleep(3)
# 2. Light and Temperature Conditions
if light_level is not None and temp is not None:
if light_level < 30 and temp > 40: # Low light + High temp
print("Low Light and High Temp! Opening curtain.")
control_servo(servo_curtain, 90) # Open curtain
lcd.move_to(0, 3)
lcd.putstr("ALERT: Low Light")
blynk.log_event("low_light_high_temp")
time.sleep(3)
elif light_level < 30 and temp <= 40: # Low light + Low temp
print("Low Light and Low Temp! Opening curtain.")
control_servo(servo_curtain, 90) # Open curtain
blynk.log_event("low_light_low_temp")
time.sleep(3)
elif light_level >= 30 and temp <= 40: # High light + Low temp
print("High Light and Low Temp: Ideal conditions.")
control_servo(servo_curtain, 0) # Close curtain
blynk.log_event("high_light_low_temp") # Notify Blynk
elif light_level >= 30 and temp > 40: # High light + High temp
print("High Light and High Temp! Closing curtain.")
control_servo(servo_curtain, 0) # Close curtain
lcd.move_to(0, 3)
lcd.putstr("ALERT: High Temp!")
blynk.log_event("high_light_high_temp")
time.sleep(3)
# 3. Motion Detected -> Open Door and Trigger Zone Scanning
if motion_detected:
print("Motion detected! Opening door...")
control_servo(servo_door, 90) # Open the door
blynk.log_event("motion_detected")
time.sleep(3) # Keep the door open briefly
control_servo(servo_door, 0) # Close the door
# Trigger zone scanning
print("Scanning zones...")
lcd.clear()
lcd.putstr("Scanning Zones...")
time.sleep(2)
# Zone Scanning Logic (Full Scan from 0° to 180°)
zone_angles = [0, 45, 90, 135, 180]
detected_angle = None
for angle in zone_angles:
control_servo(servo_scan, angle) # Move the scanning servo
time.sleep(1) # Wait for the servo to stabilize
# Check motion detection at this angle
if pir.value() == 1:
detected_angle = angle
print(f"Motion detected at {angle}°!")
lcd.clear()
lcd.putstr(f"Motion at {detected_angle}°")
blynk.log_event(f"motion_detected_{detected_angle}")
break # Stop scanning once motion is detected
if detected_angle is None:
print("No motion detected during scan.")
lcd.clear()
lcd.putstr("No Motion Found")
time.sleep(2)
else:
print(f"Motion confirmed at {detected_angle}°!")
lcd.clear()
lcd.putstr(f"Confirmed: {detected_angle}°")
time.sleep(3)
# Motion Status LED
print("Turning on motion status LED")
led = Pin(2, Pin.OUT)
led.on() # Turn LED on
time.sleep(1) # Keep LED on briefly
led.off() # Turn LED off
time.sleep(1)
except Exception as e:
print("Error in main loop:", e)
lcd.clear()
lcd.putstr("System Error!")
time.sleep(5)