Button-Activated Siren

In this program, you use a variable to control the pitch of a speaker. By changing that variable very smoothly and quickly with code, you'll create a cool sound effect.

Code

/* * Use a button to create an ascending tone on a speaker. When the button is * released, let the pitch on the speaker descends. */ int pitch = 40; //variable for pitch with value of 40 (hz) void setup(){ pinMode(A5,OUTPUT); //speaker pinMode(12,INPUT_PULLUP);//button } void loop(){ tone(A5,pitch); //play the 'pitch' variable to the speaker delay(5); //time between playing each pitch if(digitalRead(12)==LOW){ //if the button is pressed pitch = pitch +1; //increase the value of 'pitch' by 1 } else{ //otherwise (if button not pressed) pitch = pitch -1; //decrease the value of 'pitch' by 1 } if(pitch <=40){ //ensure pitch doesn't descend to negative number pitch = 40; } } // (c) 2017 Let's Start Coding. License: www.letsstartcoding.com/bsdlicense
 

Challenges

How many can you complete? Change the code and hardware according to the challenges below. Upload your code to see the effect when you're finished. Complete a challenge? Check it off the list!

Videos

Read the Code Walkthrough Text (click to open)

Concepts

New Concept: Unknown Variable Value

Up to this point, you could probably figure out the value of your variables just by watching your programs run, even if you weren't looking at the screen. In this program, you see something different: variables that are changing quickly and somewhat automatically. 

This demonstrates the real power of a variable. It's a word that holds a value-sometimes a value you don't know. Now the program is doing work for you- taking your commands like 'add one to whatever you were before' and executing it. 

Quiz

If you're having trouble, try to run a program that can help you find the answer.

1. What is a different way to code variable = variable + 1; ?



2. In the button-activated siren example, what is the lowest value that the pitch variable can have?