Turn a buzzer off when the code is stopped
# play middle c for 1 second
try:
speaker.play('c4')
finally: # when code is stopped by user
speaker.off() # turns speaker off
lightbulb Use `try` and `finally`
If you stop your code from running whilst the buzzer is playing a note,
the note will continue to sound. To stop this, use try and finally.
Turn a buzzer off when the code is stopped
my_tune = [ ['d5', 0.4], ['d#5', 0.4],
['f5', 0.4], ['d6', 0.4],
['a#5', 0.4], ['d5', 0.4]
]
try:
for note in my_tune:
speaker.play(note)
finally:
speaker.off()
lightbulb Use `try` and `finally`
If you stop your code from running whilst the buzzer is playing a note,
the note will continue to sound. To stop this, use try and finally.