1 /*=======0=========1=========2=========3=========4=========5=========6=========7=========8=========9=========0=========1====*/
5 The CMSIS-RTOS manages the resources of the microcontroller system and implements the concept of parallel threads that run concurrently.
6 There are many advantages of using an CMSIS-RTOS v2 compliant kernel as it provides a standardized interface.
8 Applications frequently require several concurrent activities. CMSIS-RTOS can manage multiple concurrent activities at the time when
9 they are needed. Each activity gets a separate thread which executes a specific task and this simplifies the overall program structure.
10 The CMSIS-RTOS system is scalable and additional threads can be added easily at a later time. Threads have a priority allowing faster
11 execution of time-critical parts of an user application.
13 The CMSIS-RTOS offers services needed in many real-time applications, for example, periodical activation of timer functions,
14 memory management, and message exchange between threads with time limits.
16 The <b>CMSIS-RTOS API v2</b> addresses the following new requirements:
17 - Dynamic object creation no longer requires static memory, static memory buffers are now optional.
18 - Support for ARMv8-M architecture that provides a Secure and Non-Secure state of code execution.
19 - Provisions for message passing in multi-core systems.
20 - Full support of C++ run-time environments.
21 - C interface which is binary compatible across <a class="el" href="http://infocenter.arm.com/help/topic/com.arm.doc.subset.swdev.abi/index.html">ABI compatible compilers</a>.
23 As a consequence of these requirements the CMSIS-RTOS API v2 has the following fundamental modifications:
24 - The functions osXxxxNew replace osXxxxCreate functions; osXxxxNew and osXxxxDelete create and destroy objects.
25 - The C function main is not longer started as a thread (this was an optional feature in CMSIS-RTOS v1).
26 - Functions that return osEvent have been replaced.
28 CMSIS-RTOS API v2 provides an translation layer for the
29 <a class="el" href="../../RTOS/html/index.html">CMSIS-RTOS API v1</a>.
30 It is possible to intermix CMSIS-RTOS API v2 and CMSIS-RTOS API v1 within the same application.
31 You may migrate overtime to the new API as explained in \ref os2Migration.
33 CMSIS-RTOS API v2 is not POSIX compliant, but has provisions to enable a C++11/C++14 interface.
37 CMSIS-RTOS in ARM::CMSIS Pack
38 -----------------------------
40 The following files relevant to CMSIS-RTOS are present in the <b>ARM::CMSIS</b> Pack directories:
42 -----------------------------|------------------------------------------------------------------------
43 \b CMSIS/Documentation/RTOS2 | This documentation
44 \b CMSIS/Documentation/RTOS | CMSIS-RTOS API v1 documentation
45 \b CMSIS/RTOS2/Include | \ref cmsis_os2_h
49 /*=======0=========1=========2=========3=========4=========5=========6=========7=========8=========9=========0=========1====*/
51 \page rtos_revisionHistory Revision History
53 <table class="cmtable" summary="Revision History">
62 -- added: osKernelGetInfo, osKernelGetState.\n
63 -- added: osKernelLock, osKernelUnlock.\n
64 -- added: osKernelSuspend, osKernelResume.\n
65 -- added: osKernelGetTime.\n
66 -- renamed osKernelSysTick to osKernelGetSysTick.\n
68 -- extended number of thread priorities.\n
69 -- changed thread return value.\n
70 -- replaced osThreadCreate with osThreadNew.\n
71 -- added: osThreadGetState.\n
72 -- added: osThreadSuspend, osThreadResume.\n
73 -- added: osThreadJoin, osThreadDetach, osThreadExit.\n
75 -- renamed osSignals to osThreadFlags.\n
76 -- changed return value of Set/Clear/Wait functions.\n
77 -- Clear function limited to current running thread.\n
78 -- extended Wait function (options).\n
79 -- added: osThreadFlagsGet.\n
80 - Event Flags: added new independent object for handling Event Flags.\n
81 - Delay and Wait functions:\n
82 -- added: osDelayUntil.\n
83 -- deprecated: osWait.\n
85 -- replaced osTimerCreate with osTimerNew.\n
86 -- added: osTimerIsRunning.\n
88 -- extended: attributes (Recursive, Priority Inherit, Robust).\n
89 -- replaced osMutexCreate with osMutexNew.\n
90 -- renamed osMutexWait to osMutexAcquire.\n
91 -- added: osMutexGetOwner.\n
93 -- extended: maximum and initial token count.\n
94 -- replaced osSemaphoreCreate with osSemaphoreNew.\n
95 -- renamed osSemaphoreWait to osSemaphoreAcquire (changed return value).\n
96 -- added: osSemaphoreGetCount.\n
98 -- using osMemoryPool prefix instead of osPool.\n
99 -- replaced osPoolCreate with osMemoryPoolNew.\n
100 -- extended: osMemoryPoolAlloc (timeout).\n
101 -- added: osMemoryPoolGetCapacity, osMemoryPoolGetBlockSize.\n
102 -- added: osMemoryPoolGetCount, osMemoryPoolGetSpace.\n
103 -- added: osMemoryPoolDelete.\n
104 -- deprecated: osPoolCAlloc.\n
106 -- fixed size messages instead of a single 32-bit values.\n
107 -- using osMessageQueue prefix instead of osMessage.\n
108 -- replaced osMessageCreate with osMessageQueueNew.\n
109 -- updated: osMessageQueuePut, osMessageQueueGet.\n
110 -- added: osMessageQueueGetCapacity, osMessageQueueGetMsgSize.\n
111 -- added: osMessageQueueGetCount, osMessageQueueGetSpace.\n
112 -- added: osMessageQueueReset, osMessageQueueDelete.\n
113 - Mail Queue: deprecated (superseded by extended Message Queue functionality).\n
117 <td>V1.02 - only documentation changes</td>
119 Added: Overview of the \ref rtosValidation "CMSIS-RTOS Validation" Software Pack.\n
120 Clarified: Behavior of \ref CMSIS_RTOS_TimeOutValue.
125 <td>Added: New control functions for short timeouts in microsecond resolution \b osKernelSysTick,
126 \b osKernelSysTickFrequency, \b osKernelSysTickMicroSec.\n
127 Removed: osSignalGet.
132 <td>Added capabilities for C++, kernel initialization and object deletion.\n
133 Prepared for C++ class interface. In this context to \em const attribute has been moved from osXxxxDef_t typedefs to
134 the osXxxxDef macros.\n
135 Added: \ref osTimerDelete, \ref osMutexDelete, \ref osSemaphoreDelete.\n
136 Added: \ref osKernelInitialize that prepares the Kernel for object creation.\n
142 <td>First official Release.\n
143 Added: \ref osKernelStart; starting 'main' as a thread is now an optional feature.\n
144 Semaphores have now the standard behavior.\n
145 \b osTimerCreate does no longer start the timer. Added: \ref osTimerStart (replaces osTimerRestart).\n
146 Changed: osThreadPass is renamed to \ref osThreadYield.
151 <td>Preview Release.</td>
157 /*=======0=========1=========2=========3=========4=========5=========6=========7=========8=========9=========0=========1====*/
159 \page functionOverview Function Overview
161 CMSIS-RTOS v2 provides multiple API interfaces:
162 - \subpage rtos_api2 is the new C function API that supports dynamic object creation, ARMv8-M, and multi-processor communication.
163 - <a class="el" href="../../RTOS/html/functionOverview.html">CMSIS-RTOS C API v1</a> is a C function API the is backward compatible with CMSIS-RTOS v1.
164 - \subpage rtos_apicpp is a C++ class function API.
166 It is possible to intermix the different API variants in the same application and even in the same C/C++ source module.
167 However, the functions of the <b>C API Version 1</b> may be deprecated in future versions of CMSIS-RTOS.
169 \section CMSIS_RTOS_TimeOutValue Timeout Value
171 Timeout values are an argument to several \b osXxx functions to allow time for resolving a request.
172 A timeout value of \b 0 means that the RTOS does not wait and returns instantly, even when no resource is available.
173 A timeout value of \ref osWaitForever means that the RTOS waits infinite until a resource becomes available.
175 The timeout value specifies the number of timer ticks until the time delay elapses. The value is an upper bound and
176 depends on the actual time elapsed since the last timer tick.
179 - timeout value \b 0 : the system does not wait, even when no resource is available the RTOS function returns instantly.
180 - timeout value \b 1 : the system waits until the next timer tick occurs; depending on the previous timer tick, it may be a very short wait time.
181 - timeout value \b 2 : actual wait time is between 1 and 2 timer ticks.
182 - timeout value \ref osWaitForever : system waits infinite until a resource becomes available.
184 \todo B: remove first '|' to make the picture clearer, make ... before first tick, add word 'time' after the arrow.
186 \image html TimerValues.png "Timer Values"
188 \section CMSIS_RTOS_ISR_Calls Calls from Interrupt Service Routines
190 The following CMSIS-RTOS2 functions can be called from threads and Interrupt Service Routines (ISR):
191 - \ref osThreadFlagsSet
192 - \ref osEventFlagsSet, \ref osEventFlagsClear, \ref osEventFlagsGet, \ref osEventFlagsWait
193 - \ref osSemaphoreAcquire, \ref osSemaphoreRelease, \ref osSemaphoreGetCount
194 - \ref osMemoryPoolAlloc, \ref osMemoryPoolFree, \ref osMemoryPoolGetCapacity, \ref osMemoryPoolGetBlockSize, \ref osMemoryPoolGetCount, \ref osMemoryPoolGetSpace
195 - \ref osMessageQueuePut, \ref osMessageQueueGet, \ref osMessageQueueGetCapacity, \ref osMessageQueueGetMsgSize, \ref osMessageQueueGetCount, \ref osMessageQueueGetSpace
198 Functions that cannot be called from an ISR are verifying the interrupt status and return, in case they are called
199 from an ISR context, the status code \b osErrorISR. In some implementations, this condition might be caught using the HARD
206 /*=======0=========1=========2=========3=========4=========5=========6=========7=========8=========9=========0=========1====*/
208 \page rtos_api2 CMSIS-RTOS C API v2
210 Overview of all CMSIS-RTOS C API v2 functions.
212 - \ref CMSIS_RTOS_KernelCtrl
213 - \ref osKernelGetInfo : \copybrief osKernelGetInfo
214 - \ref osKernelGetState : \copybrief osKernelGetState
215 - \ref osKernelGetSysTimerCount : \copybrief osKernelGetSysTimerCount
216 - \ref osKernelGetSysTimerFreq : \copybrief osKernelGetSysTimerFreq
217 - \ref osKernelInitialize : \copybrief osKernelInitialize
218 - \ref osKernelLock : \copybrief osKernelLock
219 - \ref osKernelResume : \copybrief osKernelResume
220 - \ref osKernelStart : \copybrief osKernelStart
221 - \ref osKernelSuspend : \copybrief osKernelSuspend
222 - \ref osKernelGetTickCount : \copybrief osKernelGetTickCount
223 - \ref osKernelGetTickFreq : \copybrief osKernelGetTickFreq
224 - \ref osKernelUnlock : \copybrief osKernelUnlock
226 - \ref CMSIS_RTOS_ThreadMgmt
227 - \ref osThreadDetach : \copybrief osThreadDetach
228 - \ref osThreadExit : \copybrief osThreadExit
229 - \ref osThreadGetName : \copybrief osThreadGetName
230 - \ref osThreadGetId : \copybrief osThreadGetId
231 - \ref osThreadGetPriority : \copybrief osThreadGetPriority
232 - \ref osThreadGetState : \copybrief osThreadGetState
233 - \ref osThreadJoin : \copybrief osThreadJoin
234 - \ref osThreadNew : \copybrief osThreadNew
235 - \ref osThreadResume : \copybrief osThreadResume
236 - \ref osThreadSetPriority : \copybrief osThreadSetPriority
237 - \ref osThreadSuspend : \copybrief osThreadSuspend
238 - \ref osThreadTerminate : \copybrief osThreadTerminate
239 - \ref osThreadYield : \copybrief osThreadYield
241 - \ref CMSIS_RTOS_Wait
242 - \ref osDelay : \copybrief osDelay
243 - \ref osDelayUntil : \copybrief osDelayUntil
245 - \ref CMSIS_RTOS_TimerMgmt
246 - \ref osTimerDelete : \copybrief osTimerDelete
247 - \ref osTimerIsRunning : \copybrief osTimerIsRunning
248 - \ref osTimerNew : \copybrief osTimerNew
249 - \ref osTimerStart : \copybrief osTimerStart
250 - \ref osTimerStop : \copybrief osTimerStop
252 - \ref CMSIS_RTOS_EventFlags
253 - \ref osEventFlagsNew : \copybrief osEventFlagsNew
254 - \ref osEventFlagsDelete : \copybrief osEventFlagsDelete
255 - \ref osEventFlagsSet : \copybrief osEventFlagsSet
256 - \ref osEventFlagsClear : \copybrief osEventFlagsClear
257 - \ref osEventFlagsGet : \copybrief osEventFlagsGet
258 - \ref osEventFlagsWait : \copybrief osEventFlagsWait
260 - \ref CMSIS_RTOS_ThreadFlagsMgmt
261 - \ref osThreadFlagsSet : \copybrief osThreadFlagsSet
262 - \ref osThreadFlagsClear : \copybrief osThreadFlagsClear
263 - \ref osThreadFlagsGet : \copybrief osThreadFlagsGet
264 - \ref osThreadFlagsWait : \copybrief osThreadFlagsWait
266 - \ref CMSIS_RTOS_Message
267 - \ref osMessageQueueDelete : \copybrief osMessageQueueDelete
268 - \ref osMessageQueueGet : \copybrief osMessageQueueGet
269 - \ref osMessageQueueGetCapacity : \copybrief osMessageQueueGetCapacity
270 - \ref osMessageQueueGetCount : \copybrief osMessageQueueGetCount
271 - \ref osMessageQueueGetMsgSize : \copybrief osMessageQueueGetMsgSize
272 - \ref osMessageQueueGetSpace : \copybrief osMessageQueueGetSpace
273 - \ref osMessageQueueNew : \copybrief osMessageQueueNew
274 - \ref osMessageQueuePut : \copybrief osMessageQueuePut
275 - \ref osMessageQueueReset : \copybrief osMessageQueueReset
277 - \ref CMSIS_RTOS_PoolMgmt
278 - \ref osMemoryPoolAlloc : \copybrief osMemoryPoolAlloc
279 - \ref osMemoryPoolDelete : \copybrief osMemoryPoolDelete
280 - \ref osMemoryPoolFree : \copybrief osMemoryPoolFree
281 - \ref osMemoryPoolGetBlockSize : \copybrief osMemoryPoolGetBlockSize
282 - \ref osMemoryPoolGetCapacity : \copybrief osMemoryPoolGetCapacity
283 - \ref osMemoryPoolGetCount : \copybrief osMemoryPoolGetCount
284 - \ref osMemoryPoolGetSpace : \copybrief osMemoryPoolGetSpace
285 - \ref osMemoryPoolNew : \copybrief osMemoryPoolNew
287 - \ref CMSIS_RTOS_MutexMgmt
288 - \ref osMutexAcquire : \copybrief osMutexAcquire
289 - \ref osMutexDelete : \copybrief osMutexDelete
290 - \ref osMutexGetOwner : \copybrief osMutexGetOwner
291 - \ref osMutexNew : \copybrief osMutexNew
292 - \ref osMutexRelease : \copybrief osMutexRelease
294 - \ref CMSIS_RTOS_SemaphoreMgmt
295 - \ref osSemaphoreAcquire : \copybrief osSemaphoreAcquire
296 - \ref osSemaphoreDelete : \copybrief osSemaphoreDelete
297 - \ref osSemaphoreGetCount : \copybrief osSemaphoreGetCount
298 - \ref osSemaphoreNew : \copybrief osSemaphoreNew
299 - \ref osSemaphoreRelease : \copybrief osSemaphoreRelease
302 /*=======0=========1=========2=========3=========4=========5=========6=========7=========8=========9=========0=========1====*/
304 \page rtos_apicpp CMSIS-RTOS C++ API
310 /*=======0=========1=========2=========3=========4=========5=========6=========7=========8=========9=========0=========1====*/
312 \page cmsis_os2_h Header File: cmsis_os2.h
314 The file \b cmsis_os2.h is a standard header file that interfaces to every CMSIS-RTOS API v2 compliant Real-Time Operating Systems (RTOS).
315 Each implementation is provided the same cmsis_os2.h which defines the interface to the \ref rtos_api2.
317 Using the \b cmsis_os2.h along with dynamic object allocation allows to create source code or libraries that require no modifications
318 when using on a different CMSIS-RTOS v2 implementation.
320 <b>Header file %cmsis_os2.h</b>
325 /*=======0=========1=========2=========3=========4=========5=========6=========7=========8=========9=========0=========1====*/
327 \page rtx5_impl RTX v5 Implementation
329 The RTX version 5 implements the CMSIS-RTOS API v2 as native RTOS interface for Cortex-M processor-based devices.
330 A translation layer to CMSIS-RTOS API v1 is provided and with minimal effort RTX version 5 can be used in applications that
331 where previously based on RTX version 4 and CMSIS-RTOS v1.
333 The following sections provide further details:
334 - \subpage theory_op : provides general information about the operation of RTX version 5.
335 - \subpage cre_rtx_proj
336 - \subpage config_rtx
339 /*=======0=========1=========2=========3=========4=========5=========6=========7=========8=========9=========0=========1====*/
341 \page theory_op Theory of Operation
343 This section describes how RTX version 5 manages the resources of the target system. Many aspects of the kernel are configurable
344 and the configuration options are mentioned where applicable.
346 \section KernelTimer RTX Kernel Timer Tick and Thread Management
348 By default, CMSIS-RTOS RTX5 uses the Cortex-M
349 <a href="http://www.keil.com/support/man/docs/gsac/GSAC_SYSTICKtimer.htm" target="_blank">SysTick</a> timer to generate
350 periodic interrupts for the RTX kernel timer tick. CMSIS-RTOS provides \ref CMSIS_RTOS_TimerMgmt functions and several
351 CMSIS-RTOS functions have a timeout parameter. This periodic RTX kernel timer tick interrupt is used to derive the required
352 time interval. CMSIS-RTOS RTX also provides configuration options for a alternative timer and tick-less operation.
354 To handle timeout and time delays for threads, the CMSIS-RTOS RTX thread management is controlled by the RTX kernel timer
355 tick interrupt. The thread context contains all CPU registers (R0 - R12), the return address (LR), the program counter (PC), and the processor
356 status register (xPSR). For the Cortex-M4 FPU and Cortex-M7 FPU the floating point status and registers (S0 - S32, FPSCR) are
357 also part of the thread context.
359 When a thread switch occurs:
360 - the thread context of the current running thread is stored on the local stack of this thread.
361 - the stack pointer is switched to the next running thread.
362 - the thread context of this next running thread is restored and this thread starts to run.
365 - For Cortex-M0, Cortex-M3, Cortex-M4, and Cortex-M7 the thread context requires 64 bytes on the local stack.
366 - For Cortex-M4 FPU and Cortex-M7 FPU the thread context requires 200 bytes on the local stack. For devices with Cortex-M4 FPU and Cortex-M7 FPU the default stack space should be increased to a minimum of 300 bytes.
368 Each thread is provided with an separate stack that holds the thread context and stack space for automatic variables and return addresses for function call nesting. The stack sizes of the RTX threads are flexible configurable as explained in the section \ref threadConfig. RTX even offers a configurable checking for stack overflows and stack utilization.
371 \section MemoryAllocation Memory Allocation
373 The RTX objects (thread, mutex, semaphore, timer, message, event and memory pool) require dedicated RAM memory.
374 Objects can be created using os<i>object</i>New() calls and deleted using os<i>object</i>Delete() calls. The related
375 object memory needs to be available during the life-time of the object.
377 RTX5 offers three different memory allocation methods for objects:
379 - \ref GlobalMemoryPool uses a single global memory pool for all objects. It is easy to configure, but may have
380 the disadvantage for memory fragmentation when different object sizes are created and deleted.
382 - \ref ObjectMemoryPool uses a fixed-size memory pool for each object type. The method is time deterministic
383 and avoids memory fragmentation.
385 - \ref StaticObjectMemory is reserved during the compile time and completely avoids that a system can be out of memory.
386 This is required for some safety critical applications.
388 It possible to intermix the usage of the all memory allocation methods in the same application.
391 \subsection GlobalMemoryPool Global Memory Pool
392 \image html MemAllocGlob.png "Global Memory Pool for all objects"
393 The global memory pool allocates all objects from a one memory area.
394 This method of memory allocation is the default configuration setting of RTX5.
396 When pool does not provide sufficient memory the creation of the object fails and the related os<i>object</i>New() function returns \token{NULL}.
398 \todo refer to object counters once available
400 Enabled in \ref systemConfig.
402 \subsection ObjectMemoryPool Object-specific Memory Pools
403 \image html MemAllocSpec.png "One memory pool per object type"
404 Object-specific memory pools may be enabled for a selected object type, e.g: mutex or thread using the RTX configuration file:
405 - Enabled in \ref threadConfig for thread objects.
406 - Enabled in \ref timerConfig for timer objects. <br>
407 - Enabled in \ref eventFlagsConfig for event objects. <br>
408 - Enabled in \ref mutexConfig for mutex objects. <br>
409 - Enabled in \ref semaphoreConfig for semaphore. <br>
410 - Enabled in \ref memPoolConfig for memory pools. <br>
411 - Enabled in \ref msgQueueConfig for message objects. <br>
413 This dedicated fixed-size memory pool ensures time deterministic behaviour and avoids memory fragmentation.
414 As the memory pool is specific to an object the handling of out-of-memory situations may be simplified.
416 When pool does not provide sufficient memory the creation of the object fails and the related os<i>object</i>New() function returns \token{NULL}.
418 \todo explain how to Map pools to different memory spaces (e.g. for systems with different speed grades of RAM memory)
420 \subsection StaticObjectMemory Static Object Memory
421 \image html MemAllocStat.png "Statically allocated memory for all objects"
422 In contrast to the dynamic memory allocations the static memory allocation requires compile-time allocation of object memory.
423 The following example shows how to create an OS object using static memory.
425 <b> Code Example: </b>
427 /*----------------------------------------------------------------------------
428 * CMSIS-RTOS 'main' function template
429 *---------------------------------------------------------------------------*/
431 #include "RTE_Components.h"
432 #include CMSIS_device_header
433 #include "cmsis_os2.h"
435 //include rtx_os.h for types of RTX objects
438 //The thread function instanced in this example
439 void worker(void *arg)
448 // Define objects that are statically allocated for worker threads 1 and 2
449 os_thread_t worker_thread_tcb_1;
451 // Reserve two areas for the stacks of worker threads 1 and 2
452 // uint64_t makes sure the memory alignment is 8
453 uint64_t worker_thread_stk_1[64];
455 // Define the attributes which are used for thread creation
456 // Optional const saves RAM memory and includes the values in periodic ROM tests
457 const osThreadAttr_t worker_attr_1 = {
460 &worker_thread_tcb_1,
461 sizeof(worker_thread_tcb_1),
462 &worker_thread_stk_1[0],
463 sizeof(worker_thread_stk_1),
464 osPriorityAboveNormal,
469 // Define ID object for thread
472 /*----------------------------------------------------------------------------
473 * Application main thread
474 *---------------------------------------------------------------------------*/
475 void app_main (void *argument) {
476 uint32_t param = NULL;
478 //Create an instance of the worker thread with static resources (TCB and stack)
479 th1 = osThreadNew(worker, ¶m, &worker_attr_1);
486 // System Initialization
487 SystemCoreClockUpdate();
490 osKernelInitialize(); // Initialize CMSIS-RTOS
491 osThreadNew(app_main, NULL, NULL); // Create application main thread
492 osKernelStart(); // Start thread execution
503 /*=======0=========1=========2=========3=========4=========5=========6=========7=========8=========9=========0=========1====*/
505 \page cre_rtx_proj Create an RTX Project
507 Example projects using CMSIS-RTOS RTX are available for various development boards. To make use of these examples, you need
508 to install a Device Family Pack in µVision and use Pack Installer to open a CMSIS-RTOS2 Blinky project. If you wish to start a CMSIS-RTOS RTX5 from scratch, follow these steps:
509 - Create a new project and select a device.
510 - In the Manage Run-Time Environment window that opens, select <b>CMSIS\::CORE</b> and <b>CMSIS\::RTOS2 (API)\::Keil RTX5</b>.
511 If the <b>Validation Output</b> requires other components to be present, try to use the \b Resolve button:
513 \image html manage_rte_output.png
515 - Click \b OK. In the \b Project window, you will see the files that have been automatically added to you project, such as
516 \b %RTX_Config.c and the system and startup files:
518 \image html project_window.png
520 - You can add template files to the project by right-clicking on <b>Source Group 1</b> and selecting
521 <b>Add New Item to 'Source Group 1'</b>. In the new window, click on <b>User Code Template</b>. On the right-hand side
522 you will see all available template files for CMSIS-RTOS RTX:
524 \image html add_item.png
526 - Finally, \ref config_rtx "configure" RTX to the application's needs using the \b %RTX_Config.c file.
529 /*=======0=========1=========2=========3=========4=========5=========6=========7=========8=========9=========0=========1====*/
531 \page config_rtx Configure RTX
533 The file "RTX_Config.c" defines the configuration parameters of CMSIS-RTOS RTX and must be part of every project that is using the CMSIS-RTOS RTX kernel.
535 The configuration file uses
536 <a class="el" href="http://www.keil.com/pack/doc/CMSIS/Pack/html/_config_wizard.html" target="_blank">Configuration Wizard Annotations</a>.
537 Depending on the development tool, the annotations might lead to a more user-friendly graphical representation of the settings.
538 The screenshot below shows the configuration file represented by the µVision Configuration Wizard:
540 \image html config_wizard.png "RTX_Conf_CM.c in Configuration Wizard View"
542 The configuration options are explained on these pages:
543 - \subpage systemConfig
544 - \subpage threadConfig
545 - \subpage timerConfig
546 - \subpage eventFlagsConfig
547 - \subpage mutexConfig
548 - \subpage semaphoreConfig
549 - \subpage memPoolConfig
550 - \subpage msgQueueConfig
554 /* ========================================================================================================================== */
556 \page systemConfig System Configuration
558 \image html config_wizard_system.png "RTX_Conf_CM.c: System Configuration"
561 Name | \#define | Description
562 ---------------------------------------|--------------------------|----------------------------------------------------------------
563 Global Dynamic Memory size [bytes] | \c OS_DYNAMIC_MEM_SIZE | Defines the combined global dynamic memory size for the \ref GlobalMemoryPool. Default value is \token{4096}. Value range is \token{[0-1073741824]} bytes, in multiples of \token{8} bytes.
564 Round-Robin Thread switching | \c OS_ROBIN_ENABLE | Enables Round-Robin Thread switching.
565 Round-Robin Timeout [ms] | \c OS_ROBIN_TIMEOUT | Defines how long a thread will execute before a thread switch. Default value is \token{5}. Value range is \token{[1-1000]}.
566 ISR FIFO Queue | \c OS_ISR_FIFO_QUEUE | RTOS Functions called from ISR store requests to this buffer. Default value is \token{16 entries}. Value range is \token{[4-256]} entries in multiples of \token{4}.
569 /* ========================================================================================================================== */
571 \page threadConfig Thread Configuration
573 The CMSIS-RTOS RTX provides several parameters to configure threads.
575 \section stackConfig Configuration of Thread count and Stack Space
577 \ref osThreadAttr_t is passed to osThreadNew to set the options of a thread.
579 CMSIS-RTOS RTX defines two methods for defining the stack requirements:
580 - when \a *stack_mem in osThreadAttr_t is NULL, a fixed-size memory pool is used for the thread stack. In this case, \b OS_STKSIZE specifies the stack size for the thread function.
581 - when \a *stack_mem specifies a memory location, the thread stack provided there. The size of this user space is specified with \b stack_size.
583 Stack memory for threads is configured either statically by Static Resources - Number of Threads (total). Static memory in the size of Number of Threads * Default Thread Stack size is reserved.
584 Alternatively the memory is allocated on demand from the Dynamic Resources pool (configured by System Configuration - Dynamic Resources - Memory size [bytes] for Stack).
586 The CMSIS-RTOS RTX kernel uses a separate stack for each thread it creates. However, before the kernel is started by the \ref osKernelInitialize() function, the main stack size that is configured in the file startup_<i>device</i>.s is used.
588 \image html config_wizard_threads.png "RTX_Conf_CM.c: Thread Configuration"
590 Main stack is also used when:
591 - the user application calls the majority of RTX functions from Thread mode (ending up in an SVC call)
592 - running from handlers (user interrupt of exception handlers like SVCm PendSV, Faults, etc.)
594 Name | \#define | Description
595 ---------------------------------------------------------|------------------------|----------------------------------------------------------------
596 Object specific Memory allocation | \c OS_THREAD_OBJ_MEM | Enables object specific memory allocation. See /ref ObjectMemoryPool.
597 Number of user Threads (total) | \c OS_THREAD_NUM | Defines maximum number of user threads that can be active at the same time. Applies to user threads with system provided memory for control blocks. Default value is \token{6}. Value range is \token{[1-1000]}.
598 Number of user Threads with user-provided Stack size | \c OS_THREAD_USER_STACK_NUM | Defines maximum number of user threads with user-provided stack size. Default value is \token{0}. Value range is \token{[0-1000]}.
599 Total Stack size [bytes] for user Threads with user-provided Stack size | \c OS_THREAD_USER_STACK_SIZE | Defines the combined stack size for user threads with user-provided stack size. Default value is \token{0}. Value range is \token{[0-1073741824]} bits, sepping \token{8} bits.
600 Default Thread Stack size [bytes] | \c OS_STACK_SIZE | Defines stack size for threads with zero stack size specified. Default value is \token{200}. Value range is \token{[96-1073741824]} bits, sepping \token{8} bits.
601 Idle Thread Stack size [bytes] | \c OS_IDLE_THREAD_STACK_SIZE | Defines stack size for Idle thread. Default value is \token{200}. Value range is \token{[72-1073741824]} bits, sepping \token{8} bits.
602 Stack overrun checking | \c OS_STACK_CHECK | Enable stack overrun checks at thread switch. Enabling this option increases slightly the execution time of a thread switch. If a stack overflow is detected at a thread switch, the function \b os_error with error code = 1 is called. By default, this function is implemented as endless loop and will practically stop code execution.
603 Stack usage watermark | \c OS_STACK_WATERMARK | Initialize thread stack with watermark pattern for analyzing stack usage. Enabling this option increases significantly the execution time of thread creation.
604 Processor mode for Thread execution | \c OS_PRIVILEGE_MODE | Controls the processor mode. Default value is \token{Privileged} mode. Value range is \token{[0=Unprivileged; 1=Privileged]} mode.
608 /* ========================================================================================================================== */
610 \page timerConfig Timer Configuration
612 \image html config_wizard_timer.png "RTX_Conf_CM.c: Timer Configuration"
615 Name | \#define | Description
616 ---------------------------------------|--------------------------|----------------------------------------------------------------
617 Object specific Memory allocation | \c OS_TIMER_OBJ_MEM | Enables object specific memory allocation. See /ref ObjectMemoryPool.
618 Number of Timer objects | \c OS_TIMER_NUM | Defines maximum number of objects that can be active at the same time. Applies to objects with system provided memory for control blocks. Value range is \token{[1-1000]}.
619 Timer Thread Priority | \c OS_TIMER_THREAD_PRIO | Defines priority for timer thread. Default value is \token{40}. Value range is \token{[8-48]}, stepping \token{8}. The numbers have the following priority correlation: \token{8=Low}; \token{16=Below Normal}; \token{24=Normal}; \token{32=Above Normal}; \token{40=High}; \token{48=Realtime}
620 Timer Thread Stack size [bytes] | \c OS_TIMER_THREAD_STACK_SIZE | Defines stack size for Timer thread. May be set to 0 when timers are not used. Default value is \token{200}. Value range is \token{[0-1073741824]}, stepping \token{8}.
621 Timer Callback Queue entries | \c OS_TIMER_CB_QUEUE | Number of concurrent active timer callback functions. May be set to 0 when timers are not used. Default value is \token{4}. Value range is \token{[0-256]}.
624 /* ========================================================================================================================== */
626 \page eventFlagsConfig Event Flags Configuration
628 \image html config_wizard_eventFlags.png "RTX_Conf_CM.c: Event Flags Configuration"
631 Name | \#define | Description
632 ---------------------------------------|--------------------------|----------------------------------------------------------------
633 Object specific Memory allocation | \c OS_EVFLAGS_OBJ_MEM | Enables object specific memory allocation. See /ref ObjectMemoryPool.
634 Number of Event Flags objects | \c OS_EVFLAGS_NUM | Defines maximum number of objects that can be active at the same time. Applies to objects with system provided memory for control blocks. Value range is \token{[0-1000]}.
638 /* ========================================================================================================================== */
640 \page mutexConfig Mutex Configuration
642 \image html config_wizard_mutex.png "RTX_Conf_CM.c: Mutex Configuration"
645 Name | \#define | Description
646 ---------------------------------------|--------------------------|----------------------------------------------------------------
647 Object specific Memory allocation | \c OS_MUTEX_OBJ_MEM | Enables object specific memory allocation. See /ref ObjectMemoryPool.
648 Number of Mutex objects | \c OS_MUTEX_NUM | Defines maximum number of objects that can be active at the same time. Applies to objects with system provided memory for control blocks. Value range is \token{[0-1000]}.
652 /* ========================================================================================================================== */
654 \page semaphoreConfig Semaphore Configuration
656 \image html config_wizard_semaphore.png "RTX_Conf_CM.c: Semaphore Configuration"
659 Name | \#define | Description
660 ---------------------------------------|--------------------------|----------------------------------------------------------------
661 Object specific Memory allocation | \c OS_SEMAPHORE_OBJ_MEM | Enables object specific memory allocation. See /ref ObjectMemoryPool.
662 Number of Semaphore objects | \c OS_SEMAPHORE_NUM | Defines maximum number of objects that can be active at the same time. Applies to objects with system provided memory for control blocks. Value range is \token{[0-1000]}.
666 /* ========================================================================================================================== */
668 \page memPoolConfig Memory Pool Configuration
670 \image html config_wizard_memPool.png "RTX_Conf_CM.c: Memory Pool Configuration"
673 Name | \#define | Description
674 ---------------------------------------|--------------------------|----------------------------------------------------------------
675 Object specific Memory allocation | \c OS_MEMPOOL_OBJ_MEM | Enables object specific memory allocation. See /ref ObjectMemoryPool.
676 Number of Memory Pool objects | \c OS_MEMPOOL_NUM | Defines maximum number of objects that can be active at the same time. Applies to objects with system provided memory for control blocks. Value range is \token{[0-1000]}.
677 Data Storage Memory size [bytes] | \c OS_MEMPOOL_DATA_SIZE | Defines the combined data storage memory size. Applies to objects with system provided memory for data storage. Default value is \token{0}. Value range is \token{[0-1073741824]}, stepping \token{4}.
682 /* ========================================================================================================================== */
684 \page msgQueueConfig Message Queue Configuration
686 \image html config_wizard_msgQueue.png "RTX_Conf_CM.c: Message Queue Configuration"
689 Name | \#define | Description
690 ---------------------------------------|--------------------------|----------------------------------------------------------------
691 Object specific Memory allocation | \c OS_MSGQUEUE_OBJ_MEM | Enables object specific memory allocation. See /ref ObjectMemoryPool.
692 Number of Message Queue objects | \c OS_MSGQUEUE_NUM | Defines maximum number of objects that can be active at the same time. Applies to objects with system provided memory for control blocks. Value range is \token{[0-1000]}.
693 Data Storage Memory size [bytes] | \c OS_MSGQUEUE_DATA_SIZE | Defines the combined data storage memory size. Applies to objects with system provided memory for data storage. Default value is \token{0}. Value range is \token{[0-1073741824]}, stepping \token{4}.
697 /* ========================================================================================================================== */
699 \page lowPower Configuration for Low-Power Modes
701 The system thread \b os_IdleThread can be use to switch the system into a low-power mode. The easiest form to enter a
702 low-power mode is the execution of the \c __WFE function that puts the processor into a sleep mode where it waits for an
705 <b>Configuration Example:</b>
708 #include "RTE_Components.h"
709 #include CMSIS_device_header /* Device definitions */
711 void os_IdleThread (void) {
712 /* The idle demon is a system thread, running when no other thread is */
716 __WFE(); /* Enter sleep mode */
722 \c __WFE() is not available at every Cortex-M implementation. Check device manuals for availability.
724 \section TickLess Tick-less operation
726 RTX5 provides extension for tick-less operation which is useful for applications that use extensively low-power
727 modes where the SysTick timer is also disabled. To provide a time-tick in such power-saving modes a wake-up timer is used to
728 derive timer intervals. The CMSIS-RTOS2 functions \ref osKernelSuspend and \ref osKernelResume control the tick-less operation.
730 Using this functions allows the RTX5 thread scheduler to stop the periodic kernel tick interrupt. When all active threads
731 are suspended, the system enters power-down and calculates how long it can stay in this power-down mode. In the power-down
732 mode the processor and potentially peripherals can be switched off. Only a wake-up timer must remain powered, because this
733 timer is responsible to wake-up the system after the power-down period expires.
735 The tick-less operation is controlled from the \b os_IdleThread thread. The wake-up timeout value is set before the system
736 enters the power-down mode. The function \ref osKernelSuspend calculates the wake-up timeout measured in RTX Timer Ticks; this
737 value is used to setup the wake-up timer that runs during the power-down mode of the system.
739 Once the system resumes operation (either by a wake-up time out or other interrupts) the RTX5 thread scheduler is started with
740 the function \ref osKernelResume. The parameter \a sleep_time specifies the time (in RTX Timer Ticks) that the system was in
745 #include "msp.h" // Device header
747 /*----------------------------------------------------------------------------
748 * MSP432 Low-Power Extension Functions
749 *---------------------------------------------------------------------------*/
750 static void MSP432_LP_Entry(void) {
751 /* Enable PCM rude mode, which allows to device to enter LPM3 without waiting for peripherals */
752 PCM->CTL1 = PCM_CTL1_KEY_VAL | PCM_CTL1_FORCE_LPM_ENTRY;
753 /* Enable all SRAM bank retentions prior to going to LPM3 */
754 SYSCTL->SRAM_BANKRET |= SYSCTL_SRAM_BANKRET_BNK7_RET;
755 __enable_interrupt();
756 NVIC_EnableIRQ(RTC_C_IRQn);
757 /* Do not wake up on exit from ISR */
758 SCB->SCR |= SCB_SCR_SLEEPONEXIT_Msk;
759 /* Setting the sleep deep bit */
760 SCB->SCR |= (SCB_SCR_SLEEPDEEP_Msk);
763 static volatile unsigned int tc;
764 static volatile unsigned int tc_wakeup;
766 void RTC_C_IRQHandler(void)
768 if (tc++ > tc_wakeup)
770 SCB->SCR &= ~SCB_SCR_SLEEPONEXIT_Msk;
771 NVIC_DisableIRQ(RTC_C_IRQn);
772 NVIC_ClearPendingIRQ(RTC_C_IRQn);
775 if (RTC_C->PS0CTL & RTC_C_PS0CTL_RT0PSIFG)
777 RTC_C->CTL0 = RTC_C_KEY_VAL; // Unlock RTC key protected registers
778 RTC_C->PS0CTL &= ~RTC_C_PS0CTL_RT0PSIFG;
780 SCB->SCR |= (SCB_SCR_SLEEPDEEP_Msk);
784 uint32_t g_enable_sleep = 0;
786 void os_IdleThread (void) {
789 tc_wakeup = osKernelSuspend();
790 /* Is there some time to sleep? */
793 /* Enter the low power state */
797 /* Adjust the kernel ticks with the amount of ticks slept */
804 \c __WFE() is not available at every Cortex-M implementation. Check device manuals for availability.
807 /*=======0=========1=========2=========3=========4=========5=========6=========7=========8=========9=========0=========1====*/
809 \page rtosValidation RTOS Validation
812 The test suite is available only for RTOS v1 API.
814 ARM offers a <a class=el href="http://www.keil.com/pack" target="_blank">Software Pack</a> for the CMSIS-RTOS Validation.
815 The <b>ARM::CMSIS-RTOS_Validation</b> Pack contains the following:
817 - Source code of a CMSIS-RTOS Validation Suite along with configuration file.
818 - Documentation of the CMSIS-RTOS Validation Suite.
819 - Example that shows the usage of the CMSIS-RTOS Validation Suite using simulation.
821 The CMSIS-RTOS Validation Suite is currently available in beta release and performs generic validation of various
822 RTOS features. The test cases verify the functional behavior, test invalid parameters and call management
825 The following CMSIS-RTOS features can be tested with the current release:
826 - Thread : Create multiple threads, terminate, restart, yield, change priority
827 - Timer : Create periodic and one-shot timers
828 - GenWait : Call generic wait functions (osDelay and osWait)
829 - WaitFunc : Measure wait ticks (delay, mail, message, mutex, semaphore, signal)
831 Moreover the following inter-thread communication functions can be tested:
832 - Signal : Verify signal events
833 - Memory Pool : Verify memory allocation
834 - Message Queue : Exchange messages between threads
835 - Mail Queue : Exchange data between threads
836 - Mutex : Synchronize resource access
837 - Semaphore : Access shared resources
839 The RTOS Validation output can be printed to a console, output via ITM printf, or output to a memory buffer.
841 \section test_output Sample Test Output
843 CMSIS-RTOS Test Suite Oct 21 2015 16:39:16
845 TEST 01: TC_ThreadCreate PASSED
846 TEST 02: TC_ThreadMultiInstance PASSED
847 TEST 03: TC_ThreadTerminate PASSED
850 TEST 08: TC_ThreadChainedCreate PASSED
851 TEST 09: TC_ThreadYield NOT EXECUTED
852 TEST 10: TC_ThreadParam PASSED
855 TEST 60: TC_MailFromISRToThread PASSED
857 Test Summary: 60 Tests, 59 Executed, 59 Passed, 0 Failed, 0 Warnings.
862 /* ========================================================================================================================== */
863 // Group creation for Reference
865 \addtogroup CMSIS_RTOS1 CMSIS-RTOS API v1
866 \brief This section describes the CMSIS-RTOS API v1.
868 The CMSIS-RTOS is a generic API layer that interfaces to an existing RTOS kernel.
870 CMSIS-RTOS API v2 provides an translation layer for the
871 <a class="el" href="../../RTOS/html/index.html">CMSIS-RTOS API v1</a> that simplifies migration.
873 Refer to the <a class="el" href="../../RTOS/html/modules.html">Reference</a> guide of the CMSIS-RTOS API v1 for details.
876 // Group creation for Reference
878 \addtogroup CMSIS_RTOS CMSIS-RTOS API v2
879 \brief This section describes the CMSIS-RTOS API v2.
881 The CMSIS-RTOS is a generic API layer that interfaces to an existing RTOS kernel.