-
Notifications
You must be signed in to change notification settings - Fork 0
/
eeprom.c
101 lines (79 loc) · 1.94 KB
/
eeprom.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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
#include "i2c.h"
#include "eeprom.h"
#define BlockSelect(x) x >= 0x8000 ? 1 : 0
byte __inline__ EEPROMGetControlByte(uint16 eepromAddress, uint16 slaveAddress, byte readMode)
{
return (0xA << 4 | ((BlockSelect(eepromAddress) & 1) << 3) | ((slaveAddress & 3) << 1) | (readMode & 1));
}
void EEPROMWriteControlByte(uint16 eepromAddress, uint16 slaveAddress, byte readMode)
{
byte c = EEPROMGetControlByte(eepromAddress, slaveAddress, readMode);
I2CWriteByte(c);
}
void EEPROMWriteAddressBytes(uint16 eepromAddress)
{
/* High */
I2CWriteByte((eepromAddress >> 8) & 0xFF);
/* Low */
I2CWriteByte(eepromAddress & 0xFF);
}
void EEPROMReadBytes(
byte * buffer,
int count,
uint16 slaveAddress,
uint16 eepromAddress)
{
int i = 0;
I2C1ADD = slaveAddress;
I2CStart();
EEPROMWriteControlByte(eepromAddress, slaveAddress, 0);
EEPROMWriteAddressBytes(eepromAddress);
I2CStart();
EEPROMWriteControlByte(eepromAddress, slaveAddress, 1);
if (count > 1)
{
for (i = 0; i < count && i < 64; i++)
{
*(buffer + i) = I2CReadByte();
if ((i + 1) < count)
{
I2CAck();
}
else
{
I2CNack();
}
}
}
else
{
*buffer = I2CReadByte();
I2CNack();
}
I2CStop();
}
void EEPROMWriteBytes(
const byte * buffer,
int count,
uint16 slaveAddress,
uint16 eepromAddress)
{
int i = 0;
I2C1ADD = slaveAddress;
I2CStart();
EEPROMWriteControlByte(eepromAddress, slaveAddress, 0);
EEPROMWriteAddressBytes(eepromAddress);
if (count > 1)
{
for (i = 0; i < count && i < 64; i++)
{
I2CWriteByte(*(buffer + i));
}
}
else
{
I2CWriteByte(*buffer);
}
I2CStop();
__delay_ms(5);
}