当前位置:网站首页>FreeRTOS learning easy notes
FreeRTOS learning easy notes
2022-07-01 08:42:00 【Craftsman in Jianghu】
The first 1 Chapter FreeRTOS Introduction and stack
1.1 FreeRTOS Three stages of learning
1)、 understand RTOS General principle , Will transplant official Demo, Will use .
2)、 Know the internal mechanism , I haven't seen the source code yet !
3)、 Know the internal implementation , Can understand the source code ! And can easily transplant any single-chip microcomputer .
1.2 RTOS operating system And Bare metal development ( Front and rear systems ) difference
RTOS: According to the task Manual task switching CPU resources , Some tasks may not run completely , And protect and manage the operating environment , Quite virtual CPU.
Bare metal development ( Front and rear systems ): Each task can only be obtained sequentially CPU resources . One task runs once before it turns to the next task .
1.3 The difference between interrupt service function and calling function
| Interrupt service function | Call function |
|---|---|
| Hardware trigger | Software triggers |
| When it happens may be unpredictable , It is necessary to set occurrence conditions | When will it happen , Call... Where needed |
| The entry address is relatively fixed | The entrance address can be set at will |
| Can't pass on the reference | Can't pass on the reference |
| no return value | no return value |
| Before scheduling , Are kept on site |
1.4 Stack
| Pile up | Stack ( Generally speaking, stack ) | |
|---|---|---|
| The same thing | A data structure , Managed memory | |
| Different management methods | The programmer controls the allocation manually / Release | The compiler automatically manages |
| Different ways of distribution | Dynamic allocation | 2 Ways of distribution : Static allocation is done by the compiler , For example, the allocation of local variables ; Dynamic allocation is made by alloca Function assignment , The compiler releases ; |
| The size of the space is different | There is no limit to | There is a certain space size limit |
| It's different to produce fragments | Frequent distribution / Release will cause memory space discontinuity | Because the stack is an in and out queue , So there will be no fragmentation problem |
| Distribution efficiency is different | Heap is to allocate a block of memory , According to a certain algorithm | The stack allocates special registers , So the stack is more efficient |
| Growing in different directions | Growing up , Increase in the direction of increasing memory addresses ; | Downward growth , Increase in the direction of memory address reduction ; |
| Memory leak | overflow | |
| The effect is different | Large blocks of space used by programmers | Protect the operating environment and the site ( interrupt 、 Function call 、 Task switching ) |
| Array | |
|---|---|
| Arrays are global variables | Allocated in static storage |
| Arrays are local variables | Assigned to the stack |
| Arrays are dynamically allocated | Allocated on the heap |
1.5 Interrupt service function 、 Call function 、 Operating system tasks The difference between stack operations
| Interrupt service function | Call function | Operating system tasks |
|---|---|---|
| 1、 The hardware stores a register on the stack ;( for example M3, There will be some agreements ,R0~2 Used to calculate ) 2、 The software saves some registers or temporary variables to the stack ; | 1、 Some registers or temporary variables used by the software to save ; Some registers do not need to be saved to the stack ;( for example M3, There will be some agreements ,R0~2 It's used to pass on references , So don't save ) | 1, The software should save all the registers to the stack ; |
1.6 FreeRTOS And STM32 Startup file Stack differences in
| Pile up | ||
|---|---|---|
| STM32 Startup file | FreeRTOS | |
| source | User use malloc function ( Or other allocation functions ) Allocated memory . If the user does not allocate space with the allocation function , The size can be set to 0. Pay attention to whether the calling third-party library or function uses , for example USB、SD、 Network, etc . | FreeRTOS A total heap size is defined in the configuration file , It's actually an array , Then allocate stacks for each task on the array , The remaining space is used as a heap . The user allocates memory with the allocation function . |
| effect | In big data storage , Sometimes we need large storage space in a certain period of time , Due to limited memory , I hope this memory can be reused . Heap is just right for this flexible requirement . Heaps can be used as local temporary storage , It can also be stored statically . The static or global arrays we usually define in memory cannot be released and reused , In this way, when the memory demand is large, the memory cannot be satisfied ! | |
| Management style | User assignment / Release | |
| Manage function types | standard C Library memory management function ; Custom memory management functions ; | FreeRTOS Memory management functions in ; standard C Library memory management function ; Custom memory management functions ; |
The first 2 Chapter Mission
2.1 What is a mission ?
Mission : Running functions
Handle : Structure pointer
2.2 Create tasks
2.2.1 Create the parameters required for the task
TCB Structure : Task control block . There are mainly function pointers ,SP Location , priority , Parameters, etc. .
Task to handle (TaskHandle_t ): Namely TCB Structure pointer .
BaseType_t xTaskCreate( TaskFunction_t pxTaskCode, // The function pointer points to the task function ( An endless loop function )
const char * const pcName, // The name of the mission ,FreeRTOS It is not used internally , Just for debugging . The length is :configMAX_TASK_NAME_LEN
const configSTACK_DEPTH_TYPE usStackDepth, // Task stack size , Each task has its own stack . Company u32, Input 10 Said is 40 Bytes
void * const pvParameters, // Parameters passed in when calling the task function
UBaseType_t uxPriority, // priority
TaskHandle_t * const pxCreatedTask ); // Outgoing task handle , Use it later to operate this task 2.2.2 Where are the parameters when creating a task
1)、 Allocated TCB Mechanism , Add task name 、 Assign task priority to TCB Structure .
2)、 Allocated stack . Write the function address in the stack 、 Parameter pointer .
2.3 Task scheduling mechanism
2.3.1 Task priority
High priority tasks , priority , Preempt low priority tasks
High priority tasks don't stop , Low priority tasks can never be performed
Tasks of equal priority , Take turns to execute ( Or time slice rotation )
| Value range of priority | The higher the priority | Task running sequence |
|---|---|---|
| 0~(configMAX_PRIORITIES – 1) | The greater the numerical | High priority runs first ; Same priority , Runnable tasks , Take turns to execute |
| Scheduler method | configMAX_PRIORITIES size | Method enables | |
|---|---|---|---|
| Use C When language is realized | The same code for all architectures | There is no limit to , But the larger the value, the more wasteful Memory and Time . | configUSE_PORT_OPTIMISED_TASK_SELECTION Is defined as 0 |
| When using assembly implementation | For architecture related optimization . | The value cannot exceed 32 | configUSE_PORT_OPTIMISED_TASK_SELECTION Is defined as 1 |
Priority related configuration :
| Configuration item description | Configuration item | Configuration mode | ||||
|---|---|---|---|---|---|---|
| A | B | C | D | E | ||
| --- | --- | --- | --- | --- | --- | --- |
| Commonly used | Rarely used | Rarely used | Rarely used | Almost no use | ||
| whether preemptable | configUSE_PREEMPTION | 1 | 1 | 1 | 1 | 0 |
| whether Time slice rotation | configUSE_TIME_SLICING | 1 | 1 | 0 | 0 | x |
| whether Idle tasks | configIDLE_SHOULD_YIELD | 1 | 0 | 1 | 0 | x |
| close Tick Interrupt to save power | configUSE_TICKLESS_IDLE | 0 | 0 | 0 | 0 | 0 |
2.3.2 Task status
function (Running): The task is in progress , At this time, the processor is occupied . for example , The car is moving .
be ready (Ready): Tasks that can be run at any time , But it's not its turn yet . The newly created task is in ready status .
Blocking (Blocked): Wait for an event ( time delay , Events, etc. ). for example , The car waits for the green light .
Pause (Suspended)( Hang up ): Don't wait for , Just go and have a rest .
2.3.3 How to manage
FreeRTOS Through three linked lists ( Ready task linked list 、 Block task linked list 、 Pause task linked list ) To manage tasks . Ready task linked list There are as many priorities as there are Ready task linked list ; Block task linked list 、 Pause task linked list various 1 individual .
1、 From high priority Ready task linked list To low priority Ready task linked list Found the ready task , Get the task handle to the run pointer , Run it .
2、 If there are tasks of the same level , Line up to take turns , Run first in front of the linked list , function 1 individual tick Back to the back of the line .
3、 If a task is blocked , Then change the task from The ready task linked list is moved to Block task linked list in ; Unblock , On the contrary .
4、 If a task is suspended , Then change the task from The ready task linked list is moved to Pause task linked list in ; Remove suspended , On the contrary .
2.3.4 How to schedule
TICK Timed interrupt , stay Tick Task switching will be performed in the interrupt function ( The linked list is used to get the appropriate task to run ). Each interrupt checks which delayed tasks expire , Remove it from the deferred task list and add it to the ready list . If all ready tasks have the same priority , If time slice polling is enabled , Every tick Perform a task , Polling execution .
Tick What did the interrupt do : 1)、 Find the highest priority ready task
2)、 Save the information of the current task , And insert it into the end of the ready task chain
3)、 Resume new tasks
The first 3 Chapter Synchronization and mutual exclusion
3.1 The concepts of synchronization and mutual exclusion
Sync : Dependencies between tasks , such as A The operation of the task depends on B Data generated by the task . for example : In team activities , colleagues A Finish writing the report , The manager B To report to the leader . The manager B I have to wait for my colleagues A Complete the report ,AB There is dependence between .
Mutually exclusive : When accessing resources at the same time , Only one can get resources , Only after one is used can it be the next , Mutually exclusive access is often required . for example : The printer can only print one task at a time ;A、B Two people rob the toilet ,A Take up... First ,B Only wait A Use up and reuse .
3.2 The general implementation method of synchronization and mutual exclusion
Can achieve synchronization 、 Mutually exclusive kernel methods are : Task to inform (task notification)、 queue (queue)、 Event group (event group)、 Semaphore (semaphoe)、 The mutex (mutex).
They all have similar methods of operation : obtain / Release 、 Blocking / Wake up the 、 Overtime .
queue (queue) It can be used for " Task to task "、" Task to interrupt "、" Interrupt to task " Direct transmission of information .
| Kernel object | Application scenarios | producer | consumer | data / state | explain |
|---|---|---|---|---|---|
| queue | Pass any number of data | ALL | ALL | Mission 、 Interrupt can write data ; Mission 、 Interrupts can read data ; | Used to transfer data , sender 、 The recipient is unlimited , One data can only wake up one receiver |
| Count the semaphore | Count the number of resources | ALL | ALL | The core is " Count " Mission 、 Interrupts can release semaphores ( Count plus 1); Mission 、 Interrupt can get semaphore ( Count minus 1); | Number of resources used to maintain , producer 、 Consumers have no restrictions , 1 A resource can only wake up 1 A receiver : Like a parking lot , Out of a , To get in one |
| Binary semaphore | Binary semaphores are usually used for mutually exclusive access or synchronization of resources | ALL | ALL | The core is " Count " Mission 、 Interrupts can release semaphores ( The number 1); Mission 、 Interrupt can get semaphore ( The number 0); | Number of resources used to maintain , producer 、 Consumers have no restrictions , 1 A resource can only wake up 1 A receiver : Like a parking lot , Out of a , To get in one |
| The mutex | Priority inherited binary semaphore | A locked | A The lock | The number is only 0 or 1 Mission release semaphore ( The number 1); The task obtains the semaphore ( The number 0); | Like an empty toilet , Who uses who locks , He can only unlock |
| Event group | ALL | ALL | An event uses one bit Express : 1 Indicates that the event has occurred , 0 Indicates that the event did not occur ; | Used to deliver Events , It can be N Events , sender 、 The recipient is unlimited , You can wake up multiple recipients : Like radio | |
| Task to inform | ALL | 1 middle school | data 、 Status can be transmitted , The core of the task is TCB The number in , Will be covered ; To whom ? Receive task must be specified ; The notification can only be obtained by the receiving task itself ; | N Yes 1 The relationship between : The sender is unlimited , The receiver can only be this task |
The first 3 Chapter queue
3.1 queue
queue It's for tasks and tasks 、 Variable length messages are passed between tasks and interrupts . One or more messages can be written to the queue ; One or more messages can also be read from the queue .uCOS Passing messages is the way of passing pointers , and FreeRTOS It adopts the method of copying messages , However, you can also pass pointers ( Copying data pointers can be achieved ).
Queue core operations :1- Close the interrupt ,2- Operation queue buffer ,3- Linked list ( Record due to sending / receive (2 Species linked list ) And enter the blocking task )

characteristic :
- Read / write queue supports timeout mechanism .
- Messages support the first in first out principle (FIFO), But it also supports the principle of last in, first out (LIFO).
- Any type of message with different length can be allowed ( No more than the maximum number of queue nodes ).
- A task can receive and send messages from any message queue .
- Multiple tasks can receive and send messages from the same message queue .
- When the queue is finished , You can delete by deleting the queue function .
3.2 Message email
Message email The message queue length is 1 The situation of .
The first 4 Chapter Semaphore
A signal is a sign , Like a signal light ; Quantity is used to count . seeing the name of a thing one thinks of its function , Is the flag count . The essence of semaphore function is counting . Semaphore In fact, there is only one queue item , This queue item is not used to deliver messages , But to count . commonly For resource management and Synchronization tasks , Between tasks Sync or Exclusive access to critical resources .
Semaphore mainly realizes two functions :
- Synchronization between two tasks or between interrupt function and task , This is similar to the event flag group . In fact, sharing resources for 1 When .
- Management of multiple shared resources . How many resources are in use , The semaphore is reduced by how much .
4.1 Count the semaphore
Count the semaphore Used to count the number of events Or right Management of resource quantity , Count unlimited . stay Mission and interrupt in You can use .
Event count : The event occurred — Release semaphore ( Semaphore +1); Event handling — Acquisition semaphore ( Semaphore -1), Decreasing to zero means that all events have been handled .
Resource management : The semaphore value represents the available quantity of the current resource , For example, the number of remaining parking spaces in the parking lot . The semaphore value is 0 It means that there are no resources .
Priority reversal phenomenon : In many cases , Some resources have only one , When a low priority task is occupying the resource , Even high priority tasks can only wait for low priority tasks to release resources after using the resources . Here, the phenomenon that high priority tasks cannot run while low priority tasks can run is called “ Priority flipping ”.
4.2 Binary semaphore
- Semaphore resources are acquired , The semaphore value is 0; Semaphore resources are released , The semaphore value is 1, Only 0 and 1 The semaphores in both cases are called binary semaphores .
- Similar to a flag bit , Event generation set 1, Post event processing 0.
- It can be used in tasks and interrupts
4.3 Mutex semaphore
Mutex semaphore In fact, it is a binary semaphore with priority inheritance , In synchronous applications ( Synchronization between tasks or interruptions ) Binary semaphores are most suitable for .
Priority inheritance : When a mutex semaphore is being used by a low priority task , At this time, if a high priority task also tries to obtain the mutex semaphore, it will be blocked . However, this high priority task will raise the priority of low priority tasks to the same priority as itself , This process is priority inheritance . Priority inheritance reduces the blocking time of high priority tasks as much as possible , And will have appeared “ Priority flipping ” Minimize the impact of .
Can be used in tasks , Cannot be used in interrupts .
Mutex semaphores cannot be used in interrupt service functions , Here's why :
- Mutex semaphores have a priority inheritance mechanism , So it can only be used in tasks , Cannot be used to interrupt service functions .
- In the interrupt service function, you cannot set the blocking time to enter the blocking state because you want to wait for a mutually exclusive semaphore .
4.4 Recursive semaphore
Recursive mutex semaphores , In fact, that is Mutex semaphore Inside nesting Mutex semaphore .
The first 5 Chapter Event group
Event is a mechanism for communication between tasks , It is mainly used to realize the synchronization between multiple tasks , But event communication can only be event type communication , No data transfer . Unlike semaphores , It can realize one to many , Many to many synchronization . That is, a task can wait for multiple events to happen : Can be any event occurs when the wake-up task for event processing ; It is also possible to wake up the task for event processing after several events . Again , It can also be multiple tasks synchronizing multiple events .( It can be used in tasks and interrupts )
characteristic :
- Events are only associated with tasks , Events are independent of each other , One 32 Bit event set (EventBits_t Variable of type , The only things that are actually available and represent events are 24 position ), Used to identify the type of event that the task occurs , Each bit represents an event type (0 Indicates that the event type did not occur 、1 Indicates that the event type has occurred ), altogether 24 Types of events .
- Events are used for synchronization only , Data transmission function is not provided .
- Event non queueing , That is, set the same event to the task several times ( If the task hasn't been read yet ), Equivalent to Set only once .
- Allow multiple tasks to read and write to the same event .
- Support event waiting timeout mechanism .
The first 6 Chapter Task to inform
adopt Task to inform The way to do it Message email , Count the semaphore , Binary semaphore , Event flag set .
Using queues 、 Before semaphore , You must first create queues and semaphores , The purpose is to create a queue data structure . Because the data structure of the task notification is contained in the task control block , As long as the mission exists , The task notification data structure has been created , You can use it directly . Faster task notification processing ,RAM It costs less .
Task notification can send notification to the specified task in the task , You can also send a notification to the specified task in the interrupt ,FreeRTOS Every task has a 32 Notification value of bit , Member variables in the task control block ulNotifiedValue This is the notification value .
You can only wait for notification during a task , It is not allowed to wait for notification during interruption .
Task notification restrictions :
- Task notification can only be used when there is only one task waiting for semaphore , Message mailbox or event flag group .
- When the message queue is replaced by the message mailbox implemented by task notification , The task of sending messages does not support timeout , That is, the data in the message queue is full , You can wait for the message queue to have space to store new data , The message mailbox implemented by task notification does not support overtime waiting .
FreeRTOS There are several ways to send notifications to tasks :
- Send notification to task , If there is a notice unread , Do not overwrite notification values .
- Send notification to task , Override the notification value directly .
- Send notification to task , Set one or more bits of the notification value , It can be used as an event group .
- Send notification to task , Increment the notification value , It can be used as a counting semaphore
The first 7 Chapter Software timer
FreeRTOS The software timer is based on Tick Hardware timer interrupts to run , Other operating systems are also , However, other operating systems call the software timer function in the hardware timer , and FreeRTOS No .FreeRTOS It thinks that if the timer function is time-consuming , Will affect the whole system , therefore FreeRTOS Is to process software timers through tasks .
When FreeRTOS Configuration item for configUSE_TIMERS Set to 1 when , When starting the scheduler , Automatically created RTOS Damemon Task( Guardian task ).Tick The hardware timer interrupt function finds that a certain time has expired , Write command queue , Read timer command queue in daemon task , Deal with the data , Sleep without data .
The first 8 Chapter Interrupt mechanism
FreeRTOS hold MCU Hardware interrupts fall into two categories , High priority interrupts ; Low priority interrupt . Cannot be used in high priority interrupts FreeRTOS Of API function , It is used to deal with more urgent things , Don't depend on FreeRTOS. Low priority interrupts can be used in interrupts FreeRTOS Of API function .
The first 9 Chapter Critical resources
Critical resources : A shared resource that is allowed to be used by only one process or task at a time . for example : The hardware has a printer 、 Tape drive etc. ; The software has a message buffer queue 、 Variable The mutex 、 Variable 、 Array 、 Buffer, etc. .
Mutually exclusive access to critical resources is through shielding / To interrupt 、 Pause / Recovery scheduler To achieve . In this way, access to critical resources can be undisturbed .
A critical region : In every process or task , Access to critical resources Period Code . That is, shielding / Enable code between interrupts 、 Pause / Recover code between schedulers .
边栏推荐
猜你喜欢

Pipeline detection of UAV Based on gazebo

Nacos - 配置管理

Audio-AudioRecord create(一)

截图小妙招

Internet of things technology is widely used to promote intelligent water automation management

【MFC开发(17)】高级列表控件List Control

Matlab tips (16) consistency verification of matrix eigenvector eigenvalue solution -- analytic hierarchy process

The use of word in graduation thesis

为什么LTD独立站就是Web3.0网站!

DID的使用指南,原理
随机推荐
Yolov3, 4, 5 and 6 Summary of target detection
MD文档中插入数学公式,Typora中插入数学公式
The era of low threshold programmers is gone forever behind the sharp increase in the number of school recruitment for Internet companies
毕业论文中word的使用1-代码域标公式
Insert mathematical formula in MD document and mathematical formula in typora
View drawing process analysis
factory type_id::create过程解析
Internet of things technology is widely used to promote intelligent water automation management
Li Kou 1358 -- number of substrings containing all three characters (double pointer)
截图小妙招
分享2022上半年我读过的7本书
Brief introduction to AES
Nacos - 配置管理
yolov5训练可视化指标的含义
Mavros sends a custom topic message to Px4
MAVROS发送自定义话题消息给PX4
明明设计的是高带宽,差点加工成开路?
固定资产管理系统让企业动态掌握资产情况
电脑小技巧
Review of week 280 of leetcode