Random Piano Tones

Let the code ‘choose’ which tone to play next on your speaker. You set the speed and the range, then settle in for a wild ride!

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.

// Play a random tone on Speaker that changes every loop void setup(){ pinMode(10,OUTPUT); //Set the speaker as an OUTPUT } void loop(){ tone(10,random(40,800)); //Select a random hertz value from 40 to 799 to play delay(150); //delay 150 milliseconds before the next random tone is played } // (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: Random

The computer ‘makes a choice’ in this program about which tones it plays. Using this function can make your code do some things that are unpredictable, even to you, the programmer! This same logic is how some code in the real world, like slot machines, makes a random choice.

You can replace most number in code with functions like ‘random’. The important thing to remember is the syntax, or punctuation, that is required for the function. Use the purple cards in your kit as a reference for the syntax that each function requires.

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. Which syntax ends the entire 'void loop' function?




2. Which syntax ends a single code command?