In this project, we improve on the Simple Piano we created in the previous project by monitoring the buttons and playing the notes for the duration of the button press (instead of for a predefined time period).
Using the same hardware setup from the project, we can turn our CREATOR Kit into a mini-keyboard. We will modify the code so that each time you press one of the buttons on the CREATOR Kit, the corresponding note plays for as long as the button is held.
Your breadboard should still have the circuit we wired in the project. As a reminder, here is what it should look like:
Here, we fix the popping/crackling sound from the previous project when a
button is held down. Instead of trying to play()
the note each
time we see that the button is pressed down, we will instead only only play
the note when we see a button press and the note is not already
playing. This way, we only start the note once at the start of the button
press and aren't continually restarting the note each time through the
loop.
In addition, if the button is not pressed, we stop()
playing the note. This only has an affect if the note was already playing
(right after we release the button). If the note wasn't playing, stopping it
doesn't do anything.
Here is what the code should look like:
There's one new function used above that we hadn't mentioned before. The
function is_playing()
tells us whether or not a given note is
currently playing, which allows us to verify whether the note is currently
playing before deciding whether or not to start it.
We used the new function is_playing()
in the code above.
However, the code can be written without it. How? Hint: You'll likely need
a variable (or variables) to keep track of whether or not each note is
playing. Can you rewrite the code above without
is_playing()
?
Pushing multiple buttons at the same time will play notes simultaneously. Can you modify the code to only play one note at a time?
Your piano can easily be converted to a sound machine by playing
Sound
s instead of Note
s. Give it a try!
Your piano plays one note for each button that is pressed. Can you play more than one note at the same time for each button?
Can you modify your piano so that the first three buttons play a note when pressed, and the note keeps on playing even when the button is released. Then, if the fourth button is pressed, stop all notes from playing.