Basic AVR EEPROM Tutorial
AVR microcontrollers have built-in EEPROM. EEPROM stands for Electrically Eraseable Programmable Read Only Memory. What is the point of EEPROM? Even when the microcontroller is turned off, any data stored in the EEPROM will remain. This is essential in data-logging projects, and storing settings a user can decide upon.
Step 1: Preparing your AVR microcontroller for EEPROM
The first thing we have to do is set the proper fuses. I will be using AVR Studio 4 with a MKII ISP programmer to set the fuses. Below is an image of the fuses tab where you can select fuses. Boxed in red is the EESAVE fuse - this makes sure your EEPROM data will be saved when you power on and off. Check the EESAVE fuse.
Directly below the EESAVE fuse is a pull-down menu to set the brown out detection level. BOD (Brown Out Detection) shuts down the microcontroller at a certain voltage. EEPROM gets messed up at low voltage levels, so set the BOD fuse to a voltage right under your normal operating voltage. Most AVR circuits run at about 5v, so select the 4.3v option. Remember to hit the "program" button at the bottom to program your fuses!
Step 2: Include
Now, in the code, we have to make sure we are using the EEPROM library. Put this at the top of the file where you will be writing and reading EEPROM :
Step 3: Write
Next is the code to actually write a byte to the EEPROM. Here is the method to do so:
eeprom_write_byte ((uint8_t*)<<location>>, <<byte to be written>>);
Look in your datasheet to see how many bytes of EEPROM you have. If your microcontroller has 2kb of EEPROM, <<location>> can be anything up to 2000. So for example, if we were to write the byte 64 to location 23 of the EEPROM, the code would look like this:
eeprom_write_byte ((uint8_t*) 23, 64);
Step 4: Read
To read data from the EEPROM, we will use this method:
uint8_t <<byte read>> = eeprom_read_byte((uint8_t*)<<location>>);
Where byte read is... the byte read, and location is the location of the byte in the EEPROM. For example, to read the byte we just wrote in step 3, we would do:
uint8_t byteRead = eeprom_read_byte((uint8_t*)23);
Now you know the basics of EEPROM - how to prepare you microcontroller, how to write a byte, and how to read a byte. There is a lot more to EEPROM than what this tutorial covers - I just skimmed the surface.