PROJECT: LED Flashlight
Step 1 - Build the Project

To create an LED flashlight, you need to set up a button that 'holds its state', meaning it can clicked on and then clicked off.


PROJECT: LED Flashlight
Step 2 - Upload the Code

/* * Use a button to turn a light on and off */ int pressCount = 0; // count how many presses on the button void setup(){ pinMode(12,OUTPUT); //LED pinMode(A5,INPUT_PULLUP); //pushbutton } void loop(){ //if the button is pressed, increase the value of pressCount by one if(digitalRead(A5) == LOW){ pressCount++; //++ is shorthand for pressCount = pressCount + 1 delay(250); //This delay keeps one press from counting many times } if(pressCount == 1){ digitalWrite(12,HIGH); } else { digitalWrite(12,LOW); pressCount = 0; //reset the count to 0 to start over. } } // Write a program with 2 LEDs so that the button toggles which is on // (c) 2017 Let's Start Coding. License: www.letsstartcoding.com/bsdlicense
 

PROJECT: LED Flashlight
Step 3 - Read the Walkthrough

You'll first create a variable to hold the number of presses on the button. Then set up your LED and button in the setup().

The loop checks the state of the button. If it is pressed, the button will send a LOW signal and pressCount will increase by one with the ++ incrementor. A short delay ensures that one press isn't counted multiple times. Using an if statement, you create two scenarios.

Either the pressCount is 1 and the light is on, or else the light is off and pressCount is set equal to 0 again.