📄 i2c.c
字号:
void I2cWait(void) //file://延/时,I2c大约30k/s
{
unsigned char i;
for(i=0;i<10;i++)
{
i=i;//_nop_();
}
}
void I2cStart(void) // file://起/始信号
{
SDA = 1;
SCL = 1;
I2cWait();
SDA = 0;
I2cWait();
SCL = 0;
}
void I2cStop(void) //file://停/止信号
{
SDA = 0;
I2cWait();
SCL = 1;
I2cWait();
SDA = 1;
I2cWait();
}
void SendAck(bit ack) // file://送/确认信号到slave
{
SDA = ack;
SCL = 1;
I2cWait();
SCL = 0;
}
bit I2cSendByte(unsigned char bytedata) //file://送/一字节数据到slave
{
unsigned char i;
bit ack;
for(i=0;i<8;i++)
{
if(bytedata & 0x80)
SDA = 1;
else
SDA = 0;
bytedata <<= 1;
I2cWait();
SCL = 1;
I2cWait();
SCL = 0;
I2cWait();
}
SDA = 1;
I2cWait();
SCL = 1;
I2cWait();
ack = SDA; // file://接/收确认信号:1,没收到应答;0,收到应答
SCL = 0;
I2cWait();
return ack;
}
unsigned char I2cReceiveByte(void) //file://接/收1字节数据
{
unsigned char i;
unsigned char bytedata = 0;
for(i=0;i<8;i++)
{
SCL = 1;
I2cWait();
bytedata <<= 1;
if(SDA)
{
bytedata |= 0x01;
}
SCL = 0;
I2cWait();
}
return bytedata;
}
unsigned char I2cByteRead(unsigned char device,unsigned char address)
{ //file://从/slave接收1字节数据
unsigned char bytedata;
I2cStart();
I2cSendByte(device);
I2cSendByte(0);
I2cSendByte(address);
I2cStart();
I2cSendByte(device|0x01);
bytedata = I2cReceiveByte();
SendAck(1);
I2cStop();
return bytedata;
}
void I2cByteWrite(unsigned char device,unsigned int address,unsigned char bytedata)
{ //file://将/数据写入指定slave的地址内
unsigned char i;
unsigned char addressh,addressl;
bit ack;
addressl = address&0xFF;
addressh = address>>8;
for(i=0;i<10;i++)
{
I2cStart();
ack = I2cSendByte(device);
if(ack==1)
{
I2cStop();
continue;
}
ack = I2cSendByte(addressh);
if(ack==1)
{
I2cStop();
continue;
}
ack = I2cSendByte(addressl);
if(ack==1)
{
I2cStop();
continue;
}
ack = I2cSendByte(bytedata);
if(ack==1)
{
I2cStop();
continue;
}
I2cStop();
if(ack==0) break; //file://正/常,跳出循环
}
// DelayX5ms(2);
}
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -