Saving & keeping variables.
It would be very nice to make the DDS start up where we left it. To achieve this we have to look into the memory capacity of the Arduino. The Atmega328 chip has the following amount of memory:
- Flash: 32k
- SRAM: 4k
- EEPROM: 1k
The Atmega2560 looks like this:
- Flash: 256k
- SRAM: 8k
- EEPROM: 4k
Flash memory is where the sketch resides. SRAM is where the Arduino handles your variables during runtime. Flash-memory is persistent and holds the sketch which stays onboard even after you power off. SRAM however is volatile and that is why the actual state of the variables in your sketch is not stored. EEPROM is the place to keep information for long time storage after power off.
Luckily there is a library out there. EEPROM it is called and luckily it was installed with the Arduino IDE.
EEPROM provides us with two sets of methods to access memory:
- ‘write’ ‘read’
- ‘put’ ‘get’
The first set operates on a byte-by-byte basis: i.e one way or the other you have to split your variables into bytes before writing them to EEPROM. Byte by byte – address by address.
The second set of methods handles things for you, as it distinguishes between the different types of data and allocates the required space. But YOU must be very careful handling the addresses in such a way, that no variable interferes with other variables. There is no protection of cells in EEPROM, so YOU have to take care of things. In this DDS-sketch each of the persistent variables is allocated 8 bytes. By me!
An example can be seen here:
For the fun of it, do change line 12 and line 22 like below. Upload the sketch and watch the result.
Things go terrible wrong!