const int LED = 13; // the pin for the LED
const int BUTTON = 7; // the input pin where the pushbutton is connected
int val = 0; // val will be used to store the state of the input pin
int old_val = 0; // this variable stores the previous value of "val"
int state = 0; // 0 = LED off and 1 = LED on
void setup() {
pinMode(LED, OUTPUT); // tell Arduino LED is an output
pinMode(BUTTON, INPUT); // and BUTTON is an input
}
void loop(){
val = digitalRead(BUTTON); // read input value and store it
// check if there was a transition
if ((val == HIGH) && (old_val == LOW)){
state = 1 - state;
}
old_val = val; // val is now old, let's store it
if (state == 1) {
digitalWrite(LED, HIGH); // turn LED ON
} else {
digitalWrite(LED, LOW);
}
}
EXPLAIN
We have three variables and initial it to 0 :
int val = 0;
int Old_val = 0;
int state = 0;
LED Turn On
*Press the Button :
When we pressed the button val variable = 1 and old_val variable = 0 it means that
=>state = 1
=>old_val = 1
if(state == 1)
=>LED turn on.
*Release the Button
When we released the button val variable = 0, state variable still = 1, and old_val variable = 0.
if(state == 1)
=> LED turn on.
LED turn off
*Press the Button
When we pressed the button val variable = 1 and we had state = 1 in this case state = 0 and
old_val = 1.
if(state == 0)
=>LED turn off.
*Release the Button
When we released the button val variable = 0, state variable = 0, and old_val variable = 0.
if(state == 0)
=>LED turn off.
0 Comments