from machine import Pin, PWM
import time
# Inizializzazione dei pin
led_pin = Pin(28, Pin.OUT)
buzzer_pin = PWM(Pin(22))
pulsante_pin = Pin(4, Pin.IN, Pin.PULL_UP)
# Tempi in millisecondi
LED_INTERVALLO_ACCESO = 500
LED_INTERVALLO_SPENTO = 500
BUZZER_INTERVALLLO_TIC = 800
BUZZER_DURATA_TIC = 100
# Frequenze Buzzer
FREQUENZA_NORMALE_BUZZER = 1000 # Frequenza per il ticchettio regolare
FREQUENZA_ALTA_BUZZER = 5000 # Frequenza quando il pulsante è premuto
# Variabili di stato
led_stato = False
buzzer_stato = False
pulsante_premuto = False
# Timer
ultimo_tempo_led = time.ticks_ms()
ultimo_tempo_buzzer_tic = time.ticks_ms()
ultimo_tempo_buzzer_suono = time.ticks_ms()
# Configurazione iniziale del Buzzer
buzzer_pin.freq(FREQUENZA_NORMALE_BUZZER)
buzzer_pin.duty_u16(0) # Buzzer inizialmente spento
while True:
tempo_corrente = time.ticks_ms()
# --------------------------------------------------------------
# Gestione LED Lampeggiante
# --------------------------------------------------------------
if not led_stato:
if time.ticks_diff(tempo_corrente, ultimo_tempo_led) >= LED_INTERVALLO_SPENTO:
led_stato = True
led_pin.value(1) # Accendi il LED
ultimo_tempo_led = tempo_corrente
else:
if time.ticks_diff(tempo_corrente, ultimo_tempo_led) >= LED_INTERVALLO_ACCESO:
led_stato = False
led_pin.value(0) # Spegni il LED
ultimo_tempo_led = tempo_corrente
# --------------------------------------------------------------
# Gestione Buzzer: frequenza dinamica in base al pulsante
# --------------------------------------------------------------
if pulsante_premuto:
buzzer_pin.freq(FREQUENZA_ALTA_BUZZER)
else:
buzzer_pin.freq(FREQUENZA_NORMALE_BUZZER)
if not buzzer_stato:
if time.ticks_diff(tempo_corrente, ultimo_tempo_buzzer_tic) >= BUZZER_INTERVALLLO_TIC:
buzzer_stato = True
buzzer_pin.duty_u16(32768) # Buzzer ON
ultimo_tempo_buzzer_suono = tempo_corrente
ultimo_tempo_buzzer_tic = tempo_corrente
else:
if time.ticks_diff(tempo_corrente, ultimo_tempo_buzzer_suono) >= BUZZER_DURATA_TIC:
buzzer_stato = False
buzzer_pin.duty_u16(0) # Buzzer OFF
# --------------------------------------------------------------
# Gestione Pulsante: cambia la frequenza del Buzzer
# --------------------------------------------------------------
if pulsante_pin.value() == 0:
# Pulsante premuto
if not pulsante_premuto:
print("Pulsante Premuto - Buzzer ALTA Frequenza!")
pulsante_premuto = True
else:
# Pulsante rilasciato
if pulsante_premuto:
pulsante_premuto = False
# Un piccolo ritardo per stabilizzare la simulazione
time.sleep_ms(10)