FreeRTOS Stm32 Cube
FreeRTOS Stm32 Cube
User manual
Developing Applications on STM32Cube with RTOS
Introduction
The STMCubeTM initiative was originated by STMicroelectronics to ease developers life by
reducing development efforts, time and cost. STM32Cube covers the STM32 portfolio.
STM32Cube Version 1.x includes:
A Real Time Operating System is an operating system optimized for use in embedded/real
time applications. Their primary objective is to ensure a timely and deterministic response to
events. Using a real time operating system allows applications to be written as a set of
independent threads that inter-communicate using message queues and semaphores.
This user manual is intended for developers who use STM32Cube firmware on STM32
microcontrollers. It provides a full description of how to use the STM32Cube firmware
components with a real time operating system (RTOS); this user manual comes also with
description of a set of examples based on FreeRTOS using the common APIs provided by
the CMSIS-OS wrapping layer.
In the STM32Cube firmware FreeRTOS is used as real time operating system through the
generic CMSIS-OS wrapping layer provided by ARM. Examples and applications using the
FreeRTOS can be direcltly ported on any other RTOS without modifying the high level APIs,
only the CMSIS-OS wrapper has to be changed in this case.
Please refer to the release notes of the package to know the version of FreeRTOS and
CMSIS-RTOS firmware components used with the STM32CubeTM.
This document is applicable to all STM32 devices; however for simplicity reason, the
STM32F4xx devices and STM32CubeF4 are used as reference platform. To know more
about the examples implementation on your STM32 device, please refer to the readme file
provided within the associated STM32Cube FW package.
June 2014
DocID025801 Rev 2
1/26
www.st.com
Contents
UM1722
Contents
1
Free RTOS . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5
1.1
Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5
1.2
License . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6
1.3
1.4
1.5
FreeRTOS API . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8
1.6
1.7
1.8
CMSIS-RTOS module . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12
2.1
Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12
2.2
CMSIS-RTOS API . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13
FreeRTOS applications . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16
3.1
3.2
Semaphores examples . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17
3.2.1
3.2.2
3.3
Mutexes example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19
3.4
Queues example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19
3.5
Timer example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20
3.6
Conclusions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23
FAQ . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24
Revision history . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 25
2/26
DocID025801 Rev 2
UM1722
List of tables
List of tables
Table 1.
Table 2.
Table 3.
Table 4.
Table 5.
DocID025801 Rev 2
3/26
3
List of figures
UM1722
List of figures
Figure 1.
Figure 2.
Figure 3.
Figure 4.
Figure 5.
Figure 6.
Figure 7.
Figure 8.
Figure 9.
Figure 10.
4/26
FreeRTOS license . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6
Free RTOS architecture . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7
Free RTOS port . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7
FreeRTOS configuration . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11
CMSIS-RTOS architecture . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12
Thread example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17
Semaphore example. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18
Obtaining semaphore from ISR . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 18
Queue process . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20
Periodic timer . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21
DocID025801 Rev 2
UM1722
Free RTOS
Free RTOS
1.1
Overview
FreeRTOS is a class of RTOS that is designed to be small enough to run on a
microcontroller, although its use is not limited to microcontroller applications.
A microcontroller is a small and resource constrained processor that incorporates, on a
single chip, the processor itself, read only memory (ROM or Flash) to hold the program to be
executed, and the random access memory (RAM) needed by the programs it executes.
Typically the program is executed directly from the read only memory.
Microcontrollers are used in deeply embedded applications (those applications where you
never actually see the processors themselves or the software they are running) that
normally have a very specific and dedicated job to do. The size constraints, and dedicated
end application nature, rarely warrant the use of a full RTOS implementation - or indeed
make the use of a full RTOS implementation possible. FreeRTOS therefore provides the
core real time scheduling functionality, inter-task communication, timing and synchronization
primitives only. This means it is more accurately described as a real time kernel, or real time
executive. Additional functionality, such as a command console interface, or networking
stacks, can be then be included with add-on components.
FreeRTOS is a scalable real time demonstration builder core designed specifically for small
embedded systems. Highlights include
Official support for 27 architectures (counting ARM7 and ARM Cortex M3 as one
architecture each).
Designed to be small, simple and easy to use. Typically a demonstration builder core
binary image will be in the region of 4K to 9K bytes.
Pre-configured demo applications for selected single board computers allowing out of
the box operation and fast learning curve.
No restrictions imposed on priority assignment - more than one task can be assigned
the same priority.
DocID025801 Rev 2
5/26
25
Free RTOS
UM1722
Royalty free.
The heap2 scheme of FreeRTOS is used for the memory allocation management, this
scheme uses a best fit algorithm allows previously allocated blocks to be freed. It does not
however combine adjacent free blocks into a single large block. The total amount of
available RAM is set by the definition configTOTAL_HEAP_SIZE - which is defined in
FreeRTOSConfig.h.
1.2
License
The FreeRTOS source code is licensed by a modified GNU General Public License. The
modification takes the form of an exception. The full text of the GNU General Public License
is shown here:
Figure 1. FreeRTOS license
7KH)UHH5726RUJVRXUFHFRGHLVOLFHQVHGE\WKHPRGLILHG*18*HQHUDO3XEOLF
/LFHQVH*3/WH[WSURYLGHGEHORZ7KH)UHH5726GRZQORDGDOVRLQFOXGHV
GHPRDSSOLFDWLRQVRXUFHFRGHVRPHRIZKLFKLVSURYLGHGE\WKLUGSDUWLHV
$1',6/,&(16('6(3$5$7(/<)520)5((572625*
)RUWKHDYRLGDQFHRIDQ\GRXEWUHIHUWRWKHFRPPHQWLQFOXGHGDWWKHWRS
RIHDFKVRXUFHDQGKHDGHUILOHIRUOLFHQVHDQGFRS\ULJKWLQIRUPDWLRQ
7KLVLVDOLVWRIILOHVIRUZKLFK5HDO7LPH(QJLQHHUV/WGDUHQRWWKH
FRS\ULJKWRZQHUDQGDUH127&29(5('%<7+(*3/
9DULRXVKHDGHUILOHVSURYLGHGE\VLOLFRQPDQXIDFWXUHUVDQGWRROYHQGRUV
WKDWGHILQHSURFHVVRUVSHFLILFPHPRU\DGGUHVVHVDQGXWLOLW\PDFURV
3HUPLVVLRQKDVEHHQJUDQWHGE\WKHYDULRXVFRS\ULJKWKROGHUVIRUWKHVH
ILOHVWREHLQFOXGHGLQWKH)UHH5726GRZQORDG8VHUVPXVWHQVXUHOLFHQVH
FRQGLWLRQVDUHDGKHUHGWRIRUDQ\XVHRWKHUWKDQFRPSLODWLRQRIWKH
)UHH5726GHPRDSSOLFDWLRQV
7KHX,37&3,3VWDFNWKHFRS\ULJKWRIZKLFKLVKHOGE\$GDP'XQNHOV
8VHUVPXVWHQVXUHWKHRSHQVRXUFHOLFHQVHFRQGLWLRQVVWDWHGDWWKHWRS
RIHDFKX,3VRXUFHILOHLVXQGHUVWRRGDQGDGKHUHGWR
7KHOZ,37&3,3VWDFNWKHFRS\ULJKWRIZKLFKLVKHOGE\WKH6ZHGLVK
,QVWLWXWHRI&RPSXWHU6FLHQFH8VHUVPXVWHQVXUHWKHRSHQVRXUFHOLFHQVH
FRQGLWLRQVVWDWHGDWWKHWRSRIHDFKOZ,3VRXUFHILOHLVXQGHUVWRRGDQG
DGKHUHGWR
9DULRXVSHULSKHUDOGULYHUVRXUFHILOHVDQGELQDULHVSURYLGHGE\VLOLFRQ
PDQXIDFWXUHUVDQGWRROYHQGRUV3HUPLVVLRQKDVEHHQJUDQWHGE\WKH
YDULRXVFRS\ULJKWKROGHUVIRUWKHVHILOHVWREHLQFOXGHGLQWKH)UHH5726
GRZQORDG8VHUVPXVWHQVXUHOLFHQVHFRQGLWLRQVDUHDGKHUHGWRIRUDQ\
XVHRWKHUWKDQFRPSLODWLRQRIWKH)UHH5726GHPRDSSOLFDWLRQV
7KHILOHVFRQWDLQHGZLWKLQ)UHH5726?'HPR?:L]1(7B'(02B7(51B?WHUQBFRGH
ZKLFKDUHVOLJKWO\PRGLILHGYHUVLRQVRIFRGHSURYLGHGE\DQGFRS\ULJKWWR
7HUQ,QF
(UURUVDQGRPLVVLRQVVKRXOGEHUHSRUWHGWR5LFKDUG%DUU\FRQWDFWGHWDLOVIRU
ZKRPFDQEHREWDLQHGIURPKWWSZZZ)UHH5726RUJ
7KH*3/OLFHQVHWH[WIROORZV
$VSHFLDOH[FHSWLRQWRWKH*3/LVLQFOXGHGWRDOORZ\RXWRGLVWULEXWHD
FRPELQHGZRUNWKDWLQFOXGHV)UHH5726ZLWKRXWEHLQJREOLJHGWRSURYLGH
WKHVRXUFHFRGHIRUDQ\SURSULHWDU\FRPSRQHQWV6HHWKHOLFHQVLQJVHFWLRQ
RIKWWSZZZ)UHH5726RUJIRUIXOOGHWDLOV7KHH[FHSWLRQWH[WLVDOVR
LQFOXGHGDWWKHERWWRPRIWKLVILOH
6/26
DocID025801 Rev 2
UM1722
1.3
Free RTOS
'HPR
6RXUFH
7DVNF
3RUWDEOH
4XHXHF
&RPSLOHU
/LVWF
3RUWF
,
>
,>
3ODWIRUP
The core RTOS code is contained in three files, called tasks.c, queue.c and list.c., in the
FreeRTOS/Source directory. The same directory contains two optional files called timers.c
and croutine.c which implement software timer and co-routine functionality. Each supported
processor architecture requires a small amount of architecture specific RTOS code. This is
the RTOS portable layer, located in the FreeRTOS/Source/Portable/[compiler]/[architecture]
sub directories, where [compiler] and [architecture] are the compiler used to create the port,
and the architecture on which the port runs, respectively.
The sample heap allocation schemes are also located in the portable layer. The various
sample heap_x.c files are located in the FreeRTOS/Source/portable/MemMang directory.
1.4
DocID025801 Rev 2
7/26
25
Free RTOS
1.5
UM1722
FreeRTOS API
Table 1. Free RTOS API
APIs Categories
8/26
API
Task Creation
xTaskCreate
vTaskDelete
Task Control
vTaskDelay
vTaskDelayUntil
uxTaskPriorityGet
vTaskPrioritySet
vTaskSuspend
vTaskResume
xTaskResumeFromISR
vTaskSetApplicationTag
xTaskCallApplicationTaskHook
Task Utilities
xTaskGetCurrentTaskHandle
xTaskGetSchedulerState
uxTaskGetNumberOfTasks
vTaskList
vTaskStartTrace
ulTaskEndTrace
vTaskGetRunTimeStats
Kernel Control
vTaskStartScheduler
vTaskEndScheduler
vTaskSuspendAll
xTaskResumeAll
Queue Management
xQueueCreate
xQueueSend
xQueueReceive
xQueuePeek
xQueueSendFromISR
xQueueSendToBackFromISR
xQueueSendToFrontFromISR
xQueueReceiveFromISR
vQueueAddToRegistry
vQueueUnregisterQueue
Semaphores
vSemaphoreCreateBinary
vSemaphoreCreateCounting
xSemaphoreCreateMutex
xSemaphoreTake
xSemaphoreGive
xSemaphoreGiveFromISR
DocID025801 Rev 2
UM1722
1.6
Free RTOS
Scheme 1 - heap_1.c
This is the simplest scheme of all. It does not permit memory to be freed once it has been
allocated, but despite this is suitable for a surprisingly large number of applications.
The algorithm simply subdivides a single array into smaller blocks as requests for RAM are
made. The total size of the array is set by the definition configTOTAL_HEAP_SIZE - which is
defined in FreeRTOSConfig.h. This scheme:
can be used if your application never deletes a task or queue (no calls to vTaskDelete () or
vQueueDelete () are ever made).
is always deterministic (always takes the same amount of time to return a block).
is used by the PIC, AVR and 8051 demo applications - as these do not dynamically
create or delete tasks after vTaskStartScheduler() has been called.
heap_1.c is suitable for a lot of small real time systems provided that all tasks and
queues are created before the kernel is started.
Scheme 2 - heap_2.c
This scheme uses a best fit algorithm and, unlike scheme 1, allows previously allocated
blocks to be freed. It does not however combine adjacent free blocks into a single large
block.
Again the total amount of available RAM is set by the definition configTOTAL_HEAP_SIZE which is defined in FreeRTOSConfig.h.
This scheme:
can be used even when the application repeatedly calls vTaskCreate ()/vTaskDelete ()
or vQueueCreate ()/vQueueDelete () (causing multiple calls to pvPortMalloc() and
vPortFree()).
should not be used if the memory being allocated and freed is of a random size - this
would only be the case if tasks being deleted each had a different stack depth, or
queues being deleted were of different lengths.
could possibly result in memory fragmentation problems should your application create
blocks of queues and tasks in an unpredictable order. This would be unlikely for nearly
all applications but
heap_2.c is suitable for most small real time systems that have to dynamically create tasks.
DocID025801 Rev 2
9/26
25
Free RTOS
UM1722
Scheme 3 - heap_3.c
This is just a wrapper for the standard malloc() and free() functions. It makes them thread
safe. This scheme:
Requires the linker to setup a heap, and the compiler library to provide malloc() and
free() implementations.
Is not deterministic.
Scheme 4 - heap_4.c
This scheme uses a first fit algorithm and, unlike scheme 2, does combine adjacent free
memory blocks into a single large block (it does include a coalescence algorithm).
The total amount of available heap space is set by configTOTAL_HEAP_SIZE - which is
defined in FreeRTOSConfig.h.
The xPortGetFreeHeapSize() API function returns the total amount of heap space that
remains unallocated (allowing the configTOTAL_HEAP_SIZE setting to be optimised), but
does not provide information on how the unallocated memory is fragmented into smaller
blocks.
This implementation:
Can be used even when the application repeatedly deletes tasks, queues,
semaphores, mutexes, etc..
Is much less likely than the heap_2 implementation to result in a heap space that is
badly fragmented into multiple small blocks - even when the memory being allocated
and freed is of random size.
Is not deterministic - but is much more efficient that most standard C library malloc
implementations.
heap_4.c is particularly useful for applications that want to use the portable layer memory
allocation schemes directly in the application code (rather than just indirectly by calling API
functions that themselves call pvPortMalloc() and vPortFree()).
1.7
10/26
DocID025801 Rev 2
UM1722
1.8
Free RTOS
FreeRTOS configuration
A number of configurable parameters exist that allow the FreeRTOS kernel to be tailored to
your particular application. These items are located in a file called FreeRTOSConfig.h. Each
demo application included in the FreeRTOS source code download has its own
FreeRTOSConfig.h file. Here is a typical example
Figure 4. FreeRTOS configuration
/* Ensure stdint is only used by the compiler, and not the assembler. */
#if defined(__ICCARM__) || defined(__CC_ARM) || defined(__GNUC__)
#include <stdint.h>
extern uint32_t SystemCoreClock;
#endif
#define configUSE_PREEMPTION
1
#define configUSE_IDLE_HOOK
0
#define configUSE_TICK_HOOK
0
#define configCPU_CLOCK_HZ
( SystemCoreClock )
#define configTICK_RATE_HZ
( ( portTickType ) 1000 )
#define configMAX_PRIORITIES
( ( unsigned portBASE_TYPE ) 7 )
#define configMINIMAL_STACK_SIZE
( ( unsigned short ) 128 )
#define configTOTAL_HEAP_SIZE
( ( size_t ) ( 15 * 1024 ) )
#define configMAX_TASK_NAME_LEN
( 16 )
#define configUSE_TRACE_FACILITY
1
#define configUSE_16_BIT_TICKS
0
#define configIDLE_SHOULD_YIELD
1
#define configUSE_MUTEXES
1
#define configQUEUE_REGISTRY_SIZE
8
#define configCHECK_FOR_STACK_OVERFLOW
0
#define configUSE_RECURSIVE_MUTEXES
1
#define configUSE_MALLOC_FAILED_HOOK
0
#define configUSE_APPLICATION_TASK_TAG
0
#define configUSE_COUNTING_SEMAPHORES
1
/* Cortex-M specific definitions. */
#ifdef __NVIC_PRIO_BITS
/* __BVIC_PRIO_BITS will be specified when CMSIS is being used. */
#define configPRIO_BITS
__NVIC_PRIO_BITS
#else
#define configPRIO_BITS
4
/* 15 priority levels */
#endif
/* The lowest interrupt priority that can be used in a call to a "set priority"
function. */
#define configLIBRARY_LOWEST_INTERRUPT_PRIORITY
0xf
/* The highest interrupt priority that can be used by any interrupt service
routine that makes calls to interrupt safe FreeRTOS API functions */
#define configLIBRARY_MAX_SYSCALL_INTERRUPT_PRIORITY
5
/* Interrupt priorities used by the kernel port layer itself.
These are generic
to all Cortex-M ports, and do not rely on any particular library functions. */
#define configKERNEL_INTERRUPT_PRIORITY
(
configLIBRARY_LOWEST_INTERRUPT_PRIORITY << (8 - configPRIO_BITS) )
#define configMAX_SYSCALL_INTERRUPT_PRIORITY
(
configLIBRARY_MAX_SYSCALL_INTERRUPT_PRIORITY << (8 - configPRIO_BITS) )
/* Definitions that map the FreeRTOS port interrupt handlers to their CMSIS
standard names. */
#define vPortSVCHandler SVC_Handler
#define xPortPendSVHandler PendSV_Handler
/* IMPORTANT: This define MUST be commented when used with STM32Cube firmware,
to prevent overwriting SysTick_Handler defined within STM32Cube HAL
*/
/* #define xPortSysTickHandler SysTick_Handler */
Note:
11/26
25
CMSIS-RTOS module
UM1722
CMSIS-RTOS module
2.1
Overview
The CMSIS-RTOS is a common API for Real-Time operating systems. It provides a
standardized programming interface that is portable to many RTOS and enables therefore
software templates, middleware, libraries, and other components that can work across
supported the RTOS systems.
This module is represented by cmsis_os.c/h files located under the following repository
Middlewares\Third_Party\FreeRTOS\CMSIS_RTOS.
Figure 5. CMSIS-RTOS architecture
Function names, identifiers, and parameters are descriptive and easy to understand.
The functions are powerful and flexible which reduces the number of functions exposed
to the user.
Interrupt Service Routines (ISR) can call many CMSIS-RTOS functions. When a
CMSIS-RTOS function cannot be called from ISR context it rejects the invocation.
Three different thread event types support communication between multiple threads
and/or ISR:
Signals: are flags that may be used to signal specific conditions to a thread.
Signals can be modified in an ISR or set from other threads.
Message: is a 32-bit value that can be sent to a thread or an ISR. Messages are
buffered in a queue. The message type and queue size
Mail: is a fixed-size memory block that can be sent to a thread or an ISR. Mails are
buffered in a queue and memory allocation is provided. The mail type and queue
size
12/26
UM1722
CMSIS-RTOS module
The osDelay function puts a thread into the state WAITING for a specified period
of time.
The generic osWait function waits for events that are assigned to a thread.
2.2
Zero interrupt latency by using the Cortex-M3/M4 instructions LDEX and STEX.
CMSIS-RTOS API
The following list provides a brief overview of all CMSIS-RTOS API:
Table 2. CMSIS-RTOS API
Module
API
osKernelInitialize
osKernelStart
osKernelRunning
Kernel Information and
osKernelSys Tick (*)
Control
Description
Initialize the RTOS kernel
Start the RTOS kernel
Query if the RTOS kernel is running
Get RTOS kernel system timer counter
DocID025801 Rev 2
13/26
25
CMSIS-RTOS module
UM1722
Table 2. CMSIS-RTOS API (continued)
Module
API
osThreadCreate
osThreadTerminate
osThreadYield
Thread Management:
Define, create and control osThreadGetId
thread functions
Signal Management:
Control or wait for signal
flags.
osThreadGetPriority
osTimerCreate
osTimerStart
osSignalSet
osSignalClear
osSignalClear
osMutexCreate
14/26
osThreadSetPriority
Description
DocID025801 Rev 2
UM1722
CMSIS-RTOS module
Table 2. CMSIS-RTOS API (continued)
Module
API
osMessageCreate
Message Queue
Management (*):
osMessageCreate
Control, send, receive, or
wait for messages.
osMessageCreate
osMailCreate
osMailAlloc
Mail Queue
osMailCAlloc
Management (*):
Control, send, receive, or
osMailPut
wait for mail.
Description
Define and initialize a message queue.
Put a message into a message queue.
Get a message or suspend thread
execution until message arrives
Define and initialize a mail queue with fixsize memory blocks
Allocate a memory block
Allocate a memory block and zero-set this
block
Put a memory block into a mail queue
osMailGet
osMailFree
DocID025801 Rev 2
15/26
25
FreeRTOS applications
UM1722
FreeRTOS applications
The STM32CubeF4 FreeRTOS package comes with several applications that use the stack
API sets.
The applications are divided into two categories
Table 3. Free RTOS application categories
Categories
Applications
Thread creation example
Semaphore between threads example
Features
3.1
Thread 2: this thread toggles the LED2 each 500 ms for 10 seconds then it suspend itself.
Thread 1 will resume the execution of thread 2 after 5 seconds.
16/26
DocID025801 Rev 2
UM1722
FreeRTOS applications
Figure 6. Thread example
dd
d
d>
d>
d>
d
dd
3.2
Build and program the application code into the STM32 Flash memory
Run the example and check that LEDs are toggling as described in Figure 6.
Semaphores examples
Semaphores are used for both mutual exclusion and synchronization purposes.
3.2.1
The thread 1 which has the higher priority obtains the semaphore and toggle the LED1
for 5 seconds
2.
3.
The low priority thread can execute now, it obtains the semaphore and resume
execution of the thread 2.
4.
As it has the higher priority the thread 1 will try to obtain the semaphore, but it blocks
because the semaphore is already taken by the low priority thread,
5.
Thread 2 will toggle the LED2 for 5 seconds, before releasing the semaphore and
begin a new cycle.
DocID025801 Rev 2
17/26
25
FreeRTOS applications
UM1722
Figure 7. Semaphore example
d
>
d
>
d
d
d>
d
3.2.2
1.
Build and program the application code into the STM32 Flash memory
2.
Run the example and check that LEDs are toggling as described in Figure 7.
,QWHUUXSW
,QWHUUXSW
7KUHDGUXQQLQJ
7KUHDGUXQQLQJ
RV6HPDSKRUH5HOHDVH
RV6HPDSKRUH5HOHDVH
RV6HPDSKRUH:DLW
RV6HPDSKRUH:DLW
18/26
1.
Build and program the application code into the STM32 Flash memory
2.
Run the example and check that LED1 is toggling when pushing KEY button of the
evaluation board.
DocID025801 Rev 2
UM1722
3.3
FreeRTOS applications
Mutexes example
Mutexes are binary semaphores that include a priority inheritance mechanism. Whereas
binary semaphores are the better choice for implementing synchronization (between tasks
or between tasks and an interrupt), mutexes are the better choice for implementing simple
mutual exclusion.
This example creates three threads with different priorities, which access to the same
mutex. Following
1.
the High priority thread executes first and grabs the mutex and sleeps for a short period
to let the lower priority threads execute.
2.
the Medium priority thread attempts to access the mutex by performing a blocking
'wait'. This thread blocks when the mutex is already taken by the high priority thread. It
does not unblock until the high priority thread has released the mutex, and it does not
actually run until the high priority thread has suspended itself.
3.
the Low priority thread spins round a tight loop attempting to obtain the mutex with a
non-blocking call. As the lowest priority thread it will not successfully obtain the mutex
until both high and medium priority threads are suspended.
4.
the High priority thread gives the mutex back before suspending itself.
5.
the Medium priority thread obtain the mutex, all it does is give the mutex back prior to
also suspending itself. At this point both the high and medium priority threads are
suspended.
6.
the Low priority thread obtain the mutex, it first resumes both suspended threads prior
to giving the mutex back, resulting in the low priority thread temporarily inheriting the
highest thread priority.
3.4
1.
Build and program the application code into the STM32 Flash memory
2.
When running in debug mode, add the following variables to the debugger live watch:
HighPriorityThreadCycles, MediumPriorityThreadCycles and LowPriorityThreadCycles;
these three variables must remain equal. LED1, LED2 and LED4 should toggle
indefinitely and LED3 will turn on in case of error
Queues example
Queues are the primary form of intertask communications. They can be used to send
messages between tasks, and between interrupts and tasks. In most cases they are used
as thread safe FIFO (First In First Out) buffers with new data being sent to the back of the
queue, although data can also be sent to the front.
This example creates two threads that send and receive an incrementing number to/from a
queue. One thread acts as a producer and the other as the consumer.
DocID025801 Rev 2
19/26
25
FreeRTOS applications
UM1722
The consumer is a higher priority than the producer and is set to block on queue reads. The
queue only has space for one item, as soon as the producer posts a message on the queue
the consumer will unblock, preempt the producer, and remove the item.
Figure 9. Queue process
4XHXH
4XHXH
7KUHDG3URGXFHU
7KUHDG3URGXFHU
7KUHDG&RQVXPHU
7KUHDG&RQVXPHU
RV0HVVDJH3XW
RV0HVVDJH3XW
RV0HVVDJH*HW
RV0HVVDJH*HW
0HVVDJH
0HVVDJH
3.5
1.
Build and program the application code into the STM32 Flash memory
2.
Run the example and check that LED1 toggles for each correct message received, else
LED3 will toggle.
Timer example
A timer allows a function to be executed at a set time in the future. The function executed by
the timer is called the timers callback function. The time between a timer being started, and
its callback function being executed, is called the timers period. Put simply, the timer's
callback function is executed when the timer's period expires.
This example demonstrates how to use timers of CMSIS RTOS API based on FreeRTOS
API., creating a periodic timer that calls a callback function every 200 ms to toggle the LED1
of the evaluation board.
20/26
DocID025801 Rev 2
UM1722
FreeRTOS applications
Figure 10. Periodic timer
7LPHU VWDUWHG
7LPHUH[SLUHVDIWHUPVDQG
H[HFXWHVLWVFDOOEDFNIXQFWLRQ
7LPHPV
Build and program the application code into the STM32 Flash memory
2.
Run the example and check that LED1 toggles every 200 ms (Timer expiration)
Note:
To use FreeRTOS software timers please add timers.c to your project workspace.
3.6
The first thread RxThread blocks on a queue to wait for data, toggles an LED each
time data is received (turning it on and then off again) before returning to block on the
queue once more.
The second thread TxThread repeatedly enters the blocked state for 500ms. On
exiting the blocked state the TxThread sends a message through the queue to the
RxThread (causing the RxThread to exit the blocked state and toggle the LED).
When the two threads are blocked, the kernel stops the tick interrupt and place the STM32
into low power (sleep) mode to reduce the power consumption.
Table 4 present power consumption measured on STM32F4 devices in the context of the
example described above.
DocID025801 Rev 2
21/26
25
FreeRTOS applications
UM1722
22/26
Hardware platform
Runtime mode
Sleep mode
STM324xG-EVAL
62.4 mA
14.2 mA
STM324x9I-EVAL
80.5 mA
20.8 mA
DocID025801 Rev 2
UM1722
Conclusions
Conclusions
This User Manual explains how to integrate the FreeRTOS middleware components within
the STM32Cube HAL drivers.
A set of examples have been described to help users developing applications with CMSISRTOS API based on FreeRTOS operating system.
DocID025801 Rev 2
23/26
25
FAQ
UM1722
FAQ
How to port FreeRTOS to different Cortex-M cores?
To port FreeRTOS to the right Cortex-M product you have to import the port.c from the
correct folder. For example if the microcontroller has Cortex-M0 core with IAR tool, you have
to get the port.c file from FreeRTOS\Source\portable\IAR\ARM_CM0 repository.
How to use a clock other than SysTick to generate the tick interrupt?
User can optionally provide its own tick interrupt source by generating an interrupt from a
timer other than SysTick:
Install xPortSysTickHandler() as the handler for the timer interrupt, and ensure
xPortSysTickHandler() is not mapped to SysTick_Handler() in FreeRTOSConfig.h, or
renamed as SysTick_Handler() in port.c.
24/26
DocID025801 Rev 2
UM1722
Revision history
Revision history
Table 5. Document revision history
Date
Revision
Changes
18-Feb-2014
Initial release.
23-Jun-2014
DocID025801 Rev 2
25/26
25
UM1722
Information in this document is provided solely in connection with ST products. STMicroelectronics NV and its subsidiaries (ST) reserve the
right to make changes, corrections, modifications or improvements, to this document, and the products and services described herein at any
time, without notice.
All ST products are sold pursuant to STs terms and conditions of sale.
Purchasers are solely responsible for the choice, selection and use of the ST products and services described herein, and ST assumes no
liability whatsoever relating to the choice, selection or use of the ST products and services described herein.
No license, express or implied, by estoppel or otherwise, to any intellectual property rights is granted under this document. If any part of this
document refers to any third party products or services it shall not be deemed a license grant by ST for the use of such third party products
or services, or any intellectual property contained therein or considered as a warranty covering the use in any manner whatsoever of such
third party products or services or any intellectual property contained therein.
UNLESS OTHERWISE SET FORTH IN STS TERMS AND CONDITIONS OF SALE ST DISCLAIMS ANY EXPRESS OR IMPLIED
WARRANTY WITH RESPECT TO THE USE AND/OR SALE OF ST PRODUCTS INCLUDING WITHOUT LIMITATION IMPLIED
WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE (AND THEIR EQUIVALENTS UNDER THE LAWS
OF ANY JURISDICTION), OR INFRINGEMENT OF ANY PATENT, COPYRIGHT OR OTHER INTELLECTUAL PROPERTY RIGHT.
ST PRODUCTS ARE NOT DESIGNED OR AUTHORIZED FOR USE IN: (A) SAFETY CRITICAL APPLICATIONS SUCH AS LIFE
SUPPORTING, ACTIVE IMPLANTED DEVICES OR SYSTEMS WITH PRODUCT FUNCTIONAL SAFETY REQUIREMENTS; (B)
AERONAUTIC APPLICATIONS; (C) AUTOMOTIVE APPLICATIONS OR ENVIRONMENTS, AND/OR (D) AEROSPACE APPLICATIONS
OR ENVIRONMENTS. WHERE ST PRODUCTS ARE NOT DESIGNED FOR SUCH USE, THE PURCHASER SHALL USE PRODUCTS AT
PURCHASERS SOLE RISK, EVEN IF ST HAS BEEN INFORMED IN WRITING OF SUCH USAGE, UNLESS A PRODUCT IS
EXPRESSLY DESIGNATED BY ST AS BEING INTENDED FOR AUTOMOTIVE, AUTOMOTIVE SAFETY OR MEDICAL INDUSTRY
DOMAINS ACCORDING TO ST PRODUCT DESIGN SPECIFICATIONS. PRODUCTS FORMALLY ESCC, QML OR JAN QUALIFIED ARE
DEEMED SUITABLE FOR USE IN AEROSPACE BY THE CORRESPONDING GOVERNMENTAL AGENCY.
Resale of ST products with provisions different from the statements and/or technical features set forth in this document shall immediately void
any warranty granted by ST for the ST product or service described herein and shall not create or extend in any manner whatsoever, any
liability of ST.
ST and the ST logo are trademarks or registered trademarks of ST in various countries.
Information in this document supersedes and replaces all information previously supplied.
The ST logo is a registered trademark of STMicroelectronics. All other names are the property of their respective owners.
26/26
DocID025801 Rev 2