from machine import Pin, ADC, PWM
from time import sleep
ldr = ADC(34)
r_led = Pin(25, Pin.OUT)
y_led = Pin(26, Pin.OUT)
g_led = Pin(27, Pin.OUT)
buzzer = PWM(Pin(23, Pin.OUT))
buzzer.freq(400)
previous_times_to_alert = 0
def adc_to_percent(value):
return 100 * (value / 4095)
while True:
darkness_percent = adc_to_percent(ldr.read())
luminosity_percent = abs(darkness_percent - 100)
times_to_alert = 0
print(f"Luminosidade local: {luminosity_percent}%")
if luminosity_percent <= 100 and luminosity_percent >= 80:
r_led.on()
y_led.off()
g_led.off()
times_to_alert = 3
elif luminosity_percent < 80 and luminosity_percent >= 50:
r_led.off()
y_led.on()
g_led.off()
times_to_alert = 2
elif luminosity_percent < 50:
r_led.off()
y_led.off()
g_led.on()
times_to_alert = 1
if times_to_alert != previous_times_to_alert:
for _ in range(times_to_alert):
buzzer.duty(1)
sleep(1)
buzzer.duty(0)
sleep(1)
previous_times_to_alert = times_to_alert
sleep(0.2)