【发布时间】:2021-08-14 06:15:50
【问题描述】:
我是 FreeRTOS 新手,一直在阅读 FreeRTOS 文档并在 STM32F767 Nucleo 板上使用 FreeRTOS 编写简单代码。在我编写的简单程序中,我使用二进制信号量仅在通过xSemaphoreGiveFromISR() 发生 LPTIM 和 GPIO 中断时向某些任务发出信号,并通过xSemaphoreGive() 向另一个任务发出信号以执行来自另一个任务的某些操作。
假设我有一个 I2C1 外设连接到两个不同的设备:
- 一个加速度计,只要发生活动/移动,就会触发微控制器的 GPIO 中断。此 GPIO 中断向微控制器发出信号,表明必须读取其中断事件寄存器中的一段数据,以便可以再次发出下一个活动/移动事件的信号。
- 必须定期读取的设备,将通过 LPTIM 或 TIM 外围设备触发
我可以在上述情况下使用互斥量和二进制信号量吗?
二进制信号量将向任务指示需要根据触发的相应中断执行操作,但互斥锁将在这两个任务之间共享,其中 Task1 将负责从加速度计读取数据, Task2 将负责从其他设备读取数据。我在想将使用互斥锁,因为这两个操作永远不应该一起发生,这样就不会在总线上发生可能锁定任一 I2C 设备的重叠 I2C 事务。
代码如下所示:
void Task1_AccelerometerOperations(void *argument)
{
/* The Semaphore will be given from the GPIO Interrupt Handler, signalling that a piece of
data needs to be read from the accelerometer through I2C. */
if(xSemaphoreTake(xSemaphore_GPIOInterruptFlag, portMAX_DELAY) == pdTRUE)
{
/* This Mutex should ensure that only one I2C transaction can happen at a time */
if(xSemaphoreTakeRecursive(xMutex_I2CBus, 2000/portTICK_PERIOD_MS) == pdTRUE)
{
/* Perform I2C Transaction */
/* Perform operations with the data received */
/* Mutex will be given back, indicating that the shared I2C Bus is now available */
xSemaphoreGiveRecursive(xMutex_I2CBus);
}
else
{
/* Mutex was not available even after 2 seconds since the GPIO interrupt triggered.
Perform Error Handling for the event that the I2C bus was locked */
}
/* Piece of code that could take a few hundreds milliseconds to execute */
}
}
void Task2_OtherEquipmentOperations(void *argument)
{
/* The Semaphore will be given from the LPTIM Interrupt Handler, signalling that some maintenance
or periodic operation needs to be performed through I2C. */
if(xSemaphoreTake(xSemaphore_LPTIMInterruptFlag, portMAX_DELAY) == pdTRUE)
{
/* Only perform the I2C operations when the Mutex is available */
if(xSemaphoreTakeRecursive(xMutex_I2CBus, 2000/portTICK_PERIOD_MS) == pdTRUE)
{
/* Perform I2C Transaction */
/* Mutex will be given back, indicating that the shared I2C Bus is now available */
xSemaphoreGiveRecursive(xMutex_I2CBus);
}
else
{
/* Mutex was not available even after 2 seconds since the LPTIM interrupt triggered.
Perform Error Handling for the event that the I2C bus was locked */
}
/* Piece of code that could take a few seconds to execute */
}
}
互斥锁是否经常用于避免优先级反转场景,或者它们(更经常)被广泛用于防止两个操作可能同时发生?我想不出一个简单的场景,如果一个发生优先级反转,这可能对软件至关重要。
谢谢!
【问题讨论】:
-
你是对的。
-
@MikeRobinson 人们使用互斥锁来避免优先级倒置的例子有哪些?在尝试确定优先级倒置的可能性时是否有某些指导方针/技巧?或者当更耗时的任务具有较低的优先级时,优先级反转不是一个大问题?
-
也许this 会帮助你?
标签: c arm stm32 microcontroller freertos