数据有效性:
起始和终止信号时序:
设备地址:
写字节时序:
读数据时序:
函数模拟 IIC 总线 时序:
/**************************************/
/******模拟I2C总线操作函数*************/
/**************************************/
//延时函数
void Delay()
{ ; ; }
//初始化
void I2C_Init()
{
SDA = 1;
SCL = 1;
}
//起始信号
void I2C_Start()
{
SDA = 1;
Delay();
SCL = 1;
Delay();
SDA = 0;
Delay();
}
//终止信号
void I2C_Stop()
{
SDA = 0;
Delay();
SCL = 1;
Delay();
SDA = 1;
Delay();
}
//应答信号
void I2C_Acknowledge()
{
unsigned char i;
SCL = 1;
Delay();
while((SDA == 1) && (i<250)){ //在一定时间内等待应答信号
i++;
}
SCL = 0;
Delay();
}
//写一个字节
void I2C_WriteByte(unsigned char Data)
{
unsigned char i,temp;
temp = Data;
SCL = 0;
Delay();
for(i = 0;i < 8;i++){
temp = temp<<1;
SDA = CY; //CY为PSW寄存器的溢出位
Delay();
SCL = 1;
Delay();
SCL = 0;
Delay();
}
SDA = 1;
Delay();
}
//读一个字节
unsigned char I2C_ReadByte()
{
unsigned char i,temp,Data;
SCL = 0;
Delay();
SDA = 1;
Delay();
for(i = 0;i < 8;i++){
SCL = 1;
Delay();
temp = SDA;
Data = (Data<<1)|temp;
SCL = 0;
Delay();
}
return Data;
}
//在特定位置写一个字节数据
void I2C_WriteByteAt(unsigned char address,unsigned char Data)
{
I2C_Init();
I2C_Start();
I2C_WriteByte(0xa0);//写器件地址,最后一位表示数据方向
I2C_Acknowledge();
I2C_WriteByte(address);//写存储地址
I2C_Acknowledge();
I2C_WriteByte(Data);//写数据
I2C_Acknowledge();
I2C_Stop();
}
//从特定位置读一个字节数据
unsigned char I2C_ReadByteAt(unsigned char address)
{
unsigned char Data;
I2C_Init();
I2C_Start();
I2C_WriteByte(0xa0);//写器件地址,最后一位表示数据方向
I2C_Acknowledge();
I2C_WriteByte(address);//写存储地址
I2C_Acknowledge();
I2C_Start();
I2C_WriteByte(0xa1);//再次写器件地址,注意改变数据方向
I2C_Acknowledge();
Data = I2C_ReadByte();//读数据
I2C_Stop();
return Data;
}单片机模拟 IIC 总线与 EEPROM(AT24C02)通信,码迷,mamicode.com
单片机模拟 IIC 总线与 EEPROM(AT24C02)通信
原文地址:http://blog.csdn.net/crazy_xiaohe/article/details/24813389