Two Key Piano

Add another key to your Piano and learn about the ‘if - else if’ statement that will allow your code to have many ‘options’ about how it runs!

Code

The code in the editor below already works Just plug in your Code Piano and press upload to see what it does! Tinker with it and make changes to see what each line of code controls.

//Beep a tone when you press button 2 on Code Piano, and a different tone for button 3 void setup(){ pinMode(10,OUTPUT); //Set speaker as an OUTPUT pinMode(2,INPUT_PULLUP); //Button 2 as an INPUT_PULLUP pinMode(3,INPUT_PULLUP); //Button 3 as an INPUT_PULLUP } void loop(){ if(digitalRead(2)==LOW){ //if button 2 is sending a low signal... tone(10,500); //...play a tone of 500 hertz on the speaker } else if(digitalRead(3)==LOW){ //if button 3 is sending a low signal... tone(10,600); //...play a tone of 600 hertz on the speaker } else{ //in all other cases (button is not sending a low signal)... noTone(10); //send a noTone command to the speaker } } // (c) 2018 Let's Start Coding. License: www.letsstartcoding.com/bsdlicense
 

Walkthrough Videos

Watch the videos for line-by-line explanation of how the example program works. Then you'll be ready to make some changes of your own!

Challenges

Can you complete the challenge? Change the code in your code editor above. Upload your code to see the effect when you're finished. Complete a challenge? Check it off the list!

Concepts

These are the new code concepts covered in this example program. To become a great coder, read through these concepts to learn new vocabulary.

New Concept: ‘If’ and ‘else if’ statements

In this program, you see that the code can react to two different inputs and react differently to each of them. Every time the void loop runs, the code checks the conditions of the ‘if’ and ‘else if’ statements until it finds one that is true. Then, it runs the action that goes along with the true condition.

Remember that the program runs from top to bottom, so the first ‘if’ statement gets checked before the next ‘else if’ statement. Once a ‘true’ condition is found, the rest of the ‘if’ and ‘else if’ statements are skipped. This means that the higher up in the code an ‘else if’ statement is, the higher priority it has if you hold down multiple buttons at once.

Quiz

If you're having trouble coming up with an answer to a quiz question, try to run an experimental program or look at the example code to help you find the answer.

1. In the example program, when the condition of the 'if' statement is not true, what does the code check next?