NerdKits - electronics education for a digital generation

You are not logged in. [log in]

NEW: Learning electronics? Ask your questions on the new Electronics Questions & Answers site hosted by CircuitLab.

Microcontroller Programming » Saving variables

July 27, 2010
by devinsbusiness
devinsbusiness's Avatar

When I declare my variables I assign values to them. In the project I am working on, the values of the variables can be changed by the use of pushbuttons. When I power off my project, then power it back on the values of my variables go back to what I had originally assigned them to be instead of what they last were after being adjusted by the pushbuttons. My question is, how do I set it up to where my MCU remembers the values of variables after they have been adjusted from the original declared values in the event of power outage? Thanks for any ideas Devin

July 27, 2010
by bretm
bretm's Avatar

Look up EEPROM in the Atmega data sheet. The Atmega168 has 512 bytes of EEPROM storage which retains its content when power is removed.

If you #include <avr/eeprom.h>, you can use the avr-libc routines for writing to and reading from EEPROM. See the documentation and this good tutorial. You can use functions such as eeprom_read_byte to read a byte, eeprom_read_word to read two bytes, eeprom_write_byte to write a byte, etc.

Note that the EEPROM only allows a limited number of read/write cycles, so when you store a value you should read it first and compare it with the value you want to write, and only write it if the value is different.

EEPROM will contain unknown values on a new chip, so you'll need to store some sort of indicator to tell whether you have good data or not. What I usually do is use a couple of bytes to store a known pattern, such as 0x12, 0x34, 0x56. If I've written to the EEPROM those values will be found, and if not, those bytes will contain something different.

A very sophisticated application will vary the location at which the content is stored in the EEPROM in order to distribute the write cycles over all of the EEPROM addresses in order to maximize the life of the chip.

Post a Reply

Please log in to post a reply.

Did you know that a motor's no-load current at a given voltage is much less than it's resistance would suggest? Learn more...