Random Tone 'Latching' Button

Code

The code in the editor below is ready to run! Plug your Code Lab in to your computer's USB port with the cable and hit 'Upload Your Code!' to see what it does. Change something in the code, like a delay or pin number. Try to add something new to the program - it's yours to tinker with! You can always press the 'Restore' button to return the code to the working example.


/* Create a random tone generator on the speaker that can 'latch' on and off with the press of a button. */ int pressCount = 0; //An integer (whole number) variable to keep track of how many times the button is pressed void setup(){ pinMode(A5,OUTPUT); //speaker pinMode(8,INPUT_PULLUP); //button } void loop(){ if(digitalRead(8)==LOW){ //if button 8 is pressed pressCount++; //++ is a way to add one to a variable. Now pressCount = its former value + 1 delay(250); //a delay allows you to release your finger from the button without counting multiple presses } if(pressCount == 1){ //if pressCount equals 1.. tone(A5,random(100,1000)); //play a tone between 100 and 999 on the speaker delay(70); //wait 70 milliseconds (0.7 seconds) with the tone playing } else{ //if pressCount is anything other than 1... noTone(A5); //stop the tone from playing on the speaker pressCount = 0; //reset the count to 0 before the loop starts again } } // (c) 2021 Let's Start Coding. License: www.letsstartcoding.com/bsdlicense
 

Walkthrough Video

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

Video Notes for Code Lab Users:

  • Your button is on port 8 instead of port 6 as the video says.

Challenges

Can you complete the challenges? 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.

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?