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