Skip to content

Instantly share code, notes, and snippets.

@helloCaller
Last active January 20, 2016 03:08
Show Gist options
  • Save helloCaller/9e215b4d71fdba24adad to your computer and use it in GitHub Desktop.
Save helloCaller/9e215b4d71fdba24adad to your computer and use it in GitHub Desktop.
Arduino code for button click on and off of LED. Physical Computing 2002-001
/*
Buttony
Click an LED on and off with a button.
Adapted by Luke Garwood after example 4-5 from Getting Started With Arduino by Massimo Banzi and Michael Shiloh
*/
int LEDPIN = 13; //set up variable LEDPIN as the pin to which the LED connects
int BUTTONPIN = 7; //set up variable BUTTONPIN as the pin to which the button connects
int ButtonValue; // set up variable to hold value input from BUTTONPIN.
int Old_ButtonValue; //set up variable to determine the previous value of ButtonValue
int LightOn = 0; // Used to determine whether the light is on or off, 1 being true = on, 0 being false = off
void setup() { //function that only runs once initially
pinMode(LEDPIN, OUTPUT); //pinMode(pin number, either INPUT or OUTPUT)
//Set up LEDPIN as an output
pinMode(BUTTONPIN, INPUT);// Set up BUTTONPIN as an Input (it recieves information from the Arduino rather than sending information/values)
}
void loop() { //function that continues to loop
ButtonValue = digitalRead(BUTTONPIN); //digitalRead tells us if the value for this pin is HIGH or LOW
//when button is pushed down digitalRead(BUTTONPIN) returns HIGH
if((ButtonValue == HIGH) && (Old_ButtonValue == LOW)) { //a condition that asserts if ButtonValue is read as HIGH (button is pushed)
//AND was previously LOW
LightOn = 1 - LightOn; // this alternates LightOn to be either 1 or 0 (1 being light on, 0 light off)
delay(10); //for debouncing purposes, putting in a delay so that only one button press is registered
}
Old_ButtonValue = ButtonValue; //after the above code has been executed, giving Old_ButtonValue the ButtonValue to detect the moment of button press.
if(LightOn == 1){ // condition of if LightOn has a value of 1 (true)
digitalWrite(LEDPIN, HIGH); //turn the LED light on by setting digitalWrite on the LED pin to HIGH
} else { // or if the condition of LightOn is anthing other than 1
digitalWrite(LEDPIN, LOW); //turn, or keep, the LED off by setting digitalWrite to LOW
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment