-
Notifications
You must be signed in to change notification settings - Fork 0
/
eeprom_workaround.c
55 lines (45 loc) · 2.44 KB
/
eeprom_workaround.c
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
//! @brief Reads a single byte of data from the EEPROM.
//! @param address The EEPROM address to write the data to (note that not all
//! 16-bits of this variable may be supported).
//! @returns The byte of data read from EEPROM.
//! @warning This function does not return until read operation is complete.
unsigned char Eeprom_ReadByte(unsigned int address)
{
// Set address registers
EEADRH = (unsigned char)(address >> 8);
EEADR = (unsigned char)address;
EECON1bits.EEPGD = 0; // Select EEPROM Data Memory
EECON1bits.CFGS = 0; // Access flash/EEPROM NOT config. registers
EECON1bits.RD = 1; // Start a read cycle
// A read should only take one cycle, and then the hardware will clear
// the RD bit
while(EECON1bits.RD == 1);
return EEDATA; // Return data
}
//! @brief Writes a single byte of data to the EEPROM.
//! @param address The EEPROM address to write the data to (note that not all
//! 16-bits of this variable may be supported).
//! @param data The data to write to EEPROM.
//! @warning This function does not return until write operation is complete.
void Eeprom_WriteByte(unsigned int address, unsigned char data)
{
// Set address registers
EEADRH = (unsigned char)(address >> 8);
EEADR = (unsigned char)address;
EEDATA = data; // Write data we want to write to SFR
EECON1bits.EEPGD = 0; // Select EEPROM data memory
EECON1bits.CFGS = 0; // Access flash/EEPROM NOT config. registers
EECON1bits.WREN = 1; // Enable writing of EEPROM (this is disabled again after the write completes)
// The next three lines of code perform the required operations to
// initiate a EEPROM write
EECON2 = 0x55; // Part of required sequence for write to internal EEPROM
EECON2 = 0xAA; // Part of required sequence for write to internal EEPROM
EECON1bits.WR = 1; // Part of required sequence for write to internal EEPROM
// Loop until write operation is complete
while(PIR2bits.EEIF == 0)
{
continue; // Do nothing, are just waiting
}
PIR2bits.EEIF = 0; //Clearing EEIF bit (this MUST be cleared in software after each write)
EECON1bits.WREN = 0; // Disable write (for safety, it is re-enabled next time a EEPROM write is performed)
}