by Budd Churchward - WB7FHC - NIBBLES AND BITS LIBRARY
'My Dog Has Fleas' - A Binary Music Machine
« 1 2 3 4 5 6 7 8 9 10 11 12 »
Section 10 - Four Buttons → Fifteen Notes [Changing the Sketch]
Copy and paste this new procedure into your sketch.
Here is what's happening:
We start with a fresh variable 'myNum' and make it '0'. Then we check to see if button 4 is down. If it is, we add '1' to our variable.
Check out the next line:
We do that for each button.
Think of your buttons as binary digits in a 4 bit nibble. If you hold all of them down at once, you get 1111 or the decimal number 15. If you hold down the middle two, you get 0110 or the decimal number 6.
We do something special if no button is down:
Finally we have two nearly identical lines that we use to play the note. You will always want to 'REM' one of these lines out with two // marks depending on which of the two scales you want to play.
tone(speaker, pentatonic[myNum]); tone(speaker, naturals[myNum]);Arduino uses the value of 'myNum' to pull a frequency out of one of our arrays. Notice that we have not added a duration. We don't need it because as soon as you lift your fingers we turn everything off.
Which brings up one last thing. In our main loop, you will find a short delay. That is there because, try as you might, it is nearly impossible to press and release multiple buttons at the exact same time. The delay gives you some 'wiggle time' to get the job done.
And if there is anything Arduino loves, it's 'wiggle time'!