I have run the example from the EEPROM tutorial with the checkLedState() user defined function. What is weird is that on rebooting, th function prints out”LedStatus on restart” and then either “LedPin State is 1” or “…0” depending on what it was prior to the reboot. The weird part is that the “digitalWrite(ledPin,ledState);” is opposite what it should be each time. If the ledState is 1, then the led is off and vice versa. I’ve tried changing ledState to a boolean function, and substituting true/false, 1/0 etc to no avail. It is always opposite. I tried copying and pasting as will as writing the sketch out- no difference. Still the contrary behavior. I ran this on my Uno with led on pin 2 and button on pin 3.
<code#include
/*EEPROM lesson
a pushbutton that will turn an LED on and off.
*/
const int8_t ledPin = 2; //led pin
const int8_t Button = 3; //pushbutton pin
int8_t ledState;
int8_t buttonState=0; //uses reading instead of buttonState or buttonVal
int8_t lastButtonState = 0; // the previous button State///
int reading; //the reading from the pushbutton
unsigned long lastDebounceTime = 0; //the last time the button was toggled
unsigned long debounceDelay = 50; //the debounce time for voltage to settle down, canvary
void setup() {
// put your setup code here, to run once:
Serial.begin(9600);
pinMode(ledPin, OUTPUT);
pinMode(Button, INPUT);
digitalWrite(ledPin, ledState); // sets the intitial LED state
checkLedState(); //user defined function to check stored LEDstate in EEPROM
}
void loop() {
// put your main code here, to run repeatedly:
reading = digitalRead(Button);
Serial.println(reading);
//EEPROM.write(0,ledState);
if (reading != lastButtonState) {
//reset the debouncing time
lastDebounceTime = millis();
}
/*whatever the reading is at, it’s been there longer than the debounce delay ,
so take it as the reading
*/
if ((millis() – lastDebounceTime) > debounceDelay){
//IF the BUTTON state has changed:
if (reading != buttonState) {
buttonState = reading;
//only toggle the LED if the new button state is high
if (buttonState == HIGH) {
ledState = !ledState;
}
}
}
digitalWrite(ledPin,ledState);
//save the reading/. next time throught eh llop, it’ll be the lastButtonState
lastButtonState = reading;
EEPROM.update(0,ledState);
}
//prints and updates the led state when the board restarts
void checkLedState(){
Serial.println(“LED status after restart:”);
ledState = EEPROM.read(0);
if (ledState ==1){
Serial.println(“LedPin State is 1”);
digitalWrite(ledPin,ledState);
}
if (ledState ==0){
Serial.println(“LedPin State is 0”);
digitalWrite(ledPin,ledState);
}
}
Hi.
You have several digitalWrite() functions in the code. In which one are you having the issues?
Add some print statement before each digitalWrite that print in which section of code it’s running and what’s the current value on that section. Then, it’s easier to figure out where the issue is actually occurring.
Regards,
Sara