// 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.
 

Using a variable, set the 'mode' of the headlight to on or off with the press of a button, so you don't have to hold a button to keep your headlights on all the time!

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 a button that 'locks' the headlight on until you press it again */ int pressCount = 0; //create an 'integer' variable called 'pressCount' void setup() { pinMode(4,OUTPUT); // headlight pinMode(8,INPUT_PULLUP); //button to control headlight } void loop() { if(digitalRead(8)==LOW){ //if the button is pressed pressCount = pressCount + 1; //increase pressCount by 1 delay(250); //wait 250 milliseconds before increasing pressCount again } if(pressCount == 1){ //if pressCount is equal to 1 digitalWrite(4,HIGH); //the headlight is on } else{ //otherwise, turn the headlight off and set pressCount to 0 digitalWrite(4,LOW); pressCount = 0; } } //This brace closes the void loop // (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 to Set "Modes"

If you spell out the logic of this program, the press of your button sets the value of the variable pressCount, then the value of pressCount determines whether or not the LED is lit. Because the program can 'remember' the value of the variable, when you use the button to change the variable, you're changing the 'mode' of that LED. You have probably flipped on a light switch today or maybe turned a key in a lock. Those are physical representations of 'on/off' or 'locked/unlocked' like what you're recreating in code. Unlike the key or the lock, though, your code variables can have any number of 'modes' or values, so that pressCount = 1 does something different than pressCount = 2, 3, 4, or so on. 


Quiz

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

Why is it important to set pressCount=0 in the 'else' statement?




To reverse the way this program works- have the backup alarm on by default and only off when the button is pressed, what would you do?