// Copyright 2007, Sandeep Gangadharan // For more free scripts go to http://www.sivamdesign.com/scripts/

Rising Horn Pitch on Code Car

 
Blink Hookup: 1 LED in pin 13. Remember shorter leg of LED is ground.
 

Make Code Car's horn honk a little higher each time you honk it, or create a rising tone 'honk' that turns into a dog whistle!

Code

The code below already works and is ready to upload! Upload the code to Code Car and see what happens. Then, you'll 'take apart' the code to learn what each piece of the program does.

/* * Make the horn beep a higher tone every time it's pressed with a variable */ int pitch = 100; //an integer type variable named 'pitch' with a starting value of 100 void setup(){ pinMode(9,INPUT_PULLUP); // the horn button pinMode(2,OUTPUT); // Code Car speaker } void loop(){ if(digitalRead(9)==LOW){ //if the horn button is pressed... tone(2,pitch); //use the value of the variable 'pitch' as the hertz pitch = pitch + 50; //increase pitch by 50 delay(500); //delay 500 milliseconds before checking the 'if' again } else{ noTone(2); } } // (c) 2017 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

How many can you complete? Change the code according to the challenges below. 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: Updating Variables in the Loop

In the last lesson, you learned about replacing a variable for a fixed value, like a pin number. When the program is running, the button that activates the horn probably shouldn't change- that would be some strange code! But in this program, you start to see the value of a variable that can change as the code runs. This makes for much more interactive programs since the program is always updating.

You can refer to a variable that replaces a constant number as a constant variable. A variable whose value changes throughout a program is a non-constant variable.

 

Quiz

If you're having trouble, try to run an experimental program or look at the example code to help you find the answer.

How many times would you have to press the button for the horn honk to be 500 hertz?




An 'if' statement always has two basic parts. What are they?