帮忙看下 这个i2c有问题呢没?
void delay_us(__IO uint32_t nTime)
{
u16 i=0;
while(nTime--)
{
i=10; //×Ô¼º¶¨Òå
while(i--);
}
}
void I2C_INIT_1(void)
{
GPIO_InitTypeDef GPIO_InitStructure;
/* GPIOC Periph clock enable */
RCC_AHBPeriphClockCmd(RCC_AHBPeriph_GPIOA, ENABLE);
/* Configure PA5 and PA7 in output pushpull mode */
GPIO_InitStructure.GPIO_Pin =GPIO_Pin_4|GPIO_Pin_5;
GPIO_InitStructure.GPIO_Mode = GPIO_Mode_Out_OD;
//GPIO_InitStructure.GPIO_OType = GPIO_OType_PP;
GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;
//GPIO_InitStructure.GPIO_PuPd = GPIO_PuPd_NOPULL;
GPIO_Init(GPIOA, &GPIO_InitStructure);
// I2C_SCL_H;
// I2C_SDA_H;
GPIO_SetBits(GPIOA,GPIO_Pin_4);
GPIO_SetBits(GPIOA,GPIO_Pin_5);
}
void I2C_SDA_OUT(void)
{
GPIO_InitTypeDef GPIO_InitStructure;
GPIO_InitStructure.GPIO_Pin=GPIO_Pin_4;
GPIO_InitStructure.GPIO_Speed=GPIO_Speed_50MHz;
GPIO_InitStructure.GPIO_Mode=GPIO_Mode_Out_PP;
GPIO_Init(GPIOA,&GPIO_InitStructure);
}
void I2C_SDA_IN(void)
{
GPIO_InitTypeDef GPIO_InitStructure;
GPIO_InitStructure.GPIO_Pin=GPIO_Pin_4;
// GPIO_InitStructure.GPIO_Mode=GPIO_Mode_Out_PP;
GPIO_InitStructure.GPIO_Mode=GPIO_Mode_IPU;
GPIO_Init(GPIOA,&GPIO_InitStructure);
}
//²úÉúÆðʼÐźÅ
void I2C_Start(void)
{
I2C_SDA_OUT();
I2C_SDA_H;
I2C_SCL_H;
delay_us(5);
I2C_SDA_L;
delay_us(6);
I2C_SCL_L;
}
//²úÉúÍ£Ö¹ÐźÅ
void I2C_Stop(void)
{
I2C_SDA_OUT();
I2C_SCL_L;
I2C_SDA_L;
I2C_SCL_H;
delay_us(6);
I2C_SDA_H;
delay_us(6);
}
//Ö÷»ú²úÉúÓ¦´ðÐźÅACK
void I2C_Ack(void)
{
I2C_SCL_L;
I2C_SDA_OUT();
I2C_SDA_L;
delay_us(2);
I2C_SCL_H;
delay_us(5);
I2C_SCL_L;
}
//Ö÷»ú²»²úÉúÓ¦´ðÐźÅNACK
void I2C_NAck(void)
{
I2C_SCL_L;
I2C_SDA_OUT();
I2C_SDA_H;
delay_us(2);
I2C_SCL_H;
delay_us(5);
I2C_SCL_L;
}
//µÈ´ý´Ó»úÓ¦´ðÐźÅ
//·µ»ØÖµ£º1 ½ÓÊÕÓ¦´ðʧ°Ü
// 0 ½ÓÊÕÓ¦´ð³É¹¦
uint8_t I2C_Wait_Ack(void)
{
uint8_t tempTime=0;
I2C_SDA_IN();
I2C_SDA_H;
delay_us(1);
I2C_SCL_H;
delay_us(1);
while(GPIO_ReadInputDataBit(GPIOA,GPIO_Pin_4))
{
tempTime++;
if(tempTime>250)
{
I2C_Stop();
return 1;
}
}
I2C_SCL_L;
return 0;
}
//I2C ·¢ËÍÒ»¸ö×Ö½Ú
void I2C_Send_Byte(uint8_t txd)
{
uint8_t i=0;
I2C_SDA_OUT();
I2C_SCL_L;//ÀµÍʱÖÓ¿ªÊ¼Êý¾Ý´«Êä
for(i=0;i<8;i++)
{
if((txd&0x80)>0) //0x80 1000 0000
I2C_SDA_H;
else
I2C_SDA_L;
txd<<=1;
I2C_SCL_H;
delay_us(2); //·¢ËÍÊý¾Ý
I2C_SCL_L;
delay_us(2);
}
}
//I2C ¶Áȡһ¸ö×Ö½Ú
uint8_t I2C_Read_Byte(uint8_t ack)
{
uint8_t i=0,receive=0;
I2C_SDA_IN();
for(i=0;i<8;i++)
{
I2C_SCL_L;
delay_us(2);
I2C_SCL_H;
receive<<=1;
if(GPIO_ReadInputDataBit(GPIOA,GPIO_Pin_4))
receive++;
delay_us(1);
}
if(ack==0)
I2C_NAck();
else
I2C_Ack();
return receive;
}
void LED_WriteOneByte(uint8_t DEVID,uint8_t addr,uint8_t dt)
{
I2C_Start();
printf("dtÊý¾ÝÊÇ£º%d\r\n",dt);
printf("addrÊý¾ÝÊÇ£º%d\r\n",addr);
I2C_Send_Byte(DEVID);
I2C_Wait_Ack();
//I2C_Wait_Ack();
I2C_Send_Byte(addr);//Ë«×Ö½ÚÊÇÊý¾ÝµØÖ·µÍλ
//µ¥×Ö½ÚÊÇÊý¾ÝµØÖ·µÍλ
I2C_Wait_Ack();
I2C_Send_Byte(dt);
I2C_Wait_Ack();
I2C_Stop();
delay_ms(10);
}
|