/* . A program that turns on the LED when the push button is pressed and turns it off
when the push button is pressed again and so on. Every time the push button is pressed, the
state of LED is changed between ON and OFF. Stores this state of change in EEPROM so that in
the rare event of a power reset, the previous state of LED can be restored. */
// Resources: https://roboticsbackend.com/arduino-turn-led-on-and-off-with-button/
#include <EEPROM.h>
// Global variables
// Pins
const int LED_PIN = 7;
const int BUTTON_PIN = 4;
// State
int last_button_state = LOW;
int led_state = LOW;
int current_button_state;
// Debouncing timing
unsigned long debounce_duration = 50; // how long to wait before validating next change in button state (millis)
unsigned long last_time_button_state_changed = 0; // starting point to compare debounce duration to
//EEROM
int address = 0;
void setup() {
Serial.begin(9600);
// Setup the digital pins as outputs
pinMode(LED_PIN, OUTPUT);
pinMode(BUTTON_PIN, INPUT_PULLUP); // activate internal pull-up resistor
// Set initial value in EEROM
EEPROM.write(address, led_state);
// debug only - for simulation to check if state has been saved correctly or not
// We are printing directly from the memory address
Serial.print("The current LED state ");
Serial.print(EEPROM.read(address));
Serial.println(" is stored in EEPROM.");
}
void loop() {
// Only start the button functionality if enough time has past (i.e. update time is greater than debounce duration)
if (millis() - last_time_button_state_changed > debounce_duration) {
// read the new state of the button. HIGH = pressed, LOW = not pressed.
current_button_state = digitalRead(BUTTON_PIN);
// Control the led state depending on the button value
if (current_button_state != last_button_state) {
// Update starting point for the debounce timer
last_time_button_state_changed = millis(); // millis() returns the number of milliseconds passed since the Arduino board began running the current program.
// Update the last state
last_button_state = current_button_state;
// If the previous state is HIGH and the current state is low (pressed to not pressed) then,
// toggle the state of the LED
if (current_button_state == LOW) {
// if LED is currently ON, then turn it OFF, otherwise turn it on
led_state = (led_state == HIGH) ? LOW: HIGH; // assignment = (condition to evaluate) ? if true use this value : if false use this value
digitalWrite(LED_PIN, led_state);
// EEPROM.update only stores a new value
EEPROM.update(address, led_state);
// debug only - for simulation to check if state has been saved correctly or not
// We are printing directly from the memory address
Serial.print("The current LED state ");
Serial.print(EEPROM.read(address));
Serial.println(" is stored in EEPROM.");
}
}
}
}