Last active
December 21, 2018 14:20
-
-
Save topin89/5bc7a0ce282c4a134a8f051d000653a4 to your computer and use it in GitHub Desktop.
Save some variables across all Arduino resets and most reprogrammings without EEPROM
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
struct SaveableData{ | |
uint32_t update_counter; | |
}; | |
struct UploadSafe{ | |
char dummy[64]; | |
uint32_t flag; | |
//Unless more than 64 bytes of global/static variables | |
//added/removed this will be saved | |
SaveableData data; | |
char dummy_2[64]; | |
}; | |
union { | |
UploadSafe us; | |
char data[sizeof(us)]; | |
} upload_safe __attribute__ ((section (".noinit"))); | |
//convenience accessor | |
#define permadata() upload_safe.us.data | |
//Must be unique 4 byte sequence across all static/global variables | |
#define FLAG 0xDEADBEEF | |
void restore_after_new_vars(){ | |
auto posend=&upload_safe.data[sizeof(upload_safe)]; | |
for(auto pos = &upload_safe.data[0]; pos<posend; pos++){ | |
if( (*(uint32_t*)(pos)) == FLAG){ | |
auto data=(*(SaveableData*)(pos+4)); | |
__builtin_memset(&upload_safe, 0, sizeof(upload_safe)); | |
upload_safe.us.flag = FLAG; | |
permadata() = data; | |
break; | |
} | |
} | |
if (upload_safe.us.flag != FLAG){ | |
__builtin_memset(&upload_safe, 0, sizeof(upload_safe)); | |
upload_safe.us.flag = FLAG; | |
} | |
} | |
void setup() { | |
restore_after_new_vars(); | |
if (upload_safe.us.flag == FLAG){ | |
permadata().update_counter++; | |
} | |
Serial.begin(115200); | |
Serial.print("uploads: ");Serial.println(permadata().update_counter); | |
} | |
void loop(){ | |
Serial.println (permadata().update_counter); | |
delay(1000); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment