I2C_WaitOnFlagUntilTimeout
是一个在STM32的HAL库中用于等待I2C操作完成的函数。FreeRTOS是一个可以运行在嵌入式系统上的实时操作系统。在FreeRTOS中,如果你想要实现I2C操作的阻塞式等待,可以使用I2C_WaitOnFlagUntilTimeout
函数。
但是,FreeRTOS提供了一种更好的方式来处理阻塞操作,那就是使用信号量(semaphores)。这样可以避免任务在等待I2C操作完成时进入不必要的阻塞状态,这对于提高系统的响应性和时间管理非常重要。
以下是使用信号量实现阻塞式I2C操作的一个简单例子:
#include "FreeRTOS.h"
#include "semphr.h"
#include "stm32f4xx_hal.h"I2C_HandleTypeDef hi2c1;
SemaphoreHandle_t xSemaphoreI2C1;void I2C1_Init(void) {__HAL_RCC_I2C1_CLK_ENABLE();hi2c1.Instance = I2C1;hi2c1.Init.ClockSpeed = 100000;hi2c1.Init.DutyCycle = I2C_DUTYCYCLE_2;hi2c1.Init.OwnAddress1 = 0;hi2c1.Init.AddressingMode = I2C_ADDRESSINGMODE_7BIT;hi2c1.Init.DualAddressMode = I2C_DUALADDRESS_DISABLE;hi2c1.Init.OwnAddress2 = 0;hi2c1.Init.GeneralCallMode = I2C_GENERALCALL_DISABLE;hi2c1.Init.NoStretchMode = I2C_NOSTRETCH_DISABLE;if (HAL_I2C_Init(&hi2c1) != HAL_OK) {Error_Handler();}xSemaphoreI2C1 = xSemaphoreCreateBinary();if (xSemaphoreI2C1 == NULL) {Error_Handler();}HAL_I2C_RegisterCallback(&hi2c1, HAL_I2C_MASTER_TX_COMPLETE_CB_ID, I2C1_TxCompleteCallback);HAL_I2C_RegisterCallback(&hi2c1, HAL_I2C_MASTER_RX_COMPLETE_CB_ID, I2C1_RxCompleteCallback);HAL_I2C_RegisterCallback(&hi2c1, HAL_I2C_ERROR_CB_ID, I2C1_ErrorCallback);
}void I2C1_TxCompleteCallback(I2C_HandleTypeDef *hi2c) {xSemaphoreGiveFromISR(xSemaphoreI2C1, NULL);
}void I2C1_RxCompleteCallback(I2C_HandleTypeDef *hi2c) {xSemaphoreGiveFromISR(xSemaphoreI2C1, NULL);
}void I2C1_ErrorCallback(I2C_HandleTypeDef *hi2c) {xSemaphoreGiveFromISR(xSemaphoreI2C1, NULL);
}void I2C1_Write(uint16_t DevAddress, uint8_t *pData, uint16_t Size) {if (HAL_I2C_Master_Transmit_IT(&hi2c1, DevAddress, pData, Size) != HAL_OK) {Error_Handler();}if (xSemaphoreTake(xSemaphoreI2C1, portMAX_DELAY) != pdTRUE) {Error_Handler();}
}