STM32F3 I2C读取数据

时间:2013-10-24 20:39:18

标签: embedded i2c stm32 stm32f4discovery

我正在使用STM32F373微控制器并编写了一个简单的函数来从总线i2c 1(PB7 PB6)上的MPU6050陀螺仪+加速器读取数据。 问题是,当我尝试读取传感器寄存器数据时 - 标志I2C_ISR_TXIS总是等于RESET(未设置)。 为什么会这样?

以下是有问题的源代码。

void i2c1_init(void)
{
  GPIO_InitTypeDef GPIO_InitStructure;
  I2C_InitTypeDef  I2C_InitStructure;

  RCC_I2CCLKConfig(RCC_I2C1CLK_SYSCLK);  

  RCC_APB1PeriphClockCmd(RCC_APB1Periph_I2C1, ENABLE);  
  RCC_AHBPeriphClockCmd(RCC_AHBPeriph_GPIOB, ENABLE);

  GPIO_PinAFConfig(GPIOB, GPIO_PinSource6, GPIO_AF_4);
  GPIO_PinAFConfig(GPIOB, GPIO_PinSource7, GPIO_AF_4);

  GPIO_InitStructure.GPIO_Mode = GPIO_Mode_AF;
  GPIO_InitStructure.GPIO_OType = GPIO_OType_OD;
  GPIO_InitStructure.GPIO_PuPd  = GPIO_PuPd_NOPULL;
  GPIO_InitStructure.GPIO_Speed = GPIO_Speed_50MHz;

  GPIO_InitStructure.GPIO_Pin = GPIO_Pin_6;
  GPIO_Init(GPIOB, &GPIO_InitStructure);

  GPIO_InitStructure.GPIO_Pin =  GPIO_Pin_7;
  GPIO_Init(GPIOB, &GPIO_InitStructure);

  I2C_DeInit(I2C1);
  I2C_InitStructure.I2C_Mode = I2C_Mode_I2C;  
  I2C_InitStructure.I2C_AnalogFilter = I2C_AnalogFilter_Enable;
  I2C_InitStructure.I2C_DigitalFilter = 0x00;
  I2C_InitStructure.I2C_Ack = I2C_Ack_Enable;
  I2C_InitStructure.I2C_AcknowledgedAddress = I2C_AcknowledgedAddress_7bit;
  I2C_InitStructure.I2C_Timing = 0xC062121F; 

  I2C_Init(I2C1, &I2C_InitStructure);  
  I2C_Cmd(I2C1, ENABLE);
}

uint8_t i2c_read(uint8_t DeviceAddr, uint8_t RegAddr, uint8_t* pBuffer, uint16_t len)
{    
  /* Test on BUSY Flag */
  uint32_t timeout = I2C_TIMEOUT;
  while(I2C_GetFlagStatus(I2C1, I2C_ISR_BUSY) != RESET)
  {
    if((timeout--) == 0) return 0;
  }    
  I2C_TransferHandling(I2C1, DeviceAddr, 1, I2C_SoftEnd_Mode, I2C_Generate_Start_Write);


  /* !!! Wait until TXIS flag is set !!! */
  timeout = I2C_TIMEOUT;
  while(I2C_GetFlagStatus(I2C1, I2C_ISR_TXIS) == RESET) // PROBLEM HERE!!!!!!!!!!!!!!!
  {
    if((timeout--) == 0) return 0;          
  }


  ....
  ....
}

1 个答案:

答案 0 :(得分:8)

好的,我发现了问题。标志I2C_ISR_TXIS没有得到,因为i2c上的设备没有响应发送的地址。需要将设备地址转换为7位。

(DeviceAddr & 0x7f) << 1