51單片機(jī)I2C總線協(xié)議的實(shí)現(xiàn)
#include
#include
sbit SDA=P1^0;// 將p1.0口模擬數(shù)據(jù)口
sbit SCL=P1^1;// 將p1.1口模擬時(shí)鐘口
#define NUM 10 // 接收和發(fā)送緩存區(qū)的深度
#define delayNOP(); {_nop_();_nop_();_nop_();_nop_();};
unsigned
unsignedcharidata receivebuf[NUM];// 數(shù)據(jù)接收緩沖區(qū)
bit bdata SystemError;// 從機(jī)錯(cuò)誤標(biāo)志位
//------------------------------------------------------------------------------------------------
// 函數(shù)名稱: iic_start()
// 函數(shù)功能: 啟動(dòng)I2C總線子程序
//------------------------------------------------------------------------------------------------
voidiic_start(void)
{ EA=0;//時(shí)鐘保持高,數(shù)據(jù)線從高到低一次跳變,I2C通信開始
SDA = 1;
SCL = 1;
delayNOP();// 延時(shí)5us
SDA = 0;
delayNOP();
SCL = 0;
}
//------------------------------------------------------------------------------------------------
// 函數(shù)名稱: iic_stop()
// 函數(shù)功能: 停止I2C總線數(shù)據(jù)傳送子程序
//------------------------------------------------------------------------------------------------
voidiic_stop(void)
{
SDA = 0;//時(shí)鐘保持高,數(shù)據(jù)線從低到高一次跳變,I2C通信停止
SCL = 1;
delayNOP();
SDA = 1;
delayNOP();
SCL = 0;
}
//------------------------------------------------------------------------------------------------
// 函數(shù)名稱: slave_ACK
// 函數(shù)功能: 從機(jī)發(fā)送應(yīng)答位子程序
//------------------------------------------------------------------------------------------------
voidslave_ACK(void)
{
SDA = 0;
SCL = 1;
delayNOP();
SDA = 1;
SCL = 0;
}
//------------------------------------------------------------------------------------------------
// 函數(shù)名稱: slave_NOACK
// 函數(shù)功能: 從機(jī)發(fā)送非應(yīng)答位子程序,迫使數(shù)據(jù)傳輸過程結(jié)束
//------------------------------------------------------------------------------------------------
voidslave_NOACK(void)
{
SDA = 1;
SCL = 1;
delayNOP();
SDA = 0;
SCL = 0;
}
//------------------------------------------------------------------------------------------------
// 函數(shù)名稱: check_ACK
// 函數(shù)功能: 主機(jī)應(yīng)答位檢查子程序,迫使數(shù)據(jù)傳輸過程結(jié)束
//------------------------------------------------------------------------------------------------
voidcheck_ACK(void)
{
SDA = 1;// 將p1.0設(shè)置成輸入,必須先向端口寫1
SCL = 1;
F0 = 0;
if(SDA == 1)// 若SDA=1表明非應(yīng)答,置位非應(yīng)答標(biāo)志F0
F0 = 1;
SCL = 0;
}
評(píng)論