Nibbles and Bits
The Care and Feeding of My Pet Arduino


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 12 - The Complete Sketch
/* Barnacle Budd's Binary Music Machine -  v. 0.1
   (c) 2011, Budd Churchward - WB7FHC
   04-10-11
  
  visit http://bit.ly/h7R5Qt 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

 // These two arrays store the frequencies of our musical notes
 // Only one set is used at a time.
 int naturals[] = {0,131,147,165,175,196,220,247,262,294,330,349,392,440,494,523};
 int pentatonic[] = {0,139,156,185,208,233,277,311,370,415,466,554,622,740,831,932};
 
 void setup() {
   // define 4 input and 1 output pins:
   pinMode(button4,INPUT);
   pinMode(button3,INPUT);
   pinMode(button2,INPUT);
   pinMode(button1,INPUT);
   
   pinMode(speaker,OUTPUT);
 }
 
 void loop() {
  delay(200);      // Adjust this delay if you have trouble pressing and releasing multiple 
                   // buttons at the same time.
  buildNote();     // Go check our buttons and build us a note if any are down
}


void buildNote () {   
  int myNum = 0;                          // Start with zero
  myNum = myNum + digitalRead(button4);   // Add 1 if button 4 is down
  myNum = myNum << 1;                     // Shift the bits to the left one place
  myNum = myNum + digitalRead(button3);   // Add 1 if button 3 is down
  myNum = myNum << 1;                     // Shift once more
  myNum = myNum + digitalRead(button2);   // Add 1 if button 2 is down
  myNum = myNum << 1;                     // Shift for the last time
  myNum = myNum + digitalRead(button1);   // Add 1 if button 1 is down
  
  if (myNum==0) {                         // If no buttons were down, myNum is still zero
    noTone(speaker);                      // There are no buttons down so shut off the tone
    return;                               // Jump out of here early
  }
  
  // Rem out one of the following two lines to choose which scale to play
  //tone(speaker, pentatonic[myNum]);     // Pick out a frequency from our pentatonic array
                                          // and play it indefinitely
  tone(speaker, naturals[myNum]);         // Pick out a frequency from our natural array and 
                                          // play it indefinitely
  
  
  
}