关于I2C锁死的解决方案

void I2C_Again_Init(I2C_HandleTypeDef *hi2c)
{
    GPIO_InitTypeDef GPIO_InitStruct;
   
    if(hi2c->Instance==I2C2)
    {
        __HAL_RCC_I2C2_CLK_ENABLE();
      /* USER CODE BEGIN I2C2_MspInit 0 */

      /* USER CODE END I2C2_MspInit 0 */
     //A ½«SCLºÍSDAÇл»³ÉGPIOµÄODģʽ
        GPIO_InitStruct.Pin = I2C2_SCL_Pin|I2C2_SDA_Pin;
        GPIO_InitStruct.Mode = GPIO_MODE_OUTPUT_PP;
        GPIO_InitStruct.Speed = GPIO_SPEED_HIGH;
        HAL_GPIO_Init(GPIOB, &GPIO_InitStruct);
     
        HAL_GPIO_WritePin(I2C2_SCL_GPIO_Port, I2C2_SCL_Pin, GPIO_PIN_SET);
        HAL_GPIO_WritePin(I2C2_SDA_GPIO_Port, I2C2_SDA_Pin, GPIO_PIN_SET);
        
        hi2c->Instance->CR1 = I2C_CR1_SWRST;
        hi2c->Instance->CR1 = 0;
        
        HAL_Delay(2);
        
        if((hi2c->Instance->SR2 & I2C_SR2_BUSY) == I2C_SR2_BUSY)
        {
            HAL_Delay(2);
           // I2C_Again_Init(hi2c);  
          //  HAL_I2C_DeInit(hi2c);
            //return HAL_BUSY;
        }
                /**I2C2 GPIO Configuration    
        PB10     ------> I2C2_SCL
        PB3     ------> I2C2_SDA
        */
        
      
        uint8_t counter = 9 , ret = 0xde;
模式8位数据1位stop 唤醒slave
        while(counter > 0)
        {
            counter--;
                
           HAL_GPIO_WritePin(I2C2_SDA_GPIO_Port, I2C2_SCL_Pin, GPIO_PIN_RESET);
            DelayUs(10);
            HAL_GPIO_WritePin(I2C2_SDA_GPIO_Port, I2C2_SCL_Pin, GPIO_PIN_SET);
            DelayUs(10);   
        }
             ret = HAL_GPIO_ReadPin(I2C2_SDA_GPIO_Port, I2C2_SDA_Pin);

            if(HAL_GPIO_ReadPin(I2C2_SDA_GPIO_Port, I2C2_SDA_Pin) == GPIO_PIN_SET)
            {
//                break;
            }        
        
          hi2c->Instance->CR1 = I2C_CR1_SWRST;
            
         HAL_Delay(9);
         hi2c->Instance->CR1 = 0;
            
         HAL_Delay(9);
         HAL_I2C_DeInit(hi2c);
         MX_I2C2_Init();


//      /* USER CODE BEGIN I2C2_MspInit 1 */

//      /* USER CODE END I2C2_MspInit 1 */
   }
}   

你可能感兴趣的:(I2C)