james1236 / buzzer_music

RPI Pico / Micropython library to play music through one or more buzzers, can automatically replace chords with fast arpeggios to simulate polyphony with a single buzzer. Music can be easily taken from onlinesequencer.net
MIT License
85 stars 17 forks source link

Stop the music with button #5

Closed cmacollins82 closed 1 year ago

cmacollins82 commented 2 years ago

Hi I'm quite new to python but I've used your code to play music along side a light show. I'd like to stop the music playing unless my button latch is true. I can't use GOTO in pyton to skip the code, and I can't use an IF before CLASS.

If you have an idea how to do it I'd appreciate your help Proton lights with dim & Music v3.11.zip .

jose1711 commented 2 years ago

You can achieve that easily using interrupts. Button is wired between GP16 and GND, we'll use can_play global variable that can be set to True if the music should play, False otherwise.

# define handler that manipulates our variable
def stop_music(_):
    global can_play
    can_play = False

can_play = True
button = Pin(16, Pin.IN, Pin.PULL_UP)
button.irq(trigger=Pin.IRQ_FALLING, handler=stop_music)

while can_play:
    mySong.tick()
    sleep(0.04)

The playback stops immediately once the button is pressed.