MicriumµC/OS II RTOS Introduction -...

Post on 26-Mar-2018

230 views 1 download

Transcript of MicriumµC/OS II RTOS Introduction -...

Micrium µC/OS‐II RTOS Introduction(by Jean Labrosse)(by Jean Labrosse)

EE599‐001 Fall 2012Fall 2012J. E. Lumpp

μC/OS ‐‐ IIμC/OS  II• μC/OS‐II is a highly portable, ROMable, very scalable, 

preemptive real‐time, deterministic, multitasking kernel• It can manage up to 64 tasks (56 user tasks available)• It has connectivity with μC/GUI and μC/FS (GUI and FileIt has connectivity with μC/GUI and μC/FS (GUI and File• Systems for μC/OS‐II)• It is ported to more than 100 microprocessors and

i t ll• microcontrollers• It is simple to use and simple to implement but very• effective compared to the price/performance ratio.p p p• It supports all type of processors from 8‐bit to 64‐bit

2

µC/OS PortingµC/OS Porting

3

Task Management – ServicesTask Management  Services

• Task CreationTask Creation• Task Stack & Stack Checking

k l i• Task Deletion• Change a Task’s Priority• Suspend and Resume a Task• Get Information about a TaskGet Information about a Task

4

Task FeaturesTask Features

• μC/OS‐II can manage up to 64 tasks.μC/OS II can manage up to 64 tasks.• The four highest priority tasks and the four lowest priority tasks are reserved for its ownlowest priority tasks are reserved for its own use. This leaves us with 56 application tasks.

• The lower the value of the priority, the higherThe lower the value of the priority, the higher the priority of the task. (e.g., Rate Monotonic Scheduling)

• The task priority number also serves as the task identifier

5

Embedded Program w/o RTOSEmbedded Program w/o RTOS

Foreground #2 ISR #2

Foreground #1 ISR #1 ISR #1

Background Task #1 Task #2 Task #3

Infinite loop

Time

Infinite loop

6

Super LoopSuper Loop

• Background response time is the backgroundBackground response time is the background execution time– Non‐deterministic

• Affected by control flow (if, while…)

– High latencyChanges to code changes timing– Changes to code changes timing

ISRPoll to see if ISR occurredAffected by if, for, while

ISRPoll to see if ISR occurredAffected by if, for, while

Task #1 Task #2 Task #3 Task #4Task #1 Task #2 Task #3 Task #4

7

Task #1 Task #2 Task #3

Infinite loop

Task #4Task #1 Task #2 Task #3

Infinite loop

Task #4

Foreground/Background Tasksg / g

• All ‘tasks’/functions() have the same priorityAll  tasks /functions() have the same priority– Code executes in sequence => No Shared Data BugsBugs

– If an important event occurs, it’s handled at the same priority as everything elsesame priority as everything else

– May need to execute the same code often to avoid missing an eventg

Task #1 Task #2 Task #3

I fi it l

Task #4Task #1 Task #2 Task #3

I fi it l

Task #4

8

Infinite loopInfinite loop

RTOSRTOS

• Real‐Time Operating SystemReal Time Operating System– Software that manages the time of a microprocessor, microcontroller, 

or a digital signal processor– Prioritizes the work to be donePrioritizes the work to be done– Provides ‘multitasking’– Provides ‘services’ to the application

• SemaphoresSemaphores• Message mailboxes and queues• Event flags• Time delays timers and timeouts• Time delays, timers, and timeouts• Task management• Memory management• Bandwidth assessment ‘idle time’• Bandwidth assessment  idle time

9

PreemptionPreemption1.  Pre‐emptive:

Always runs the highest available t k T k f id ti l i ittask. Tasks of identical priority share CPU time (fully pre‐emptive with round robin time slicing)

2 . Cooperative:pContext switches only occur if a task blocks, or explicitly relinquishes CPU control

10

RTOS AdvantagesRTOS Advantages• Software that manages the time of a microprocessor or 

i t llmicrocontroller– Ensures that the most important code runs first

• Allows Multitasking– Do more than one thing at the same time– Application is broken down into multiple tasks, each handling one aspect of your applicationhandling one aspect of your application

– It’s like having multiple CPUs• Provides valuable services to your application

Ti d l– Time delays– Resource sharing– Inter‐task communication and synchronizationy

11

RTOS TasksRTOS Tasks

• A task is a function that appears it has the CPUA task is a function that appears it has the CPU all to itself

• Each Task has• Each Task has– Its own stack spaceA i i b d i i– A priority based on its importance

• A task contains application code and calls to OS functions

12

Example TaskExample Task

• A task is an infinite loopA task is an infinite loopvoid Task (void *p_arg){

D thi ith ‘ t’Do something with ‘argument’ p_arg;Task initialization;for (;;) {

/* Processing (Your Code) *// Processing (Your Code) /Wait for event; /* Time to expire ... */

/* Signal from ISR ... *//* Signal from task ... *// Signal from task ... /

/* Processing (Your Code) */}

}

13

}

Designing with µC/OS‐IIDesigning with µC/OS IIHigh Priority Task Task

Task Each Task

Task Event EventImportance

Task Task

I fi it LLow Priority Task Task Infinite Loop

14

Task StatesTask States

15

uC/OS‐II API

• ● There are several functions called API of uc/os● There are several functions called API of uc/os• II using these api functions we can write our• application on uc/os II• application on uc/os II• ● API is used to handle• Tasks• Semaphores and Mutex• Memory Management• Timer etc.

16

Kernel StructureKernel Structure• ● How μC/OS‐II handles access to critical sections of code,

• ●What a task is, and how μC/OS‐II knows about your tasks,tasks,

• ● How tasks are scheduled,• ● How μC/OS‐II can determine how much of CPU your• application is using,• ● How do to write Interrupt Service Routines (ISRs),• ●What a clock tick is and how μC/OS II handles it• ●What a clock tick is and how μC/OS‐II handles it,• ● How to initialize μC/OS‐II and,• ● How to start multitasking.g

17

TasksTasks

18

Tasks ManagementTasks Management

• ● Uc os II can manage up to 64 tasks but it is• recommended that leave the 4 above and 4• below priorities so effectively we have 56 task• ● It means we can create upto 56 tasks• ● OS_LOWEST_PRIO the lowest priority task is• for the idle task

Idl k h if h i k i d• ● Idle task means that if there is no task in ready• queue still the cpu will execute this idle task.

19

Task StatisticsTask Statistics• ● Uc/os II contains a task that provide run time statistics• OS_TaskStat() and is created by uc/os II if you set the• configuration constant OS_TASK_STAT_EN to 1• ●When enabled OS TaskStat() executes every second and• ●When enabled OS_TaskStat() executes every second and• computes the percentage of CPU usages• ● OS_TaskStat() tells you how much CPU time is used by 

your• application as a percentage• ● This value is placed in 8 bit signed integer OSCPUUsagep g g g• variable• ● Resolution of OSCPUUsage is 1 percent

20

Interrupts under uC/OS‐IIInterrupts under uC/OS II• ● μC/OS‐II requires that an Interrupt Service Routine (ISR) be 

itt iwritten in• assembly language.• ● μC/OS‐II needs to know that you are servicing an ISR and thus, 

you need toyou need to• either call OSIntEnter() or, increment the global variable 

OSIntNesting.• ● μC/OS‐II allows you to nest interrupts because it keeps track of• ● μC/OS‐II allows you to nest interrupts because it keeps track of 

nesting in• OSIntNesting.• ● ISR concludes by calling OSIntExit() which decrements the● ISR concludes by calling OSIntExit() which decrements the 

interrupt nesting• counter.

21

Interrupts under uc/os II

• This function notify uc/os II about beginningThis function notify uc/os II about beginning of

• of an interrupt• of an interrupt• ● Funtions OSIntExit() notify about the ending 

fof• an interrupt

22

Task ManagementTask Management• ● Task is either an infinite loop function or a function that• deletes itself• ● Task code is not actually deleted, uc os II doesn't know about• the task anymore so that code will not run.• ● Task loop like any other C function• ● Task must never return return type of a task must always be• void• ● Task functions are described in OS_TASK.C• ● Using the function we can create, delete, change task's• priority, suspend, resume and obtain information about a taskp y, p ,

23

24

Time ManagementTime Management• Clock Tick: A clock tick is a periodic time source to keep• track of time delays and time outs.• Tick intervals: 10 ~ 100 ms.• The faster the tick rate, the higher the overhead imposed on• the system.• When ever a clock tick occurs μC/OS‐II increments a 32‐• bit counter• The counter starts at zero, and rolls over to 4,294,967,295• (2^32‐1) ticks.• A task can be delayed and a delayed task can also bey y• resumed

25

Time ManagementTime Management

• Five services:Five services:• OSTimeDLY()

OS i S ()• OSTimeDLYHMSM()• OSTimeDlyResume()• OSTimeGet()• OSTimeSet()OSTimeSet()

26

Inter‐‐task communicationInter task communication

• Inter‐task or inter process communication in pμC/OS takes

• place using• Semaphores• Message mailbox

M• Message queues• Tasks and Interrupt service routines (ISR) can interactinteract

• with each other through an ECB (event control block)

27

SemaphoresSemaphores

• A semaphore consists of a wait list and an integer counter.• OSSemPend():• Counter‐‐;• Counter‐‐;• If the value of the semaphore <0, then the task is blocked 

and moved to the wait list immediately.A ti t l b ifi d• A time‐out value can be specified.

• OSSemPost():• Counter++;• If the value of the semaphore >= 0, then a task in the wait 

list is removed from the wait list.• Reschedule if neededReschedule if needed.

Single task waitingSingle task waiting

29

Multiple tasks waiting and signalingMultiple tasks waiting and signaling

30

Tasks can wait and signal along with an loptional time out

31

SempahoresSempahores

• μC/OS‐II semaphores consist of two elementsμC/OS II semaphores consist of two elements• 16‐bit unsigned integer count• list of tasks waiting for semaphorelist of tasks waiting for semaphore• μC/OSII provides• Create post pend accept and query services• Create, post, pend accept and query services

32

μC/OS‐II message‐mailboxesμC/OS II message mailboxes

• μC/OSII object thatμC/OSII object thatallows a task or ISR to send a pointer sized variablevariable(pointing to a message) to another task.

33

μC/OS‐II message‐queuesμC/OS II message queues

• Available services: Create, Post (FIFO), PostFrontAvailable services: Create, Post (FIFO), PostFront (LIFO),

• Pend, Accept, Query, Flush, p , Q y,• N = #of entries in the queue: Queue full if Post or PostFront

• called N times before a Pend or Accept• μC/OS‐II message‐queues organized as circular μ / g q gbuffers.

34

Tasks loopsTasks loops• Tasks running under a multitasking kernel should be• written in one of two ways:• A non‐returning forever loop. For example:• void Task (void *)• {• {• DoInitStuff();• while (1)• {{• do this;• do that;• do the other thing;g;• call OS service (); // e.g. OSTimeDelay, OSSemPend, etc.• }• }

35

Rate Monotonic SchedulingRate Monotonic Scheduling• In Rate Monotonic Scheduling tasks with the highest rate• of execution are given the highest priority• Assumptions:• All tasks are periodic• Tasks do not synchronize with one another, share• resources, etc.• Preemptive scheduling is used (always runs the highest• priority task that is ready)• Under these assumptions, let n be the number of tasks, Ei• be the execution time of task i, and Ti be the period of task, p f• i. Then, all deadlines will be met if the following inequality• is satisfied:• ΣEi / Ti ≤ n(21/n – 1)/ ( / )

36

Rate Monotonic Scheduling: ExampleRate Monotonic Scheduling: Example

• Suppose we have 3 tasks. Task 1 runs at 100 Hz andpp• takes 2 ms. Task 2 runs at 50 Hz and takes 1 ms. Task 3• runs at 66.7 Hz and takes 7 ms. Apply RMS theory…• (2/10) + (1/20) + (7/15) = 0.717 ≤ 3(21/3 – 1) = 0.780• Thus, all the deadlines will be met• General Solution?• As n →∞, the right‐hand side of the inequality goes to ln(2)=to ln(2)=

• 0.6931. Thus, you should design

37