Hardware Reference
In-Depth Information
The code for the piano is actually very simple. In each iteration through the
loop, each button is checked. So long as a button is pressed, a note is played. Here,
tone() is used without a duration because the note will play as long as the button
is held. Instead, noTone() is called at the end of loop() to ensure that the speaker
stops making noise when all the buttons have been released. Because only a few
notes are needed, you can copy the values from the header file that you care about
directly into the main program file. In a new sketch, load up the code shown in
Listing 5-2 and upload it to your Arduino. Then, jam away on your piano!
Listing 5-2: Pentatonic Micro Piano—piano.ino
//Pentatonic Piano
//C D E G A
#define NOTE_C 262 //Hz
#define NOTE_D 294 //Hz
#define NOTE_E 330 //Hz
#define NOTE_G 392 //Hz
#define NOTE_A 440 //Hz
const int SPEAKER=9; //Speaker on pin 9
const int BUTTON_C=7; //Button pin
const int BUTTON_D=6; //Button pin
const int BUTTON_E=5; //Button pin
const int BUTTON_G=4; //Button pin
const int BUTTON_A=3; //Button pin
void setup()
{
//No setup needed
//Tone function sets outputs
}
void loop()
{
while (digitalRead(BUTTON_C))
tone(SPEAKER, NOTE_C);
while(digitalRead(BUTTON_D))
tone(SPEAKER, NOTE_D);
while(digitalRead(BUTTON_E))
tone(SPEAKER, NOTE_E);
while(digitalRead(BUTTON_G))
tone(SPEAKER, NOTE_G);
while(digitalRead(BUTTON_A))
tone(SPEAKER, NOTE_A);
//Stop playing if all buttons have been released
noTone(SPEAKER);
}
Search WWH ::




Custom Search