In trial one, if the button is pressed down, you change the state of the light from on to off or vice versa:
void loop(){
val = digitalRead(BUTTON); //read input value and store it
if (val == HIGH){ //if there is voltage coming in from the button
state = 1 - state; //change the state, which later is used to
} //turn the light on or off
//...etc...
}But since instructions are executed so rapidly, if the button is held for more than a split second, the "state" of the light will change as many hundreds of a second as you held it. The next example attempts to fix this by making sure there has actually been a transition:
void loop(){
val = digitalRead(BUTTON); //read input value and store it
if ((val == HIGH) && (old_val == LOW){ //check for transition
state = 1 - state;
}
old_val = val; //now remember whether the button was pressed
//...etc...
}
This works to some extent, but there is still a problem: when you press a button, the spring within it bounces and contact is made and broken a few (short) times in a fraction of a second. The final revision of Example 3 includes "simple debouncing" by including a delay of between 10 and 50 ms (I used 25) after the state change. The result is a working pushbutton light.
Push button (and release), receive light!
Example 3 complete!

No comments:
Post a Comment