from machine import Pin, PWM
from time import sleep_ms
import time
btn=Pin(4,Pin.IN,Pin.PULL_DOWN)
tempo=500#definisco la velocità della melodia a 1x
class BUZZER:
def __init__(self, sig_pin):
self.pwm = PWM(Pin(sig_pin, Pin.OUT))
def play(self, melodies, duty):
for note in melodies:
if note == 0:
self.pwm.duty(0)
else:
self.pwm.freq(note)
self.pwm.duty(duty)
sleep_ms(tempo)
self.pwm.duty(0)
A4=400
Ct5=550
E5=660
A5=880
melodia = [
A4,Ct5,E5,A5,A5,E5,Ct5,A4
]
start = 0#tale variabile serve per il pulsante
def switchFreq(bt1):
global start
global tempo
current = time.ticks_ms()#prende il tempo della pressione attuale
delta = time.ticks_diff(current, start)
if delta < 200:
return
start=current
if tempo==500:
tempo=(int)(tempo/2)
else:
tempo=tempo*2
btn.irq(handler= switchFreq,trigger=Pin.IRQ_RISING)#tale riga va inserita in questo posto e non dopo il while perchè altrimenti non la legge
b= BUZZER(23)
while True:
b.play(melodia,512)