Nibbles and Bits
The Care and Feeding of My Pet Arduino


'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.

      void loop() 
While he is spinning around, we have him check our buttons (one of these for each button):
       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?

Next Section »

/* Barnacle Budd's Binary Organ - Part 1: MyDogHasFleas v. 0.1
   (c) 2011, Budd Churchward - WB7FHC
  visit for hook up instructions

 int button4=7;      // declare top button on pin 7
 int button3=6;      // declare next button on pin 6
 int button2=5;      // declare next button on pin 5
 int button1=4;      // declare bottom button on pin 4
 int speaker=11;     // declare speaker output on pin 11
 int MY=392;         // freq. of note: G
 int DOG=262;        // freq. of note: C
 int HAS=330;        // freq. of note: E
 int FLEAS=440;      // freq. of note: A
 int duration = 500; // adjust note duration here
 void setup() {
   // define 4 input and 1 output pins:
 void loop() {
   // if button 4 is down play note: G
   if (digitalRead(button4)) tone(speaker,MY,duration);
   // if button 3 is down play note: C   
   if (digitalRead(button3)) tone(speaker,DOG,duration);
   // if button 2 is down play note: E   
   if (digitalRead(button2)) tone(speaker,HAS,duration);  
   // if button 1 is down play note: A
   if (digitalRead(button1)) tone(speaker,FLEAS,duration);