利用单片机的硬件I2C读取24C02具有更高的执行效率。代码更为精简。
1 I2C写数据
void I2CWrite(u8 sub, u8* ptr, u16 len)
{
do {
I2C_SendPacket(sub, ptr, len); //write data
while(i2c.busy); //till I2C is not work
} while(!i2c.ack);
}
u8 I2C_SendPacket(u8 sub, u8* ptr, u16 cnt)
{
u8 i;
i2c.opt = WR; //i2c option flag set to write
i2c.cnt = cnt; //number to send
i2c.sub = sub; //sub address
i2c.busy = true; //I2C operation starts
i2c.ack = false;
if ((sub % PAGESIZE) > 0) {
u8 temp = MIN((PAGESIZE - sub % PAGESIZE), i2c.cnt); //Need temp number of data, just right to the page address
if(I2C_SendBytes(sub, ptr, temp)) { //If WRITE successful
ptr += temp; //Point to the next page
i2c.cnt -= temp;
sub += temp;
}
if (i2c.cnt == 0) return true; //i2c.cnt = 0 means transmition complete
}
for (i = 0; i < (i2c.cnt / PAGESIZE); i++) {
if (I2C_SendBytes(sub, ptr, PAGESIZE)) { //Full page write
ptr += PAGESIZE; //Point to the next page
sub += PAGESIZE;
i2c.cnt -= PAGESIZE;
}
if (i2c.cnt == 0) return true;
}
if (i2c.cnt > 0) {
if (I2C_SendBytes(sub, ptr, i2c.cnt)) return true;
}
i2c.busy = false; //I2C operation ends
i2c.ack = true;
return false;
}
2 I2C读数据
void I2CRead(u8 sub, u8* ptr, u16 len)
{
do {
I2C_RcvPacket(sub, ptr, len); //read data
while(i2c.busy); //till I2C is not work
} while(!i2c.ack);
}
void I2C_RcvPacket(u8 sub, u8* ptr, u16 cnt)
{
i2c.busy = true; //I2C operation starts
i2c.ack = false;
i2c.sub = sub;
i2c.ptr = ptr;
i2c.cnt = cnt;
I2C_TXByte(i2c.sub); //Send sub address
I2C_RevBytes(); //receive bytes
I2C_GenerateSTOP(I2C1, ENABLE); //Stop transmission
while((I2C_GetITStatus(I2C1, I2C_IT_STOP_DET)) == 0); //Checks whether stop condition has occurred or not.
i2c.busy = false; //I2C operation ends
i2c.ack = true;
I2C_WaitEEready();
}
3 main函数
int main(void)
{
u8 temp,i;
InitSystick();
LED_Init();
/*
Use I2C1 Port to connect external I2C interface type EEPROM 24C02;
run Write and Read series bytes Data;
*/
I2C_Initialize(); //Initial I2C
I2CWrite(0x10, buffer0, 0x08); //Write 8 bytes from buffer0[128] to 0x10 of EEPROM
I2CRead(0x10, buffer1, 0x08); //Read 8 bytes from 0x10 of EEPROM to buffer1[128]
temp = 0;
for(i = 0; i < 0x08; i++) {
if((buffer0[i]) == (buffer1[i])) {
temp++;
}
}
while(1) {
LED1_TOGGLE();
if(temp < 0x08) {
delay_ms(100);
}
else {
delay_ms(500);
}
}
}
如果写入的数据与读取出来一致,则LED慢闪,否则LED快闪。