一、写数据
unsigned char I2CWriteByte(unsigned int mem_addr,unsigned char*DDATAp,unsigned int count) { u8 i = 0;unsigned int Timer_1ms; for(i=0;i<count;i++) { I2cStart2(); I2cSend2(0xA0); //发送写命令 WaitAck2(); I2cSend2(mem_addr+i); //发送写入的地址 WaitAck2(); I2cSend2(DDATAp[i]); WaitAck2(); I2cStop2(); //发送停止信号 Timer_1ms=0xFFFF; while(Timer_1ms--) { __NOP(); } } }
以上是IIC写数据命令,注意,如果count超过8个,每次写一个字节都需要从I2cStart2()开始,如果从写Address开始循环,数据会出错,因为AT24C02每页有8个字节;
写数据代码技巧,这是看一个开发板的例子
const unsigned char cucBit2[] = {0x80, 0x40, 0x20, 0x10, 0x08, 0x04, 0x02, 0x01};
void I2cSend2(unsigned char ucData2) { unsigned char IIC_i; SDA_Out();//设置为输出 CLR_SCL2(); for (IIC_i=0;IIC_i<8;IIC_i++) { if ( (ucData2 & cucBit2[IIC_i]) != 0) { SET_SDA2(); } else { CLR_SDA2(); } DelayIntr2(2); SET_SCL2(); DelayIntr2(2); CLR_SCL2(); DelayIntr2(2); }; }
注意ucData2 & cucBit2[IIC_i]一行,这种方式可以代替移位。
二、读数据
需要注意,需要两个START信号
参考http://www.eefocus.com/stm3222/blog/16-10/393817_4e6f0.html