The Application

The example in the following erases or writes an EEPROM word. Consult the technical documentation for your derivative or CPU to adapt the example for your processor.

Note: Consult your technical documentation before initiating write operations to the EEPROM. Limits on the number of writes available vary depending on the device and manufacturer.
Listing: Erasing and Writing an EEPROM


/*
 Definition of a variable in EEPROM

   The variable VAR is located in EEPROM.

   - It is defined in a user-defined segment EEPROM_DATA

   - In the PRM file, EEPROM_DATA is placed at address 0xD00.

Be careful, the EEPROM can only be written a limited number of times.

Running this application too frequently may surpass this limit and the 
EEPROM may be unusable afterwards.

*/

#include <hidef.h>

#include <stdio.h>

#include <math.h>

/* INIT register. */

typedef struct {

  union {

    struct {

      unsigned int   bit0:1;

      unsigned int   bit1:1;

      unsigned int   bit2:1;

      unsigned int   bit3:1;

      unsigned int   bit4:1;

      unsigned int   bit5:1;

      unsigned int   bit6:1;

      unsigned int   bit7:1;

    } INITEE_Bits;

    unsigned char INITEE_Byte;

  } INITEE;

} INIT;

volatile INIT INITEE @0x0012;

#define EEON INITEE.INITEE.INITEE_Bits.bit0

/* EEPROG register. */

volatile struct {

  unsigned int   EEPGM:1;

  unsigned int   EELAT:1;

  unsigned int   ERASE:1;

  unsigned int   ROW:1;

  unsigned int   BYTE:1;

  unsigned int   dummy1:1;

  unsigned int   dummy2:1;

  unsigned int   BULKP:1;

} EEPROG @0x00F3;

/* EEPROT register. */

volatile struct {

  unsigned int   BPROT0:1;

  unsigned int   BPROT1:1;

  unsigned int   BPROT2:1;

  unsigned int   BPROT3:1;

  unsigned int   BPROT4:1;

  unsigned int   dummy1:1;

  unsigned int   dummy2:1;

  unsigned int   dummy3:1;

} EEPROT @0x00F1;

#pragma DATA_SEG EEPROM_DATA

unsigned int VAR;

#pragma DATA_SEG DEFAULT

void EraseEEPROM(void) {

  /* Function used to erase one word in the EEPROM. */

  unsigned long int i;

  EEPROG.BYTE = 1;

  EEPROG.ERASE = 1;

  EEPROG.EELAT = 1;

  VAR = 0;

  EEPROG.EEPGM =1;

  for (i = 0; i<4000; i++) {

    /* Wait until EEPROM is erased. */

  }

  EEPROG.EEPGM = 0;

  EEPROG.EELAT = 0;

  EEPROG.ERASE = 0;

}

void WriteEEPROM(unsigned int val) {

  /* Function used to write one word in the EEPROM. */

  unsigned long int i;

  EraseEEPROM();

  EEPROG.ERASE = 0;

  EEPROG.EELAT = 1;

  VAR = val;

  EEPROG.EEPGM = 1;

  for (i = 0; i<4000; i++) {

  /* Wait until EEPROM is written. */

  }

  EEPROG.EEPGM = 0;

  EEPROG.EELAT = 0;

  EEPROG.ERASE = 0;

}

void func1(void) {

  unsigned int i;

  unsigned long int ll;

  i = 0;

    do

    {

    i++;

    WriteEEPROM(i);

    for (ll = 0; ll<200000; ll++) {

    }

  }

  while (1);

}

void main(void) {

  EEPROT.BPROT4 = 0;

  EEON=1;

  WriteEEPROM(0);

  func1();

}