/*
when it is powered up, the previously lit LED is lit. Every button press turns off current LED and lights
next LED in sequence. After LED 9, loop returns back to LED 1. Putting a high momentarily on
resetPin causes sequence to go back to LED1 (index0). When power is turned on, last
LED that was lit when powered down lights,LED number is saved in EEPROM.
*/
#include<EEPROM.h>
const int buttonPin = 2;
const int resetPin = 3;
const int LEDPinArray[] = {12, 11, 10, 9, 8, 7, 6, 5, 4};
const int defaultLED = 0; //selects the first element in the array as the default; can be changed to suit
const int nLED = sizeof(LEDPinArray) / sizeof(LEDPinArray[0]);
const int EEPROMLoc = 10; //location for storing index of last lit LED
//end of header *****************************************************************************************
void Select(int index) { //turns on selected LED, turns off all others
for (int i = 0; i < nLED; i++) {
if (i == index) {
digitalWrite(LEDPinArray[i], HIGH);
EEPROM.put(EEPROMLoc, i);
// Serial.println(i);
}
else digitalWrite(LEDPinArray[i], LOW);
}
}//end Select ******************************************************************************************
int chosenLED = defaultLED;
void setup() { //self evident
// Serial.begin(115200);
for (int i = 0; i < nLED; i++) pinMode(LEDPinArray[i], OUTPUT);
pinMode(buttonPin, INPUT);
pinMode(resetPin, INPUT);
int temp = EEPROM.get(EEPROMLoc, temp);
if (temp < nLED && temp >= 0) chosenLED = temp; //only keep retrieved value if within range, else chosenLED remains as compiled value
// Serial.print("initial value of chosenLED: ");Serial.println(chosenLED);
Select(chosenLED); //for consistency, use the select routine already defined
} //end setup **********************************************************************************************
int lastButtonState = 0;
void loop() { //self evident
// reset function; no logic, state memory, or debounce, just do it
if (digitalRead(resetPin) == HIGH) {
chosenLED = defaultLED;
Select(chosenLED); //lights new LED, but only if we changed something
}
//button press function
int buttonState = digitalRead(buttonPin);
if (buttonState != lastButtonState) {
if (buttonState == HIGH) {
chosenLED++;
if (chosenLED >= nLED) chosenLED = 0; //limit value to valid array indices
Select(chosenLED); //lights new LED, but only if we changed something
}
delay(50);//N.B. debounce - if we reduce this, we risk multiple increments per press
lastButtonState = buttonState; //only need to write if state changes
}
} //end loop ***************************************************************************************************8