#include <EEPROM.h> // include to use EEPROM
int BPin = 5; // button Pin is declared
int LED = 11; // LED Pin is declared
int ledState; // the current state of the LED
int presentBState; // button's present state
int oldBState = HIGH; // button's old state
/* time and debounce is assigned to unsigned long datatype to avoid
overflow as millis () can increase rapidly*/
unsigned long time = 0;
unsigned long debounce = 50;
void setup() {
pinMode(BPin, INPUT); // declare button Pin as input
pinMode(LED, OUTPUT); // declare LED Pin as output
// Initial LED state is set
digitalWrite(LED, ledState);
}
void loop() {
// read the state of the button
int State = digitalRead(BPin);
// If the button is pressed, reset the debouncing timer
if (State != oldBState) {
time = millis();
}
if ((millis() - time) > debounce) {
// the following codes is to toggle LED by pressing button.
if (State != presentBState) {
if(ledState == HIGH){
ledState = LOW; }
else {
ledState = HIGH; }
}
digitalWrite(LED, ledState);
// store present state of LED
EEPROM.write(0, ledState);}
// the old state value of the button is updated
oldBState = State;
}