import time
import network
import BlynkLib
from machine import Pin, ADC
from dht import DHT22
import network
# Wi-Fi credentials
ssid = 'Wokwi-GUEST'
password = ''
wlan = network.WLAN(network.STA_IF)
wlan.active(True)
wlan.connect(ssid, password)
# Wait for connection
print("Connecting to Wi-Fi...")
for _ in range(10): # Wait for up to 10 seconds
if wlan.isconnected():
print("Connected successfully!")
print("Network config:", wlan.ifconfig()) # Print IP address and more
break
print("Still connecting...")
time.sleep(1)
if not wlan.isconnected():
print("Failed to connect to Wi-Fi. Check your credentials or router settings.")
# Blynk credentials
BLYNK_TEMPLATE_ID = "TMPL5LenGf4Ok"
BLYNK_TEMPLATE_NAME = "Smart Home ESP32"
BLYNK_AUTH_TOKEN = "ZiBJ6yaOyDRxjKycpBz6DQ8nJGrRzQpx"
# Pin definitions
DHT_PIN = 15 # DHT22 sensor
LDR_PIN = 34 # Photoresistor (LDR)
PIR_PIN = 27 # PIR motion sensor
LED1_PIN = 16 # LED 1
LED2_PIN = 17 # LED 2
BUZZER_PIN = 26 # Buzzer
# Initialize Blynk
blynk = BlynkLib.Blynk(BLYNK_AUTH_TOKEN)
# Initialize components
dht_sensor = DHT22(Pin(DHT_PIN))
ldr = ADC(Pin(LDR_PIN))
ldr.atten(ADC.ATTN_11DB) # Set LDR ADC to read full range (0-3.3V)
pir_sensor = Pin(PIR_PIN, Pin.IN)
led1 = Pin(LED1_PIN, Pin.OUT)
led2 = Pin(LED2_PIN, Pin.OUT)
buzzer = Pin(BUZZER_PIN, Pin.OUT)
# Variables for sensor state tracking
last_temperature = -1
last_humidity = -1
# Function to connect to Wi-Fi
def connect_wifi():
wlan = network.WLAN(network.STA_IF)
wlan.active(True)
wlan.connect(ssid, password)
while not wlan.isconnected():
time.sleep(0.5)
print(".", end="")
print("\nWiFi connected!")
# Function to update sensors and send data to Blynk
def update_sensors():
global last_temperature, last_humidity
# Read temperature and humidity from DHT22
try:
dht_sensor.measure()
temperature = dht_sensor.temperature()
humidity = dht_sensor.humidity()
# Send temperature to Blynk (V0) if it changes
if temperature != last_temperature:
blynk.virtual_write(0, temperature)
print(f"Temperature: {temperature} °C")
last_temperature = temperature
# Send humidity to Blynk (V1) if it changes
if humidity != last_humidity:
blynk.virtual_write(1, humidity)
print(f"Humidity: {humidity} %")
last_humidity = humidity
except Exception as e:
print(f"Error reading DHT22: {e}")
# Simulate LDR and LEDs
light_level = ldr.read()
if light_level < 2000:
led1.value(1)
led2.value(1)
else:
led1.value(0)
led2.value(0)
# Simulate PIR and buzzer
if pir_sensor.value() == 1: # Motion detected
print("Motion detected! Buzzer ON")
buzzer.value(1)
else:
buzzer.value(0)
# Main function
def main():
connect_wifi()
print("Connected to WiFi and Blynk!")
while True:
update_sensors()
blynk.run() # Handle Blynk communication
time.sleep(1) # Wait 1 second
# Run the main program
if __name__ == "__main__":
main()