1
$\begingroup$

So I'm new to using Arduino's in general and just want to have my code by reversed each subsequent startup using the eeprom on my Arduino uno. I've been trying to read up on how to use the eeprom but I'm kind of confused so I've posted below a picture of some sample code that I think should work (but it's probably wrong). Basically I want to on start-up, execute some code, and next startup it executes some other code (the reverse of the original. Then the next startup to execute the original code. I'm unsure of how to fit my Boolean system into the loop part though, so any help would be greatly appreciated!

sample code

So What I want this code to do is the first time I power the Arduino to print "Code A". Then after its shutdown, and restarted again to print "Code B" But what I get at the moment is output of code

$\endgroup$
1
2
$\begingroup$

The problem is that during setup, you first write the EEPROM address to 1 and printA, and then you read the same address which is now 1 so the if condition is again true.

What you should use :

if(EEPROM.read(address)==0)
{
   Serial.println('A');
   EEPROM.write(address)==1;
} else {
{
   Serial.println('B');
   EEPROM.write(address)==0;
}

(Hopefully I explained clear enough the problem. I'am a bit distracted by the newsfeed).

$\endgroup$
4
  • $\begingroup$ Yup that was the problem! Thanks for the reply. And do u know if it would be ok to leave all this code in the void setup() part, since I only want it to run on startup? Also does void setup() only run once when the code is flashed to the arduino, or when the arduino gets power because I want this code to run each time it turns on (from the 9V power port not via USB)? Thanks again! $\endgroup$
    – Geo
    Jan 8 at 3:09
  • $\begingroup$ void setup() is executed once everytime arduino is reset. Which is when you power it up, reset it other means or flashed. $\endgroup$
    – NMech
    Jan 8 at 5:30
  • $\begingroup$ Perfect, thanks so much! $\endgroup$
    – Geo
    Jan 8 at 21:03
  • $\begingroup$ @Geo, thanks for accepting! $\endgroup$
    – NMech
    Jun 8 at 7:46

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.