Deep Space Headlights

When you're flying through space near light speed, you probably want to see what's coming up ahead. Turn on the Code Rocket's headlights for some assistance.

Code

The code in the editor below already works Just plug in your Code Rocket and press upload to see what it does! Tinker with it and make changes to see what each line of code controls.

/* Press button 12 to 'lock' the headlights of the spaceship on. Press it again to turn them off*/ int headlights = 0; //Variable for the status of the headlights. If the variable = 1, the headlights are on. Otherwise, they're off. void setup(){ pinMode(12,INPUT_PULLUP); //Button 12 pinMode(3,OUTPUT); //LED 3 pinMode(4,OUTPUT); //LED 4 } void loop(){ if(digitalRead(12)==LOW){ //if the button is pressed... headlights++; //...increase the value of 'headlights' by one delay(250); // Wait 250 milliseconds before counting another press } if(headlights == 1){ //If the headlights variable = 1, turn on lights 3 and 4 digitalWrite(3,HIGH); digitalWrite(4,HIGH); } else{ //If headlights variable is anything other than 1, turn off the headlights digitalWrite(3,LOW); digitalWrite(4,LOW); headlights = 0; //resetting the headlights variable to 0 ensures the variable doesn't increase to 2,3,4 and higher. } } // (c) 2018 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

Can you complete the challenges? Change the code in the editor above, then upload it to your Code Rocket and see if you got the result. Don't stop here, keep experimenting with the code!

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: Changing variable values

You’ve been using variables throughout your Code Rocket projects, but here, the variable value is changing based on a button press. The button press changes the variable value, then you use the ‘if’ statements to interpret that variable value. Is the variable equal to 1? If so, turn on the lights! If it’s anything else, turn off the lights and set the variable equal to zero.

Because the button affects the variable and the variable affects the action, you can create lots of different actions from just one button input to the code.

Quiz

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

1. What does the ++ do in this program?