from machine import Pin, ADC, PWM
import dht
import time
import math
# --- Pinos ---
POT_PIN = 32
LDR_PIN = 35
BUTTON_PIN = 14
DHT_PIN = 4
BUZZER_PIN = 22
LED_R_PIN = 27
LED_G_PIN = 26
LED_B_PIN = 25
# --- Constantes ---
LUX_THRESHOLD = 1500
GAMMA = 0.7
RL10 = 50 # kΩ em 10 lux
# --- Objetos ---
dht_sensor = dht.DHT22(Pin(DHT_PIN))
pot = ADC(Pin(POT_PIN))
pot.atten(ADC.ATTN_11DB) # range 0–3.3V
ldr = ADC(Pin(LDR_PIN))
ldr.atten(ADC.ATTN_11DB)
button = Pin(BUTTON_PIN, Pin.IN, Pin.PULL_UP)
buzzer_pwm = PWM(Pin(BUZZER_PIN), duty=0)
led_r = PWM(Pin(LED_R_PIN), freq=1000, duty=0)
led_g = PWM(Pin(LED_G_PIN), freq=1000, duty=0)
led_b = PWM(Pin(LED_B_PIN), freq=1000, duty=0)
# --- Variáveis globais ---
rgb_enabled = True
last_interrupt_time = 0
temperature = 0.0
lux_value = 0
pot_value = 0
temp_warning = False
# --- Funções Auxiliares ---
def map_value(x, in_min, in_max, out_min, out_max):
return int((x - in_min) * (out_max - out_min) / (in_max - in_min) + out_min)
def write_rgb(r, g, b):
# PWM no ESP32 em MicroPython usa range 0–1023 (10 bits), não 4095
led_r.duty(map_value(r, 0, 4095, 0, 1023))
led_g.duty(map_value(g, 0, 4095, 0, 1023))
led_b.duty(map_value(b, 0, 4095, 0, 1023))
def read_sensors():
global temperature, lux_value, pot_value, temp_warning
try:
dht_sensor.measure()
temperature = dht_sensor.temperature()
except:
temperature = 0.0
temp_warning = (temperature < 0 or temperature > 30)
analog_value = ldr.read()
volts = analog_value / 4095 * 3.3
resistance = 2000 * volts / (3.3 - volts) if volts < 3.3 else 1e9
lux = math.pow(RL10 * 1e3 * math.pow(10, GAMMA) / resistance, 1.0 / GAMMA)
lux_value = lux / 10
pot_value = pot.read()
def set_led_color_from_pot(value):
r = g = b = 0
if value < 820:
r = 4095
g = map_value(value, 0, 819, 0, 2650)
b = 0
elif value < 1640:
r = 4095
g = map_value(value, 820, 1639, 2650, 4095)
b = 0
elif value < 2460:
r = 4095
g = 4095
b = map_value(value, 1640, 2459, 0, 4095)
elif value < 3280:
r = map_value(value, 2460, 3279, 4095, 0)
g = map_value(value, 2460, 3279, 4095, 3200)
b = 4095
else:
r = 0
g = map_value(value, 3280, 4095, 3200, 0)
b = 4095
write_rgb(r, g, b)
def update_rgb_led():
if (not rgb_enabled) or temp_warning or (lux_value > LUX_THRESHOLD):
write_rgb(0, 0, 0)
else:
set_led_color_from_pot(pot_value)
def update_buzzer():
if rgb_enabled and temp_warning:
buzzer_pwm.freq(2000)
buzzer_pwm.duty(512) # meio duty
else:
buzzer_pwm.duty(0)
# --- Interrupção ---
def handle_button(pin):
global rgb_enabled, last_interrupt_time
now = time.ticks_ms()
if time.ticks_diff(now, last_interrupt_time) > 200:
rgb_enabled = not rgb_enabled
last_interrupt_time = now
button.irq(trigger=Pin.IRQ_FALLING, handler=handle_button)
# --- Loop Principal ---
while True:
if rgb_enabled:
read_sensors()
update_buzzer()
update_rgb_led()
print("Temp:", temperature, "°C")
print("Lux:", lux_value)
print("ON")
else:
update_buzzer()
update_rgb_led()
print("OFF")
time.sleep(1)