Watch “Luna’s wrestling partner for the day” on YouTube
May 13, 2013Using a Headcollar to walk Your Dog
May 15, 2013The code below is a simple script that will allow you to turn an LED on and off with a button. I am using the Arduino Uno, Breadboard, LED, button, 10ohm resistor, 3 wires, and a USB cable to power the Arduino.
It’s a pretty simple setup and I will soon explain why it’s setup this way. For now, feel free to follow the images for the inputs and code to activate the button which will function to turn the LED on and off.
Feel free to comment if you have any questions or improvements to my code or setup.
// Turn on an LED when a button is pushed and keep it on after it's released.
const int LED = 13; // Create a Constant for the Pin which Activated the LED
const int BUTTON = 7; // The input pin where the button is located to turn the LED on and off
int val = 0; // value that stores the state of the input pin
int old_val = 0; // variable that stores the previous state of val
int state = 0; // 0 means that the LED is off and 1 means that the LED is turned on (LIKE YOUR MOM)
void setup() {
pinMode(LED, OUTPUT); // tell arduino that the LED is an output
pinMode(BUTTON, INPUT); // and the BUTTON is an input
}
void loop(){
val = digitalRead(BUTTON); // read input value and store it
// check if there is any transition
if ((val == HIGH) && (old_val == LOW)) {
state = 1 - state;
delay(10);
}
old_val = val; // val is now old, so store it
if (state == 1){
digitalWrite(LED, HIGH); // turn LED on
}else{
digitalWrite(LED, LOW); // or else turn it off
}
}