Homework 4.5 Turn on LED while the button is pressed
const int LED = 13; // Arduino digital pin 13 is the pin for the LED
const int BUTTON = 7; // Arduino digital pin 13 the input pin where the push-button 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); // tell Arduino BUTTON is an input
}
void loop()
{
val = digitalRead(BUTTON); // read input value and store it
if ((val == HIGH) && (old_val == LOW)){
state = 1 - state;
delay(10);
}
old_val = val;
if (state == 1)
{
digitalWrite(LED, HIGH);
}
else
{
digitalWrite(LED, LOW);
}
}
////////////////////////////////////////////////////////
//Explain
val = 0
old-val = 0
state = 0
// HIGH = 1,LOW = 0
+When a push button is pressed
val = 1
old-val = 0
state = 0
if((val == HIGH)&&(old-val==LOW)) //true
state = 1-0 = 1
old-val = val = 1
if(state == 1) //true
(LED,HIGH) = Bright
+When a push button is released
val = 0
old-val = 1
state = 1
if((val == HIGH)&&(old-val==LOW)) //false : no action
old-val = val = 0
if(state == 1) //true
(LED,HIGH) = Bright
+When a push button is pressed again
val = 1
old-val = 0
state = 1
if((val == HIGH)&&(old-val==LOW)) //true
state = 1-1 = 0
old-val = val = 1
if(state == 1) //false no : action
(LED,LOW) = Dark
+When a push button is released
val = 0
old-val = 1
state = 0
if((val == HIGH)&&(old-val==LOW)) //false : no action
old-val = val = 0
if(state == 1) //false no : action
(LED,LOW) = Dark
+Picture



No comments:
Post a Comment