at24c512.c
来自「i2c 总线 at512读写程序」· C语言 代码 · 共 125 行
C
125 行
void I2cStop(void)
{
SDA=0;
SCL=1;
NOP;
SDA=1;
NOP;
SCL=0;
}
void I2cStart(void)
{
SCL=1;
SDA=1;
NOP;
SDA=0;
NOP;
SCL=0;
}
void I2cWriteByte(unsigned char wbyte)
{
unsigned char i;
for(i=0;i<8;i++)
{
wbyte<<=1;
if(CY)SDA=1;
else SDA=0;
NOP;
SCL=1;
NOP;
SCL=0;
}
SDA=1;
NOP;
SCL=1;
while(SDA);
SCL=0;
}
unsigned char I2cReadByte(void)
{
unsigned char i,rbyte;
for(i=8;i--;)
{
SCL=1;
rbyte<<=1;
if(SDA)rbyte++;
SCL=0;
}
return rbyte;
}
void I2cAck(bit ACK)
{
SDA=ACK;
NOP;
SCL=1;
NOP;
SCL=0;
SDA=1;
}
void EepromByteWrite(unsigned int addr,unsigned char wdata)
{
I2cStart();
I2cWriteByte(0xa0);
I2cWriteByte(*(char*)&addr);
I2cWriteByte(*(1+(char*)&addr));
I2cWriteByte(wdata);
I2cStop();
delay_ms(10);
}
unsigned char EepromByteRead(unsigned int addr)
{
unsigned char i;
I2cStart();
I2cWriteByte(0xa0);
I2cWriteByte(*(char*)&addr);
I2cWriteByte(*(1+(char*)&addr));
I2cStart();
I2cWriteByte(0xa1);
i=I2cReadByte();
I2cStop();
return i;
}
void delay_ms(unsigned char delaytimes)
{
unsigned char dely;
while(delaytimes--)
{
dely=154;
for (;--dely;);
}
}
unsigned char EepromSequentialWrite(unsigned int addr,unsigned char xdata *
buf,unsigned char len)
{
unsigned char i;
I2cStart();
I2cWriteByte(0xa0);
I2cWriteByte(*(char*)&addr);
I2cWriteByte(*(1+(char*)&addr));
for(i=0;i<len;i++)
{
I2cWriteByte(* buf++);
}
I2cStop();
return i;
}
unsigned char EepromSequentialRead(unsigned int addr,unsigned char xdata *
buf,unsigned char len)
{
unsigned char i;
I2cStart();
I2cWriteByte(0xa0);
I2cWriteByte(*(char*)&addr);
I2cWriteByte(*(1+(char*)&addr));
I2cStart();
I2cWriteByte(0xa1);
for(i=0;i<len;i++)
{
* buf++=I2cReadByte();
I2cAck(i==(len-1));
}
I2cStop();
return i;
}
⌨️ 快捷键说明
复制代码Ctrl + C
搜索代码Ctrl + F
全屏模式F11
增大字号Ctrl + =
减小字号Ctrl + -
显示快捷键?