keil CMSIS-RTOS API介绍

本文详细介绍了RTOS(实时操作系统)的基本功能,包括内核初始化、线程管理、信号量管理等,并提供了丰富的代码示例帮助理解。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1.Kernel information and Control:

           osKernelInitialize (void)       Initialize the RTOS Kernel for creating objects. 

       osKernelStart (void)            Start the RTOS Kernel.

       osKernelRunning (void)        Check if the RTOS kernel is already started.

       osKernelSysTick (void)         Get the RTOS kernel system timer counter.

Code Example

#include "cmsis_os.h"
int main ( void) {
if ( osKernelInitialize () != osOK) { // check osStatus for other possible valid values
// exit with an error message
}
if (! osKernelRunning ()) { // is the kernel running ?
if ( osKernelStart () != osOK) { // start the kernel
// kernel could not be started
}
}
}
2.Thread Management

keil RTOS thread 有四种状态,RUNNING,READY,WAITING,INACTIVE。

 

osThreadDef( name,priority,instances,stacksz )     Define the attributes of a thread functions that can be created by the function osThreadCreate using osThread.

osThreadCreate (const osThreadDef_t * thread_def, void *  argument )

Parameters
[in] thread_defthread definition referenced with osThread.
[in] argumentpointer that is passed to the thread function as start argument 

return thread ID.

需要注意的是,当使用osThreadCreate来创建thread时,会将线程置于READY or RUNNING 状态


osThreadId osThreadGetId(void )  得到当前线程的ID


还有线程优先级的设置osStatus osThreadSetPriority (osThreadId thread_id,osPriority priority )


CodeExample

#include "cmsis_os.h"
void Thread_1 ( void const *arg) { // Thread function
osThreadId id; // id for the currently running thread
osPriority pr; // thread priority
osStatus status; // status of the executed function
:
id = osThreadGetId (); // Obtain ID of current running thread
if ( id != NULL) {
if (status == osOK) {
// Thread priority changed to BelowNormal
}
else {
// Failed to set the priority
}
}
else {
// Failed to get the id
}
:
}


3.Generic Wait Functions

osStatus osDelay (uint32_t millisec)
 Wait for Timeout (Time Delay). 
 
osEvent osWait (uint32_t millisec)
 Wait for Signal, Message, Mail, or Timeout. 

4.Timer Management

 osTimerDef  osTimerCreate   osTimerDelete  osTimerStart  osTimerStop

Code Example

#include "cmsis_os.h"
void Timer_Callback ( void const *arg); // prototype for timer callback function
osTimerDef (Timer, Timer_Callback); // define timer
void TimerStop_example ( void) {
osTimerId id; // timer id
osStatus status; // function return status
/ Create periodic timer
exec = 1;
id = osTimerCreate ( osTimer(Timer2), osTimerPeriodic, NULL);
osTimerStart ( id, 1000); // start timer
:
status = osTimerStop ( id); // stop timer
if (status != osOK) {
// Timer could not be stopped
}
:
osTimerStart ( id, 1000); // start timer again
:
}
os_timer_type:
osTimerOnce 

      one-shot timer

osTimerPeriodic 

     repeating timer

5.Signal Management

三个函数

osSignalSet  osSignalClear osSignalWait

Example 

voidThread_2 (void const *arg);

osThreadDef(Thread_2, osPriorityHigh, 1, 0);

staticvoidEX_Signal_1 (void) {

osThreadIdthread_id;

osEventevt;

thread_id = osThreadCreate (osThread(Thread_2), NULL);

if(thread_id == NULL) {

// Failed to create a thread.

}

else{

:

// wait for a signal

evt = osSignalWait (0x01, 100);

if(evt.status == osEventSignal) {

// handle event status

}

}

}

PS: osSignalWait(0,million)意思是收到任何信号都可以

当然,这边有个疑问就是在第一个线程中发了一个信号,程序会是执行完这个线程后再去到另一个接收信号的线程执行呢,还是发完信号直接去另一个线程去处理,执行完了再返回第一个线程继续执行,有人说是跟买票一样,一人走一步。等待在板子上跑跑看
6.Mutex Management

Mutext用于各个线程之间对资源的独享,互斥锁不能被中断服务程序调用。

osMutexDef   osMutexCreate  osMutexDelete   osMutexRelease  osMutexWait

个人感觉在RTX操作系统里osMutexWait应该是UC/OSII里的OsMutexPend,

 

例子:

osMutexDef( Mutex );

osMutexId mutex;

 

void Thread0( void * arg);

void Thread1( void * arg);

 

osThreadDef( Thread0, Thread0, osPriorityNormal, 512 );

osThreadDef( Thread1, Thread1, osPriorityAboveNormal, 512 );

 

 

void Thread0( void * arg)

{

  while(1)

  {

    osMutexWait( mutex, osWaitForever );

    osDelay( 10 );

    osMutexRelease( mutex );

    osDelay( 10 );

  }

}

 

void Thread1( void * arg)

{

  while(1)

  {

    osMutexWait( mutex, osWaitForever );

    osDelay( 10 );

    osMutexRelease( mutex );

    osDelay( 10 );

  }

}

 

int main( void )

{

  osKernelInitialize();

 

  osThreadCreate( osThread(Thread0), (void *)100 );

  osThreadCreate( osThread(Thread1), (void *)200 );

 

  mutex = osMutexCreate( osMutex(Mutex) );

 

  osKernelStart();

 

  return 0;

}

7.Semaphore Management

信号量和mutex类似,mutex一次只允许一个线程访问共享资源,信号量允许固定数量的线程访问共享资源池,

8.Message Queue Management

osMessageGet(queue_id,millisec) 会挂起正在执行的线程,直到一个消息到来。当此函数在ISR调用时,millisec必须是0

osMessagePut queue_id,info,millisec)向队列发送消息,info整数(uint32_t)或指针类型

9.Mail Queue Management

使用邮箱首先要申请一块内存,使用osMailAlloc(osMailQId queue_id, uint32_t millisec)或者是osMailCAlloc(osMailQId queue_id, uint32_t millisec),两者唯一区别就是后者直接里面全赋0.发送给邮箱用osMailPut(osMailQId queue_id, void *mail),从邮箱里读信息用osMailGet(osMailQId queue_id, uint32_t millisec),osMailGet()和osMessageq_get,一样,也是挂起当前的任务直到邮箱里来消息才运行,与MessageQ好一点的是,可以传递的是结构体。

例子:

#include <stdio.h>

#include "cmsis_os.h"

  

  /* Thread IDs */

 osThreadId tid_thread1;               /* assigned ID for thread 1            */

  osThreadId tid_thread2;               /* assigned ID for thread 2            */

 

 typedef struct {                      /* Mail object structure               */

 float    voltage;                   /* AD result of measured voltage       */

   float    current;                   /* AD result of measured current       */

   uint32_t counter;                   /* A counter value                     */

 } T_MEAS;

 

 osMailQDef(mail, 16, T_MEAS);         /* Define mail queue                   */

 osMailQId  mail;

 

 /* Forward reference */

 void send_thread (void const *argument);

 void recv_thread (void const *argument);

 

 /* Thread definitions */

 osThreadDef(send_thread, osPriorityNormal, 1, 0);

 osThreadDef(recv_thread, osPriorityNormal, 1, 2000);

 

 

 /*----------------------------------------------------------------------------

  *  Thread 1: Send thread

  *---------------------------------------------------------------------------*/

 void send_thread (void const *argument) {

   T_MEAS *mptr;

 

   mptr = osMailAlloc(mail, osWaitForever);           /* Allocate memory      */

   mptr->voltage = 223.72;             /* Set the mail content                */

  mptr->current = 17.54;

  mptr->counter = 120786;

   osMailPut(mail, mptr);              /* Send Mail                           */

  osDelay(100);

 

   mptr = osMailAlloc(mail, osWaitForever);           /* Allocate memory      */

    mptr->voltage = 227.23;             /* Prepare 2nd mail                    */

   mptr->current = 12.41;

   mptr->counter = 170823;

   osMailPut(mail, mptr);              /* Send Mail                           */

   osThreadYield();                    /* Cooperative multitasking            */

   osDelay(100);

 

   mptr = osMailAlloc(mail, osWaitForever);           /* Allocate memory      */

   mptr->voltage = 229.44;             /* Prepare 3rd mail                    */

   mptr->current = 11.89;

   mptr->counter = 237178;

   osMailPut(mail, mptr);              /* Send Mail                           */

   osDelay(100);

                                       /* We are done here, exit this thread  */

 }

 

 /*----------------------------------------------------------------------------

  *  Thread 2: Receive thread

  *---------------------------------------------------------------------------*/

void recv_thread (void const *argument) {

T_MEAS  *rptr;

   osEvent  evt;

 

   for (;;) {

      evt = osMailGet(mail, osWaitForever);  /* wait for mail                  */

     if (evt.status == osEventMail) {

      rptr = evt.value.p;

       printf ("\nVoltage: %.2f V\n",rptr->voltage);

       printf ("Current: %.2f A\n",rptr->current);

       printf ("Number of cycles: %d\n",(int)rptr->counter);

       #ifdef __USE_FFLUSH

       fflush (stdout);

       #endif

       osMailFree(mail, rptr);         /* free memory allocated for mail      */

     }

   }

 }

 

 /*----------------------------------------------------------------------------

 *   Main:

  *---------------------------------------------------------------------------*/

 int main (void) {                     /* program execution starts here       */

 

   mail = osMailCreate(osMailQ(mail), NULL);  /* create mail queue            */

  tid_thread1 = osThreadCreate(osThread(send_thread), NULL);

   tid_thread2 = osThreadCreate(osThread(recv_thread), NULL);

 

   osDelay(osWaitForever);

   for (;;);

 }

 






<think>我们正在处理一个关于FreeRTOS任务创建函数差异的问题。用户提到在自行移植FreeRTOS时使用vTaskCreate函数,而STM32CubeMX生成的代码使用的是osThreadCreate(或类似的CubeMX封装函数),两者不一致,用户想知道原因以及如何解决。根据引用内容,我们可以分析:1.引用[2]展示了在FreeRTOS中直接使用xTaskCreate函数(vTaskCreate是xTaskCreate的别名)创建任务。2.引用[3]中则使用了osMutexAcquire等函数,这是CMSIS-RTOSAPI的一部分,而STM32CubeMX生成的代码通常使用CMSIS-RTOS v1或v2的封装层。 原因分析:-STM32CubeMX在配置FreeRTOS时,会生成一个中间层(CMSIS-RTOS封装),这样可以使用标准化的API(如osThreadNew)来创建任务,而不是直接调用FreeRTOSAPI。这样做的好处是代码可移植性高,如果更换RTOS,只需更换封装层。-而直接移植FreeRTOS时,我们通常直接调用FreeRTOS的原生API(如xTaskCreate)。 因此,用户遇到的情况是正常的:CubeMX生成的代码使用了CMSIS-RTOS API,而用户移植的代码直接使用FreeRTOSAPI。解决方法:如果用户希望在自己的移植代码中使用与CubeMX一致的方式(即使用封装函数),那么需要引入CMSIS-RTOS封装层。但是,如果用户希望直接使用FreeRTOSAPI,也是完全可以的,只要确保在同一个工程中不要混用两种方式(除非设计好兼容性)。如果用户已经使用了CubeMX生成代码,那么应该使用CubeMX提供的API(如osThreadCreate或osThreadNew)来创建任务。如果用户没有使用CubeMX,而是自己移植的FreeRTOS,那么直接使用vTaskCreate即可。 注意:CubeMX生成的FreeRTOS配置会包含一个cmsis_os.c或cmsis_os2.c文件,这个文件实现了CMSIS-RTOS API。因此,在CubeMX工程中,创建任务应该使用osThreadNew,而不是直接使用xTaskCreate。 在引用[2]中,用户展示的是直接使用xTaskCreate创建任务,这是FreeRTOS的原生函数。而在CubeMX生成的代码中,任务创建通常是通过osThreadNew实现的,这个函数内部会调用xTaskCreate(或xTaskCreateStatic等),但添加了一些额外的处理,比如将任务句柄存储到osThreadId_t中。 因此,用户的问题可能是:为什么CubeMX生成的代码不直接使用vTaskCreate?答案是为了兼容CMSIS-RTOS标准。如果用户希望在自己的移植代码中模仿CubeMX的方式,可以:1.包含CMSIS-RTOS的头文件(如cmsis_os.h)。2.使用osThreadNew等函数创建任务。或者,如果用户不想使用CMSIS-RTOS层,那么直接使用vTaskCreate也是正确的,但要注意不要和CubeMX生成的代码混用(除非自己清楚如何混合使用)。 总结回答要点: 1.解释CubeMX使用封装层(CMSIS-RTOS)的原因。2.说明两种方式(直接使用FreeRTOSAPI和使用CMSIS-RTOSAPI)都是可行的,但不要混用。 3.给出建议:如果用户使用CubeMX,则遵循CubeMX生成的代码风格;如果是自己移植,则可以直接使用FreeRTOSAPI。最后,生成相关问题。</think>### FreeRTOS 中 `vTaskCreate` 与 STM32CubeMX 任务创建函数的差异分析 #### 原因分析 1. **API 层级不同** - `vTaskCreate` 是 FreeRTOS 原生 API,直接调用内核函数创建任务[^2]。 - STM32CubeMX 生成的是 **CMSIS-RTOS v2 封装层** 的 API(如 `osThreadNew`),通过中间层调用 FreeRTOS 原生函数,提供标准化接口以增强可移植性[^1][^3]。 - 数学表达示例:设原生 API 调用为 $f(x)$,CubeMX 封装层为 $g(f(x))$,其中 $g$ 是 CMSIS 适配层。 2. **函数参数差异** - `vTaskCreate` 参数示例(引用[2]): ```c xTaskCreate(task1, "task1", TASK1_STACK, NULL, TASK1_PRIORITY, &task1_handle); ``` - CubeMX 生成的 `osThreadNew` 参数更抽象: ```c osThreadId_t osThreadNew(osThreadFunc_t func, void *arg, const osThreadAttr_t *attr); ``` 需通过 `osThreadAttr_t` 结构体配置栈大小、优先级等属性[^1]。 3. **资源管理方式** - 原生 API 需手动计算栈大小(如 `#define TASK1_STACK 128`)[^2]。 - CubeMX 通过 **可视化配置**(如 Config parameters / Advanced settings)自动生成资源分配代码,减少手动错误[^1]。 #### 解决方法 1. **统一使用 CubeMX 生成函数** - 在 CubeMX 工程中严格使用 `osThreadNew` 等 CMSIS 函数,避免混用原生 API- 示例(引用[3]风格): ```c osThreadAttr_t task_attr = { .name = "displayTask", .stack_size = 1024, .priority = osPriorityNormal }; osThreadNew(displayTask, NULL, &task_attr); ``` 2. **手动移植时统一用原生 API** - 若未使用 CubeMX,则全程使用 `vTaskCreate`: ```c TaskHandle_t handle; xTaskCreate(task_func, "Task", 128, NULL, 2, &handle); ``` 3. **临界区保护** - 任务创建时建议添加临界区保护(如引用[2]所示): ```c taskENTER_CRITICAL(); // 创建任务 taskEXIT_CRITICAL(); ``` #### 关键注意事项 - **禁止混用两种 API**:混用会导致资源管理冲突(如栈分配错误)。 - **优先级数值方向**:FreeRTOS 默认 **数值越大优先级越高**(0 为最低),需与 CubeMX 配置一致。 - **堆空间检查**:使用 **FreeRTOS Heap Usage** 工具监控内存,确保任务栈未溢出[^1]。 > **根本原因总结**:CubeMX 通过 CMSIS-RTOS 抽象层实现硬件无关性,而原生移植直接操作内核。二者本质功能相同,但接口封装层级不同。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值