软件模拟IIC稳定可靠

#define I2C_SCL_H Hal_Vic_GpioOutput(GPIO_IDX_10, 1) 
#define I2C_SCL_L Hal_Vic_GpioOutput(GPIO_IDX_10, 0)
#define I2C_SDA_H Hal_Vic_GpioOutput(GPIO_IDX_11, 1)
#define I2C_SDA_L Hal_Vic_GpioOutput(GPIO_IDX_11, 0)

#define SDA_STATUS Hal_Vic_GpioInput(GPIO_IDX_11)

#define I2C_WR 0x80    //地址+写
#define I2C_RD 0x81    //地址+读


void I2C_SDA_OUT(void){    }

void I2C_SDA_IN(void){    }

void I2C_Start(void)
{
I2C_SDA_OUT();
I2C_SDA_H;
delayI2C();
I2C_SCL_H;
delayI2C();
I2C_SDA_L;
delayI2C();      
I2C_SCL_L;
delayI2C();  

}

void I2C_Stop(void)
{
I2C_SDA_OUT();
I2C_SCL_L;
delayI2C();
I2C_SDA_L;
delayI2C();  
I2C_SCL_H;
delayI2C();
I2C_SDA_H;
delayI2C();

}

void I2C_Ack(void)
{
I2C_SCL_L;
I2C_SDA_OUT();
I2C_SDA_L;
delayI2C();
I2C_SCL_H;
delayI2C();
I2C_SCL_L;
delayI2C();
}

void I2C_NAck(void)
{
I2C_SCL_L;
I2C_SDA_OUT();
I2C_SDA_H;
delayI2C();
I2C_SCL_H;
delayI2C();
I2C_SCL_L;
delayI2C();

}

unsigned char I2C_Wait_Ack(void)
{
unsigned char tempTime=0;
I2C_SDA_IN();
I2C_SDA_H;
I2C_SCL_L;
delayI2C();
while(SDA_STATUS)
{
tempTime++;
if(tempTime>250)
{
I2C_Stop();
return 1;
}  
}
I2C_SCL_H;
delayI2C();
I2C_SCL_L;
delayI2C();
return 0;

}

void I2C_Send_Byte(unsigned char txd)
{
unsigned char i=0;
I2C_SDA_OUT();
I2C_SCL_L;
delayI2C();
for(i=0;i<8;i++)
{
if((txd&0x80)>0)
I2C_SDA_H;
else
I2C_SDA_L;
txd<<=1;
I2C_SCL_H;
delayI2C();
I2C_SCL_L;
delayI2C();
}

}

unsigned char I2C_Read_Byte(unsigned char ack)
{
   unsigned char i=0,receive=0;
   I2C_SDA_IN();
   for(i=0;i<8;i++)
   {
    I2C_SCL_L;
delayI2C();
I2C_SCL_H;
receive<<=1;
if(SDA_STATUS)
receive++;
delayI2C();
   }
I2C_SCL_L;
delayI2C();
if(ack==0)
I2C_NAck();
else
I2C_Ack();
return receive;

}


uint8_t Read_TouchKey_Data(void)
{
  uint8_t i,check=0;
  uint8_t packet[10]={0};

  I2C_Start();
  I2C_Send_Byte(I2C_WR);//I2C_WR   I2C_RD
  I2C_Wait_Ack();
  I2C_Send_Byte(0x02);//字节数
  I2C_Wait_Ack();
  I2C_Send_Byte(0x01);//指令
  I2C_Wait_Ack();
  I2C_Send_Byte(0x83);//校验
  I2C_NAck();
  I2C_Stop();
/////////////////////////////////////////////////////////////////////////
  delay_us(3);//

  I2C_Start();
  I2C_Send_Byte(I2C_RD);//I2C_WR   I2C_RD
  I2C_Wait_Ack();
  //delay_us(25);
  for(i=0;i<5;i++)
  {
    packet[i]=I2C_Read_Byte(1);
//    delayAck();
  }
  packet[5]=I2C_Read_Byte(0);
//  delayAck();

  I2C_Stop();

}











你可能感兴趣的:(嵌入式软件)