单片机模拟I2C总线及24C02读写实例(c源代码),24C02 read / write process
关键字:单片机模拟I2C总线及24C02读写实例(c源代码)
void Write_One_Byte(char addr,char thedata) { bit acktemp=1; /*write a byte to mem*/ I2C_Start(); WriteI2CByte(0xa0); acktemp=Check_Acknowledge(); WriteI2CByte(addr);/*address*/ acktemp=Check_Acknowledge(); WriteI2CByte(thedata);/*thedata*/ acktemp=Check_Acknowledge(); I2C_Stop(); } void Write_A_Page(char *buffer,char addr) { bit acktemp=1; bit wrtmp; int i; /*write a page to at24c02*/ I2C_Start(); WriteI2CByte(0xa0); acktemp=Check_Acknowledge(); WriteI2CByte(addr);/*address*/ acktemp=Check_Acknowledge(); for(i=0;i<7;i++) { WriteI2CByte(buffer[i]); if(!Check_Acknowledge()) { I2C_Stop(); } }
I2C_Stop();
} char Read_One_Byte(char addr) { bit acktemp=1; char mydata; /*read a byte from mem*/ I2C_Start(); WriteI2CByte(0xa0); acktemp=Check_Acknowledge(); WriteI2CByte(addr);/*address*/ acktemp=Check_Acknowledge(); I2C_Start(); WriteI2CByte(0xa1); acktemp=Check_Acknowledge();
mydata=ReadI2CByte(); acktemp=Check_Acknowledge(); return mydata; I2C_Stop(); } void Read_N_Bytes(char *buffer,char n,char addr) { bit acktemp=1; int i=0; /*read 8 bytes from mem*/ I2C_Start(); WriteI2CByte(0xa0); acktemp=Check_Acknowledge(); WriteI2CByte(addr);/*address*/ acktemp=Check_Acknowledge(); I2C_Start(); WriteI2CByte(0xa1); acktemp=Check_Acknowledge();
for(i=0;i { buffer[i]=ReadI2CByte(); if(i!=n-1) SEND_0(); /*发送应答*/ else SEND_1(); /*发送非应答*/ } I2C_Stop(); }
void main() { int i; char mybyte; char myarray[8]; char myarray2[8]; char rdarray[16]; for(i=0;i<8;i++) { myarray[i]=i; myarray2[i]=i+0x08; } Write_One_Byte(0x20,0x28); Write_A_Page(myarray,0x10); Write_A_Page(myarray2,0x18); mybyte=Read_One_Byte(0x20); Read_N_Bytes(rdarray,16,0x10); }
|