The designers of the PIC microcontroller are very concerned that if a program goes wrong it does not damage the contents of the EEPROM. A program crashing is one thing, a program which crashes and overwrites its setup information is much worse. If the EEPROM is to be as reliable as the switches it is supposed to replace they have to make sure that you only change its contents when you intend to.

To achieve security they have added a special bit which needs to be set just before you write to the EEPROM. Furthermore, this bit is regularly cleared as the PICmicro runs, so that it cannot be left set for long periods of time. To make it even more difficult to accidently set the EEPROM you also have to send two consecutive values to a special register just before you write the value.

The chances of a program going wrong and performing all these actions in the correct sequence are thought to be so unlikely that it cannot happen by mistake (of course they dismiss the chances of a program going wrong and making stupid calls to an EEPROM writing function which does all the right things in order - but then there is nothing we can do about this anyway...)

I have seen similar techniques used to store special values in things like Real Time Clock chips to protect their internal values.

The upshot of this is that our program will have to twiddle the EEPROM in just the right way to get the data stored. The PICmicro uses a number of registers to control access to the EEPROM area. One of them is set with the address of the location to be read and written, and another is used to control the write and read actions.

Because the EEPROM is much slower to write to than ordinary memory (it can take up to 10 milliseconds to write a location) we need to write code which will wait for the write to complete. The PIC microcontroller's hardware can be used to generate interrupts when an EEPROM write has finished, but we are not going to use them. Indeed, we are going to turn interrupts off while we use the EEPROM, in case an interrupt is caused during our write operations and upsets the timing of the instructions.

I have packaged up the use of the EEPROM as two functions which we can use, one of them writes to it, and accepts an address in the EEPROM area and the value to be stored as parameters. The other function returns the value at a given address and is simply supplied with the address to read from.

The 16F1937 has 256 bytes of EEPROM memory available, other PIC microcontrollers have different amounts. The locations are numbered from 0 to 255.

On the right you can see the code which I wrote to read and write EEPROM.