# main.py - ESP32 MicroPython
import time
from machine import Pin, ADC
import dht
# --- Pins ---
DHT_PIN = 25
LDR_PIN = 34 # ADC input only
RELAY_PIN = 27
# --- Setup sensors ---
dht22 = dht.DHT22(Pin(DHT_PIN))
adc = ADC(Pin(LDR_PIN))
# Atténuation pour mesurer une plus grande plage de tension (jusqu'à ~3.3V)
adc.atten(ADC.ATTN_11DB)
# Résolution (selon firmware: 0..4095 généralement)
try:
adc.width(ADC.WIDTH_12BIT)
except:
pass
relay = Pin(RELAY_PIN, Pin.OUT)
relay.value(0)
while True:
# --- Read DHT22 ---
try:
dht22.measure()
temp = dht22.temperature()
hum = dht22.humidity()
except Exception as e:
temp = None
hum = None
# --- Read LDR/Light sensor ---
raw = adc.read() # 0..4095 (souvent)
# Conversion en pourcentage (approx). 0 = sombre, 100 = très lumineux
light_pct = 100 - int((raw / 4095) * 100)
# --- Toggle relay ---
if relay.value()== 0:
relay.value(1)
relay_txt = "ON"
else:
relay.value(0)
relay_txt = "OFF"
# --- Display every 2s ---
if temp is None or hum is None:
print("Erreur DHT22 | Lumiere: {} ({}%) | Relais: {}".format(raw, light_pct, relay_txt))
else:
print("Temp: {:.1f}°C | Hum: {:.1f}% | Lumiere: {} ({}%) | Relais: {}".format(
temp, hum, raw, light_pct, relay_txt
))
time.sleep(2)