/*功能:在51单片机上用C语言实现I2C总线功能*/
/*下面的代码是基于51单片机P1口模拟I2C总线。*/
/*电平模拟函数和基本读写函数
voidIIC_Start(void);
voidIIC_Stop(void);
voidSEND_0(void);
voidSEND_1(void);
bitCheck_Acknowledge(void);
voidWrite_Byte(ucharb)reentrant;
bitWrite_N_Bytes(uchar*buffer,ucharn)reentrant;
bitRead_N_Bytes(ucharSlaveAdr,ucharn,uchar*buffer);
ucharRead_Byte(void)reentrant;
*/
#include<string.h>
#include<reg52.h>
#include<intrins.h>
#include"aiic_51.h"
sbitSCL=P1^6;
sbitSDA=P1^7;
voidDELAY(uintt)
{
while(t!=0)
t--;
}
voidIIC_Start(void)
{
//启动I2C总线的函数,当SCL为高电平时使SDA产生一个负跳变
SDA=1;
SCL=1;
DELAY(DELAY_TIME);
SDA=0;
DELAY(DELAY_TIME);
SCL=0;
DELAY(DELAY_TIME);
}
voidIIC_Stop(void)
{
//终止I2C总线,当SCL为高电平时使SDA产生一个正跳变
SDA=0;
SCL=1;
DELAY(DELAY_TIME);
SDA=1;
DELAY(DELAY_TIME);
SCL=0;
DELAY(DELAY_TIME);
}
voidSEND_0(void)
{
//发送0,在SCL为高电平时使SDA信号为低
SDA=0;
SCL=1;
DELAY(DELAY_TIME);
SCL=0;
DELAY(DELAY_TIME);
}
voidSEND_1(void)
{
//发送1,在SCL为高电平时使SDA信号为高
SDA=1;
SCL=1;
DELAY(DELAY_TIME);
SCL=0;
DELAY(DELAY_TIME);
}
bitCheck_Acknowledge(void)
{
//发送完一个字节后检验设备的应答信号
SDA=1;
SCL=1;
DELAY(DELAY_TIME/2);
F0=SDA;
DELAY(DELAY_TIME/2);
SCL=0;
DELAY(DELAY_TIME);
if(F0==1)
returnFALSE;
returnTRUE;
}
voidWrite_Byte(ucharb)reentrant
{
//向IIC总线写一个字节
uchari;
for(i=0;i<8;i++)
if((b<<i)&0x80)
SEND_1();
else
SEND_0();
}
bitWrite_N_Bytes(uchar*buffer,ucharn)reentrant
{
//向I2C总线写n个字节
uchari;
IIC_Start();
for(i=0;i<n;i++)
{
Write_Byte(buffer[i]);
if(!Check_Acknowledge())
{
IIC_Stop();
return(i==n);
}
}
IIC_Stop();
returnTRUE;
}
ucharRead_Byte(void)reentrant
{
//从I2C总线读一个字节
ucharb=0,i;
for(i=0;i<8;i++)
{
SDA=1;//释放总线
SCL=1;//接受数据
DELAY(10);
F0=SDA;
DELAY(10);
SCL=0;
if(F0==1)
{
b=b<<1;
b=b|0x01;
}
else
b=b<<1;
}
returnb;
}
bitRead_N_Bytes(ucharSlaveAdr,ucharn,uchar*buffer)
{
//从I2C总线读n个字节
uchari;
IIC_Start();
Write_Byte(SlaveAdr);//向总线发送接收器地址
if(!Check_Acknowledge())//等待接收器应答信号
returnFALSE;
for(i=0;i<n;i++)
{
buffer[i]=Read_Byte();
if(i!=n)
SEND_0();//发送应答
else
SEND_1();//发送非应答
}
IIC_Stop();
returnTRUE;
}