// Copyright 2007, Sandeep Gangadharan // For more free scripts go to http://www.sivamdesign.com/scripts/
 
Blink Hookup: 1 LED in pin 13. Remember shorter leg of LED is ground.
 

Honk your horn with a button on Code Car, but this time using a variable. 

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.

/* * Press button 9 to honk the horn on Code Car using a variable */ int horn = 9; //an integer variable called 'horn' void setup(){ pinMode(horn,INPUT_PULLUP); //button to activate the horn pinMode(2,OUTPUT); //speaker on Code Car } void loop(){ //if the pushbutton is pressed, start playing a tone if(digitalRead(horn)==LOW) { //if the horn button is pressed... tone(2,250); //the code between the braces will run } else { //an else statement runs when the 'if' condition isn't true noTone(2); //silence the horn } } // (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: Variables Replace Fixed Numbers

Variables are something that you interact with all the time and they're a very important concept in coding. In this lesson, you're simply replacing a fixed number with a variable. But imagine if you had written 1000 lines of code that all relied on pressing button 8, then button 8 broke! It would be so much easier to have a variable 'button' standing in for button 8 that you could change in one location and affect the rest of your code.

There are a number of different ways to use variables in coding (you'll see more ways in future lessons), but their purpose is always to make code easier to understand, simpler to change, and less repetitive.


Quiz

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

When creating a variable, you have to decide 3 'qualities' of the variable in order. What's the order?



When naming a variable, give it a name that _________________