Random Rocket Sounds

If your signals get garbled by a black hole in space, you might hear some wild sounds on the radio.

Code

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

/* Make a random beep on the speaker when you press button 12. */ void setup(){ pinMode(2,OUTPUT);//Speaker pinMode(12,INPUT_PULLUP); //Button } void loop(){ if(digitalRead(12)==LOW){ //if the button sends a LOW (pressed) signal tone(2,random(50,1000)); //play a tone randomly between 50 and 1000 hertz on pin 2 (speaker) delay(50); //a small delay ensures it doesn't just sound like static } else{ //otherwise if no LOW signal from button noTone(2); //stop any tones that are playing on 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 challenges? Change the code in the editor above, then upload it to your Code Rocket and see if you got the result. Don't stop here, keep experimenting with the code!

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 program shows you a new way that you can replace numbers in a program with other functions. In past projects, you’ve replaced number values with variables, but those variables were stable values. Now you see how you can use functions or equations in place of a single number (assuming you get your syntax right!).

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. What are the two arguments that the random function requires?