#include"iom16v.h"
#define CLK_IO(x) (x?(DDRA|=0X01):(DDRA&=0XFE))
#define SDA_IO(x) (x?(DDRA|=0X02):(DDRA&=0XFD))
#define CLK(x) (x?(PORTA|=0X01):(PORTA&=0XFE))
#define SDA(x) (x?(PORTA|=0X02):(PORTA&=0XFD))
#define CLK_IN() (PINA&0X01)
#define SDA_IN() (PINA&0X02)
unsigned char flag =0;
void IIC_INIT(void)
{
CLK_IO(0);
SDA_IO(0);
SDA(0);
SDA(0);
}
/*****************************************
检测iic 开始信号 检测到返回一
*****************************************/
unsigned char CHECK_START(void)
{
if(CLK_IN()==0x01)
{
if((SDA_IN()==0x02)&&((flag&0x01)==0))
{
flag = 0x10;
}
if((SDA_IN()==0x00)&&((flag&0x10)==0x10))
{
flag = 0x01;
while(CLK_IN()==0x01);
return 1;
}
}
else flag = 0x00;
return 0;
}
/*********************************
检测是否结束iic结束返回一
*********************************/
unsigned char CHECK_stop(void)
{
if(CLK_IN()==0x01)
{
if((SDA_IN()==0x00)&&((flag&0x01)==0))
{
flag |= 0x20;
}
if((SDA_IN()==0x02)&&((flag&0x20)==0x20))
{
flag |= 0x02;
return 1;
}
}
else flag = 0x00;
return 0;
}
/************************************
IIC 从机接收总线数据
************************************/
unsigned char RECEIVE_DAT()
{
unsigned char count,dat;
count = 0;
do{
if(CLK_IN()==0x01)
{
if(SDA_IN()==0x02) dat|=0x01;
else dat&=0xfe;
while(CLK_IN()==0x01);
if(count<7)
dat =dat<<1;
count++;
}
}while(count<8);
SDA_IO(1);
SDA(0);
for(count=2;count>0;count--)
SDA(0);
SDA_IO(0);
return dat;
}
/********************************************
iic从机发送数据
********************************************/
unsigned char SEND_DAT(unsigned char dat)
{
unsigned char count;
SDA(1);
SDA_IO(1);
count = 0;
do{
if(CLK_IN()==0x00)
{
if(dat&0x80) SDA(1);
else SDA(0);
//if(count<7)
while(CLK_IN()==0x00);
dat =dat<<1;
count++;
}
}while(count<9);
SDA(0);
SDA_IO(0);
// while(CLK_IN()==0x00);//等低电平
while(CLK_IN()==0x00);//等高电平
if(SDA_IN()==0x02) return 0;//无应答
else return 1;
}
void main(void)
{
unsigned char count =0;
DDRB =0XFF;
DDRC =0XFF;
IIC_INIT();
while(1)
{
if(CHECK_START())
{
PORTB = RECEIVE_DAT();
//PORTB = RECEIVE_DAT();
//PORTB =0x55;
//count++;
//PORTB = RECEIVE_DAT();
}
PORTC++;
}
} |