我在 ATMega328 和 STM32 F302R8 控制器之间开发 i2c 通信时遇到问题。
在 Cube 生成的 st 控制器的初始化代码下方。
void MX_I2C2_Init(void) {
hi2c2.Instance = I2C2;
hi2c2.Init.Timing = 0x2000090E;
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(__FILE__, __LINE__);
}
/**Configure Analogue filter
*/
if (HAL_I2CEx_ConfigAnalogFilter(&hi2c2, I2C_ANALOGFILTER_ENABLE)
!= HAL_OK) {
_Error_Handler(__FILE__, __LINE__);
}
/**Configure Digital filter
*/
if (HAL_I2CEx_ConfigDigitalFilter(&hi2c2, 0) != HAL_OK) {
_Error_Handler(__FILE__, __LINE__);
}
HAL_I2C_MspInit(&hi2c2);
}
void HAL_I2C_MspInit(I2C_HandleTypeDef* i2cHandle) {
GPIO_InitTypeDef GPIO_InitStruct;
if (i2cHandle->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);
/* I2C2 clock enable */
__HAL_RCC_I2C2_CLK_ENABLE()
;
/* USER CODE BEGIN I2C2_MspInit 1 */
/* USER CODE END I2C2_MspInit 1 */
}
}
我添加了HAL_I2C_MspInit(&hi2c2);
将引脚设置为正确模式的调用。
线程的函数 SerialMain 部分,将定期调用。
void SerialMain(void const* arg) {
MX_USART1_UART_Init();
MX_I2C2_Init();
char *buffer = "Hello World! ";
int cnt = 0;
for (;;) {
cnt++;
if (HAL_I2C_Master_Transmit(&hi2c2, 8 , buffer, 13, 1000) != HAL_OK) { //PA9 SCL PA10 SDA
SerialError();
}
if (HAL_I2C_Master_Transmit(&hi2c2, 8 >> 1, &cnt, sizeof(cnt), 1000)
!= HAL_OK) { //PA9 SCL PA10 SDA
SerialError();
}
osDelay(10);
}
}
在尝试传输 Hello World 消息后,HAL_I2C_Master_Transmit 将返回 HAL_TIMEOUT。
有人知道它为什么返回 HAL_TIMEOUT 吗?
有人知道如何成功传输数据吗?