本人在一个项目中使用了STM32F302C8T6这个芯片,碰到硬件I2C奇怪的问题,过程如下:
1、通过STM32CubeMX生成初始代码;
2、初始代码如下;
void HAL_I2C_MspInit(I2C_HandleTypeDef* hi2c)
{
GPIO_InitTypeDef GPIO_InitStruct;
if(hi2c->Instance==I2C2)
{
/* USER CODE BEGIN I2C2_MspInit 0 */
/* USER CODE END I2C2_MspInit 0 */
/**I2C2 GPIO Configuration
PA9 ------> I2C2_SCL
PA10 ------> I2C2_SDA
*/
GPIO_InitStruct.Pin = GPIO_PIN_9|GPIO_PIN_10;
GPIO_InitStruct.Mode = GPIO_MODE_AF_OD;
GPIO_InitStruct.Pull = GPIO_PULLUP;
GPIO_InitStruct.Speed = GPIO_SPEED_FREQ_HIGH;
GPIO_InitStruct.Alternate = GPIO_AF4_I2C2;
HAL_GPIO_Init(GPIOA, &GPIO_InitStruct);
/* Peripheral clock enable */
__HAL_RCC_I2C2_CLK_ENABLE();
/* USER CODE BEGIN I2C2_MspInit 1 */
/* USER CODE END I2C2_MspInit 1 */
}
}
/* I2C2 init function */
static void MX_I2C2_Init(void)
{
hi2c2.Instance = I2C2;
hi2c2.Init.Timing = 0x0010020A;
hi2c2.Init.OwnAddress1 = 0;
hi2c2.Init.AddressingMode = I2C_ADDRESSINGMODE_7BIT;
hi2c2.Init.DualAddressMode = I2C_DUALADDRESS_DISABLE;
hi2c2.Init.OwnAddress2 = 0;
hi2c2.Init.OwnAddress2Masks = I2C_OA2_NOMASK;
hi2c2.Init.GeneralCallMode = I2C_GENERALCALL_DISABLE;
hi2c2.Init.NoStretchMode = I2C_NOSTRETCH_DISABLE;
if (HAL_I2C_Init(&hi2c2) != HAL_OK)
{
Error_Handler();
}
/**Configure Analogue filter
*/
if (HAL_I2CEx_ConfigAnalogFilter(&hi2c2, I2C_ANALOGFILTER_ENABLE) != HAL_OK)
{
Error_Handler();
}
}
3、循环发送数据;
int main(void)
{
/* USER CODE BEGIN 1 */
uint8_t data[2] = {0x75, 0x04};
/* USER CODE END 1 */
/* MCU Configuration----------------------------------------------------------*/
/* Reset of all peripherals, Initializes the Flash interface and the Systick. */
HAL_Init();
/* Configure the system clock */
SystemClock_Config();
/* Initialize all configured peripherals */
MX_GPIO_Init();
MX_I2C2_Init();
/* USER CODE BEGIN 2 */
if(HAL_OK != HAL_I2C_IsDeviceReady(&hi2c2, (uint16_t)0xD0, 3, 1000))
{
hi2c2.Instance->CR1 |= I2C_CR1_SWRST;
hi2c2.Instance->CR1 &= ~I2C_CR1_SWRST;
HAL_Delay(2);
}
/* USER CODE END 2 */
/* Infinite loop */
/* USER CODE BEGIN WHILE */
while(1)
{
/* USER CODE END WHILE */
/* USER CODE BEGIN 3 */
HAL_Delay(20);
HAL_I2C_Master_Transmit(&hi2c2, (uint16_t)0xD0, data, sizeof(data), 5);
}
/* USER CODE END 3 */
}
4、用逻辑分析仪测量SCL和SDA,发现只有SDA有波形数据,而SCL一直为高,换I2C1和I2C3情况相同;
目前小弟水深火热中,请各位大神出手搭救
|