Use buttons to ‘tune in’ the pitch of a variable note or hold them down to create fun sound effects.

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.

// Raise the tone's pitch when button 9 is pressed, lower it when button 2 is pressed int pitch = 40; void setup(){ pinMode(10,OUTPUT); //speaker set to OUTPUT pinMode(9,INPUT_PULLUP); //button that will raise the pitch of the tone pinMode(2,INPUT_PULLUP); //button that will lower the pitch of the tone } void loop(){ tone(10,pitch); //Play a tone of 'pitch' every time the loop runs. The value of 'pitch' will change if(digitalRead(9)==LOW){ //If button 9 is pressed, sending a LOW signal... pitch++; //increase the value of 'pitch' by one with the ++ command delay(2); //delay 2 milliseconds before running the rest of the void loop } else if(digitalRead(2)==LOW){ //if button 2 is pressed... pitch--; //decrease the value of 'pitch' by one with the -- command delay(2); //wait 2 milliseconds } if(pitch<40){ //if pitch ever goes lower than 40... pitch = 40; //...make pitch equal 40. This keeps the tones from going to negative numbers (unhearable) } } // (c) 2018 Let's Start Coding. License:

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!


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!

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: Changing variable values

So far, you’ve used variables as ‘names for numbers’ that made your code easier to change and update by programmers. In this project, you instead use a variable as a number that can be changed by the code and doesn’t have a constant value as the code runs. This is another important feature of variables - you can update them as the code runs.

It’s almost impossible to keep track of the value of the pitch variable in this code because it can change so quickly, but try to imagine what value ‘pitch’ has as you play with this project. If you can visualize the value of a variable that you’re using, it’s much easier to find and solve problems that can come up when you’re using them in place of number values.


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. What does ++ do to a variable? Hint: watch the walkthrough video!