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 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:

  myNum = myNum << 1; 
This is 'bit shifting'. We are taking the binary version of our number: 00000001 and shifting all the bits one place to the left so it becomes: 00000010.

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:

 if (myNum==0) {     
    noTone(speaker); 
    return;          
  }                  
First we turn the speaker off. Then we return to our main loop without playing another note so we can do it all over again.

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'!
In the next section we will treat you to a sequence of numbers that you can play on your music machine and show you a short video of a child making music with the pentatonic scale. In the final section you will find the complete sketch fully documented that you can copy and paste to your computer.

Next Section »


 void loop() {
  delay(200);
  buildNote();
}


void buildNote () {   
  int myNum = 0;
  myNum = myNum + digitalRead(button4);            
  myNum = myNum << 1;
  myNum = myNum + digitalRead(button3);
  myNum = myNum << 1;
  myNum = myNum + digitalRead(button2);
  myNum = myNum << 1;
  myNum = myNum + digitalRead(button1);
  







  if (myNum==0) {
    noTone(speaker);
    return;
  }




  //tone(speaker, pentatonic[myNum]);
  tone(speaker, naturals[myNum]);
  
  
}