全部博文(685)
分类: 嵌入式
2015-03-05 11:12:06
#include
#include
#include
sbit SCK=0x91;//时钟线端口
sbit SDA=0x90;//数据线端口
#define I2C_Address 0xa0 //I2C芯片地址
#define nop _nop_()
#define NOP nop;nop;nop;nop;nop;nop//延时应大于4.7us
//开始信号
//在时钟线为高电平时,数据线由高向低跳变.
void StartI2C(void)
{ SCK=1;
SDA=1;
NOP;
SDA=0;
NOP;
SCK=0;
NOP;
}
//停止信号
//在时钟线为高电平时,数据线由低向高跳变.
void StopI2C(void)
{ SDA=0;
NOP;
SCK=1;
NOP;
SDA=1;
}
//发送一个字节.
bit SendChar(unsigned char SendData)
{ unsigned char i;
bit ACK;
for(i=0;i<8;i++)
{ if((SendData<
else SDA=0;
SCK=1;
NOP;
SCK=0;
NOP;
}
//发送一个字节后,读取来自I2C芯片的响应.
//即在发送完8个字节后,在第九个时钟内,SDA总线应为低电平,表示I2C芯片已经读取了数据.
//否则为高电平.即发送收败.
SDA=1;
SCK=1;
NOP;
ACK=SDA;
SCK=0;
NOP;
return ACK;
}
//在读取完来自I2C的8位数据后,发出读取正确位.
//即发送一个低电平,表示已经读取到来自I2C的数据,并允许I2芯片发送下一字节.
void ACK(void)
{ SDA=0;
NOP;
SCK=1;
NOP;
SCK=0;
}
//在读取完来自I2C的8位数据后,发送不响应位.
//即发送一个高电平,表示已经读取完来自I2C的数据,并且不允许I2C发送下一字节.
void NAK(void)
{
SDA=1;
NOP;
SCK=1;
NOP;
SCK=0;
}
//读入一个字节的数据.
unsigned char ReadChar(void)
{ unsigned char i,BackData;
BackData=0;
SDA=1;
for(i=0;i<8;i++)
{ SCK=1;
nop;nop;nop;
BackData=BackData<<1;
if(SDA)BackData++;
SCK=0;
}
return BackData;
}
//以下所有为测试使用...
//应注意,在读I2C芯片时,在发送完I2C片内地址后,
//一定要发送一个重开始信号,然后再发送读命令.
bit WriteI2C(unsigned char Address,unsigned char WriteData)
{ SENDSTART:
StartI2C();
if(SendChar(I2C_Address)) goto SENDSTART;
SENDADD:
if(SendChar(Address)){StartI2C;goto SENDADD;}
SENDDATA:
if(SendChar(WriteData)){StartI2C;goto SENDDATA;}
if(SendChar(WriteData)){StartI2C;goto SENDDATA;}
StopI2C();
return 0;
}
unsigned char ReadI2C(unsigned char Address)
{ unsigned char BackData;
ReadSTART:
StartI2C();
if(SendChar(I2C_Address)) goto ReadSTART;
ReadADD:
if(SendChar(Address)){StartI2C;goto ReadADD;}
ReadSTART2:
StartI2C();
if(SendChar(I2C_Address+1)) goto ReadSTART2;
BackData=ReadChar();
ACK();
BackData=ReadChar();
NAK();
StopI2C();
return BackData;
}
void Delay(unsigned int ms)
{ unsigned int i,j;
for(i=0;i
}
void main(void)
{ bit j;
unsigned char i,BackData=0;
unsigned char Address=0x00,ReadData=0x00;
while(1)
{ ResetI2C;
ReadData=ReadI2C(Address);
ReadData++;
Delay(5);
WriteI2C(Address,ReadData);
Delay(5);
Address++;Address++;
}
}