#include "i2c.h"
void delay(void) // 10us
{
unsigned char a,b;
for(b=1;b>0;b--)
for(a=2;a>0;a--);
}
void I2cStart() //起始信号
{
SDA=1;
delay();
SCL=1;
delay();
SDA=0;
delay();
SCL=0;
delay();
}
void I2cStop() //终止信号
{
SDA=0;
delay();
SCL=1;
delay();
SDA=1;
delay();
}
unsigned char I2cSendByte(unsigned char dat) //发送函数
{
unsigned char a=0,b;
for(a=0;a<8;a++)
{
SDA=dat>>7;
dat=dat<<1;
delay();
SCL=1; //高电平数据保持稳定
delay();
SCL=0; //低电平数据可以改变
delay();
}
SDA=1; //数据线和时钟线释放出来,等待从机应答
delay();
SCL=1;
while(SDA)
{
b++; //等待一段时间出去
if(b>200)
{
SCL=0;
delay();
return 0;//发送失败返回0
}
}
SCL=0;
delay();
return 1;//发送成功返回1
}
unsigned char I2cReadByte()
{
unsigned char a=0,dat=0;
SDA=1; //拉高,等待数据线数据
delay();
for(a=0;a<8;a++)
{
SCL=1; // 高电平数据保持稳定
delay();
dat<<=1;
dat|=SDA;
delay();
SCL=0;
delay();
}
return dat;
}
void At24c02Write(unsigned char addr,unsigned char dat)
{
I2cStart();
I2cSendByte(0xa0);
I2cSendByte(addr);
I2cSendByte(dat);
I2cStop();
}
unsigned char At24c02Read(unsigned char addr)
{
unsigned char num;
I2cStart();
I2cSendByte(0xa0);
I2cSendByte(addr);
I2cStart();
I2cSendByte(0xa1);
num=I2cReadByte();
I2cStop();
return num;
}