Mastering the FreeRTOS Real Time Kernel · 中文版 /6 中断管理

6 · 原书 208–259 页中断管理

Interrupt Management

6.1本章引言与范围

6.1.1事件

嵌入式实时系统必须响应来自环境的事件而采取动作。例如以太网外设收到数据包(事件),可能需要交给 TCP/IP 协议栈处理(动作)。非平凡系统要服务来自多个来源的事件,各来源的处理开销与响应时间要求各不相同。对每种情况,都要判断最佳的事件处理实现策略:

FreeRTOS 不强制应用设计者采用某种事件处理策略,但提供了让所选策略以简单、可维护方式落地的特性。

必须区分任务优先级与中断优先级:

运行 FreeRTOS 的所有架构都能处理中断,但中断入口与中断优先级分配的细节随架构而异。

6.1.2范围

本章帮助读者理解:哪些 FreeRTOS API 可在 ISR 内使用;把中断处理延迟到任务的方法;如何创建与使用二值信号量和计数信号量;二者区别;如何用队列向 ISR 传入与传出数据;部分 FreeRTOS 移植可用的中断嵌套模型。

6.2在 ISR 中使用 FreeRTOS API

6.2.1中断安全 API

经常需要在 ISR 中使用某个 FreeRTOS API 提供的功能,但许多 API 函数执行的动作在 ISR 内并不合法——最典型的是把调用 API 的任务放入阻塞态;从 ISR 调用 API 时并不存在可进入阻塞态的调用任务。FreeRTOS 为此为部分 API 提供两个版本:任务版与 ISR 版。供 ISR 使用的函数名以“FromISR”结尾。

注意:绝不要从 ISR 中调用名称不含“FromISR”的 FreeRTOS API 函数。

6.2.2独立中断安全 API 的好处

为中断单独提供一套 API,可以让任务代码、ISR 代码都更高效,中断入口也更简单。设想另一种方案:每个 API 只提供一个版本,既可由任务调用也可由 ISR 调用。若如此:

6.2.3独立中断安全 API 的代价

部分 API 分两个版本让任务与 ISR 都更高效,但带来一个新问题:有时需要同时从任务和 ISR 调用某个不属于 FreeRTOS API、但内部使用 FreeRTOS API 的函数。这通常只在集成第三方代码时才成问题——那时软件设计不在应用设计者掌控之内。若确实遇到,可用以下技术之一解决:

6.2.4xHigherPriorityTaskWoken 参数

本节引入 xHigherPriorityTaskWoken 参数的概念;若暂时没完全理解也不必担心,后续小节有实际示例。

若由一次中断执行了上下文切换,中断退出时运行的任务可能与中断进入时不同——中断打断了一个任务,却返回到另一个任务。

部分 FreeRTOS API 可把任务从阻塞态移入就绪态,例如 xQueueSendToBack():若有任务正阻塞等待对应队列出现数据,发数据会解除其阻塞。

若被 API 解除阻塞的任务优先级高于运行态任务,按 FreeRTOS 调度策略,应切换到该高优先级任务。切换实际何时发生,取决于 API 的调用上下文:

若应用设计者选择不从 ISR 请求上下文切换,高优先级任务将留在就绪态,直到调度器下次运行——最坏情况是下次节拍中断时。

FreeRTOS API 只能把 *pxHigherPriorityTaskWoken 置为 pdTRUE。若 ISR 调用多个 API,每次调用都可传入同一变量作为 pxHigherPriorityTaskWoken;该变量只需在首次使用前初始化为 pdFALSE。

中断安全版本 API 内部不自动执行上下文切换,原因有五:

使用 pxHigherPriorityTaskWoken 参数是可选的;若不需要,把它设为 NULL 即可。

6.2.5portYIELD_FROM_ISR() 与 portEND_SWITCHING_ISR() 宏

本节介绍用于从 ISR 请求上下文切换的宏;暂不理解也无妨,后续有实例。

taskYIELD() 是可在任务中调用以请求上下文切换的宏。portYIELD_FROM_ISR() 与 portEND_SWITCHING_ISR() 都是 taskYIELD() 的中断安全版本,用法与功能相同。部分移植只提供其中一个,较新的移植两个都提供;本书示例使用 portYIELD_FROM_ISR()。

portEND_SWITCHING_ISR( xHigherPriorityTaskWoken );
清单 87 · portEND_SWITCHING_ISR() 宏
portYIELD_FROM_ISR( xHigherPriorityTaskWoken );
清单 88 · portYIELD_FROM_ISR() 宏

从中断安全 API 传出的 xHigherPriorityTaskWoken 值,可直接作为 portYIELD_FROM_ISR() 的参数。若该参数为 pdFALSE(0),不请求上下文切换,宏不起作用;若非 pdFALSE,则请求上下文切换,运行态任务可能改变。即使中断执行期间运行态任务发生改变,中断也总是返回到运行态任务。多数移植允许在 ISR 内任意位置调用 portYIELD_FROM_ISR();少数移植(主要是较小架构)只允许在 ISR 最末尾调用。

6.3延迟中断处理

通常认为最佳实践是尽量缩短 ISR。原因包括:

ISR 必须记录中断原因并清除中断;中断所需的其他处理往往可放到任务中完成,使 ISR 尽快退出。这称为“延迟中断处理”——把中断所需处理从 ISR“延迟”到任务。

把中断处理延迟到任务,还使设计者能按应用中其他任务为处理安排优先级,并使用全部 FreeRTOS API。若延迟处理任务的优先级高于其他任务,处理将立即执行,就像在 ISR 内完成一样。场景见图 48:Task1 为普通应用任务,Task2 为延迟处理任务。

图 48(在高优先级任务中完成中断处理,优先级 Task2 > Task1):① t1,Task1 运行时发生中断;② ISR 执行,处理中断外设、清除中断,然后解除 Task2 阻塞;③ Task2 优先级高于 Task1,ISR 直接返回到 Task2,在其中完成中断处理;④ Task2 进入阻塞态等待下一次中断,Task1 重新进入运行态。

图 48 中,中断处理从 t2 开始、实际到 t4 结束,但只有 t2 到 t3 这段时间在 ISR 内;若不使用延迟处理,t2 到 t4 整段都将在 ISR 内。

何时把中断所需处理全部放在 ISR、何时把一部分延迟到任务,并无绝对规则。延迟到任务在以下情况最有用:

6.4用于同步的二值信号量

二值信号量的中断安全版本可在每次特定中断发生时解除一个任务阻塞,从而使任务与中断同步。这样大部分中断事件处理在被同步的任务中实现,ISR 内只保留极快极短的一小段。如上节所述,二值信号量用于把中断处理“延迟”到任务。

如图 48 所示,若中断处理时间要求特别严格,可设置延迟处理任务的优先级,确保它总能抢占系统中其他任务;ISR 中可加入对 portYIELD_FROM_ISR() 的调用,确保 ISR 直接返回到被延迟处理的任务。这保证整个事件处理在时间上连续(不被打断),就像全部在 ISR 内实现一样。图 49 重复图 48 场景,但文字改为描述如何用信号量控制延迟处理任务的执行。

图 49(用二值信号量实现延迟中断处理):① 中断发生时 Task1 运行,Task2 阻塞等待信号量;② ISR 执行、处理外设、清除中断,然后“给出”信号量解除 Task2 阻塞;③ Task2 完成中断所需的进一步处理,然后在信号量上阻塞,等待下一次中断再次解除阻塞。

延迟处理任务用阻塞式“获取”信号量作为进入阻塞态等待事件发生的手段;事件发生时,ISR 对同一信号量执行“给出”操作解除任务阻塞,使所需事件处理得以继续。

“获取信号量”与“给出信号量”的含义随使用场景不同。在中断同步场景中,二值信号量可概念上看作长度为 1 的队列:队列任一时刻最多含一项,因此总是空或满(故为“二值”)。延迟处理任务调用 xSemaphoreTake(),相当于带阻塞时间尝试读队列,队列空时进入阻塞态;事件发生时,ISR 用 xSemaphoreGiveFromISR() 把一个令牌(信号量)放入队列,队列变满,任务退出阻塞态并取走令牌,队列再次变空。任务处理完后再次尝试读队列,发现队列为空,重新进入阻塞态等待下一事件。时序见图 50。

图 50(用二值信号量使任务与中断同步):任务先在信号量上 xSemaphoreTake(),信号量不可用,任务阻塞等待;中断发生,xSemaphoreGiveFromISR()“给出”信号量,解除任务阻塞(信号量可用);任务成功“获取”信号量,信号量再次不可用;任务执行动作,完成后再次尝试“获取”,因信号量仍不可用而重新阻塞。

图 50 中中断先“给出”信号量(之前并未“获取”),任务“获取”后从不归还。这正是该场景在概念上类似队列读写的原因;它常引起困惑,因为与其他信号量场景规则不同——第 7 章“资源管理”等场景中,获取信号量的任务必须归还信号量。

6.4.1xSemaphoreCreateBinary() API 函数

FreeRTOS V9.0.0 还提供 xSemaphoreCreateBinaryStatic(),在编译期静态分配创建二值信号量所需内存。各类 FreeRTOS 信号量的句柄都存于 SemaphoreHandle_t 类型变量。信号量必须先创建才能使用;创建二值信号量用 xSemaphoreCreateBinary()。

SemaphoreHandle_t xSemaphoreCreateBinary( void );
清单 89 · xSemaphoreCreateBinary() API 原型
参数名说明
返回值返回 NULL 表示堆内存不足,FreeRTOS 无法分配信号量数据结构;返回非 NULL 表示创建成功,返回值应保存为所创建信号量的句柄。

6.4.2xSemaphoreTake() API 函数

“获取”信号量即“取得”或“收到”信号量;只有信号量可用时才能获取。除递归互斥量外,各类 FreeRTOS 信号量都可用 xSemaphoreTake() 获取。xSemaphoreTake() 不得在 ISR 中使用。

BaseType_t xSemaphoreTake( SemaphoreHandle_t xSemaphore, TickType_t xTicksToWait );
清单 90 · xSemaphoreTake() API 原型
参数名 / 返回值说明
xSemaphore被“获取”的信号量。信号量由 SemaphoreHandle_t 类型变量引用,使用前必须显式创建。
xTicksToWait信号量尚不可用时,任务在阻塞态等待其可用的最长时间。为 0 且信号量不可用时立即返回。阻塞时间以节拍为单位,绝对时长取决于节拍频率;pdMS_TO_TICKS() 可换算毫秒。INCLUDE_vTaskSuspend 为 1 时,设为 portMAX_DELAY 表示无限等待(不超时)。
返回值① pdPASS:仅在成功取得信号量时返回;若指定阻塞时间,任务可能曾在信号量不可用时阻塞等待,但在到期前信号量变为可用。② pdFALSE:信号量不可用;若指定阻塞时间,则曾阻塞等待,但到期前信号量仍未可用。

6.4.3xSemaphoreGiveFromISR() API 函数

二值信号量与计数信号量都可用 xSemaphoreGiveFromISR()“给出”。它是 xSemaphoreGive() 的中断安全版本,因此带本章开头所述的 pxHigherPriorityTaskWoken 参数。

BaseType_t xSemaphoreGiveFromISR( SemaphoreHandle_t xSemaphore,
                                  BaseType_t *pxHigherPriorityTaskWoken );
清单 91 · xSemaphoreGiveFromISR() API 原型
参数名 / 返回值说明
xSemaphore被“给出”的信号量。
pxHigherPriorityTaskWoken一个信号量上可能有一个或多个任务阻塞等待其可用。调用 xSemaphoreGiveFromISR() 可使信号量可用,从而解除等待任务阻塞。若被解除阻塞的任务优先级高于当前正在执行的任务(被中断的任务),函数内部会把 *pxHigherPriorityTaskWoken 置为 pdTRUE。若被置为 pdTRUE,通常应在退出中断前执行一次上下文切换,确保中断直接返回到最高优先级就绪态任务。
返回值① pdPASS:仅在调用成功时返回。② pdFAIL:信号量已可用则无法再给出,返回 pdFAIL。

6.4.4示例 16:用二值信号量使任务与中断同步

本示例用二值信号量在 ISR 中解除一个任务阻塞,使任务与中断同步。一个简单周期任务每 500 毫秒产生一次软件中断;因某些目标环境接入真实中断较复杂,这里用软件中断便于演示。周期任务实现见清单 92;注意它在产生中断前后各打印一条字符串,便于在输出中观察执行序列。

/* The number of the software interrupt used in this example.  The code shown is from
   the Windows project, where numbers 0 to 2 are used by the FreeRTOS Windows port
   itself, so 3 is the first number available to the application. */
#define mainINTERRUPT_NUMBER    3

static void vPeriodicTask( void *pvParameters )
{
    const TickType_t xDelay500ms = pdMS_TO_TICKS( 500UL );

    /* As per most tasks, this task is implemented within an infinite loop. */
    for( ;; )
    {
        /* Block until it is time to generate the software interrupt again. */
        vTaskDelay( xDelay500ms );

        /* Generate the interrupt, printing a message both before and after
           the interrupt has been generated, so the sequence of execution is evident
           from the output.
           The syntax used to generate a software interrupt is dependent on the
           FreeRTOS port being used.  The syntax used below can only be used with
           the FreeRTOS Windows port, in which such interrupts are only simulated. */
        vPrintString( "Periodic task - About to generate an interrupt.\r\n" );
        vPortGenerateSimulatedInterrupt( mainINTERRUPT_NUMBER );
        vPrintString( "Periodic task - Interrupt generated.\r\n\r\n\r\n" );
    }
}
清单 92 · 示例 16 中周期性产生软件中断的任务实现

清单 93 是延迟中断处理任务的实现——它通过二值信号量与软件中断同步。任务每次迭代也打印字符串,便于从输出看出任务与中断的执行先后。

注意:清单 93 的代码对本示例(中断由软件产生)是足够的,但不适合硬件外设产生中断的场景;后面小节会说明代码结构应如何调整。
static void vHandlerTask( void *pvParameters )
{
    /* As per most tasks, this task is implemented within an infinite loop. */
    for( ;; )
    {
        /* Use the semaphore to wait for the event.  The semaphore was created
           before the scheduler was started, so before this task ran for the first
           time.  The task blocks indefinitely, meaning this function call will only
           return once the semaphore has been successfully obtained - so there is
           no need to check the value returned by xSemaphoreTake(). */
        xSemaphoreTake( xBinarySemaphore, portMAX_DELAY );

        /* To get here the event must have occurred.  Process the event (in this
           Case, just print out a message). */
        vPrintString( "Handler task - Processing event.\r\n" );
    }
}
清单 93 · 示例 16 中延迟中断处理任务(与中断同步的任务)实现

清单 94 是 ISR:除了“给出”信号量解除延迟处理任务阻塞外几乎不做其他事。注意 xHigherPriorityTaskWoken 的用法:调用 xSemaphoreGiveFromISR() 前置为 pdFALSE,随后作为调用 portYIELD_FROM_ISR() 的参数;若该变量等于 pdTRUE,则在 portYIELD_FROM_ISR() 宏内请求上下文切换。

ISR 原型与强制上下文切换所用宏都适用于 FreeRTOS Windows 移植,其他移植可能不同;请查阅 FreeRTOS.org 网站对应移植的文档页及 FreeRTOS 下载包中的示例。与多数架构不同,Windows 移植要求 ISR 返回一个值;Windows 版 portYIELD_FROM_ISR() 宏的实现已包含 return 语句,因此清单 94 不显式返回值。

static uint32_t ulExampleInterruptHandler( void )
{
    BaseType_t xHigherPriorityTaskWoken;

    /* The xHigherPriorityTaskWoken parameter must be initialized to pdFALSE as
       it will get set to pdTRUE inside the interrupt safe API function if a
       context switch is required. */
    xHigherPriorityTaskWoken = pdFALSE;

    /* 'Give' the semaphore to unblock the task, passing in the address of
       xHigherPriorityTaskWoken as the interrupt safe API function's
       pxHigherPriorityTaskWoken parameter. */
    xSemaphoreGiveFromISR( xBinarySemaphore, &xHigherPriorityTaskWoken );

    /* Pass the xHigherPriorityTaskWoken value into portYIELD_FROM_ISR().  If
       xHigherPriorityTaskWoken was set to pdTRUE inside xSemaphoreGiveFromISR()
       then calling portYIELD_FROM_ISR() will request a context switch.  If
       xHigherPriorityTaskWoken is still pdFALSE then calling
       portYIELD_FROM_ISR() will have no effect. Unlike most FreeRTOS ports, the
       Windows port requires the ISR to return a value - the return statement
       is inside the Windows version of portYIELD_FROM_ISR(). */
    portYIELD_FROM_ISR( xHigherPriorityTaskWoken );
}
清单 94 · 示例 16 软件中断所用 ISR

main() 创建二值信号量、创建任务、安装中断处理程序并启动调度器,实现见清单 95。安装中断处理程序所用函数语法是 Windows 移植专用,其他移植可能不同。

int main( void )
{
    /* Before a semaphore is used it must be explicitly created.  In this example
       a binary semaphore is created. */
    xBinarySemaphore = xSemaphoreCreateBinary();

    /* Check the semaphore was created successfully. */
    if( xBinarySemaphore != NULL )
    {
        /* Create the 'handler' task, which is the task to which interrupt
           processing is deferred.  This is the task that will be synchronized with
           the interrupt.  The handler task is created with a high priority to ensure
           it runs immediately after the interrupt exits.  In this case a priority of
           3 is chosen. */
        xTaskCreate( vHandlerTask, "Handler", 1000, NULL, 3, NULL );

        /* Create the task that will periodically generate a software interrupt.
           This is created with a priority below the handler task to ensure it will
           get preempted each time the handler task exits the Blocked state. */
        xTaskCreate( vPeriodicTask, "Periodic", 1000, NULL, 1, NULL );

        /* Install the handler for the software interrupt.  The syntax necessary
           to do this is dependent on the FreeRTOS port being used.  The syntax
           shown here can only be used with the FreeRTOS windows port, where such
           interrupts are only simulated. */
        vPortSetInterruptHandler( mainINTERRUPT_NUMBER, ulExampleInterruptHandler );

        /* Start the scheduler so the created tasks start executing. */
        vTaskStartScheduler();
    }

    /* As normal, the following line should never be reached. */
    for( ;; );
}
清单 95 · 示例 16 的 main() 实现
图 51 · 执行示例 16 时产生的输出
图 51 · 执行示例 16 时产生的输出

如预期,vHandlerTask() 在中断产生后立即进入运行态,因此任务输出穿插在周期任务产生的输出之间;进一步解释见图 52。

图 52(示例 16 执行序列):① 大部分时间运行空闲任务,每 500ms 被周期任务抢占;② 周期任务打印第一条消息后强制中断,ISR 立即执行;③ ISR“给出”信号量解除 vHandlerTask() 阻塞;因该任务是最高优先级就绪态任务,ISR 直接返回到它,它打印消息后回到阻塞态等待下次中断;④ 周期任务再次成为最高优先级任务,打印第二条消息后再次阻塞等待下一周期,只剩空闲任务可运行。

6.4.5改进示例 16 所用任务的实现

示例 16 用二值信号量使任务与中断同步,执行序列为:① 中断发生;② ISR 执行并“给出”信号量解除任务阻塞;③ 任务在 ISR 之后立即执行并“获取”信号量;④ 任务处理事件,然后再次尝试“获取”信号量——因信号量尚不可用(下一次中断还没发生)而进入阻塞态。

该任务结构只在中断频率相对较低时才够用。原因:设想任务尚未处理完第一次中断时,又发生第二次、第三次中断会怎样:

图 53(任务尚未处理完第一个事件时发生一次中断):任务仍在处理第一个事件时又来一次中断,ISR 再次给出信号量,相当于锁存该事件使其不丢失;任务处理完第一个事件后再次 xSemaphoreTake(),因信号量已可用而不进入阻塞态,直接处理第二个事件。
图 54(任务尚未处理完第一个事件时发生两次中断):第二次中断再次给出信号量锁存事件;第三次中断时信号量已可用,无法再次给出,事件丢失。任务处理完第一个事件后取到信号量处理第二个事件;再次获取时信号量不可用,进入阻塞态等待下次中断——尽管第三个事件尚未处理。

示例 16 的延迟处理任务(清单 93)结构是:每次调用 xSemaphoreTake() 之间只处理一个事件。这对示例 16 够用,因为产生事件的中断由软件触发、发生时刻可预测。真实应用中中断由硬件产生、时刻不可预测;因此为尽量减少漏中断,延迟处理任务必须组织成:每次调用 xSemaphoreTake() 之间处理完所有已可用事件。

清单 96 演示 UART 延迟中断处理任务可如何组织:假定 UART 每收到一个字符产生一次接收中断,并把收到的字符放入硬件 FIFO(硬件缓冲区)。

示例 16 的延迟处理任务还有另一个弱点:调用 xSemaphoreTake() 时没有使用超时,而是把 portMAX_DELAY 作为 xTicksToWait,任务无限等待信号量可用。示例代码常用无限超时以简化结构、便于理解;但真实应用中无限超时通常是不良实践,因为出错后难以恢复。例如任务等待中断给出信号量,而硬件错误状态阻止了中断产生:无超时等待则任务永远不知道错误状态、一直等下去;带超时等待则超时到期时 xSemaphoreTake() 返回 pdFAIL,任务可在下次执行时检测并清除错误。清单 96 也演示了这种场景。

static void vUARTReceiveHandlerTask( void *pvParameters )
{
    /* xMaxExpectedBlockTime holds the maximum time expected between two interrupts. */
    const TickType_t xMaxExpectedBlockTime = pdMS_TO_TICKS( 500 );

    /* As per most tasks, this task is implemented within an infinite loop. */
    for( ;; )
    {
        /* The semaphore is 'given' by the UART's receive (Rx) interrupt.  Wait a
           maximum of xMaxExpectedBlockTime ticks for the next interrupt. */
        if( xSemaphoreTake( xBinarySemaphore, xMaxExpectedBlockTime ) == pdPASS )
        {
            /* The semaphore was obtained.  Process ALL pending Rx events before
               calling xSemaphoreTake() again.  Each Rx event will have placed a
               character in the UART’s receive FIFO, and UART_RxCount() is assumed to
               return the number of characters in the FIFO. */
            while( UART_RxCount() > 0 )
            {
                /* UART_ProcessNextRxEvent() is assumed to process one Rx character,
                   reducing the number of characters in the FIFO by 1. */
                UART_ProcessNextRxEvent();
            }

            /* No more Rx events are pending (there are no more characters in the
               FIFO), so loop back and call xSemaphoreTake() to wait for the next
               interrupt.  Any interrupts occurring between this point in the code and
               the call to xSemaphoreTake() will be latched in the semaphore, so will
               not be lost. */
        }
        else
        {
            /* An event was not received within the expected time.  Check for, and if
               necessary clear, any error conditions in the UART that might be
               preventing the UART from generating any more interrupts. */
            UART_ClearErrors();
        }
    }
}
清单 96 · 以 UART 接收处理为例,推荐的延迟中断处理任务结构

6.5计数信号量

二值信号量可看作长度为 1 的队列;计数信号量可看作长度大于 1 的队列。任务不关心队列中存的数据,只关心队列中项的数量。要使用计数信号量,必须在 FreeRTOSConfig.h 中把 configUSE_COUNTING_SEMAPHORES 设为 1。

每次“给出”计数信号量,其队列就占用一个空位;队列中项数即信号量的“计数值”。计数信号量通常用于两件事:

图 55(用计数信号量“计数”事件):初始计数值 0,任务阻塞等待信号量;中断“给出”信号量,任务解除阻塞、计数值变 1,开始处理事件;任务处理第一个事件期间又来两次中断,两次 ISR 都给出信号量,两个事件都被锁存不丢失;任务处理完第一个事件后再次获取,此时已有两个可用信号量,取走一个不进入阻塞态,仍留一个锁存信号量可用。

6.5.1xSemaphoreCreateCounting() API 函数

FreeRTOS V9.0.0 还提供 xSemaphoreCreateCountingStatic(),在编译期静态分配创建计数信号量所需内存。使用前必须先创建;创建计数信号量用 xSemaphoreCreateCounting()。

SemaphoreHandle_t xSemaphoreCreateCounting( UBaseType_t uxMaxCount,
                                            UBaseType_t uxInitialCount );
清单 97 · xSemaphoreCreateCounting() API 原型
参数名 / 返回值说明
uxMaxCount信号量可计数到的最大值。沿用队列类比,uxMaxCount 实际就是队列长度。用于计数或锁存事件时,它是可锁存事件的最大数量;用于管理一组资源访问时,应设为可用资源总数。
uxInitialCount信号量创建后的初始计数值。用于计数/锁存事件时设为 0(创建时假定尚无事件发生);用于管理资源时设为等于 uxMaxCount(创建时假定所有资源可用)。
返回值返回 NULL 表示堆内存不足,无法分配信号量数据结构;返回非 NULL 表示创建成功,返回值保存为信号量句柄。堆管理见第 2 章。

6.5.2示例 17:用计数信号量使任务与中断同步

示例 17 在示例 16 基础上改进,用计数信号量代替二值信号量。main() 中以 xSemaphoreCreateCounting() 调用代替 xSemaphoreCreateBinary(),新调用见清单 98。

/* Before a semaphore is used it must be explicitly created.  In this example a
   counting semaphore is created.  The semaphore is created to have a maximum count
   value of 10, and an initial count value of 0. */
xCountingSemaphore = xSemaphoreCreateCounting( 10, 0 );
清单 98 · 示例 17 中创建计数信号量的调用

为模拟高频发生的多个事件,ISR 改为每次中断多次“给出”信号量;每个事件锁存进信号量计数值。修改后的 ISR 见清单 99。

static uint32_t ulExampleInterruptHandler( void )
{
    BaseType_t xHigherPriorityTaskWoken;

    /* The xHigherPriorityTaskWoken parameter must be initialized to pdFALSE as it
       will get set to pdTRUE inside the interrupt safe API function if a context switch
       is required. */
    xHigherPriorityTaskWoken = pdFALSE;

    /* 'Give' the semaphore multiple times.  The first will unblock the deferred
       interrupt handling task, the following 'gives' are to demonstrate that the
       semaphore latches the events to allow the task to which interrupts are deferred
       to process them in turn, without events getting lost.  This simulates multiple
       interrupts being received by the processor, even though in this case the events
       are simulated within a single interrupt occurrence. */
    xSemaphoreGiveFromISR( xCountingSemaphore, &xHigherPriorityTaskWoken );
    xSemaphoreGiveFromISR( xCountingSemaphore, &xHigherPriorityTaskWoken );
    xSemaphoreGiveFromISR( xCountingSemaphore, &xHigherPriorityTaskWoken );

    /* Pass the xHigherPriorityTaskWoken value into portYIELD_FROM_ISR().  If
       xHigherPriorityTaskWoken was set to pdTRUE inside xSemaphoreGiveFromISR() then
       calling portYIELD_FROM_ISR() will request a context switch.  If
       xHigherPriorityTaskWoken is still pdFALSE then calling portYIELD_FROM_ISR() will
       have no effect. Unlike most FreeRTOS ports, the Windows port requires the ISR to
       return a value - the return statement is inside the Windows version of
       portYIELD_FROM_ISR(). */
    portYIELD_FROM_ISR( xHigherPriorityTaskWoken );
}
清单 99 · 示例 17 所用 ISR 实现

其余函数与示例 16 相同。示例 17 输出见图 56:每次产生中断,延迟处理任务处理全部三个(模拟)事件;事件被锁存进信号量计数值,任务可依次处理。

图 56 · 执行示例 17 时产生的输出
图 56 · 执行示例 17 时产生的输出

6.6把工作延迟到 RTOS 守护任务

前面的延迟中断处理示例要求为每个使用延迟处理技术的中断创建一个任务。也可用 xTimerPendFunctionCallFromISR() API 把中断处理延迟到 RTOS 守护任务——无需为每个中断单独创建任务。这种方式称为“集中式延迟中断处理”。

第 5 章介绍过,软件定时器相关 API 通过定时器命令队列向守护任务发送命令;xTimerPendFunctionCall() 与 xTimerPendFunctionCallFromISR() 复用同一定时器命令队列,向守护任务发送“执行函数”命令;被发送的函数随后在守护任务上下文中执行。

集中式延迟中断处理的优点:

缺点:

不同中断有不同时序约束,同一应用中两种延迟方式通常都会用到。

6.6.1xTimerPendFunctionCallFromISR() API 函数

xTimerPendFunctionCallFromISR() 是 xTimerPendFunctionCall() 的中断安全版本。两个 API 都允许由应用设计者提供的函数在守护任务上下文中执行;待执行函数及其输入参数值都经定时器命令队列发给守护任务。函数实际何时执行,取决于守护任务相对应用中其他任务的优先级。

BaseType_t xTimerPendFunctionCallFromISR( PendedFunction_t xFunctionToPend,
                                          void *pvParameter1,
                                          uint32_t ulParameter2,
                                          BaseType_t *pxHigherPriorityTaskWoken );
清单 100 · xTimerPendFunctionCallFromISR() API 原型
void vPendableFunction( void *pvParameter1, uint32_t ulParameter2 );
清单 101 · 传入 xFunctionToPend 参数的函数必须符合的原型
参数名 / 返回值说明
xFunctionToPend将在守护任务中执行的函数指针(实际即函数名);函数原型必须与清单 101 相同。
pvParameter1作为函数 pvParameter1 参数传入的值。参数为 void * 类型,可传递任意数据类型:整数类型可直接转换为 void *,也可用 void * 指向结构体。
ulParameter2作为函数 ulParameter2 参数传入的值。
pxHigherPriorityTaskWoken函数写定时器命令队列。若守护任务正阻塞等待队列出现数据,写队列会使其退出阻塞态;若守护任务优先级高于当前执行任务(被中断任务),函数内部会把 *pxHigherPriorityTaskWoken 置为 pdTRUE。置为 pdTRUE 时,退出中断前必须执行上下文切换,确保中断直接返回到守护任务(它将是最高优先级就绪态任务)。
返回值① pdPASS:“执行函数”命令已写入命令队列。② pdFAIL:命令未能写入,因命令队列已满。命令队列长度设置见第 5 章。

6.6.2示例 18:集中式延迟中断处理

示例 18 提供与示例 16 类似的功能,但不使用信号量,也不专门创建任务执行中断所需处理;处理由 RTOS 守护任务完成。

示例 18 的 ISR 见清单 102:它调用 xTimerPendFunctionCallFromISR(),把指向 vDeferredHandlingFunction() 的指针传给守护任务;延迟中断处理由该函数完成。ISR 每次执行时递增变量 ulParameterValue;该值作为 xTimerPendFunctionCallFromISR() 调用的 ulParameter2,因此守护任务执行 vDeferredHandlingFunction() 时也作为其 ulParameter2。函数另一参数 pvParameter1 在本示例中未使用。

static uint32_t ulExampleInterruptHandler( void )
{
    static uint32_t ulParameterValue = 0;
    BaseType_t xHigherPriorityTaskWoken;

    /* The xHigherPriorityTaskWoken parameter must be initialized to pdFALSE as it will
       get set to pdTRUE inside the interrupt safe API function if a context switch is
       required. */
    xHigherPriorityTaskWoken = pdFALSE;

    /* Send a pointer to the interrupt's deferred handling function to the daemon task.
       The deferred handling function's pvParameter1 parameter is not used so just set to
       NULL.  The deferred handling function's ulParameter2 parameter is used to pass a
       number that is incremented by one each time this interrupt handler executes. */
    xTimerPendFunctionCallFromISR( vDeferredHandlingFunction, /* Function to execute. */
                                   NULL,                      /* Not used. */
                                   ulParameterValue,          /* Incrementing value. */
                                   &xHigherPriorityTaskWoken );
    ulParameterValue++;

    /* Pass the xHigherPriorityTaskWoken value into portYIELD_FROM_ISR().  If
       xHigherPriorityTaskWoken was set to pdTRUE inside xTimerPendFunctionCallFromISR() then
       calling portYIELD_FROM_ISR() will request a context switch.  If
       xHigherPriorityTaskWoken is still pdFALSE then calling portYIELD_FROM_ISR() will have
       no effect. Unlike most FreeRTOS ports, the Windows port requires the ISR to return a
       value - the return statement is inside the Windows version of portYIELD_FROM_ISR(). */
    portYIELD_FROM_ISR( xHigherPriorityTaskWoken );
}
清单 102 · 示例 18 软件中断处理程序

vDeferredHandlingFunction() 实现见清单 103:打印一条固定字符串及其 ulParameter2 参数值。即使本示例只用了其中一个参数,函数也必须符合清单 101 原型。

static void vDeferredHandlingFunction( void *pvParameter1, uint32_t ulParameter2 )
{
    /* Process the event - in this case just print out a message and the value of
       ulParameter2. pvParameter1 is not used in this example. */
    vPrintStringAndNumber( "Handler function - Processing event ", ulParameter2 );
}
清单 103 · 示例 18 中执行中断所需处理的函数

示例 18 的 main() 见清单 104;比示例 16 的 main() 简单,因为既不创建信号量,也不创建执行延迟处理的任务。

vPeriodicTask() 是周期性产生软件中断的任务,其优先级创建在守护任务优先级之下,确保守护任务一旦退出阻塞态就抢占它。

int main( void )
{
    /* The task that generates the software interrupt is created at a priority below the
       priority of the daemon task.  The priority of the daemon task is set by the
       configTIMER_TASK_PRIORITY compile time configuration constant in FreeRTOSConfig.h. */
    const UBaseType_t ulPeriodicTaskPriority = configTIMER_TASK_PRIORITY - 1;

    /* Create the task that will periodically generate a software interrupt. */
    xTaskCreate( vPeriodicTask, "Periodic", 1000, NULL, ulPeriodicTaskPriority, NULL );

    /* Install the handler for the software interrupt.  The syntax necessary to do
       this is dependent on the FreeRTOS port being used.  The syntax shown here can
       only be used with the FreeRTOS windows port, where such interrupts are only
       simulated. */
    vPortSetInterruptHandler( mainINTERRUPT_NUMBER, ulExampleInterruptHandler );

    /* Start the scheduler so the created task starts executing. */
    vTaskStartScheduler();

    /* As normal, the following line should never be reached. */
    for( ;; );
}
清单 104 · 示例 18 的 main() 实现
图 57 · 执行示例 18 时产生的输出
图 57 · 执行示例 18 时产生的输出

守护任务优先级高于产生软件中断的任务,因此中断一产生,守护任务就执行 vDeferredHandlingFunction();其消息出现在周期任务两条消息之间,与用信号量解除专用延迟任务阻塞时一样。进一步解释见图 58。

图 58(示例 18 执行序列):① 大部分时间运行空闲任务,每 500ms 被周期任务抢占;② 周期任务打印第一条消息后强制中断,ISR 立即执行;③ 中断调用 xTimerPendFunctionCallFromISR() 写定时器命令队列,解除守护任务阻塞;守护任务是最高优先级就绪态任务,ISR 直接返回到它;守护任务打印消息(含递增参数值)后回到阻塞态,等待命令队列再来消息或定时器到期;④ 周期任务再次成为最高优先级任务,打印第二条消息后阻塞等待下一周期,只剩空闲任务可运行。

6.7在中断服务程序中使用队列

二值与计数信号量用于传达事件;队列既用于传达事件,也用于传递数据。xQueueSendToFrontFromISR() 是 xQueueSendToFront() 的 ISR 安全版本,xQueueSendToBackFromISR() 是 xQueueSendToBack() 的 ISR 安全版本,xQueueReceiveFromISR() 是 xQueueReceive() 的 ISR 安全版本。

6.7.1xQueueSendToFrontFromISR() 与 xQueueSendToBackFromISR() API 函数

BaseType_t xQueueSendToFrontFromISR( QueueHandle_t xQueue,
                                     void *pvItemToQueue
                                     BaseType_t *pxHigherPriorityTaskWoken
                                    );
清单 105 · xQueueSendToFrontFromISR() API 原型
BaseType_t xQueueSendToBackFromISR( QueueHandle_t xQueue,
                                     void *pvItemToQueue
                                     BaseType_t *pxHigherPriorityTaskWoken
                                    );
清单 106 · xQueueSendToBackFromISR() API 原型

xQueueSendFromISR() 与 xQueueSendToBackFromISR() 功能等价。

参数名 / 返回值说明
xQueue数据被发送(写入)到的队列句柄,来自创建队列的 xQueueCreate()。
pvItemToQueue指向待拷贝进队列数据的指针。队列每项大小在创建时设定,从 pvItemToQueue 拷贝相应字节数到队列存储区。
pxHigherPriorityTaskWoken一个队列上可能有一个或多个任务阻塞等待数据可用。调用发送 API 可使数据可用,从而解除任务阻塞。若被解除阻塞任务优先级高于当前执行任务(被中断任务),函数内部会把 *pxHigherPriorityTaskWoken 置为 pdTRUE;置为 pdTRUE 时应在退出中断前执行上下文切换,确保中断直接返回到最高优先级就绪态任务。
返回值① pdPASS:仅在数据成功发送到队列时返回。② errQUEUE_FULL:队列已满,数据无法发送。

6.7.2在 ISR 中使用队列的注意事项

队列提供了从中断向任务传数据的简便方式,但数据高频到达时用队列效率不高。FreeRTOS 下载包中许多演示应用含一个简单 UART 驱动,用队列把字符从 UART 接收 ISR 传出;这些演示用队列有两个原因:演示在 ISR 中使用队列,以及故意给系统加压以测试移植。以这种方式用队列的 ISR 绝不是高效设计的范例;除非数据到达较慢,建议生产代码不要照搬。适合生产代码的更高效技术包括:

6.7.3示例 19:在中断内收发队列

本示例演示在同一中断中使用 xQueueSendToBackFromISR() 与 xQueueReceiveFromISR()。同样为方便起见,中断由软件产生。

创建一个周期任务,每 200 毫秒向队列发送五个数字;五个值全部发完后才产生软件中断。任务实现见清单 107。

static void vIntegerGenerator( void *pvParameters )
{
    TickType_t xLastExecutionTime;
    uint32_t ulValueToSend = 0;
    int i;

    /* Initialize the variable used by the call to vTaskDelayUntil(). */
    xLastExecutionTime = xTaskGetTickCount();

    for( ;; )
    {
        /* This is a periodic task.  Block until it is time to run again.  The task
           will execute every 200ms. */
        vTaskDelayUntil( &xLastExecutionTime, pdMS_TO_TICKS( 200 ) );

        /* Send five numbers to the queue, each value one higher than the previous
           value.  The numbers are read from the queue by the interrupt service routine.
           The interrupt service routine always empties the queue, so this task is
           guaranteed to be able to write all five values without needing to specify a
           block time. */
        for( i = 0; i < 5; i++ )
        {
            xQueueSendToBack( xIntegerQueue, &ulValueToSend, 0 );
            ulValueToSend++;
        }

        /* Generate the interrupt so the interrupt service routine can read the
           values from the queue. The syntax used to generate a software interrupt is
           dependent on the FreeRTOS port being used.  The syntax used below can only be
           used with the FreeRTOS Windows port, in which such interrupts are only
           simulated.*/
        vPrintString( "Generator task - About to generate an interrupt.\r\n" );
        vPortGenerateSimulatedInterrupt( mainINTERRUPT_NUMBER );
        vPrintString( "Generator task - Interrupt generated.\r\n\r\n\r\n" );
    }
}
清单 107 · 示例 19 中写队列的任务实现

ISR 反复调用 xQueueReceiveFromISR(),直到周期任务写入队列的所有值都被读出、队列清空。每个收到值的最后两位作为字符串数组下标,再用 xQueueSendFromISR() 把对应下标位置的字符串指针发到另一个队列。ISR 实现见清单 108。

static uint32_t ulExampleInterruptHandler( void )
{
    BaseType_t xHigherPriorityTaskWoken;
    uint32_t ulReceivedNumber;

    /* The strings are declared static const to ensure they are not allocated on the
       interrupt service routine's stack, and so exist even when the interrupt service
       routine is not executing. */
    static const char *pcStrings[] =
    {
        "String 0\r\n",
        "String 1\r\n",
        "String 2\r\n",
        "String 3\r\n"
    };

    /* As always, xHigherPriorityTaskWoken is initialized to pdFALSE to be able to
       detect it getting set to pdTRUE inside an interrupt safe API function. Note that
       as an interrupt safe API function can only set xHigherPriorityTaskWoken to
       pdTRUE, it is safe to use the same xHigherPriorityTaskWoken variable in both
       the call to xQueueReceiveFromISR() and the call to xQueueSendToBackFromISR(). */
    xHigherPriorityTaskWoken = pdFALSE;

    /* Read from the queue until the queue is empty. */
    while( xQueueReceiveFromISR( xIntegerQueue,
                                &ulReceivedNumber,
                                &xHigherPriorityTaskWoken ) != errQUEUE_EMPTY )
    {
        /* Truncate the received value to the last two bits (values 0 to 3
           inclusive), then use the truncated value as an index into the pcStrings[]
           array to select a string (char *) to send on the other queue. */
        ulReceivedNumber &= 0x03;

        xQueueSendToBackFromISR( xStringQueue,
                                 &pcStrings[ ulReceivedNumber ],
                                 &xHigherPriorityTaskWoken );
    }

    /* If receiving from xIntegerQueue caused a task to leave the Blocked state, and
       if the priority of the task that left the Blocked state is higher than the
       priority of the task in the Running state, then xHigherPriorityTaskWoken will
       have been set to pdTRUE inside xQueueReceiveFromISR().
       If sending to xStringQueue caused a task to leave the Blocked state, and if the
       priority of the task that left the Blocked state is higher than the priority of
       the task in the Running state, then xHigherPriorityTaskWoken will have been set
       to pdTRUE inside xQueueSendToBackFromISR().
       xHigherPriorityTaskWoken is used as the parameter to portYIELD_FROM_ISR().  If
       xHigherPriorityTaskWoken equals pdTRUE then calling portYIELD_FROM_ISR() will
       request a context switch.  If xHigherPriorityTaskWoken is still pdFALSE then
       calling portYIELD_FROM_ISR() will have no effect.
       The implementation of portYIELD_FROM_ISR() used by the Windows port includes a
       return statement, which is why this function does not explicitly return a
       value. */
    portYIELD_FROM_ISR( xHigherPriorityTaskWoken );
}
清单 108 · 示例 19 所用 ISR 实现

从 ISR 接收字符指针的任务在队列上阻塞直到消息到达,每收到一个字符串就打印,实现见清单 109。

static void vStringPrinter( void *pvParameters )
{
    char *pcString;

    for( ;; )
    {
        /* Block on the queue to wait for data to arrive. */
        xQueueReceive( xStringQueue, &pcString, portMAX_DELAY );

        /* Print out the string received. */
        vPrintString( pcString );
    }
}
清单 109 · 示例 19 中打印 ISR 所发字符串的任务

与通常一样,main() 在启动调度器前创建所需队列与任务,实现见清单 110。

int main( void )
{
    /* Before a queue can be used it must first be created.  Create both queues used
       by this example.  One queue can hold variables of type uint32_t, the other queue
       can hold variables of type char*.  Both queues can hold a maximum of 10 items.  A
       real application should check the return values to ensure the queues have been
       successfully created. */
    xIntegerQueue = xQueueCreate( 10, sizeof( uint32_t ) );
    xStringQueue = xQueueCreate( 10, sizeof( char * ) );

    /* Create the task that uses a queue to pass integers to the interrupt service
       routine.  The task is created at priority 1. */
    xTaskCreate( vIntegerGenerator, "IntGen", 1000, NULL, 1, NULL );

    /* Create the task that prints out the strings sent to it from the interrupt
       service routine.  This task is created at the higher priority of 2. */
    xTaskCreate( vStringPrinter, "String", 1000, NULL, 2, NULL );

    /* Install the handler for the software interrupt.  The syntax necessary to do
       this is dependent on the FreeRTOS port being used.  The syntax shown here can
       only be used with the FreeRTOS Windows port, where such interrupts are only
       simulated. */
    vPortSetInterruptHandler( mainINTERRUPT_NUMBER, ulExampleInterruptHandler );

    /* Start the scheduler so the created tasks start executing. */
    vTaskStartScheduler();

    /* If all is well then main() will never reach here as the scheduler will now be
       running the tasks.  If main() does reach here then it is likely that there was
       insufficient heap memory available for the idle task to be created.  Chapter 2
       provides more information on heap memory management. */
    for( ;; );
}
清单 110 · 示例 19 的 main() 函数
图 59 · 执行示例 19 时产生的输出
图 59 · 执行示例 19 时产生的输出

可见中断收到全部五个整数,并据此产生五个字符串;进一步解释见图 60。

图 60(示例 19 执行序列):① 大部分时间运行空闲任务,每 200ms 被 IntegerGenerator 任务抢占;② IntegerGenerator 向队列写 5 个值后强制中断;③ ISR 既读队列也写队列:从一个队列每收到一个整数就向另一个队列写一个字符串;写字符串解除 StringPrinter 任务阻塞;④ StringPrinter 是最高优先级任务,ISR 后立即运行,打印队列收到的每个字符串;队列空后进入阻塞态,低优先级 IntegerGenerator 再次运行;⑤ IntegerGenerator 是周期任务,阻塞等待下一周期,空闲任务再次成为唯一可运行任务;200ms 后整个序列重复。

6.8中断嵌套

任务优先级与中断优先级常被混淆。本节讨论中断优先级,即各 ISR 相互之间的执行先后。任务所赋优先级与中断所赋优先级毫无关系:硬件决定 ISR 何时执行,软件决定任务何时执行;硬件中断响应的 ISR 可打断任务,但任务不能抢占 ISR。

支持中断嵌套的移植要求在 FreeRTOSConfig.h 中定义表 39 所列一个或两个常量。configMAX_SYSCALL_INTERRUPT_PRIORITY 与 configMAX_API_CALL_INTERRUPT_PRIORITY 定义同一属性;较老移植用前者,较新移植用后者。

常量说明
configMAX_SYSCALL_INTERRUPT_PRIORITY 或 configMAX_API_CALL_INTERRUPT_PRIORITY设定可调用中断安全 FreeRTOS API 的最高中断优先级。
configKERNEL_INTERRUPT_PRIORITY设定节拍中断使用的中断优先级,必须始终设为最低可能中断优先级。若所用移植未使用 configMAX_SYSCALL_INTERRUPT_PRIORITY 常量,则任何使用中断安全 FreeRTOS API 的中断也必须运行在 configKERNEL_INTERRUPT_PRIORITY 定义的优先级上。

每个中断源都有数值优先级与逻辑优先级:

数值优先级与逻辑优先级的关系取决于处理器架构:有些架构数值越大逻辑优先级越高,另一些架构数值越大逻辑优先级越低。

把 configMAX_SYSCALL_INTERRUPT_PRIORITY 设为比 configKERNEL_INTERRUPT_PRIORITY 更高的逻辑中断优先级,即构成完整中断嵌套模型,如图 61。场景:处理器有 7 个独立中断优先级;数值 7 的中断逻辑优先级高于数值 1;configKERNEL_INTERRUPT_PRIORITY 设为 1;configMAX_SYSCALL_INTERRUPT_PRIORITY 设为 3。

图 61(影响中断嵌套行为的常量,优先级 1–7):① 优先级 1–3 的中断在内核或应用处于临界区内时被阻止执行;这些优先级的 ISR 可使用中断安全 FreeRTOS API;② 优先级 4 及以上的中断不受临界区影响,调度器的任何动作都不会阻止其立即执行(受硬件本身限制);这些优先级的 ISR 不能使用任何 FreeRTOS API;③ 通常时序精度要求极高的功能(如电机控制)使用高于 configMAX_SYSCALL_INTERRUPT_PRIORITY 的优先级,确保调度器不给中断响应时间引入抖动。

6.8.1给 ARM Cortex-M 与 ARM GIC 用户的提示

Cortex-M 处理器上的中断配置容易混淆出错。为辅助开发,FreeRTOS Cortex-M 移植会自动检查中断配置,但前提是定义了 configASSERT()(见 11.2 节)。

ARM Cortex 内核与 ARM 通用中断控制器(GIC)用较小的数值编号表示逻辑高优先级,这看似反直觉、容易遗忘:要给中断分配逻辑低优先级,必须赋予数值较大的值;要分配逻辑高优先级,必须赋予数值较小的值。

Cortex-M 中断控制器最多可用 8 位指定每个中断优先级,故 255 为最低优先级、0 为最高优先级;但 Cortex-M 单片机通常只实现这 8 位中的一部分,实际位数取决于单片机系列。只实现部分位时,只有字节最高位可用,最低位不实现;未实现位可取任意值,通常置 1。图 62 演示二进制 101 的优先级在实现 4 个优先级位的 Cortex-M 单片机中如何存储。

图 62 · 实现 4 个优先级位的 Cortex-M 单片机如何存储二进制 101 优先级
图 62 · 实现 4 个优先级位的 Cortex-M 单片机如何存储二进制 101 优先级

图 62 中二进制 101 被左移到最高 4 位,因为最低 4 位未实现;未实现位置 1。

部分库函数要求优先级值在左移到已实现(最高)位之后指定;用这类函数时,图 62 的优先级可指定为十进制 95:95 是二进制 101 左移 4 位成为 101nnnn(n 为未实现位),未实现位置 1 成为二进制 1011111。另一些库函数要求优先级在左移之前指定;用这类函数时,图 62 的优先级必须指定为十进制 5,即未移位的二进制 101。

configMAX_SYSCALL_INTERRUPT_PRIORITY 与 configKERNEL_INTERRUPT_PRIORITY 的指定方式必须能直接写入 Cortex-M 寄存器,即优先级值已左移到已实现位之后。configKERNEL_INTERRUPT_PRIORITY 必须始终设为最低可能中断优先级;未实现优先级位可置 1,因此无论实际实现多少位,该常量都可设为 255。

Cortex-M 中断默认优先级为 0(最高可能优先级);Cortex-M 硬件实现不允许把 configMAX_SYSCALL_INTERRUPT_PRIORITY 设为 0,因此使用 FreeRTOS API 的中断,其优先级绝不能保留默认值。