from machine import Pin, ADC, PWM, I2C
import time, ssd1306, urequests

i2c = I2C(0, scl = Pin(4), sda=Pin(16))
display = ssd1306.SSD1306_I2C(128,64,i2c)

audio = ADC(Pin(35))

breaker = PWM(Pin(27),freq = 50)

ok_led = Pin(23, Pin.OUT)
warning_led = Pin(19, Pin.OUT)
alarm_led = Pin(18, Pin.OUT)

def leds_off():
    ok_led.value(0)
    warning_led(0)
    alarm_led(0)
    display.fill(0)

def enceder():
    breaker.duty(25)

def apagar():
    breaker.duty(125)  
    
while True:
    volumen = int(audio.read())
    time.sleep(0.5)
    print(volumen)
    if (volumen > 3500):
        leds_off()
        ok_led.value(1)
        display.text("Encendido con", 08, 30)
        display.text("Audio Optimo", 08, 40)
        display.show()
        enceder()
    if (volumen < 3500 and volumen > 450):
        leds_off()
        warning_led.value(1)
        display.text("Encendido con", 08, 30)
        display.text("Audio Bajo", 08, 40)
        display.show()
        enceder()
    if (volumen < 450):
        leds_off()
        alarm_led.value(1)
        time.sleep(3)
        volumen = int(audio.read())
        if (volumen < 450):
            apagar();
            display.text("Apagado", 08, 30)
            display.text("Sin Audio", 08, 40)
            display.show()