from machine import Pin, ADC, time_pulse_us
import time
import dht
# Corrected Pin Configuration
DHT_PIN = 4 # Changed to GPIO4
TRIG_PIN = 13
ECHO_PIN = 2
LDR_PIN = 35
PIR_PIN = 19
# Sensor Initialization
dht_sensor = dht.DHT22(Pin(DHT_PIN)) # Fixed syntax
trig = Pin(TRIG_PIN, Pin.OUT)
echo = Pin(ECHO_PIN, Pin.IN)
# Proper ADC Configuration for LDR
ldr = ADC(Pin(LDR_PIN))
ldr.atten(ADC.ATTN_11DB) # Full range 0-3.3V
ldr.width(ADC.WIDTH_12BIT) # 0-4095
pir = Pin(PIR_PIN, Pin.IN)
def read_sensors():
# DHT22
try:
dht_sensor.measure()
temp = dht_sensor.temperature()
hum = dht_sensor.humidity()
except:
temp, hum = None, None
# HC-SR04
trig.value(0)
time.sleep_us(2)
trig.value(1)
time.sleep_us(10)
trig.value(0)
duration = time_pulse_us(echo, 1, 30000)
distance = round(duration * 0.0343 / 2, 2) if duration > 0 else None
# LDR
ldr_val = ldr.read()
light = round(ldr_val / 4095 * 100, 1) if ldr_val is not None else None
# PIR
motion = pir.value()
return temp, hum, distance, ldr_val, light, motion
while True:
t, h, d, ldr_raw, light, m = read_sensors()
print("\n=== Sensor Readings ===")
print(f"🌡️ Temperature: {t}°C" if t else "❌ DHT Error")
print(f"💧 Humidity: {h}%" if h else "❌ DHT Error")
print(f"📏 Distance: {d}cm" if d else "❌ Distance Error")
print(f"💡 Light: {light}% (Raw: {ldr_raw})" if light else "❌ LDR Error")
print(f"🏃 Motion: {'DETECTED' if m else 'None'}")
time.sleep(5)