4. Piano on the way

4.1. else if statement

From the new variables that we declared, it is easy to assume that we are reading the value of buttonPin2 with digitalRead() and storing it in buttonState2.

We also need a new conditional statement. In order for it to make sense within the existing program, we will use an else if.

The rough idea of the sketch goes like this;

if (button 1 is pressed) {
play A;
turn on LED;
}
else if (button 2 is pressed) {
play D;
turn on LED;
}
else {
play nothing;
turn off LED;
}

So the if condition will be checked first. If it is true, the speaker will play a perfect A and the LED turns on. If it is false, the else if statement will be examined. If that is true, the speaker will play an almost perfect D and turn on the LED. If it is false all sounds and lights off. Repeat the loop forever.

Compose the sketch for the 2-piece piano!