最近做的项目中涉及了IIC总线的运用
IIC总线的运用范围十分广泛
写下博客记录
IIC总线延时 大于4.7us
#define Decoded_iic_delay() \
{\
Decoded_iic_DELAY_TMP=Decoded_iic_DELAY_VALUE;\
while(--Decoded_iic_DELAY_TMP);\
}
初始化
void Decoded_iic_init()
{
Decoded_iic_SCL=1;
Decoded_iic_delay();
Decoded_iic_SDA=1;
Decoded_iic_delay();
}
开始信号
void Decoded_iic_start()
{
Decoded_iic_SDA=1;
Decoded_iic_delay();
//Myputchar(Decoded_iic_SDA);
Decoded_iic_SCL=1;
Decoded_iic_delay();
//Myputchar(Decoded_iic_SCL);
Decoded_iic_SDA=0;
Decoded_iic_delay();
//Myputchar(Decoded_iic_SDA);
Decoded_iic_SCL=0;
Decoded_iic_delay();
//Myputchar(Decoded_iic_SCL);
}
写时序
void Decoded_iic_write(uchar dat)
{
uchar idata t=8;
while(t--)
{
Decoded_iic_SDA=(bit)(dat&0x80);
dat<<=1;
Decoded_iic_SCL=1;
Decoded_iic_delay();
Decoded_iic_SCL=0;
Decoded_iic_delay();
}
}
读时序
uchar Decoded_iic_read()
{
uchar dat=0;
uchar t=8;
//Myputchar(dat);
Decoded_iic_SDA=1;读之前SDA拉高
while(t--)
{
Decoded_iic_SCL=1;
Decoded_iic_delay();
dat <<= 1;一定要先移位后读 如果先读后移位会挤掉最高位
if(Decoded_iic_SDA)
{
dat |= 0x01;
}
Decoded_iic_SCL=0;
Decoded_iic_delay();
}
return dat;
}
获取ACK
bit Decoded_iic_getack()
{
bit ack;
Decoded_iic_SDA=1;SDA为高释放总线
Decoded_iic_delay();
Decoded_iic_SCL=1;
Decoded_iic_delay();
ack=Decoded_iic_SDA;
Decoded_iic_SCL=0;
Decoded_iic_delay();
return ack;
}
发送ACK
void Decoded_iic_putack(bit ack)
{
Decoded_iic_SDA=ack;
Decoded_iic_SCL=1;
Decoded_iic_delay();
Decoded_iic_SCL=0;
Decoded_iic_delay();
}
结束信号
void Decoded_iic_stop()
{
uint t=Decoded_iic_WAIT_VALUE;
Decoded_iic_SDA=0;
Decoded_iic_delay();
Decoded_iic_SCL=1;
Decoded_iic_delay();
Decoded_iic_SDA=1;
Decoded_iic_delay();
while(t--);
}
综合发送
bit Decoded_iic_puts(unsigned char SlaveAddr,uchar *dat,unsigned int Length)
{
if ( Length == 0 ) return 0;
Decoded_iic_start();
Decoded_iic_write(SlaveAddr);发送地址
if ( Decoded_iic_getack() )
{
Decoded_iic_stop();
return 1;
}
发送数据
do
{
Decoded_iic_write(*dat++);
if ( Decoded_iic_getack() )
{
//Myputchar('c');
break;
}
} while ( --Length != 0 );
Decoded_iic_stop();
if ( Length == 0 )
{
//Myputchar('a');
return 0;
}
else
{
//Myputchar('b');
return 1;
}
}
综合接收数据
bit Decoded_iic_gets(unsigned char SlaveAddr,uchar *dat,unsigned int Length)
{
if(!Length)
return 0;
Decoded_iic_start();
Decoded_iic_write(SlaveAddr+1);发送地址+1 +1是读的意思
if(Decoded_iic_getack())
{
Decoded_iic_stop();
return 1;
}
for (;;)
{
*dat++ = Decoded_iic_read();
if ( --Length == 0 )
{
Decoded_iic_putack(1);发送非ACK
break;
}
Decoded_iic_putack(0);发送ACK
}
//接收完毕,停止I2C总线,并返回结果
Decoded_iic_stop();
return 0;
}