//Toggle Switch with debounce
//Debouncing acounts for a few milliseconds delay resulting from
//the physics of overcoming the contact potential in a switch
//Mr. H.
//declare and initializes two globale variables to represent active pins
int button = 2;
int led = 9;
void setup()
{
//sets the function of both active pins
pinMode(led, OUTPUT);
pinMode(button, INPUT);
}
//define three additional global variables specific to loop
//these could have been declared up to with the others
int ledState = LOW;
//note: two variables are required to "toggle" something on and off,
//one to record the current state and one to keep track of changes
int currentButton = LOW;
int newButton = LOW;
void loop()
{
newButton = digitalRead(button);
//the simplest way to debounce is to set a 5 millisecond delay before
//re-reading the input state, if both readings are the same after this
//short delay then the program accepts the input
if (newButton != currentButton && newButton == HIGH)
{
delay(5);
newButton = digitalRead(button);
//efficient coding trick using boolean logic to trigger LED
ledState = (ledState == LOW);
}
digitalWrite(led, ledState);
currentButton = newButton;
}
//Debouncing acounts for a few milliseconds delay resulting from
//the physics of overcoming the contact potential in a switch
//Mr. H.
//declare and initializes two globale variables to represent active pins
int button = 2;
int led = 9;
void setup()
{
//sets the function of both active pins
pinMode(led, OUTPUT);
pinMode(button, INPUT);
}
//define three additional global variables specific to loop
//these could have been declared up to with the others
int ledState = LOW;
//note: two variables are required to "toggle" something on and off,
//one to record the current state and one to keep track of changes
int currentButton = LOW;
int newButton = LOW;
void loop()
{
newButton = digitalRead(button);
//the simplest way to debounce is to set a 5 millisecond delay before
//re-reading the input state, if both readings are the same after this
//short delay then the program accepts the input
if (newButton != currentButton && newButton == HIGH)
{
delay(5);
newButton = digitalRead(button);
//efficient coding trick using boolean logic to trigger LED
ledState = (ledState == LOW);
}
digitalWrite(led, ledState);
currentButton = newButton;
}