📄 i2c.c
字号:
#include "I2C.h"
#include <intrins.h>
void Delay(unsigned int t) // t ms
{
unsigned int i,j;
for(i=0;i<t;i++)
{
for(j=0;j<1000;j++)
_nop_();
}
}
void I2C_Wait(void)
{
_nop_(); _nop_(); _nop_(); _nop_(); _nop_();_nop_(); _nop_(); _nop_(); _nop_(); _nop_();_nop_(); _nop_(); _nop_(); _nop_(); _nop_();
}
void I2C_Start(void) //当SCL为高时,SDA由高到低,开始,然后SCL到低
{
I2C_SDA = 1;
I2C_SCL = 1;
I2C_Wait();
I2C_SDA = 0;
I2C_Wait();
I2C_SCL = 0;
}
void I2C_Stop(void) //当SCL为高时,SDA由低到高
{
I2C_SDA = 0;
I2C_Wait();
I2C_SCL = 1;
I2C_Wait();
I2C_SDA = 1;
}
bit I2C_Send_Byte(uchar bytedata)
{
uchar data i;
bit ack;
for (i = 0; i < 8; i++)
{
if (bytedata & 0x80) I2C_SDA = 1;
else I2C_SDA = 0;
bytedata <<= 1;
I2C_Wait();
I2C_SCL = 1;
I2C_Wait();
I2C_SCL = 0;
I2C_Wait();
}
I2C_SDA = 1; //发送器件释放SDA线
I2C_Wait();
I2C_SCL = 1; //产生第九个脉冲的高电平
I2C_Wait();
ack = I2C_SDA; //接收从器件的确认位
I2C_SCL = 0;
I2C_Wait();
return ack;
}
uchar I2C_Receive_Byte(void)
{
uchar i;
uchar bytedata = 0;
for ( i = 0; i < 8; i++)
{
I2C_SCL = 1;
I2C_Wait();
bytedata <<= 1;
if (I2C_SDA) bytedata |= 0x01; //若SDA=1,则将接收到的数据加1(bit0设为1),否则但左移一位时就将bit0自动清0
I2C_SCL = 0;
I2C_Wait();
}
return bytedata;
}
void Send_Ack(bit ack)
{
I2C_SDA = ack;
I2C_SCL = 1;
I2C_Wait();
I2C_SCL = 0;
}
void I2C_Byte_Write(uchar sla,uchar addr,uchar bytedata)
{
uchar data i;
bit ack;
// Flag_Timeout = 1;
for(i = 0; i < 10; i++)
{
I2C_Start();
ack = I2C_Send_Byte(sla);
if (ack)
{
I2C_Stop();
continue;
}
ack = I2C_Send_Byte(addr);
if (ack)
{
I2C_Stop();
continue;
}
ack = I2C_Send_Byte(bytedata);
if (ack)
{
I2C_Stop();
continue;
}
I2C_Stop();
// Flag_Timeout = 0;
if(0 == ack) break;
}
Delay(10); //写入一个字节必须延迟10ms
}
uchar I2C_Byte_Read(uchar sla,uchar addr)
{
uchar bytedata;
I2C_Start();
I2C_Send_Byte(sla);
I2C_Send_Byte(addr);
I2C_Start();
I2C_Send_Byte(sla+1);
bytedata = I2C_Receive_Byte();
Send_Ack(1);
I2C_Stop();
return bytedata;
}
void I2C_Data_Write(uchar addr,uchar no,uchar *s)
{
uchar data i,j;
bit ack;
// Flag_Timeout = 1;
for(i = 0; i < 10; i++)
{
I2C_Start();
ack = I2C_Send_Byte(ZLG7290);
if (ack)
{
I2C_Stop();
continue;
}
ack = I2C_Send_Byte(addr);
if (ack)
{
I2C_Stop();
continue;
}
for(j=0;j<no;j++)
{
ack=I2C_Send_Byte(*s);
if (ack)
{
I2C_Stop();
continue;
}
s++;
}
I2C_Stop();
// Flag_Timeout = 0;
if(0 == ack) break;
}
Delay(10); //写入一个字节必须延迟10ms
}
/*void I2C_Data_Read(uchar suba,uchar no,uchar *s)
{
uchar data i,j;j=no;
I2C_Start(); //启动总线
I2C_Send_Byte(ZLG7290); //发送器件地址
I2C_Send_Byte(suba); //发送器件子地址
I2C_Start();
I2C_Send_Byte(ZLG7290+1);
for(i=0;i<j-1;i++)
{
*s++=I2C_Receive_Byte(); //接收数据
Send_Ack(0); //发送就答位
Delay(5);
}
*s=I2C_Receive_Byte();;
Send_Ack(1); //发送非应位
I2C_Stop(); //结束总线
} */
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -