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 7 - Four Buttons → Four Notes
Copy and paste the sketch on the right into your project.
When you run it you should hear four different notes
when you press the buttons.
You could even use this project to tune your own ukulele! Here is how it works: We start by declaring variables for our INPUT and OUTPUT pins. We use these to designate four pins for the buttons and one pin for the speaker. int button4=7; int button3=6; int button2=5; int button1=4; int speaker=11; The next set of declarations set up the values of the four frequencies we will be using. They will be the musical notes: G C E A but I am defining them with the words from the tune: 'My Dog Has Fleas'. The variable 'duration' is something that you can play around with. We are not including noTone() in this sketch. With out 'duration' your last note would never stop playing. int MY=392; int DOG=262; int HAS=330; int FLEAS=440; int duration=500; Declare our INPUT and OUTPUT pins:
void setup()
This is where Arduino chases his tail.
if (digitalRead(button4)) ...
And if a button is down, we play the right note:
... tone(speaker,MY,duration);
OK, so that's four buttons and only four notes. But if you have been following us, you know that with a little understanding of binary numbers we can do much more. In the next section we will take what we have learned about 'nibbles' and 'bits' and write a new sketch that uses the same hardware but produces a double octave! With four buttons, why not fifteen notes? |
|