📄 i2c.c
字号:
/*****************************************************************
*文件名:I2C.c
*描述:提供I2C的底层驱动,可选的400K或100K速度。
*******************************************************************/
#define I2C_C
#include "I2C.h"
CONST uchar cucBit[] = {0x80, 0x40, 0x20, 0x10, 0x08, 0x04, 0x02, 0x01};
/******************************************************************
*函数性质:私有
*入口:无
*出口:无
*功能:实现延时功能
********************************************************************/
static void DelayIntr(void)
{
#if I2C_SPEED == I2C_100K
NOP();NOP();NOP();NOP();
#endif
}
/*****************************************************************
*函数性质:公共
*入口:无
*出口:无
*功能:启动I2C。
********************************************************************/
void I2cStart(void)
{
SET_SCL();
SET_SDA();
DelayIntr();
CLR_SDA();
DelayIntr();
CLR_SCL();
}
/***********************************************************************
*函数性质:公共
*入口:无
*出口:无
*功能:停止I2C。
******************************************************************/
void I2cStop(void)
{
CLR_SCL();
CLR_SDA();
DelayIntr();
SET_SCL();
DelayIntr();
SET_SDA();
}
/*****************************************************************
*函数性质:公共
*入口:无
*出口:应答标志,true:检测到应答标志,false:无应答标志
*功能:检测从机的应答标志
****************************************************************/
bool WaitAck(void)
{
uchar ucErrTime = 255; //因故障接收方无ACK,超时值。
CLR_SCL();
SET_SDA();
DelayIntr();
SET_SCL();
DelayIntr();
while(READ_SDA())
{
ucErrTime--;
if (ucErrTime == 0)
{
I2cStop();
return false;
}
}
CLR_SCL();
return true;
}
/******************************************************************
*函数性质:公共
*入口:无
*出口:无
*功能:发送应答标志
******************************************************************/
void SendAck(void)
{
CLR_SCL();
CLR_SDA();
DelayIntr();
SET_SCL();
DelayIntr();
CLR_SCL();
}
/*****************************************************************
*函数性质:公共
*入口:无
*出口:无
*功能:发送非应答标志
*****************************************************************/
void SendNotAck(void)
{
CLR_SCL();
SET_SDA();
DelayIntr();
SET_SCL();
DelayIntr();
CLR_SCL();
}
/******************************************************************
*函数性质:公共
*入口:待发送的字符
*出口;发送成功标志,true 发送成功 false 发送失败
*功能:向I2C接口发送一个字符
******************************************************************/
bool I2cSend(uchar ucData)
{
uchar i;
for (i = 0; i < 8; i++)
{
CLR_SCL();
DelayIntr();
if ( (ucData & cucBit[i]) != 0)
{
SET_SDA();
}
else
{
CLR_SDA();
}
DelayIntr();
SET_SCL();
DelayIntr();
}
CLR_SCL();
return true;
}
/********************************************************************
*函数性质:公共
*入口:无
*出口:从I2C接口接收到的数据
*功能:从I2C接口接收一个数据。
********************************************************************/
uchar I2cReceive(void)
{
uchar ucData = 0x00;
uchar i;
SET_SDA();
for ( i = 0; i < 8; i++)
{
CLR_SCL();
DelayIntr();
SET_SCL();
DelayIntr();
if (READ_SDA())
{
ucData |= cucBit[i];
}
}
CLR_SCL();
return ucData;
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -