IIC总线
IIC概述
IIC百科 SPI、UART、RS232、RS485、IIC 5种嵌入式经典通信总线协议精讲
IIC时序结构
Start
起始条件:SCL高电平期间,SDA从高电平切换到低电平
void I2C_Start(void)
{
I2C_SDA = 1;
I2C_SCL = 1;
I2C_SDA = 0;
I2C_SCL = 0;
}
Stop
终止条件:SCL高电平期间,SDA从低电平切换到高电平
void I2C_Stop(void)
{
I2C_SDA = 0;
I2C_SCL = 1;
I2C_SDA = 1;
}
发送一个字节
SCL低电平期间,主机将数据位一次放到SDA先上(高位在前) 拉高SCL电平,从机在SCL高电平期间读取数据位 如此循环8次即可读一个字节
void I2C_SendByte(unsigned char Byte)
{
unsigned char i;
for(i = 0; i < 8; i++){
I2C_SDA = Byte & (0x80 >> i);
I2C_SCL = 1;
I2C_SCL = 0;
}
}
接收一个字节
SCL低电平期间,从机将数据位依次放到SDA线上(高位在前) 拉高SCL,主机在SCL高电平时读取数据位 如此循环8次,即可接收一个字节(在接收前需要释放SDA,及SDA = 1)
unsigned char ReceiveByte(void)
{
unsigned char i, Byte = 0x00;
I2C_SDA = 1;
for(i = 0; i < 8; i++){
I2C_SCL = 1;
if(I2C_SDA){
Byte |= (0x80 >> i);
}
I2C_SCL = 0;
}
return Byte;
}
发送应答
在接收完一个字节后,主机在下一个时钟发送一位数据,0标识应答,1标识非应答
void I2C_SendAck(unsigned char AckBit)
{
I2C_SDA = AckBit;
I2C_SCL = 1;
I2C_SCL = 0;
}
接收应答
在发送完一个字节滞后,主机在下一个时钟接收一位数据,判断从机是否应答,0标识应答,1标识非应答(主机在接收前,需要释放SDA)
unsigned char I2C_ReceiveAck(void)
{
unsigned char AckBit;
I2C_SDA = 1;
I2C_SCL = 1;
AckBit = I2C_SDA;
I2C_SCL = 0;
return AckBit;
}
IIC数据帧
发送一帧数据
接收一帧数据
紫色部分为从机发送
AT24C02应用
void AT24C02_WriteByte(unsigned char WordAddress,Data)
{
I2C_Start();
I2C_SendByte(AT24C02_ADDRESS);
I2C_ReceiveAck();
I2C_SendByte(WordAddress);
I2C_ReceiveAck();
I2C_SendByte(Data);
I2C_ReceiveAck();
I2C_Stop();
}
unsigned char AT24C02_ReadByte(unsigned char WordAddress)
{
unsigned char Data;
I2C_Start();
I2C_SendByte(AT24C02_ADDRESS);
I2C_ReceiveAck();
I2C_SendByte(WordAddress);
I2C_ReceiveAck();
I2C_Start();
I2C_SendByte(AT24C02_ADDRESS|0x01);
I2C_ReceiveAck();
Data = I2C_ReceiveByte();
I2C_SendAck(1);
I2C_Stop();
return Data;
}
|