Persistent Global refers to a variable that retains its value even after the end of its scope or program termination. This concept is commonly used in embedded systems programming or when working with data that should not be lost during power outages.
Here are some code examples using cpp Persistent Global:
Example 1:
#include
int persistent_global_variable = 0;
void setup() { int value_read = EEPROM.read(0); // read value from EEPROM if (value_read != -1) { // if value is not -1 (uninitialized) persistent_global_variable = value_read; // set the value of the persistent variable } else { // initialize the value persistent_global_variable = 10; // save the value to EEPROM EEPROM.write(0, persistent_global_variable); } }
void loop() { // use the persistent variable persistent_global_variable++; Serial.println(persistent_global_variable); // save the value to EEPROM EEPROM.write(0, persistent_global_variable); delay(1000); }
This code initializes a persistent global variable and stores its value to the EEPROM. The program will automatically load the value from the EEPROM at startup and update it every second. The EEPROM library is used to read and write the value to the storage.
Example 2:
#include
int EEMEM persistent_global_variable = 0;
void main() { // read the value from the EEPROM int value_read = eeprom_read_word(&persistent_global_variable); if (value_read == -1) { // if the value is uninitialized // initialize the value eeprom_write_word(&persistent_global_variable, 20); value_read = 20; } while (1) { // use the persistent variable value_read++; // save the value to the EEPROM eeprom_write_word(&persistent_global_variable, value_read); _delay_ms(1000); } }
This code initializes a persistent global variable by storing its value to the EEPROM using the AVR library. The program will automatically load the value at startup and update it every second.
The package libraries used in these examples are "EEPROM.h" and "avr/eeprom.h", respectively. These libraries provide functions for reading and writing to the EEPROM of the microcontroller.
C++ (Cpp) Persistent::Global - 30 examples found. These are the top rated real world C++ (Cpp) examples of Persistent::Global extracted from open source projects. You can rate examples to help us improve the quality of examples.