|
|
代碼如下
#include<i2.h>
void Delay10us() //@11.0592MHz
{
unsigned char i;
i=2;
while (--i);
}
void I2cStart()//I2c開始信號(hào)
{
SCL=1;//SCL在高電平時(shí)SDA從高電平轉(zhuǎn)為低電平就是開始信號(hào)
Delay10us();
SDA=1;
Delay10us();//保持狀態(tài)時(shí)間要大于4.7us以便讀取
SDA=0;
Delay10us();//保持狀態(tài)時(shí)間要大于4us以便讀取
SCL=0;//結(jié)束后恢復(fù)初始狀態(tài)
Delay10us();
}
void I2cStop()//I2c結(jié)束信號(hào)
{
SCL=1;//SCL在高電平時(shí)SDA從低電平轉(zhuǎn)為高電平就是結(jié)束信號(hào)
Delay10us();
SDA=0;
Delay10us();//保持狀態(tài)時(shí)間要大于4.7us以便讀取
SDA=1;
Delay10us();//保持狀態(tài)時(shí)間要大于4us以便讀取
SCL=0;//結(jié)束后恢復(fù)初始狀態(tài)
Delay10us();
}
u8 I2cSendBaty(u8 dat)//發(fā)送一個(gè)字節(jié)的數(shù)據(jù)
{
//SCL在高電平時(shí)讀取SDA數(shù)據(jù)在低電平時(shí)允許改變SDA數(shù)據(jù)改變
u8 i,j=0,k=0;
SCL=0;
for(i=0;i<8;i++)
{
j=dat>>(7-i);
SDA=j%2;
Delay10us();
SCL=1;//開始讀取數(shù)據(jù)
Delay10us();
SCL=0;
}
SDA=1;//開始檢測(cè)從機(jī)是否接收完成
Delay10us();
SCL=1;
while(SDA)//判斷SDA狀態(tài)(低電平時(shí)說明接收完成)
{
k++;
if(k>200)//超時(shí)判斷
{
SDA=0;
Delay10us();
return 0;//返回接收失敗
}
}
SCL=0;
Delay10us();
return 1;//返回接收完成
}
u8 I2cReadBaty()//讀取一個(gè)字節(jié)的數(shù)據(jù)
{
u8 i,dat=0;
SDA=1;
Delay10us();
for(i=0;i<8;i++)
{
SCL=1;
Delay10us();
dat<<=1;
dat|=SDA;
Delay10us();
SCL=0;
Delay10us();
}
return dat;
}
void At24c02Write(u8 Chip_addr,u8 M_addr,u8 dat)//IC芯片寫入數(shù)據(jù)
{
I2cStart();//數(shù)據(jù)寫入開始
I2cSendBaty(Chip_addr);//發(fā)送儲(chǔ)存芯片地址
I2cSendBaty(M_addr);//發(fā)送儲(chǔ)存芯片儲(chǔ)存地址
I2cSendBaty(dat);//發(fā)送儲(chǔ)存數(shù)據(jù)
I2cStop();//I2c結(jié)束信號(hào)
}
u8 At24c02Read(u8 Chip_addr,u8 M_addr,u8 dat)//IC芯片讀取數(shù)據(jù)
{
u8 ret=0;
I2cStart();//數(shù)據(jù)寫入開始
I2cSendBaty(Chip_addr);//發(fā)送儲(chǔ)存芯片地址
I2cSendBaty(M_addr);//發(fā)送儲(chǔ)存芯片儲(chǔ)存地址
I2cStart();//數(shù)據(jù)寫入開始
I2cSendBaty(Chip_addr+1);//發(fā)送儲(chǔ)存芯片地址
ret= I2cReadBaty();//讀取一個(gè)字節(jié)的數(shù)據(jù)
I2cStop();//I2c結(jié)束信號(hào)
return ret;
} |
|