I2C总线协议程序
在使用的过程中一定要注意时序、时间的问题。
“i2c.h文件”
//I2C总线综合发送函数,向从机发送多个字节的数据
bit I2C_Puts(
unsigned char SlaveAddr,
unsigned int SubAddr,
unsigned char SubMod,
char *dat,
unsigned int Size
);
//I2C总线综合接收函数,从从机接收多个字节的数据
bit I2C_Gets
(
unsigned char SlaveAddr,
unsigned int SubAddr,
unsigned char SubMod,
char *dat,
unsigned int Size
);
#endif
================================================================================================
“i2c.c文件”
#include "I2C.h"
//定义延时变量,用于宏I2C_Delay()
unsigned char I2C_Delay_t;
#define I2C_Delay() {I2C_Delay_t = (I2C_DELAY_VALUE);while ( --I2C_Delay_t != 0 );}
void I2C_Start()
{
I2C_SDA = 1; I2C_Delay();
I2C_SCL = 1; I2C_Delay();
I2C_SDA = 0; I2C_Delay();
I2C_SCL = 0; I2C_Delay();
}
void I2C_Write(char dat)
{
unsigned char t = 8;
do
{
I2C_SDA = (bit)(dat & 0x80);
dat <<= 1;
I2C_SCL = 1; I2C_Delay();
I2C_SCL = 0; I2C_Delay();
} while ( --t != 0 );
}
char I2C_Read()
{
char dat;
unsigned char t = 8;
I2C_SDA = 1; //在读取数据之前,要把SDA拉高
do
{
I2C_SCL = 1;
I2C_Delay();
dat <<= 1;
if ( I2C_SDA ) dat |= 0x01;
I2C_SCL = 0;
I2C_Delay();
} while ( --t != 0 );
return dat;
}
bit I2C_GetAck()
{
bit ack;
//总线准备,接受应答
I2C_SDA = 1; I2C_Delay();
I2C_SCL = 1; I2C_Delay();
ack = I2C_SDA;
I2C_SCL = 0;
I2C_Delay();
return ack;
}