from machine import Pin, ADC
from time import sleep
import dht
# Define the pins for the sensors
dht22_pin = Pin(15) # DHT22 connected to GPIO 15
ldr_pin = ADC(Pin(34)) # LDR connected to GPIO 34 (Analog pin)
pir_pin = Pin(13, Pin.IN) # PIR sensor connected to GPIO 13
# Initialize the DHT22 sensor
dht22 = dht.DHT22(dht22_pin)
print("ESP32 Sensor Project - Monitoring Environment!")
while True:
try:
# Read temperature and humidity from DHT22
dht22.measure()
temperature = dht22.temperature()
humidity = dht22.humidity()
# Read light intensity from LDR (Analog value)
light_intensity = ldr_pin.read() # Value ranges from 0 to 4095
# Read motion status from PIR sensor
motion_detected = pir_pin.value()
# Print sensor values to Serial Monitor
print("Temperature: {:.1f} °C".format(temperature))
print("Humidity: {:.1f} %".format(humidity))
print("Light Intensity (LDR):", light_intensity)
if motion_detected:
print("Motion Detected!")
else:
print("No Motion")
print("-----------------------------")
except OSError as e:
print("Failed to read sensor data")
# Wait for 2 seconds before reading again
sleep(2)