One Key Piano

Start building a piano by getting a single key to trigger a note.

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 void setup(){ pinMode(10,OUTPUT); //Set speaker as an OUTPUT pinMode(2,INPUT_PULLUP); //Button 2 as an INPUT_PULLUP } void loop(){ if(digitalRead(2)==LOW){ //if button is sending a low signal... tone(10,500); ///...play a tone of 500 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: Inputs to your code

Up to this point, your code has run automatically after you hit the ‘Upload’ button. Only you, the programmer, had the power to make changes by digging into your code to write an update. With the ‘if’ statement, you are now allowing your code to be updated by an interaction with the outside world. The code is looking for input from the button and ‘making a decision’ based on that input.

If you think about most computer programs you interact with each day, whether an app on a phone or a setting for the microwave, they require user input to start working, so this concept of ‘listening’ for an input and the making a decision based on it is an important one.

Quiz

If you're having trouble, try to run an experimental program or look at the example code to help you find the answer.

1. The two main parts of an 'if' statement, according to the code walkthrough video, are:




2. Can you have an 'if' statement without an 'else' statement?



3. Can you have an 'else' statement without an 'if' statement?