IAR PowerPac™ RTOS

User Guide

PPRTOS-3

COPYRIGHT NOTICE
© Copyright 2006-2008 IAR Systems AB. No part of this document may be reproduced without the prior written consent of IAR Systems AB. The software described in this document is furnished under a license and may only be used or copied in accordance with the terms of such a license.

DISCLAIMER
The information in this document is subject to change without notice and does not represent a commitment on any part of IAR Systems AB. While the information contained herein is assumed to be accurate, IAR Systems assumes no responsibility for any errors or omissions. In no event shall IAR Systems, its employees, its contractors, or the authors of this document be liable for special, direct, indirect, or consequential damage, losses, costs, charges, claims, demands, claim for lost profits, fees, or expenses of any nature or kind.

TRADEMARKS
IAR Systems, IAR Embedded Workbench, C-SPY, visualSTATE, From Idea To Target, IAR KickStart Kit, IAR PowerPac, IAR YellowSuite, IAR Advanced Development Kit, IAR, and the IAR Systems logotype are trademarks or registered trademarks owned by IAR Systems AB. J-Link is a trademark licensed to IAR Systems AB. Microsoft and Windows are registered trademarks of Microsoft Corporation. All other product names are trademarks or registered trademarks of their respective owners.

EDITION NOTICE
Third edition: October 2008 Part number: PPRTOS-3

Internal reference: SW v3.62, ISUD.

PPRTOS-3

Contents
Preface ........................................................................................................................................................................ 9 Introduction to IAR PowerPac RTOS ............................................................................................................ 11
What is IAR PowerPac RTOS .................................................................................................................. 11 Features ......................................................................................................................................................... 11

Basic concepts ....................................................................................................................................................... 13
Tasks ............................................................................................................................................................... 13 Single-task systems (superloop) ............................................................................................................... 13 Multitasking systems ................................................................................................................................... 13 Cooperative multitasking ...................................................................................................................... 14 Preemptive multitasking ....................................................................................................................... 15 Scheduling ...................................................................................................................................................... 15 Round-robin scheduling algorithm ....................................................................................................... 15 Priority-controlled scheduling algorithm .............................................................................................. 16 Priority inversion .................................................................................................................................. 16 Communication between tasks ................................................................................................................ 16 Global variables .................................................................................................................................... 16 Communication mechanisms ................................................................................................................ 16 Mailboxes and queues ........................................................................................................................... 17 Semaphores ........................................................................................................................................... 17 Events .................................................................................................................................................... 17 How task-switching works ......................................................................................................................... 17 Switching stacks ........................................................................................................................................... 17 Change of task status .................................................................................................................................. 18 How the OS gains control ......................................................................................................................... 19 OS_InitKern() ....................................................................................................................................... 20 OS_Start() ............................................................................................................................................. 20 Different builds of IAR PowerPac RTOS ............................................................................................... 21 IAR PowerPac RTOSIAR PowerPac RTOSList of libraries ................................................................ 21

Tasks ......................................................................................................................................................................... 23
Introduction .................................................................................................................................................. 23 Example of task routine as an endless loop .......................................................................................... 23 Example of task routine that terminates itself ...................................................................................... 23 API function .................................................................................................................................................. 23 OS_CREATETASK() ........................................................................................................................... 24 OS_CreateTask() .................................................................................................................................. 25 OS_CREATETASK_EX() ................................................................................................................... 26 OS_CreateTaskEx() .............................................................................................................................. 27 OS_Delay() ........................................................................................................................................... 28 OS_DelayUntil() ................................................................................................................................... 28 OS_ExtendTaskContext() ..................................................................................................................... 29 OS_GetpCurrentTask() ......................................................................................................................... 31 OS_GetPriority() ................................................................................................................................... 31 OS_GetSuspendCnt() ............................................................................................................................ 31 OS_GetTaskID() ................................................................................................................................... 32
PPRTOS-3

3

........................................................................................ 49 Introduction .........................................................................................................................................................................................................................................................................................................34 OS_WakeTask() ................................................................................................................................................43 OS_CreateTimerEx() ................................................................37 OS_CREATETIMER() ..................................................................................................................................................................................35 OS_Yield() ....................................37 API functions .....................39 OS_StartTimer() .......51 OS_Unuse() ..............................................35 Software timers .............................................................................................................................................................................................................................................................................................................................................................................51 OS_CREATERSEMA() ....................................................................................................................................................................46 OS_DeleteTimerEx() ..............................................................47 OS_GetpCurrentTimerEx() ......54 OS_GetResourceOwner() .................................................................42 OS_GetpCurrentTimer() .......................................................................................................................................................................................................................................................................................................47 OS_GetTimerPeriodEx() ..........................32 OS_Resume() ........................................45 OS_SetTimerPeriodEx() ...........................................................................................................................49 API functions .....................................................................................................................................33 OS_SetTimeSlice() ................42 OS_CREATETIMER_EX() ..................................................................................45 OS_RetriggerTimerEx() .......................................................................................................................................................47 OS_GetTimerStatusEx() .....................................................................................................................................................................................................................................................................................................................................................................................................51 OS_Use() .......................................................................................................37 Extended software timer .....................................................................................................................38 OS_CreateTimer() ................................................................................................................................................................................................................................52 OS_Request() ..................................33 OS_Suspend() ....................................................................................................................48 Resource semaphores ...................................................................................................................................................................................42 OS_GetTimerStatus() .................................................................................................................................................................................32 OS_SetPriority() .........................................................................................................................................................................................34 OS_Terminate() ................33 OS_SetTaskName() ...................................................................................................................................................40 OS_DeleteTimer() ........................................... 37 Software timer .....41 OS_GetTimerValue() .......................................................................................................................54 IAR PowerPac™ RTOS 4 User Guide PPRTOS-3 ........53 OS_GetSemaValue() .....................................................................................................................................................................................................................47 OS_GetTimerValueEx() .............................54 OS_DeleteRSema() ............................................................................................................................................................................................................................................................................................................................................................................................................40 OS_SetTimerPeriod() ............................................................................................................................39 OS_StopTimer() ..............................................................................40 OS_RetriggerTimer() .................................................................................................................................................................................................................................................................................................................................................41 OS_GetTimerPeriod() ...................................44 OS_StartTimerEx() ........................................................................................OS_IsTask() ..........................................................................................................................................................................................................................45 OS_StopTimerEx() ...........

..................................................................................................................................................................................................................................................................................................................................................................................................................................................................... 71 Introduction ......................................... 71 OS_Q_Put() ...................................................................................................................................................................................................................................................................................................................................................................................................................................... 66 OS_GetMailTimed() ................................................................................................................................................................................................................................................ 77 Introduction ............................................................................................................................................. 63 OS_PutMail() / OS_PutMail1() ............................ 73 OS_Q_GetPtrTimed() ... 77 OS_WaitSingleEvent() ....................... 71 API functions ...................................................... 56 OS_WaitCSema() ......................... 55 OS_CREATECSEMA() .............. 61 Basics .................................................................................................................................................................................................................................. 64 OS_PutMailFront() / OS_PutMailFront1() ........................................................ 66 OS_GetMailCond() / OS_GetMailCond1() ................................................................................................................................................................................................................. 61 Typical applications ...................................... 74 OS_Q_Clear() ......................................................................... 58 OS_SetCSemaValue() ........................ 68 OS_GetMessageCnt() ..................................................................................... 65 OS_PutMailFrontCond() / OS_PutMailFrontCond1() ................................................................................................................ 55 API functions ........ 61 Introduction ..................................... 67 OS_WaitMail() ............................................................................................................................... 55 OS_CreateCSema() ..................................................................................................................................................................................................... 62 OS_CREATEMB() ........... 74 OS_Q_Purge() ..................................................................................................................................................... 72 OS_Q_GetPtrCond() .......................................................... 77 API functions ...................... 55 Introduction ........................................................................................................................................................................................... 72 OS_Q_GetPtr() ............................................................................................................ 56 OS_SignalCSema() ...................................................................................................................................................................... 62 API functions .................................................................................................................... 61 Single-byte mailbox functions .................................................................................... 68 OS_ClearMB() .................................................Contents Counting Semaphores ....................... 58 OS_GetCSemaValue() ............................................................................................................................................................................. 71 Basics ............. 78 PPRTOS-3 5 .................................................................................................. 71 OS_Q_Create() ................................................... 75 OS_Q_GetMessageCnt() ..................................................... 57 OS_WaitCSemaTimed() ...................................................................................... 65 OS_GetMail() / OS_GetMail1() ...................................... 68 OS_DeleteMB() .................................................... 77 OS_WaitEvent() ..................................................................................................................................................................................................................................................................................................................... 56 OS_SignalCSemaMax() ..... 58 OS_DeleteCSema() .................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................... 59 Mailboxes ........................................................................ 63 OS_PutMailCond() / OS_PutMailCond1() ............................................................................................................................................................................................................................................................................................................................................................................................................................................................................... 57 OS_CSemaRequest() ....................................................................................... 69 Queues ................................................................................. 75 Task Events ...............................................................................................................................................................................................................................................................................................................................................................................................................

........................................................................................................................... 91 Introduction .....................................................................................................92 OS_MEMF_Alloc() .............................................................................................................................................94 OS_MEMF_GetMaxUsed() ........................................................93 OS_MEMF_Release() ..........................................................................................................................................94 OS_MEMF_GetBlockSize() ............................................95 Stacks .............................................................................................................................................................................................95 OS_MEMF_IsInPool() ...................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................97 API functions .............................................94 OS_MEMF_GetNumFreeBlocks() ....87 OS_EVENT_Get() ....................................................................................................................................................97 Task stack ..........................................................................................................................................................................................................................84 OS_EVENT_Set() ........................................................................................................................................................91 API functions ..........................................89 API functions ........................................................................................................................................................................................................................................................................................................................................................................................................................83 OS_EVENT_Wait() .............................................................................................................................83 API functions ...........................................97 Interrupt stack .....................................................85 OS_EVENT_Reset() ........................................................79 OS_GetEventsOccurred() ................................................................ 97 Introduction .......................................................................................................................................................80 OS_ClearEvents() .........................................................................83 OS_EVENT_Create() .....................................................99 OS_GetStackUsed() ....................................................................................................................................................87 OS_EVENT_Delete() ................................80 Event objects ..........................79 OS_SignalEvent() ...........................................................................92 OS_MEMF_AllocTimed() ..........................92 OS_MEMF_Request() ................................................................................................................................................................................................................................................ 83 Introduction .....................................................................................................................................................................................................................................................................................................................................................OS_WaitEventTimed() ........................................................................... 89 Introduction .......................................................................................98 OS_GetStackSpace() ......................................................................................................97 System stack .......................................91 OS_MEMF_Delete() .................................................................................................................................................................................98 OS_GetStackSize() ............................................93 OS_MEMF_FreeBlock() .............................................................................................................84 OS_EVENT_WaitTimed() .................................................................................................................................................................................................................................................91 OS_MEMF_Create() ....................................................................................................................................................................................78 OS_WaitSingleEventTimed() ............................89 Fixed block size memory pools ................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................98 OS_GetStackBase() .....................87 Heap type memory management .............86 OS_EVENT_Pulse() ..................................................................94 OS_MEMF_GetNumBlocks() ........................99 IAR PowerPac™ RTOS 6 User Guide PPRTOS-3 .........................................................................................................................................................................

...................................................................... 104 OS_CallNestableISR() ......................................................102 High / low priority interrupts .......................... 107 Definitions of interrupt control macros (in RTOS...................................................................................................................................111 Low-resolution measurement .................................................................. 107 OS_EnterNestableInterrupt() ................. 102 Rules for interrupt handlers ................ 105 Enabling / disabling interrupts from C ................................................................................................. 115 System variables ................................................................................................................................................................................................................................................................................................ 103 Additional rules for preemptive multitasking ..................................................................................101 Causes of interrupt latencies ......................................................................................................................................... 117 Introduction ....................................................................................................................................................................................................................................................................................................................................................................................106 OS_IncDI() / OS_DecRI() .......108 Non-maskable interrupts (NMIs) .................................. 109 Time measurement ......................................................................................................................................................................................................... 117 System tick .....................................119 API functions ........................................................................................................................... 119 PPRTOS-3 7 .......................................................................................................................................................................................................................................................................................................................... 101 Additional causes for interrupt latencies .................................................................................................................................................................................................................................................................... 113 API functions .................................................................................................................................................................................................................................................................................................. 103 General rules .............. 108 OS_LeaveNestableInterrupt() ............................................ 117 OS_Time ........................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................... 107 Nesting interrupt routines ................................................................................................................................................................................................................................................................................................................................................................................. 106 OS_DI() / OS_EI() / OS_RestoreI() ............................................ 101 What are interrupts? ..............h) .................................................................................................................................................................................................................. 103 OS_CallISR() ...................................... 114 Example .........119 Tick handler ..... 119 Introduction ..........................................................................................................................................................................................................................117 Time variables .........................................Contents Interrupts ................................................105 Example using OS_EnterInterrupt()/OS_LeaveInterrupt() .................................................................................................................................. 109 OS_LeaveRegion() .............................................................................................................................................................................................................................................................................................................................. 103 API functions .................................................................................................... 109 Introduction ............................................................................................111 API functions ........................................................................................................ 117 OS internal variables and data-structures .............. 112 High-resolution measurement ............................109 API functions ......................................................................108 Critical Regions .................................................................................................................................104 OS_EnterInterrupt() ........................................................................117 OS_TimeDex .......................................... 104 OS_LeaveInterrupt() ........................................................................................................................... 105 OS_LeaveInterruptNoSwitch() .................105 Example using OS_EnterInterrupt()/OS_LeaveInterrupt() ............................................................................................ 111 Introduction ...................................................................................................................................................... 101 Interrupt latency ....... 109 OS_EnterRegion() .................................................................................................................................................... 101 Zero interrupt latency .................................

................................................................................................................................................................................................................................................................................................ 147 Index ......................................121 API functions ...........................126 Mailboxes ..................................................................................................................123 Using a different timer to generate the tick-interrupts for IAR PowerPac RTOS .....................................................................................................................................................................................................................133 Memory requirements .....................129 List of error codes ...................................................................................................................................................................................................................128 Debugging .. 139 Limitations .123 Setting the system frequency OS_FSYS .......................................................................................144 FAQ (frequently asked questions) ...................................................................................................................................................................................................................................... 123 Introduction ................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................ 143 Introduction ...................................................................................123 Configuration defines ...............................................................................................................................123 How to change settings .......................................124 STOP / HALT / IDLE modes ............................................................................................................................................ 125 Enabling the C-SPY plug-in module ........................................144 OS_SUPPORT_CLEANUP_ON_TERMINATE ..........................................................124 Changing the tick frequency ........130 Performance and resource usage ....................................................................................................128 Settings .................133 Measurement with port pins and oscilloscope .............................................................................................................................................................143 Major compile time switches .................................................................................................................................................125 Overview ...121 Configuration of target system (BSP) .....................................................................127 System information .................................................................................................................................................................................................................................................................................123 Hardware-specific routines ..........................................................................124 RTOS-aware debugging ..........................133 Performance ...................................................................................................................................................................... 145 Glossary .............................125 Task list ..................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................134 Reentrancy .......................................................................................133 Benchmarking ................................................................................................................................................................143 Building IAR PowerPac RTOS libraries .............................................................................................................................................. 141 Source code of kernel and library ...................................................................................................................................................................................................................................................................................................................................................................................................................................................................................Hooking into the system tick ........................ 133 Introduction ......................................................... 129 Runtime errors ....................................................................................................................127 Resource semaphores ......................126 Timers .............................................................................. 149 IAR PowerPac™ RTOS 8 User Guide PPRTOS-3 ........................................................................143 OS_RR_SUPPORTED ..........................................................................

and compiler-independent introduction to IAR PowerPac RTOS and to be a reference for all IAR PowerPac RTOS API functions. which describes the standard in C-programming and. menu names. For a quick and easy startup with IAR PowerPac RTOS. Sample code in program examples.Preface Welcome to the IAR PowerPac™ RTOS guide User Guide. refer to Chapter 2 in the CPU & Compiler Specifics manual of IAR PowerPac RTOS documentation. How to use this guide The intention of this guide is to give you a CPU. C compiler) The C programming language The target processor DOS command line. we recommend The C Programming Language by Kernighan and Richie (ISBN 0-13-1103628). dialog boxes. file. menu commands. tables and figures or other documents. also covers the ANSI C standard. linker. The purpose of this guide is to provide you with detailed reference information that can help you to use the IAR PowerPac RTOS to best suit your application requirements. Very important sections Reference GUIElement Emphasis Table 1: Typographic conventions PPRTOS-3 9 . which includes a step-by-step introduction to using IAR PowerPac RTOS. Buttons. Parameters in API functions. If you feel that your knowledge of C is not sufficient. Who should read this guide You should read this guide if you plan to develop an embedded system using IAR PowerPac RTOS and need to get detailed reference information about it. This document assumes that you already have a solid knowledge of the following: ● ● ● ● The software tools used for building your application (assembler. in newer editions. Document conventions TYPOGRAPHIC CONVENTIONS FOR SYNTAX This guide uses the following typographic conventions: Style Used for Keyword Parameter Sample Text that you enter at the command-prompt or that appears on the display (that is system functions. Reference to chapters.or pathnames).

IAR PowerPac™ RTOS 10 User Guide PPRTOS-3 .

Preemptions can be disabled for entire tasks or for sections of a program. the limited resources of microcontrollers have always been kept in mind. Unlimited number of tasks (limited only by the amount of available memory). A couple of files are supplied in source code to make sure that you do not loose any flexibility by using IAR PowerPac RTOS and that you can customize the system to fully fit your needs. Some features of IAR PowerPac RTOS include: ● ● ● ● ● ● ● ● ● ● ● ● ● ● ● ● Preemptive scheduling: Guarantees that of all tasks in READY state the one with the highest priority executes. Unlimited number of semaphores (limited only by the amount of available memory). as well as high speed and versatility. The tasks you create can easily and safely communicate with each other using a complete palette of communication mechanisms such as semaphores. Power-consumption is minimized. Unlimited number of mailboxes (limited only by the amount of available memory). IAR PowerPac RTOS is a high-performance tool that has been optimized for minimum memory consumption in both RAM and ROM. Up to 255 priorities. Power management. The internal structure of the real-time operating system (RTOS) has been optimized in a variety of applications with different customers. and events. 8-bit events for every task. designed to be used as an embedded operating system for the development of real-time applications. Unlimited number of software timers (limited only by the amount of available memory). to fit the needs of the industry. 2 types of semaphores: resource and counting. keeping the ROM size very small. Time resolution can be freely selected (default is 1ms).Introduction to IAR PowerPac RTOS What is IAR PowerPac RTOS IAR PowerPac RTOS is a priority-controlled multitasking system. which means that only those functions that are needed are linked. Unused calculation time can automatically be spent in halt mode. PPRTOS-3 11 . Round-robin scheduling for tasks with identical priorities. IAR PowerPac RTOS is highly modular. except for situations where priority inversion applies. Easily accessible time variable. Features Throughout the development process of IAR PowerPac RTOS. Every task can have an individual priority => the response of tasks can be precisely defined according to the requirements of the application. Size and number of messages can be freely defined when initializing mailboxes. mailboxes.

Very fast and efficient. IAR PowerPac™ RTOS 12 User Guide PPRTOS-3 . Initialization of microcontroller hardware as sources (BSP). Minimum RAM usage. semaphores. delete or change the priority of a task. C or C++ source code. IAR PowerPac RTOS has its own interrupt stack (usage optional). Debug version performs runtime checks. simplifying development. Nested interrupts are permitted. API can be called from assembly. as well as create. events).● ● ● ● ● ● ● ● ● ● ● Full interrupt support: Interrupts can call any function except those that require waiting for data. Frame application for an easy start. Core written in assembly language. Interrupts can wake up or suspend tasks and directly communicate with tasks using all available communication instances (mailboxes. Very short interrupt disable-time => short interrupt latency time. yet small code.

All tasks execute as if they completely “owned” the entire CPU. superloops can become difficult to maintain if the program becomes too large.Basic concepts Tasks In this context. the reaction time of one component depends on the execution time of all other components in the system. Multitasking systems In a multitasking system. Task level Superloop Interrupt level ISR Time ISR ISR (nested) Of course. uncomplex systems or if real-time behavior is not critical. meaning that the RTOS can activate and deactivate every task. only one task can be executed by the CPU at a time. because no real-time kernel is used and only one stack is used. PPRTOS-3 13 . Real-time behavior is therefore poor. Single-task systems (superloop) A superloop application is basically a program that runs in an endless loop. so interrupt service routines (ISRs) must be used for real-time parts of the software or critical operations (interrupt level). The tasks are scheduled. No real-time kernel is used. This is called a single-task system. there are fewer preemption and synchronization problems with a superloop application. there are different scheduling systems in which the calculation power of the CPU can be distributed among tasks. Also. calling OS functions to execute the appropriate operations (task level). a task is a program running on the CPU core of a microcontroller. However. Without a multitasking kernel (an RTOS). both program (ROM) and RAM size are smaller. Because one software component cannot be interrupted by another component (only by ISRs). This type of system is typically used in small. A real-time operating system allows the execution of multiple tasks on a single CPU.

If they do not. Low priority task Executing task is interrupted ISR ISR puts high priority task in READY state Time Interrupted task is completed High priority task Higher priority task Is executed IAR PowerPac™ RTOS 14 User Guide PPRTOS-3 . Even if an ISR makes a higher-priority task ready to run. the interrupted task will be returned to and finished before the task switch is made.COOPERATIVE MULTITASKING Cooperative multitasking expects cooperation of all tasks. which means that other tasks have no chance of being executed by the CPU while the first task is being carried out. This is illustrated in the diagram below. the system “hangs”. Tasks can only be suspended by calling a function of the operating system.

The task which is currently executing is referred to as the active task. the possession of the CPU changes periodically after a predefined execution time. when deactivating the active task. called schedulers. and so on). whether it is an interrupted task or not. It works well if you do not need to guarantee response time. the scheduler has a list of tasks and. waiting for semaphore. The scheduler selects one of the tasks in the READY state and activates it (executes the program of this task). Round-robin scheduling can be illustrated as follows: All tasks are on the same level. If an ISR makes a higher priority task ready. This time is called timeslice. or if all tasks have the same priority. waiting for mailbox. task switch occurs High priority task Higher priority task Is executed Time Interrupted task is completed Scheduling There are different algorithms that determine which task to execute. a task switch will occur and the task will be executed before the interrupted task is returned to. A real-time operating system needs a regular timer-interrupt to interrupt tasks at defined times and to perform task-switches if necessary. PPRTOS-3 15 .Basic concepts PREEMPTIVE MULTITASKING Real-time systems like IAR PowerPac RTOS operate with preemptive multitasking only. The main difference between schedulers is in how they distribute the computation time between the tasks in READY state. waiting for event. ROUND-ROBIN SCHEDULING ALGORITHM With round-robin scheduling. All schedulers have one thing in common: they distinguish between tasks that are ready to be executed (in the READY state) and the other tasks that are suspended for any reason (delay. if the response time is not an issue. activates the next task that is in the READY state. and may be defined individually for every task. Low priority task Executing task is interrupted ISR ISR puts high priority task in READY state. The highestpriority task in the READY state is therefore always executed. Round-robin can be used with either preemptive or cooperative multitasking.

because it will constantly switch between the identical-priority tasks. but because it cannot guarantee a specific reaction time. in an application that controls a motor. the motor needs to be controlled. For example. While the display is being updated. synchronize with another task. known as critical regions. It is more efficient to assign a different priority to each task. The order of execution depends on this priority. which will avoid unnecessary task switches. To avoid this kind of situation. wasting precious calculation time and power. it immediately becomes the active task. In certain situations. and the reaction time depends on how often you poll. PRIORITY INVERSION The rule to go by for the scheduler is: Activate the task that has the highest priority of all tasks in the READY state.PRIORITY-CONTROLLED SCHEDULING ALGORITHM In real-world applications. This is known as priority inversion. it can make sense for tasks to communicate via global variables. COMMUNICATION MECHANISMS When multiple tasks work with one another. One hint at this point: round-robin scheduling is a nice feature because you do not have to think about whether one task is more important than another. you have to poll this variable. unblocking the task which originally had highest priority. if you want to synchronize a task to start when the value of a global variable changes. or make sure that a resource is used by no more than one task at a time. different tasks require different response times. and a display. an improved algorithm should be used. But round-robin scheduling also costs time if two or more tasks of identical priority are ready and no task of higher priority is ready. But what happens if the highest-priority task is blocked because it is waiting for a resource owned by a lower-priority task? According to the above rule. This means that every time a task with higher priority than the active task gets ready. semaphores and events. Communication between tasks In a multitasking (multithreaded) program. IAR PowerPac RTOS uses a priority-controlled scheduling algorithm with round-robin between tasks of identical priority. In priority-controlled scheduling. multiple tasks work completely separately. However. they often have to: ● ● ● exchange data. For these purposes IAR PowerPac RTOS offers mailboxes. but most of the time this method has various disadvantages. For example. GLOBAL VARIABLES The easiest way to do this is by using global variables. The other rule is: No rule without exception. IAR PowerPac™ RTOS 16 User Guide PPRTOS-3 . the low-priority task that is blocking the highest-priority task gets assigned the highest priority until it releases the resource. Roundrobin might work. it will sometimes be necessary for them to exchange information with each other. queues. every task is assigned a priority. it would wait until the low-priority-task becomes active again and releases the resource. The rule is very simple: Note:The scheduler activates the task that has the highest priority of all tasks in the READY state. This makes preemptive multitasking a must. the scheduler can be switched off in sections of a program where task switches are prohibited. a keyboard. the motor usually requires faster reaction time than the keyboard and display. Tasks with identical priority cannot block each other for longer than their timeslices. Because they all work in the same application.

which usually resides in ROM (though it does not have to) A stack. or the pulse of an external real-time clock. How task-switching works A real-time multitasking system lets multiple tasks run like multiple single-task programs. there is no sense in polling if we can simply activate a task the moment the event that it is waiting for occurs. For further details. a pressed key. More information can be found in the chapter Stacks on page 97. It works without conflicts even if multiple tasks and interrupts try to access it simultaneously. and temporary storage of intermediate calculation results and register values. parameters and local variables. SEMAPHORES Two types of semaphores are used for synchronizing tasks and to manage resources. residing in RAM. PPRTOS-3 17 . quasi-simultaneously. The task control block (TCB) is a data structure assigned to a task when it is created. A task consists of three parts in the multitasking world: ● ● ● The program code. For more information. Each task can have a different stack size. This saves a great deal of calculation power and ensures that the task can respond to the event without delay. refer to the Chapter Task Events on page 77 and Chapter Event objects on page 83. including the stack pointer. Typical applications for events are those where a task waits for data. task priority. on a single CPU. The most common are resource semaphores. The idea is as simple as it is convincing. but handles larger messages than mailboxes. IAR PowerPac RTOS also automatically activates any task that is waiting for a message in a mailbox the moment it receives new data and. reason for suspension) and other management data. refer to the Chapter Resource semaphores on page 49 and Chapter Counting Semaphores on page 55. if necessary. A queue works in a similar manner. a received command or character. This information allows an interrupted task to continue execution exactly where it left off. although counting semaphores are also used. see the Chapter Mailboxes on page 61 and Chapter Queues on page 71. TCBs are only accessed by the RTOS. The stack has the same function as in a single-task system: storage of return addresses of function calls. and every message is allowed to have an individual size. waiting.Basic concepts MAILBOXES AND QUEUES A mailbox is basically a data buffer managed by the RTOS and is used for sending a message to a task. For details and examples. Switching stacks The following diagram demonstrates the process of switching from one stack to another. EVENTS A task can wait for a particular event without using any calculation time. residing in a RAM area that can be accessed by the stack pointer A task control block. current task status (ready. automatically switches to this task. It contains status information of the task.

The scheduler deactivates the task to be suspended (Task 0) by saving the processor registers on its stack. addresses CPU registers Task Control block Stack variables temp. Only one task may be active at a time. If a task with higher priority becomes READY. A task in the READY state is activated as soon as there is no other READY task with higher priority. addresses CPU registers SP SP Free Stack area Free Stack area Scheduler CPU Change of task status A task may be in one of several states at any given time. IAR PowerPac™ RTOS 18 User Guide PPRTOS-3 . it is automatically put into the READY state (TS_READY). storage ret. When a task is created. It then activates the higher-priority task (Task n) by loading the stack pointer (SP) and the processor registers from the values stored on Task n's stack. Task 0 Task Control block Task n Stack variables temp. storage ret. this higher priority task is activated and the preempted task remains in the READY state.

or queue). The startup code performs the following: ● ● ● Loads the stack pointers with the default values. in this case it is put into the DELAY state (TS_DELAY) and the next highest priority task in the READY state is activated.() or delay expiration Blocked How the OS gains control When the CPU is reset. The active task may also have to wait for an event (or semaphore. From then on. Initializes all data segments to their respective values. IAR PowerPac RTOS works with the standard C startup module without any modification.() API class such as OS_Signal. which for most CPUs is the end of the defined stack segment(s). mailbox. If there are any changes required.. it has either not been created yet or it has been terminated. they are documented in the startup file which is shipped with IAR PowerPac RTOS. main() creates one or more tasks and then starts multitasking by calling OS_Start(). the main() routine is part of your program which takes control immediately after the C startup.Basic concepts The active task may be delayed for or until a specified time. Not existing OS_CreateTask() OS_CreateTaskEx() OS_Terminate() Ready Scheduler Running API class such as OS_Delay() OS_Wait_. Calls the main() routine. OS_Start() PPRTOS-3 19 . The following illustration shows all possible task states and transitions between them.. the task is put into the waiting state and the next highest priority task in the READY state is activated. the special-function registers are set to their respective values. This start address is in a startup module shipped with the C compiler. the scheduler controls which task is executed.. creating at least one task. If the event has not yet occurred. After reset. A non-existent task is one that is not yet available to IAR PowerPac RTOS. Startup code main() OS_IncDI() OS_InitKern() OS_InitHW() Additional initialization code. and is part of the standard library. The PC register is set to the start address defined by the start vector or start address (depending on the CPU). In a single-task-program. program execution begins. Basically. The main() routine is still part of your application program..

OS_TASK TCBHP. Additional Information This function does not return. It is therefore usually recommended to create all or most of your tasks here. Prototype void OS_InitKern (void)..c) */ /* Call Init routines of all program modules which in turn will create the tasks they need . /* Initialize Hardware for OS (in RtosInit. MODULE4_Init().. OS_InitKern() Description Initializes all RTOS variables which require a non zero initial value for arithmetic types or a non NULL pointer value for pointer types. as well as your control structures such as mailboxes and semaphores. TCBLP. A typical main() looks similar to the following example: Example /*********************************************************************** * * main * ************************************************************************ */ void main(void) { OS_InitKern(). Example #include "RTOS. OS_Start() Description Starts multitasking. MODULE2_Init(). /* Start multitasking */ } With the call to OS_Start(). OS_Start(). These modules usually have an initialization routine.H" OS_STACKPTR int StackHP[128]. StackLP[128]. Additional Information OS_InitKern() is always the first function which should be called in main(). Note that OS_Start() is called only once during the startup process and does not return. MODULE3_Init(). the scheduler starts the highest-priority task that has been created in main(). The scheduler starts the highest-priority task that has been created in main(). because those tasks are executed only after the call to OS_Start().The main() routine will not be interrupted by any of the created tasks. static void HPTask(void) { while (1) { OS_Delay (10). /* Initialize OS (should be first !) */ OS_InitHW(). (Order of creation may be important) */ MODULE1_Init(). } } /* Task stacks */ /* Task-control-blocks */ IAR PowerPac™ RTOS 20 User Guide PPRTOS-3 . A good practice is to write software in the form of modules which are (up to a point) reusable. MODULE5_Init(). Prototype void OS_Start (void). which creates the required task(s) and/or control structures.

and a safer (though bigger and slower) version for development which will catch most of the common application programming errors. IAR PowerPac RTOSIAR PowerPac RTOSLIST OF LIBRARIES In your application program. The reason for different builds is that requirements vary during development. Of course. StackLP). HPTask. /* initialize OS OS_InitHW(). "LP Task". normally used for the release version of your application. Same as release. This concept gives you the best of both worlds: a compact and very efficient build for your final product (release or stack check versions of the libraries). Maximum runtime checking. But during development. While developing software. OS_CREATETASK(&TCBLP. StackHP). 50. plus stack checking. the performance (and resource usage) is not as important as in the final version which usually goes as release version into the product. you need to let the compiler know which build of IAR PowerPac RTOS you are using.h. 100. Small. Does not support round robin scheduling and task names. fast build. but it will not catch these errors.Basic concepts static void LPTask(void) { while (1) { OS_Delay (50). } } /********************************************************************* * * main * *********************************************************************/ void main(void) { OS_IncDI(). LPTask. /* initialize Hardware for OS /* You need to create at least one task here ! OS_CREATETASK(&TCBHP. This is done by defining a single identifier prior to including RTOS. /* Start multitasking } */ */ */ */ */ Different builds of IAR PowerPac RTOS IAR PowerPac RTOS comes in different builds. or versions of the libraries. Build Define Description XR: R: S: D: Extreme Release Release Stack check Debug OS_LIBMODE_XR OS_LIBMODE_R OS_LIBMODE_S OS_LIBMODE_D Smallest fastest build. /* Initially disable interrupts OS_InitKern(). Table 1: List of libraries PPRTOS-3 21 . "HP Task". even small programming errors should be caught by use of assertions. OS_Start(). These assertions are compiled into the debug version of the IAR PowerPac RTOS libraries and make the code a bit bigger (about 50%) and also slightly slower than the release or stack check version used for the final product. you may also use the release version of IAR PowerPac RTOS during development.

IAR PowerPac™ RTOS 22 User Guide PPRTOS-3 .

a routine is available allowing “fine-tuning” of all parameters. Creates a task with parameter. Suspends the calling task for a specified period of time. OS_Terminate(0). PPRTOS-3 23 . a stack. Returns the priority of a specified task Assigns a specified timeslice value to a specified task. Creates a task. Creates a task with parameter.Tasks Introduction A task that should run under IAR PowerPac RTOS needs a task control block (TCB). The task routine should be implemented as an endless loop. using the macro as in the example start project works fine. and a normal routine written in C. do { DoSomeMore = DoSomethingElse() /* Do something OS_Delay(1). or it must terminate itself (see examples below). at least initially. EXAMPLE OF TASK ROUTINE AS AN ENDLESS LOOP /* Example of a task routine as an endless loop */ void Task1(void) { while(1) { DoSomething() /* Do something */ OS_Delay(1). The following rules apply to task routines: ● ● ● The task routine can either not take parameters (void parameter list). For most applications. if you are dynamically creating and deleting tasks. in which case OS_CreateTaskEx() is used to create it. in which case OS_CreateTask() is used to create it or take one void pointer as parameter. However. /* Give other tasks a chance */ } } EXAMPLE OF TASK ROUTINE THAT TERMINATES ITSELF /* Example of a task routine that terminates void Task2(void) { char DoSomeMore. Assigns a specified priority to a specified task. Suspends the calling task until a specified time. The task routine must not return. /* Terminate yourself } */ */ */ */ There are different ways to create a task. /* Give other tasks a chance } while(DoSomeMore). Suspends the specified task. IAR PowerPac RTOS offers a simple macro that makes this easy and which is fully sufficient in most cases. API function Routine Description OS_CREATETASK() OS_CreateTask() OS_CREATETASK_EX() OS_CreateTaskEx() OS_Delay() OS_DelayUntil() OS_SetPriority() OS_GetPriority() OS_SetTimeSlice() OS_Suspend() Table 1: Task routine API list Creates a task.

Most CPUs cannot use the entire memory area as stack. Pointer to the name of the task. See the device specific manual for further details. Can be NULL (or 0) if not used. Returns a pointer to the task control block structure of the currently running task. unsigned char Priority. either from main() during initialization or from any other task. pStack Table 2: OS_CREATETASK() parameter list Additional Information OS_CREATETASK() is a macro calling an OS library function. Ends delay of a task immediately. Some CPUs and standards force other alignment values. Must be within the following range: 1 <= Priority <=255 Higher values indicate higher priorities. If there is another task with the same priority. Description Parameter pTask pName pRoutine Priority Pointer to a data structure of type OS_TASK which will be used as task control block (and reference) for this task. OS_CREATETASK() determines the size of the stack automatically. The absolute value of Priority is of no importance. Most CPUs require alignment of the stack in multiples of bytes. void* pRoutine. the new task will be placed right before it. Determines whether a task control block actually belongs to a valid task. Returns the suspension count. This is possible only if the memory area has been defined at compile time. OS_CREATETASK() Description Creates a task. The newly created task will be activated by the scheduler as soon as there is no other task with higher priority in the READY state. The size of this block of memory determines the size of the stack area. OS_CREATETASK() can be called at any time. only the value in comparison to the priorities of other tasks. when the task stack is defined as an array of integers. Important The stack that you define has to reside in an area that the CPU can actually use as stack. Prototype void OS_CREATETASK (OS_TASK* pTask. because it has fewer parameters and is therefore easier to use. Ends (terminates) a task. It creates a task and makes it ready for execution by putting it in the READY state. The recommended strategy is to create all tasks during initialization in main() to keep the structure of your tasks easy to understand. if the suspend count reaches zero.Routine Description OS_Resume() OS_GetSuspendCnt() OS_Terminate() OS_WakeTask() OS_IsTask() OS_GetTaskID() OS_GetpCurrentTask() Table 1: Task routine API list Decrements the suspend count of specified task and resumes the task. Returns the ID of the currently running task. Pointer to a routine that should run as a task Priority of the task. using sizeof(). IAR PowerPac™ RTOS 24 User Guide PPRTOS-3 . Pointer to an area of memory in RAM that will serve as stack area for the task. This macro is normally used for creating a task instead of the function call OS_CreateTask(). void* pStack). char* pName. This is automatically done.

Can be NULL (or 0) if not used. Must be within the following range: 1 <= Priority <=255 Higher values indicate higher priorities. thus enabling another task with the same priority. when the task stack is defined as an array of integers. PPRTOS-3 25 . Size of the stack Time slice value for round-robin scheduling. Pointer to the name of the task. /* Stack-space */ OS_TASK UserTCB. } } void InitTask(void) { OS_CREATETASK(&UserTCB. pRoutine. Some CPUs and standards force other alignment values.Tasks Example OS_STACKPTR int UserStack[150]. Priority of the task. StackSize. pName. 100. The task can be dynamically created because the stack size is not calculated automatically as it is with the macro. This is automatically done. UserTask. TimeSlice). UserStack). Most CPUs require alignment of the stack in multiples of bytes. See the device specific manual for further details. "UserTask". Pointer to a routine that should run as task Pointer to an area of memory in RAM that will serve as stack area for the task.TimeSlice denotes the time in IAR PowerPac RTOS timer ticks that the task will run until it suspends. The size of this block of memory determines the size of the stack area. Has an effect only if other tasks are running at the same priority. Prototype void OS_CreateTask (OS_TASK* char* unsigned char voidRoutine* void* unsigned unsigned char Parameter Description pTask. Most CPUs cannot use the entire memory area as stack. pStack. This parameter has no effect on some ports of IAR PowerPac RTOS for efficiency reasons. } OS_CreateTask() Description Creates a task. Priority. except that all parameters of the task can be specified.) pTask pName Priority Pointer to a data structure of type OS_TASK which will be used as the task control block (and reference) for this task. Important The stack that you define has to reside in an area that the CPU can actually use as stack. /* Task-control-blocks */ void UserTask(void) { while (1) { Delay (100). pRoutine pStack StackSize TimeSlice Table 3: OS_CreateTask() parameter list Additional Information This function works the same way as OS_CREATETASK().

TaskClock. StackClock[50]. The size of this block of memory determines the size of the stack area. OS_CreateTask(&TaskClock. char* pName. Can be NULL (or 0) if not used. void* pRoutine. Priority of the task. but allows passing a parameter to the task. } OS_CREATETASK_EX() Description Creates a task and passes a parameter to the task. Parameter passed to the created task function. void Clock(void) { while(1) { /* Code to update the clock */ } } void Main(void) { while (1) { /* Your code */ } } void InitTask(void) { OS_CreateTask(&TaskMain. Prototype void OS_CREATETASK_EX (OS_TASK* pTask. pStack pContext Table 4: OS_CREATETASK_EX() parameter list Additional Information OS_CREATETASK_EX() is a macro calling an IAR PowerPac RTOS library function. sizeof(StackMain). 100. void* pContext).END-OF-HEADER --------------------------------------------*/ IAR PowerPac™ RTOS 26 User Guide PPRTOS-3 . void* pStack. Must be within the following range: 1 <= Priority <=255 Higher values indicate higher priorities. unsigned char Priority. Main. Pointer to a routine that should run as a task.c Purpose : Sample program for IAR PowerPac RTOS using OC_CREATETASK_EX --------. NULL. Pointer to the name of the task.StackClock.2). Description Parameter pTask pName pRoutine Priority Pointer to a data structure of type OS_TASK which will be used as task control block (and reference) for this task. Using a void pointer as additional parameter gives the flexibility to pass any kind of data to the task function. 50. /*-----------------------------------------------------------------File : Main_TaskEx. StackMain. OS_SEMA SemaLCD. Example The following example is delivered in the RTOS\Application folder of IAR PowerPac RTOS.Example /* Demo-program to illustrate the use of OS_CreateTask */ OS_STACKPTR int StackMain[100]. Clock.sizeof(StackClock). Pointer to an area of memory in RAM that will serve as stack area for the task. NULL. It works like OS_CREATETASK(). 2). OS_TASK TaskMain.

This parameter has no effect on some ports of IAR PowerPac RTOS for efficiency reasons. pRoutine. StackHP. pRoutine pStack StackSize Timeslice pContext Table 5: OS_Create_Task_Ex() parameter list Additional Information This function works the same way as OS_CreateTask(). 100. "LP Task". pContext). Pointer to an area of memory in RAM that will serve as stack area for the task. The size of this block of memory determines the size of the stack area. pName. } OS_CreateTaskEx() Description Creates a task and passes a parameter to the task. (void*) 200). PPRTOS-3 27 .TimeSlice denotes the time in IAR PowerPac RTOS timer ticks that the task will run until it suspends. /* Task-control-blocks */ /********************************************************************/ static void TaskEx(void* pData) { while (1) { OS_Delay ((OS_TIME) pData). Priority of the task. StackLP[128]. 50. An example of passing parameters to tasks is shown under OS_CREATETASK_EX(). /* Initially disable interrupts */ OS_InitKern(). /* Task stacks */ OS_TASK TCBHP. except that a parameter is passed to the task function. } } /********************************************************************* * * main * *********************************************************************/ int main(void) { OS_IncDI(). pStack. Pointer to the name of the task. Pointer to a routine that should run as task. thus enabling another task with the same priority. Size of the stack Time slice value for round-robin scheduling. OS_CREATETASK_EX(&TCBLP.Tasks #include "RTOS. TaskEx. Can be NULL (or 0) if not used. TCBLP. /* initialize Hardware for OS */ /* You need to create at least one task before calling OS_Start() */ OS_CREATETASK_EX(&TCBHP. OS_SendString("Start project will start multitasking !\n"). StackSize. /* Start multitasking */ return 0. TimeSlice. "HP Task". Priority. OS_Start(). StackLP.) pTask pName Priority Pointer to a data structure of type OS_TASK which will be used as the task control block (and reference) for this task. Must be within the following range: 1 <= Priority <=255 Higher values indicate higher priorities. Parameter passed to the created task. /* initialize OS */ OS_InitHW(). Prototype void OS_CreateTaskEx (OS_TASK* char* unsigned char voidRoutine* void* unsigned unsigned char void* Parameter Description pTask. (void*) 50). Has an effect only if other tasks are running at the same priority. TaskEx.h" OS_STACKPTR int StackHP[128].

Example void Hello() { printf("Hello"). Example int sec. OS_DelayUntil (t0 += 1000). the task is made ready again and activated according to the rules of the scheduler. Prototype void OS_DelayUntil (int t). The OS_DelayUntil() function delays until the value of the time-variable OS_Time has reached a certain value. Prototype void OS_Delay (int ms).min. A delay can be ended prematurely by another task or by an interrupt handler calling OS_WakeTask(). if (sec < 59) sec++. The parameter ms specifies the precise interval during which the task has to be suspended specified in basic time intervals (usually 1/1000 sec.). } } } /* Routine to display time */ IAR PowerPac™ RTOS 28 User Guide PPRTOS-3 . depending on when the interrupt for the scheduler will occur.OS_Time) <= 231-1 = 0x7FFFFFFF for 32-bit CPUs Table 7: OS_DelayUntil() parameter list Additional Information The calling task will be put into the TS_DELAY state until the time specified. The actual delay (in basic time intervals) will be in the following range: ms . printf("The next output will occur in 5 seconds"). Must be within the following range: 1 <= (t . while (1) { ShowTime(). It is very useful if you have to avoid accumulating delays.OS_Time) <= 215-1 = 0x7FFF = 32767 for 8/16-bit CPUs 1 <= (t . Parameter Description ms Time interval to delay.OS_Delay() Description Suspends the calling task for a specified period of time. Parameter Description t Time to delay until. void TaskShowTime() { int t0 = OS_GetTime(). printf("Delay is over"). Must be within the following range: 1 <= ms <= 215-1 = 0x7FFF = 32767 for 8/16-bit CPUs 1 <= ms <= 231-1 = 0x7FFFFFFF for 32-bit CPUs Table 6: OS_Delay() parameter list Additional Information The calling task will be put into the TS_DELAY state for the period of time specified. The task will stay in the delayed state until the specified time has expired. min++. After the expiration of a delay. OS_Delay (5000).1 <= delay <= ms. else { sec=0. } OS_DelayUntil() Description Suspends the calling task until a specified time.

This means that the additional information (such as floating-point registers) needs to be saved only by tasks that actually use these registers.h" OS_STACKPTR int StackHP[128]. /* Task stacks */ /* Task-control-blocks */ /********************************************************************* * * _Restore * _Save * * Function description * This function pair saves and restores an extended task context. * In this case. TCBLP. Data registers of an additional hardware unit such as a CRC calculation unit This allows you to extend the task context as required by his system. stack space is required only for the tasks which actually save the additional registers. which is a global variable. StackLP[128]. the extended task context consists of just a single * member. The same thing is true for the required stack space: Add. A major advantage is that the task extension is task specific. but are not limited to: ● ● ● ● Global variables such as “errno” in the C-library. */ typedef struct { int GlobalVar. optional CPU / registers such as MAC / EMAC registers (multiply and accumulate unit) if they are not saved in the task context by default.Tasks In the example above. the use of OS_Delay() could lead to accumulating delays and would cause the simple “clock” to be slow. how the task stack has to be addressed to save and restore the extended task context. } OS_EXTEND_TASK_CONTEXT. OS_ExtendTaskContext() Description The function may be used for a variety of purposes. Typical applications include. The advantage is that the task switching time of the other tasks is not affected. PPRTOS-3 29 . Prototype void OS_ExtendTaskContext(const OS_EXTEND_TASK_CONTEXT * pExtendContext). int GlobalVar. making the C library functions thread-safe. The example below shows. This example adds a global variable to the task context of certain tasks. Additional. Example The following example is delivered in the RTOS\Application folder of IAR PowerPac RTOS. The save and restore functions have to be declared according the function type used in the structure. -------.c Purpose : Sample program for IAR PowerPac RTOS demonstrating how to dynamically extend the task context. Co-processor registers such as registers of a VFP (floating-point coprocessor). Table 8: OS_ExtendTaskContext() parameter list Additional Information The OS_EXTEND_TASK_CONTEXT structure is defined as follows: typedef struct OS_EXTEND_TASK_CONTEXT { void (*pfSave) ( void * pStack). Parameter Description pExtendContext Pointer to the OS_EXTEND_TASK_CONTEXT structure which contains the addresses of the specific save and restore functions which save and restore the extended task context during task switches. /*-------------------------------------------------------------------File : ExtendTaskContext.END-OF-HEADER ----------------------------------------------*/ #include "RTOS. void (*pfRestore)(const void * pStack). OS_ExtendTaskContext() is not available in the XR libraries. OS_TASK TCBHP.

GlobalVar = 2. } IAR PowerPac™ RTOS 30 User Guide PPRTOS-3 . "LP Task". // // Save all members of the structure // p->GlobalVar = GlobalVar.OS_STACK_AT_BOTTOM). while (1) { OS_Delay (50). } } /********************************************************************* * * LPTask * * Function description * During the execution of this function. */ static void LPTask(void) { OS_ExtendTaskContext(&_SaveRestore). */ static void HPTask(void) { OS_ExtendTaskContext(&_SaveRestore). the thread-specific * global variable has always the same value of 2. p = ((CONTEXT_EXTENSION*)pStack) . } // Create pointer // Create pointer /********************************************************************* * * Global variable which holds the function pointers * to save and restore the task context. 50. /* Start multitasking */ return 0. _Restore }. static void _Save(void * pStack) { CONTEXT_EXTENSION * p. OS_CREATETASK(&TCBLP. "HP Task". the thread-specific * global variable has always the same value of 1. /********************************************************************/ /********************************************************************* * * HPTask * * Function description * During the execution of this function. StackHP). /* Initially disable interrupts */ OS_InitKern().(1 . } static void _Restore(const void * pStack) { CONTEXT_EXTENSION * p. // // Restore all members of the structure // GlobalVar = p->GlobalVar. StackLP).OS_STACK_AT_BOTTOM). p = ((CONTEXT_EXTENSION*)pStack) . /* initialize OS */ OS_InitHW(). HPTask. /* initialize Hardware for OS */ /* You need to create at least one task here ! */ OS_CREATETASK(&TCBHP.(1 . LPTask. 100. OS_Start(). } } /********************************************************************* * * main */ int main(void) { OS_IncDI().} CONTEXT_EXTENSION. while (1) { OS_Delay (10). */ const OS_EXTEND_TASK_CONTEXT _SaveRestore = { _Save. GlobalVar = 1.

The release version of IAR PowerPac RTOS cannot check the validity of pTask and may therefore return invalid values if pTask does not specify a valid task. >0: Task is suspended by at least one call of OS_Suspend(). the debug version of IAR PowerPac RTOS calls OS_Error(). 0: Task is not suspended. Prototype unsigned char OS_GetPriority (OS_TASK* pTask). Prototype unsigned char OS_GetSuspendCnt (OS_TASK* pTask). Important This function may not be called from within an interrupt handler. Additional Information If pTask is the NULL pointer. Table 10: OS_GetSuspendCnt() parameter list Return value Suspension count of the specified task as an unsigned character value. OS_GetPriority() Description Returns the priority of a specified task. Parameter Description pTask Pointer to a data structure of type OS_TASK. This can be helpful if the reaction of any function depends on the currently running task. Parameter Description pTask Pointer to a data structure of type OS_TASK. OS_GetSuspendCnt() Description The function returns the suspension count and thus suspension state of the specified task. Prototype OS_TASK* OS_GetpCurrentTask (void). Additional Information This function can be used for determining which task is executing. Return value OS_TASK*: A pointer to the task control block structure. Table 9: OS_GetPriority() parameter list Return value Priority of the specified task as an unsigned character (range 1 to 255). If pTask does not specify a valid task. the function returns the priority of the currently running task.Tasks OS_GetpCurrentTask() Description Returns a pointer to the task control block structure of the currently running task. This function can be used for examining whether a task is suspended by previous calls of OS_Suspend(). PPRTOS-3 31 .

OS_IsTask() Description Determines whether a task control block actually belongs to a valid task. IAR PowerPac™ RTOS 32 User Guide PPRTOS-3 . Parameter Description pTask Pointer to a data structure of type OS_TASK which is used as task control block (and reference) for this task. The release version of IAR PowerPac RTOS can not check the validity of pTask and might therefore return invalid values if pTask does not specify a valid task. Table 11: OS_IsTask() parameter list Return value Character value: 0: TCB is not used by any task 1: TCB is used by a task Additional Information This function checks if the specified task is still in the internal task list. the debug version of IAR PowerPac RTOS calls OS_Error(). Additional Information This function can be used for determining which task is executing. This function can be useful to determine whether the task control block and stack for the task may be reused for another task in applications that create and terminate tasks dynamically. it is removed from the internal task list. OS_IsTask() might be called prior to calling OS_GetSuspendCnt() to examine whether the task is valid. A value of 0 (NULL) indicates that no task is executing. Return value OS_TASKID: A pointer to the task control block. if the suspend count reaches zero.Additional Information If pTask does not specify a valid task. /* May cause a task switch */ SuspendCnt--. The returned value can be used for resuming a suspended task by calling OS_Resume() as often as indicated by the returned value. If the task was terminated. OS_Resume() Description Decrements the suspend count of the specified task and resumes it. This can be helpful if the reaction of any function depends on the currently running task. } } OS_GetTaskID() Description Returns the ID of the currently running task. Example /* Demo-function to illustrate the use of OS_GetSuspendCnt() */ void ResumeTask(OS_TASK* pTask) { unsigned char SuspendCnt. Prototype OS_TASKID OS_GetTaskID (void). When tasks are created and terminated dynamically. Prototype char OS_IsTask (OS_TASK* pTask). SuspendCnt = OS_GetSuspendCnt(pTask). while(SuspendCnt > 0) { OS_Resume(pTask).

OS_SetTaskName() Description Allows modification of a task name at runtime. PPRTOS-3 33 . unsigned char Priority). Priority of the task. If the task is not blocked by other task blocking mechanisms. In debug versions of IAR PowerPac RTOS. Table 13: OS_SetPriority() parameter list Additional Information Can be called at any time from any task or software timer. const char* s). Prototype void OS_SetPriority (OS_TASK* pTask. Important This function may not be called from within an interrupt handler. Pointer to a zero terminated string which is used as task name. Must be within the following range: 1 <= Priority <= 255 Higher values indicate higher priorities. the execution of the specified task is resumed. If the resulting value is 0. the OS_Resume() function checks the suspend count of the specified task. Parameter Description pTask Pointer to a data structure of type OS_TASK which is used as task control block (and reference) for the task that should be suspended. the specified task is not currently suspended and OS_Error() is called with error OS_ERR_RESUME_BEFORE_SUSPEND. Parameter Description pTask Priority Pointer to a data structure of type OS_TASK.Tasks Prototype void OS_Resume (OS_TASK* pTask). OS_SetPriority() Description Assigns a specified priority to a specified task. OS_SetTimeSlice() Description Assigns a specified timeslice value to a specified task. Calling this function might lead to an immediate task switch. Table 14: OS_SetTaskName() parameter list Additional Information Can be called at any time from any task or software timer. When pTask is the NULL pointer. Table 12: OS_Resume() parameter list Additional Information The specified task's suspend count is decremented. the task will be set back in ready state and continues operation according to the rules of the scheduler. Parameter Description pTask s Pointer to a data structure of type OS_TASK. Prototype void OS_SetTaskNamePriority (OS_TASK* pTask. If the suspend count is 0 when OS_Resume() is called. the name of the currently running task is modified.

The specified task will be suspended immediately. Additional Information Can be called at any time from any task or software timer. the current task suspends.Prototype unsigned char OS_SetTimeSlice (OS_TASK* pTask. It does not affect the remaining timeslice of a running task. the current task terminates. Must be within the following range: 1 <= TimeSlice <= 255. The specified task will terminate immediately. the task is suspended. New timeslice value for the task. The memory used for stack and task control block can be reassigned. the task's internal suspend count is not incremented and OS_Error() is called with the error OS_ERR_SUSPEND_TOO_OFTEN. OS_Suspend() Description Suspends the specified task. Prototype void OS_Suspend (OS_TASK* pTask). OS_Terminate() Description Ends (terminates) a task. This means that another task with the same priority must exist. calling OS_Suspend() more often than OS_MAX_SUSPEND_CNT times without calling OS_Resume(). Every task has a suspend count with a maximum value of OS_MAX_SUSPEND_CNT. It is used after the next activation of the task. Prototype void OS_Terminate (OS_TASK* pTask). Table 17: OS_Terminate() parameter list Additional Information If pTask is the NULL pointer. In debug versions of IAR PowerPac RTOS. Setting the timeslice value only affects the tasks running in round-robin mode. Parameter Description pTask TimeSlice Pointer to a data structure of type OS_TASK. IAR PowerPac™ RTOS 34 User Guide PPRTOS-3 . Table 16: OS_Suspend() parameter list Additional Information If pTask is the NULL pointer. If the function succeeds. The new timeslice value is interpreted as a reload value. Parameter Description pTask Pointer to a data structure of type OS_TASK which is used as a task control block (and reference) for the task that should be suspended. If the suspend count is greater than zero. unsigned char TimeSlice). Table 15: OS_SetTimeSlice() parameter list Return value Previous timeslice value of the task as unsigned char. execution of the specified task is suspended and the task's suspend count is incremented. Parameter Description pTask Pointer to a data structure of type OS_TASK which is used as task control block (and reference) for this task. It can only be restarted by a call of OS_Resume().

Parameter Description pTask Pointer to a data structure of type OS_TASK which is used as task control block (and reference) for this task. it will be suspended if there is another task with the same priority ready for execution. or the delay has already expired. Important This function may not be called from within an interrupt handler. Any task may be terminated regardless of its state. OS_Yield() Description Calls the scheduler to force a task switch. Additional Information If the task is running on round-robin. OS_WakeTask() Description Ends delay of a task immediately. This functionality is default for any 16-bit or 32-bit CPU and may be changed by recompiling IAR PowerPac RTOS sources. On 8-bit CPUs. The specified task will be activated immediately if it has a higher priority than the priority of the task that had the highest priority before. the IAR PowerPac RTOS sources have to be recompiled with the compile time switch OS_SUPPORT_CLEANUP_ON_TERMINATE activated. Prototype void OS_WakeTask (OS_TASK* pTask). or for some other reason). which is already suspended for a certain amount of time with OS_Delay() or OS_DelayUntil() back to the state TS_READY (ready for execution). To enable safe termination. Prototype void OS_Yield (void). PPRTOS-3 35 . this command is ignored.Tasks IAR PowerPac RTOSall resources which are held by the terminated task are released. Table 18: OS_WakeTask() parameter list Additional Information Puts the specified task. terminating tasks that hold any resources is prohibited. If the specified task is not in the state TS_DELAY (because it has already been activated.

IAR PowerPac™ RTOS 36 User Guide PPRTOS-3 .

It is normally 0x7F00 for 8/16-bit systems or 0x7FFFFF00 for 32-bit Systems and defined in RTOS. OS_GetTimerValue(). The extended timer structure and related extended timer functions were implemented to allow parameter passing to the callback function. extended timers behave exactly the same as normal IAR PowerPac RTOS software timers and may be used in parallel with normal software timers. Creates a software timer without starting it. you specify any routine that is to be called after the expiration of the delay. By calling OS_RetriggerTimer() from within the callback routine. If your system spends more than 255 ticks without break in a critical section (effectively disabling the scheduler during this time. However. For that reason they should be kept short just like interrupt routines. so they can be interrupted by any hardware interrupt. (because expired time-outs are permitted). started and retriggered much like hardware timers.h as OS_TIMER_MAX_TIME. we have assumed that your system spends no more than up to 255 ticks in a row in a critical region and defined a macro which defines the maximum timeout value. a 32-bit value on 32-bit CPUs. Stops and deletes a specified timer. they have a priority higher than the priority of all tasks. This means that only 15-bits can be used on 8/16 bit CPUs. you have to make sure your application uses shorter timeouts.Software timers Software timer A software timer is an object that calls a user-specified routine after a specified delay. timers run in single-shot mode. Stops a specified timer. Maximum timeout / period The timeout value is stored as an integer. the timer is restarted with its initial delay time and therefore works just as a free-running timer. thus a 16-bit value on 8/16-bit CPUs. A basically unlimited number of software timers can be defined with the macro OS_CREATETIMER(). Another factor to take into account is the maximum time spent in critical regions. which is not recommended). to be safe. Generally. API functions Routine Description OS_CREATETIMER() OS_CreateTimer() OS_StartTimer() OS_StopTimer() OS_RetriggerTimer() OS_SetTimerPeriod() OS_DeleteTimer() Table 1: Software timers API Creates and starts a software-timer. Software timers are called by IAR PowerPac RTOS with interrupts enabled. This makes it possible to use one callback function for different software timers. 31-bits on 32-bit CPUs. EXTENDED SOFTWARE TIMER Sometimes it may be useful to pass a parameter to the timer callback function. Starts a specified timer. Sets a new timer reload value for a specified timer. PPRTOS-3 37 . the maximum time that the system spends at once in a critical region needs to be deducted. The state of timers can be checked by the functions OS_GetTimerStatus(). which means they expire only once and call their callback routine only once. and OS_GetTimerPeriod(). Timers can be stopped. Except the different callback function with parameter passing. When defining a timer. but because the timer routine can not be called from a critical region (timers are “put on hold”). In most systems. During critical regions timers may expire. Restarts a specified timer with its initial time value. Timer routines are similar to interrupt routines. The comparisons are done as signed comparisons. this is no more than a single tick.

c. Once the timeout is expired. the callback routine will be called immediately (unless the task is in a critical region or has interrupts disabled). Returns a pointer to the data structure of the timer that just expired. It is supplied for backward compatibility. Initial timeout in basic IAR PowerPac RTOS time units (nominal ms): The data type OS_TIME defaults to an integer. OS_TIMERROUTINE* Callback. Creates an extended software timer without starting it.c. Stops and deletes a specified extended timer. OS_TIMERROUTINE is defined in RTOS. Source of the macro (in RTOS. Creates and starts an extended software-timer.d).Routine Description OS_GetTimerPeriod() OS_GetTimerValue() OS_GetTimerStatus() OS_GetpCurrentTimer() OS_CREATETIMER_EX() OS_CreateTimerEx() OS_StartTimerEx() OS_StopTimerEx() OS_RetriggerTimerEx() OS_SetTimerPeriodEx() OS_DeleteTimerEx() OS_GetTimerPeriodEx() OS_GetTimerValueEx() OS_GetTimerStatusEx() OS_GetpCurrentTimerEx() Table 1: Software timers API Returns the current reload value of a specified timer. Prototype void OS_CREATETIMER (OS_TIMER* pTimer.h as follows: typedef void OS_TIMERROUTINE(void). OS_CREATETIMER() Description Macro that creates and starts a software-timer. IAR PowerPac™ RTOS 38 User Guide PPRTOS-3 . Returns a pointer to the data structure of the extended timer that just expired. Returns the remaining timer value of a specified timer. Returns the remaining timer value of a specified extended timer. Returns the current reload value of a specified extended timer. therefore valid values are 1 <= Timeout <= 215-1 = 0x7FFF = 32767 for 8/16-bit CPUs 1 <= Timeout <= 231-1 = 0x7FFFFFFF for 32-bit CPUs Table 2: OS_CREATETIMER() parameter list Additional Information IAR PowerPac RTOS keeps track of the timers by using a linked list. Returns the current timer status of a specified extended timer. Starts a specified extended timer.d) \ OS_CreateTimer(pTimer. Sets a new timer reload value for a specified extended timer. Stops a specified extended timer. OS_TIME Timeout). Restarts a specified extended timer with its initial time value.h): #define OS_CREATETIMER(pTimer. Returns the current timer status of a specified timer. \ OS_StartTimer(pTimer). Pointer to the callback routine to be called from the RTOS after expiration of the delay. This macro uses the functions OS_CreateTimer() and OS_StartTimer(). Parameter Description pTimer Callback Timeout Pointer to the OS_TIMER data structure which contains the data of the timer. in new applications these routines should be called directly instead.

Pointer to the callback routine to be called from the RTOS after expiration of the delay. 100). The timer is not automatically started. Parameter Description pTimer Pointer to the OS_TIMER data structure which contains the data of the timer.h as follows: typedef void OS_TIMERROUTINE(void). Prototype void OS_CreateTimer (OS_TIMER* pTimer. Initial timeout in basic IAR PowerPac RTOS time units (nominal ms): The data type OS_TIME defaults to an integer. OS_RetriggerTimer(&TIMER100). Timer100. Prototype void OS_StartTimer (OS_TIMER* pTimer). } /* Toggle LED */ /* Make timer periodical */ void InitTask(void) { /* Create and start Timer100 */ OS_CREATETIMER(&TIMER100. Parameter Description pTimer Callback Timeout Pointer to the OS_TIMER data structure which contains the data of the timer.Software timers Example OS_TIMER TIMER100. } OS_StartTimer() Description Starts a specified timer. OS_TIMERROUTINE is defined in RTOS. Once the timeout is expired. Timer100. } /* Toggle LED */ /* Make timer periodical */ void InitTask(void) { /* Create Timer100. OS_RetriggerTimer(&TIMER100). the callback routine will be called immediately (unless the task is in a critical region or has interrupts disabled). start it elsewhere */ OS_CreateTimer(&TIMER100. therefore valid values are 1 <= Timeout <= 215-1 = 0x7FFF = 32767 for 8/16-bit CPUs 1 <= Timeout <= 231-1 = 0x7FFFFFFF for 32-bit CPUs Table 3: OS_CreateTimer() parameter list Additional Information IAR PowerPac RTOS keeps track of the timers by using a linked list. OS_TIMERROUTINE* Callback. } OS_CreateTimer() Description Creates a software timer (but does not start it). OS_TIME Timeout). Example OS_TIMER TIMER100. 100). void Timer100(void) { LED = LED ? 0 : 1. This has to be done explicitly by a call of OS_StartTimer() or OS_RetriggerTimer(). void Timer100(void) { LED = LED ? 0 : 1. Table 4: OS_StartTimer() parameter list PPRTOS-3 39 .

The timer will start with its initial timer value. /* Make timer periodical */ } void InitTask(void) { /* Create and start TimerCursor */ OS_CREATETIMER(&TIMERCursor. but has expired. OS_RetriggerTimer() Description Restarts a specified timer with its initial time value. Prototype void OS_StopTimer (OS_TIMER* pTimer). } OS_SetTimerPeriod() Description Sets a new timer reload value for a specified timer. Parameter Description pTimer Pointer to the OS_TIMER data structure which contains the data of the timer. the timer will continue with the remaining time value which was preserved by stopping the timer. In this case. void TimerCursor(void) { if (CursorOn) ToggleCursor(). TimerCursor. Use OS_RetriggerTimer() to restart those timers. /* Invert character at cursor-position */ OS_RetriggerTimer(&TIMERCursor). Prototype void OS_RetriggerTimer (OS_TIMER* pTimer). 500). Table 5: OS_StopTimer() parameter list Additional Information The actual value of the timer (the time until expiration) is kept until OS_StartTimer() lets the timer continue. BOOL CursorOn. Important This function has no effect on running timers. It also has no effect on timers that are not running. OS_StopTimer() Description Stops a specified timer. IAR PowerPac™ RTOS 40 User Guide PPRTOS-3 . Restart a timer which was stopped by calling OS_StopTimer(). Example OS_TIMER TIMERCursor.Additional Information OS_StartTimer() is used for the following reasons: ● ● Start a timer which was created by OS_CreateTimer(). Table 6: OS_RetriggerTimer() parameter list Additional Information OS_RetriggerTimer() restarts the timer using the initial time value programmed at creation of the timer or with the function OS_SetTimerPeriod(). Parameter Description pTimer Pointer to the OS_TIMER data structure which contains the data of the timer.

BOOL CursorOn. Parameter Description pTimer Pointer to the OS_TIMER data structure which contains the data of the timer. /* Make timer periodical */ } void InitTask(void) { /* Create and start Pulse Timer with first pulse = 500ms */ OS_CREATETIMER(&TIMERPulse. } OS_DeleteTimer() Description Stops and deletes a specified timer. /* Toggle output */ OS_RetriggerTimer(&TIMERCursor). the timer is also marked as invalid. 200). OS_GetTimerPeriod() Description Returns the current reload value of a specified timer. Prototype OS_TIME OS_GetTimerPeriod (OS_TIMER* pTimer). 500). Table 9: OS_GetTimerPeriod() parameter list Return value Type OS_TIME. In debug builds of IAR PowerPac RTOS. Parameter Description pTimer Period Pointer to the OS_TIMER data structure which contains the data of the timer. TimerPulse. Period is the reload value of the timer to be used as initial value when the timer is retriggered by OS_RetriggerTimer(). /* Set timer period to 200 ms for further pulses */ OS_SetTimerPeriod(&TIMERPulse. therefore valid values are 1 <= Timeout <= 215-1 = 0x7FFF = 32767 for 8/16-bit CPUs 1 <= Timeout <= 231-1 = 0x7FFFFFFF for 32-bit CPUs Table 7: OS_SetTimerPeriod() parameter list Additional Information OS_SetTimerPeriod() sets the initial time value of the specified timer. Parameter Description pTimer Pointer to the OS_TIMER data structure which contains the data of the timer. which is defined as an integer between 1 and 215-1 = 0x7FFF = 32767 for 8/16-bit CPUs and as an integer between 1 and <= 231-1 = 0x7FFFFFFF for 32-bit CPUs. Timer period in basic IAR PowerPac RTOS time units (nominal ms): The data type OS_TIME defaults to an integer. PPRTOS-3 41 . which is the permitted range of timer values. Example OS_TIMER TIMERPulse. Prototype void OS_DeleteTimer (OS_TIMER* pTimer).Software timers Prototype void OS_SetTimerPeriod (OS_TIMER* pTimer. void TimerPulse(void) { if TogglePulseOutput(). OS_TIME Period). Table 8: OS_DeleteTimer() parameter list Additional Information The timer is stopped and therefore removed out of the linked list of running timers.

Parameter Description pTimer Pointer to the OS_TIMER data structure which contains the data of the timer. Table 11: OS_GetTimerStatus parameter list Return value Unsigned character. otherwise it is undetermined. Prototype unsigned char OS_GetTimerStatus (OS_TIMER* pTimer). OS_GetTimerValue() Description Returns the remaining timer value of a specified timer. Table 10: OS_GetTimerValue() parameter list Return value The returned time value is the remaining timer time in IAR PowerPac RTOS tick units until expiration of the timer. Additional Information The return value of OS_GetpCurrentTimer() is valid during execution of a timer callback function. denoting whether the specified timer is running or not: 0: timer has stopped ! = 0: timer is running. this function can be used for examining the timer that expired. which is defined as an integer between 1 and 215-1 = 0x7FFF = 32767 for 8/16-bit CPUs and as an integer between 1 and <= 231-1 = 0x7FFFFFFF for 32-bit CPUs. which is the permitted range of timer values. Type OS_TIME. Parameter Description pTimer Pointer to the OS_TIMER data structure which contains the data of the timer. IAR PowerPac™ RTOS 42 User Guide PPRTOS-3 . If only one callback function should be used for multiple timers. The example below shows one usage of OS_GetpCurrentTimer(). In this version of IAR PowerPac RTOS. Prototype OS_TIME OS_GetTimerValue (OS_TIMER* pTimer). Prototype OS_TIMER* OS_GetpCurrentTimer (void). the extended timer structure and functions which come with IAR PowerPac RTOS may be used to generate and use software timer with individual parameter for the callback function. OS_GetTimerStatus() Description Returns the current timer status of a specified timer. Return value OS_TIMER*: A pointer to the control structure of a timer.Additional Information The period returned is the reload value of the timer set as initial value when the timer is retriggered by OS_RetriggerTimer(). OS_GetpCurrentTimer() Description Returns a pointer to the data structure of the timer that just expired.

Pointer to the callback routine to be called from the RTOS after expiration of the delay. /* Retrigger timer */ } /******************************************************** * * main */ int main(void) { OS_InitKern(). OS_UINT Timeout. Callback. &a). /* Start multitasking */ return 0. /* Initialize OS */ OS_InitHW(). int a. /******************************************************** * * Local Functions */ void CreateTimer(TIMER_EX* timer. } */ OS_CREATETIMER_EX() Description Macro that creates and starts an extended software-timer. Timeout pData Table 12: OS_CREATETIMER_EX() parameter list PPRTOS-3 43 . OS_TIMERROUTINE* Callback. therefore valid values are: 1 <= Timeout <= 215-1 = 0x7FFF = 32767 for 8/16-bit CPUs 1 <= Timeout <= 231-1 = 0x7FFFFFFF for 32-bit CPUs A void pointer which is used as parameter for the extended timer callback function. cb. Timeout).H" /******************************************************** * * Types */ typedef struct { /* Timer object with its own user data */ OS_TIMER Timer. Callback. void* pUser.Software timers Example #include "RTOS. void* pUser) { timer->pUser = pUser. /* Initialize Hardware for OS */ CreateTimer(&Timer_User. 100. /* Examine user data */ OS_RetriggerTimer(&p->Timer). OS_Start(). } TIMER_EX. Initial timeout in basic IAR PowerPac RTOS time units (nominal ms): The data type OS_TIME is defined as an integer. } void cb(void) { /* Timer callback function for multiple timers TIMER_EX* p = (TIMER_EX*)OS_GetpCurrentTimer(). OS_CreateTimer((OS_TIMER*) timer. Prototype void OS_CREATETIMER_EX (OS_TIMER_EX* OS_TIMER_EX_ROUTINE* OS_TIME void* Parameter Description pTimerEx. The callback function has to be of type OS_TIMER_EX_ROUTINE which takes a void pointer as parameter and does not return any value. Timeout pData). pTimerEx Callback Pointer to the OS_TIMER_EX data structure which contains the data of the timer. void* pUser = p->pUser. /******************************************************** * * Variables */ TIMER_EX Timer_User.

Timeout pData). /* Toggle LED */ if (pTask != NULL) { OS_SignalEvent(0x01. OS_TASK TCB_HP void Timer100(void) { LED = LED ? 0 : 1. the callback routine will be called immediately (unless the task is in a critical region or has interrupts disabled).h as follows: typedef void OS_TIMER_EX_ROUTINE(void *). } OS_CreateTimerEx() Description Creates an extended software timer without starting it. Example OS_TIMER TIMER100. pData Table 13: OS_CreateTimerEx() parameter list Additional Information IAR PowerPac RTOS keeps track of the timers by using a linked list.cb. This has to be done explicitly by a call of OS_StartTimerEx() or OS_RetriggerTimerEx(). Pointer to the callback routine of type OS_TIMER_EX_ROUTINE to be called from the RTOS after the timer has expired.pData). (OS_TASK*)pTask) } OS_RetriggerTimerEx(&TIMER100).Timeout. pTimerEx Callback Timeout Pointer to the OS_TIMER_EX data structure which contains the data of the timer. The extended software timer is not automatically started. Callback. OS_TIMERROUTINE_EX is defined in RTOS.h as follows: typedef void OS_TIMER_EX_ROUTINE(void*).cb. Initial timeout in basic IAR PowerPac RTOS time units (nominal ms): The data type OS_TIME is defined as an integer.pData) \ OS_CreateTimerEx(pTimerEx. the callback routine will be called immediately (unless the task is in a critical region or has interrupts disabled).h): #define OS_CREATETIMER_EX(pTimerEx. Once the timeout is expired. (void*) &TCB_HP). therefore valid values are: 1 <= Timeout <= 215-1 = 0x7FFF = 32767 for 8/16-bit CPUs 1 <= Timeout <= 231-1 = 0x7FFFFFFF for 32-bit CPUs A void pointer which is used as parameter for the extended timer callback function. Once the timeout has expired.Timeout. \ OS_StartTimerEx(pTimerEx). Source of the macro (in RTOS. /* Make timer periodical */ } void InitTask(void) { /* Create and start Timer100 */ OS_CREATETIMER_Ex(&TIMER100. Timer100. 100. IAR PowerPac™ RTOS 44 User Guide PPRTOS-3 .Additional Information IAR PowerPac RTOS keeps track of the timers by using a linked list. Prototype void OS_CreateTimerEx (OS_TIMER_EX* OS_TIMER_EX_ROUTINE* OS_TIME void* Parameter Description pTimerEx. OS_TIMER_EX_ROUTINE is defined in RTOS. This macro uses the functions OS_CreateTimer_Ex() and OS_StartTimer_Ex().

/* Make timer periodical */ } void InitTask(void) { /* Create Timer100.Software timers Example OS_TIMER TIMER100. Timer100. but has expired. OS_RetriggerTimerEx() Description Restarts an extended timer with its initial time value. Table 15: OS_StopTimerEx() parameter list Additional Information The actual value of the extended software timer (the time until expiration) is kept until OS_StartTimerEx() lets the timer continue. In this case. Use OS_RetriggerTimerEx() to restart those timers. (OS_TASK*)pTask) } OS_RetriggerTimerEx(&TIMER100). PPRTOS-3 45 . /* Toggle LED */ if (pTask != NULL) { OS_SignalEvent(0x01. Prototype void OS_StartTimerEx (OS_TIMER_EX* pTimerEx). void Timer100(void* pTask) { LED = LED ? 0 : 1. Table 14: OS_StartTimerEx() parameter list Additional Information OS_StartTimerEx() is used for the following reasons: ● ● Start an extended timer which was created by OS_CreateTimerEx(). It also has no effect on timers that are not running. (void*) &TCB_HP). Prototype void OS_StopTimerEx (OS_TIMER_EX* pTimerEx). start it elsewhere later on */ OS_CreateTimerEx(&TIMER100. OS_StopTimerEx() Description Stops an extended software timer. The timer will start with its initial timer value. 100. } OS_StartTimerEx() Description Starts an extended software timer. Parameter Description pTimerEx Pointer to the OS_TIMER_EX data structure which contains the data of the extended software timer. Parameter Description pTimerEx Pointer to the OS_TIMER_EX data structure which contains the data of the extended software timer. OS_TASK TCB_HP. Important This function has no effect on running timers. Restart a timer which was stopped by calling OS_StopTimerEx(). the timer will continue with the remaining time value which was preserved by stopping the timer.

OS_TIME Period). Example OS_TIMER TIMERCursor. 500. Period is the reload value of the timer to be used as initial value when the timer is retriggered by OS_RetriggerTimerEx(). /* Make timer periodical */ } void InitTask(void) { /* Create and start TimerCursor */ OS_CREATETIMER_EX(&TIMERCursor. /* Set timer period to 200 ms for further pulses */ OS_SetTimerPeriodEx(&TIMERPulse. /* Invert character at cursor-position */ OS_SignalEvent(0x01. (OS_TASK*) pTask). A call of OS_SetTimerPeriodEx() does not affect the remaining time period of an extended software timer. Prototype void OS_SetTimerPeriodEx (OS_TIMER_EX* pTimerEx. OS_RetriggerTimerEx(&TIMERCursor). (void*) &TCB_HP). OS_TASK TCB_HP. void TimerCursor(void) { if (CursorOn != 0) ToggleCursor(). OS_TASK TCB_HP. TimerCursor. Parameter Description pTimerEx Period Pointer to the OS_TIMER_EX data structure which contains the data of the timer.Prototype void OS_RetriggerTimerEx (OS_TIMER_EX* pTimerEx). Table 16: OS_RetriggerTimerEx() parameter list Additional Information OS_RetriggerTimerEx() restarts the extended software timer using the initial time value which was set at creation of the timer or which was set using the function OS_SetTimerPeriodEx(). } IAR PowerPac™ RTOS 46 User Guide PPRTOS-3 . Example OS_TIMER TIMERPulse. BOOL CursorOn. (OS_TASK*) pTask). } OS_SetTimerPeriodEx() Description Sets a new timer reload value for a extended software timer. (void*) &TCB_HP). void TimerPulse(void) { OS_SignalEvent(0x01. Timer period in basic IAR PowerPac RTOS time units (nominal ms): The data type OS_TIME is defined as an integer. TimerPulse. /* Make timer periodical */ } void InitTask(void) { /* Create and start Pulse Timer with first pulse = 500ms */ OS_CREATETIMER_EX(&TIMERPulse. 200). OS_RetriggerTimerEx(&TIMERPulse). therefore valid values are 1 <= Timeout <= 215-1 = 0x7FFF = 32767 for 8/16-bit CPUs 1 <= Timeout <= 231-1 = 0x7FFFFFFF for 32-bit CPUs Table 17: OS_SetTimerPeriodEx() parameter list Additional Information OS_SetTimerPeriodEx() sets the initial time value of the specified extended software timer. 500. Parameter Description pTimerEx Pointer to the OS_TIMER_EX data structure which contains the data of the extended software timer.

Prototype void OS_DeleteTimerEx (OS_TIMER_EX* pTimerEx). Table 18: OS_DeleteTimerEx() parameter list Additional Information The extended software timer is stopped and therefore removed out of the linked list of running timers. which is defined as an integer between 1 and 215-1 = 0x7FFF = 32767 for 8/16-bit CPUs and as an integer between 1 and <= 231-1 = 0x7FFFFFFF for 32-bit CPUs. which is the permitted range of timer values. Table 20: OS_GetTimerValueEx() parameter list Return value Type OS_TIME. In debug builds of IAR PowerPac RTOS. Table 19: OS_GetTimerPeriodEx() parameter list Return value Type OS_TIME.Software timers OS_DeleteTimerEx() Description Stops and deletes an extended software timer. OS_GetTimerStatusEx() Description Returns the current timer status of an extended software timer. OS_GetTimerValueEx() Description Returns the remaining timer value of an extended software timer. This reload value will be used as time period when the timer is retriggered by OS_RetriggerTimerEx(). which is defined as an integer between 1 and 215-1 = 0x7FFF = 32767 for 8/16-bit CPUs and as an integer between 1 and <= 231-1 = 0x7FFFFFFF for 32-bit CPUs. Parameter Description pTimerEx Pointer to the OS_TIMER_EX data structure which contains the data of the timer. Prototype OS_TIME OS_GetTimerValueEx (OS_TIMER_EX* pTimerEx). Parameter Description pTimerEx Pointer to the OS_TIMER_EX data structure which contains the data of the timer. which is the permitted range of timer values. Additional Information The period returned is the reload value of the timer which was set as initial value when the timer was created or which was modified by a call of OS_SetTimerPeriodEx(). Parameter Description pTimerEx Pointer to the OS_TIMER_EX data structure which contains the data of the timer. Prototype OS_TIME OS_GetTimerPeriodEx (OS_TIMER_EX* pTimerEx). PPRTOS-3 47 . the timer is also marked as invalid. The returned time value is the remaining timer time in IAR PowerPac RTOS tick units until expiration of the extended software timer. OS_GetTimerPeriodEx() Description Returns the current reload value of an extended software timer.

Prototype
unsigned char OS_GetTimerStatusEx (OS_TIMER_EX* pTimerEx);
Parameter Description

pTimerEx

Pointer to the OS_TIMER_EX data structure which contains the data of the extended timer.

Table 21: OS_GetTimerStatusEx() parameter list

Return value
Unsigned character, denoting whether the specified timer is running or not:

0: timer has stopped ! = 0: timer is running.

OS_GetpCurrentTimerEx()
Description
Returns a pointer to the data structure of the timer that just expired.

Prototype
OS_TIMER_EX* OS_GetpCurrentTimerEx (void);

Return value
OS_TIMER_EX*: A pointer to the control structure of an extended software timer.

Additional Information
The return value of OS_GetpCurrentTimerEx() is valid during execution of a timer callback function; otherwise it is undetermined. If only one callback function should be used for multiple timers, this function can be used for examining the timer that expired.

Example
#include "RTOS.H" OS_TIMER_EX MyTimerEx; /******************************************************** * * Local Functions */ void cbTimerEx(void* pData) { /* Timer callback function for multiple timers */ OS_TIMER_EX* pTimerEx; pTimerEx = OS_GetpCurrentTimerEx(); OS_SignalEvent(0x01, (OS_TASK*) pData); OS_RetriggerTimer(pTimerEx); /* Retrigger timer */ }

IAR PowerPac™ RTOS

48

User Guide

PPRTOS-3

Resource semaphores
Introduction
Resource semaphores are used for managing resources by avoiding conflicts caused by simultaneous use of a resource. The resource managed can be of any kind: a part of the program that is not reentrant, a piece of hardware like the display, a flash prom that can only be written to by a single task at a time, a motor in a CNC control that can only be controlled by one task at a time, and a lot more. The basic procedure is as follows: Any task that uses a resource first claims it by calling the OS_Use() or OS_Request() routines of IAR PowerPac RTOS. If the resource is available, the program execution of the task continues, but the resource is blocked for other tasks. If a second task now tries to use the same resource while it is in use by the first task, this second task is suspended until the first task releases the resource. However, if the first task that uses the resource calls OS_Use() again for that resource, it is not suspended because the resource is blocked only for other tasks. The following diagram illustrates the process of using a resource:

OS_Use()

Access resource

OS_Unuse()

A resource semaphore contains a counter that keeps track of how many times the resource has been claimed by calling
OS_Request() or OS_Use() by a particular task. It is released when that counter reaches 0, which means the OS_Unuse() routine has to be called exactly the same number of times as OS_Use() or OS_Request(). If it is not,

the resource remains blocked for other tasks. On the other hand, a task cannot release a resource that it does not own by calling OS_Unuse(). In the debug version of IAR PowerPac RTOS, a call of OS_Unuse() for a semaphore that is not owned by this task will result in a call to the error handler OS_Error().

Example of using resource semaphores
Here, two tasks access an LC display completely independently from each other. The LCD is a resource that needs to be protected with a resource semaphore. One task may not interrupt another task which is writing to the LCD, because otherwise the following might occur:
● ● ●

Task A positions the cursor Task B interrupts Task A and repositions the cursor Task A writes to the wrong place in the LCD' s memory.

To avoid this type of situation, every the LCD must be accessed by a task, it is first claimed by a call to OS_Use() (and is automatically waited for if the resource is blocked). After the LCD has been written to, it is released by a call to OS_Unuse().

PPRTOS-3

49

/* * demo program to illustrate the use of resource semaphores */ OS_STACKPTR int StackMain[100], StackClock[50]; OS_TASK TaskMain,TaskClock; OS_SEMA SemaLCD; void TaskClock(void) { char t=-1; char s[] = "00:00"; while(1) { while (TimeSec==t) Delay(10); t= TimeSec; s[4] = TimeSec%10+'0'; s[3] = TimeSec/10+'0'; s[1] = TimeMin%10+'0'; s[0] = TimeMin/10+'0'; OS_Use(&SemaLCD); /* Make sure nobody else uses LCD */ LCD_Write(10,0,s); OS_Unuse(&SemaLCD); /* Release LCD */ } } void TaskMain(void) { signed char pos ; LCD_Write(0,0,"Software tools by OS_Delay(2000); while (1) { for ( pos=14 ; pos >=0 ; pos-OS_Use(&SemaLCD); LCD_Write(pos,1,"train "); OS_Unuse(&SemaLCD); OS_Delay(500); } OS_Use(&SemaLCD); LCD_Write(0,1," ") ; OS_Unuse(&SemaLCD); } }

IAR Systems !

") ;

) { /* Make sure nobody else uses LCD /* Draw train */ /* Release LCD */ /* Make sure nobody else uses LCD /* Release LCD */

*/

*/

void InitTask(void) { OS_CREATERSEMA(&SemaLCD); /* Creates resource semaphore OS_CREATETASK(&TaskMain, 0, Main, 50, StackMain); OS_CREATETASK(&TaskClock, 0, Clock, 100, StackClock); }

*/

In most applications, the routines that access a resource should automatically call OS_Use() and OS_Unuse() so that when using the resource you do not have to worry about it and can use it just as you would in a single-task system. The following is an example of how to implement a resource into the routines that actually access the display:
/* * Simple example when accessing single line dot matrix LCD */ OS_RSEMA RDisp; /* Define resource semaphore */ void UseDisp() { OS_Use(&RDisp); } void UnuseDisp() { OS_Unuse(&RDisp); } /* Simple routine to be called before using display */

/* Simple routine to be called after using display

*/

void DispCharAt(char c, char x) { UseDisp(); LCDGoto(x, y); LCDWrite1(ASCII2LCD(c)); UnuseDisp(); } void DISPInit(void) { OS_CREATERSEMA(&RDisp); }

IAR PowerPac™ RTOS

50

User Guide

PPRTOS-3

OS_CREATERSEMA() Description Macro that creates a resource semaphore. which means the counter of the semaphore is 0. A value larger than 1 means the resource was already locked by the calling task. If the resource is not used by a task. never reduce it. Priority inversion can only temporarily increase the priority of a task. The counter of the semaphore is simply incremented. Parameter Description pRSema Table 3: OS_Use() parameter list Pointer to the data structure for a resource semaphore. Prototype int OS_Use (OS_RSEMA* pRSema). Returns the value of the usage counter of a specified resource semaphore. The execution of this task is suspended until the resource semaphore is released. Prototype void OS_CREATERSEMA (OS_RSEMA* pRSema). Deletes a specified resource semaphore. Case C: The resource is being used by another task. Claims a resource and blocks it for other tasks. the blocking task is assigned the priority of the task requesting the resource semaphore. This is called priority inversion. Releases a semaphore currently in use by a task. the value of the counter is 0. blocks it for other tasks if it is available. The program continues without a break. Additional Information The following situations are possible: ● ● ● Case A: The resource is not in use. the resource will be blocked for other tasks by incrementing the counter and writing a unique code for the task that uses it into the semaphore. the resource is not blocked. OS_Use() Description Claims a resource and blocks it for other tasks. Continues execution in any case. Returns a pointer to the task that is currently using (blocking) a resource. Return value The counter value of the semaphore. Case B: The resource is used by this task. Parameter Description pRSema Pointer to the data structure for a resource semaphore. In the meantime if the task blocked by the resource semaphore has a higher priority than the task blocking the semaphore. Table 2: OS_CREATESEMA() parameter list Additional Information After creation.Resource semaphores API functions Routine Description OS_CREATERSEMA() OS_Use() OS_Unuse() OS_Request() OS_GetSemaValue() OS_GetResourceOwner() OS_DeleteRSema() Table 1: Resource semaphore API overview Macro that creates a resource semaphore. Requests a specified semaphore. PPRTOS-3 51 .

. According to the rules of the scheduler. The following diagram illustrates how the OS_Use() routine works: OS_Use(. by this task No Mark current task as owner Increase Usage counter Usage counter = 1 return return OS_Unuse() Description Releases a semaphore currently in use by a task. In the debug version. The error code in this case is OS_ERR_RESOURCE_OWNER. Table 4: OS_Unuse() parameter list Additional Information OS_Unuse() may be used on a resource semaphore only after that semaphore has been used by calling OS_Use() or OS_Request()..An unlimited number of tasks can wait for a resource semaphore. OS_Error() will also be called if OS_Unuse() is called from a task that does not own the resource. OS_Unuse() decrements the usage counter of the semaphore which must never become negative. by other task Wait for resource to be released Yes. Prototype void OS_Unuse (OS_RSEMA* pRSema) Parameter Description pRSema Pointer to the data structure for a resource semaphore. If this counter becomes negative. the task with the highest priority will get access to the resource and can continue program execution.) Resource in use? Yes. Important This function may not be called from within an interrupt handler. the debug version will call the IAR PowerPac RTOS error handler OS_Error() with the error code OS_ERR_UNUSE_BEFORE_USE. of all the tasks waiting for the resource. IAR PowerPac™ RTOS 52 User Guide PPRTOS-3 .

/* } DispTime(). /* OS_Unuse(&RSEMA_LCD). /* /* OS_Use(&RSEMA_LCD). Additional Information The following diagram illustrates how OS_Request() works: OS_Request (RSEMA*ps) Resource in use by other task ? No Yes return 0 In use by this task ? No Mark current task as owner Yes Inc Usage counter Usage counter = 1 return 1 return 1 Example if (!OS_Request(&RSEMA_LCD) ) { LED_LCDBUSY = 1.Resource semaphores Important This function may not be called from within an interrupt handler. OS_Request() Description Requests a specified semaphore and blocks it for other tasks if it is available. now in use by calling task 0: Resource was not available. Table 5: OS-Request() parameter list Return value 1: Resource was available. /* Indicate that task is waiting for resource Wait for resource Indicate task is no longer waiting Access the resource LCD Resource LCD is no longer needed */ */ */ */ */ */ PPRTOS-3 53 . /* LED_LCDBUSY = 0. Prototype char OS_Request (OS_RSEMA* pRSema). Parameter Description pRSema Pointer to the data structure for a resource semaphore. Continues execution in any case.

IAR PowerPac™ RTOS 54 User Guide PPRTOS-3 . The memory of that semaphore may be reused for other purposes or may be used for creating another resources semaphore using the same memory. Prototype int OS_GetSemaValue (OS_SEMA* pSema). Table 7: OS_GetResourceOwner() parameter list Return value Pointer to the task that is blocking the resource. Prototype void OS_DeleteRSema (OS_RSEMA* pRSema). Parameter Description pRSema Pointer to the data structure for a resource semaphore. before re-creating it. Table 8: OS_DeleteRSema parameter list Additional Information Before deleting a resource semaphore. make sure that no task is claiming the resources semaphore. Prototype OS_TASK* OS_GetResourceOwner (OS_RSEMA* pSema). OS_DeleteRSema() Description Deletes a specified resource semaphore.OS_GetSemaValue() Description Returns the value of the usage counter of a specified resource semaphore. A value of 0 means the resource is available. OS_GetResourceOwner() Description Returns a pointer to the task that is currently using (blocking) a resource. In systems with dynamic creation of resource semaphores. The debug version of IAR PowerPac RTOS will call OS_Error(). it is required to delete a resource semaphore. if a resources semaphore is deleted when it is already used. Parameter Description pRSema Pointer to the data structure for a resource semaphore. Otherwise the semaphore handling will not work correctly. Table 6: OS_GetSemaValue() parameter list Return value The counter of the semaphore. Parameter Description pRSema Pointer to a data structure of type OS_RSEMA. A value of 0 means the resource is available.

Sets the counter value of a specified semaphore. Task1. NULL. } /* Create Semaphore /* Create Task0 /* Create Task1 */ */ */ API functions Routine Description OS_CREATECSEMA() OS_CreateCSema() OS_SignalCSema() OS_SignalCSemaMax OS_WaitCSema() OS_CSemaRequest() OS_WaitCSemaTimed OS_GetCSemaValue() OS_SetCSemaValue() OS_DeleteCSema() Macro that creates a counting semaphore with an initial count value of zero. Stack0). PPRTOS-3 55 . /* Task stacks */ OS_TASK TCB0. goto Loop. Decrements the counter of a semaphore. Returns the counter value of a specified semaphore. 100. Increments the counter of a semaphore up to a specified maximum value. OS_CREATETASK(&TCB0. They are used in situations where a task needs to wait for something that can be signaled one or more times. /* Data-area for tasks (task-control-blocks) */ OS_CSEMA SEMALCD. any task. The semaphores can be accessed from any point. OS_SignalCSema(&SEMALCD). Disp("Task1 has signaled !!").Counting Semaphores Introduction Counting semaphores are counters that are managed by IAR PowerPac RTOS. OS_Delay(100). OS_WaitCSema(&SEMALCD). goto Loop. if available. Deletes a specified semaphore. Increments the counter of a semaphore. events or mailboxes. or any interrupt in any way. void Task0(void) { Loop: Disp("Task0 will wait for task 1 to signal"). Stack1[64]. Example of using counting semaphores OS_STACKPTR int Stack0[96]. } void Task1(void) { Loop: OS_Delay(5000). OS_CREATETASK(&TCB1. Stack1). Creates a counting semaphore with a specified initial count value. Decrements a semaphore counter if the semaphore is available within a specified time. They are not as widely used as resource semaphores. Decrements the counter of a semaphore. } void InitTask(void) { OS_CREATECSEMA(&SEMALCD). Task0. 50. but they can be very useful sometimes. TCB1. NULL. Table 1: Counting semaphores API overview OS_CREATECSEMA() Description Macro that creates a counting semaphore with an initial count value of zero.

It is the responsibility of your application to make sure that this limit will not be exceeded. Prototype void OS_CreateCSema (OS_CSEMA* OS_UINT Parameter Description pCSema. the task that has the highest priority will become the active task. pCSema InitValue Pointer to a data structure of type OS_CSEMA. If. you have to create a semaphore with an initial counting value above zero. OS_SignalCSemaMax() Description Increments the counter of a semaphore up to a specified maximum value. IAR PowerPac™ RTOS 56 User Guide PPRTOS-3 . InitValue).Prototype void OS_CREATECSEMA (OS_CSEMA* pCSema). Parameter Description pCSema Pointer to a data structure of type OS_CSEMA. OS_SignalCSema() Description Increments the counter of a semaphore. Prototype void OS_SignalCSema (OS_CSEMA * pCSema). If one or more tasks are waiting for an event to be signaled to this semaphore. The debug version of IAR PowerPac RTOS detects a counter overflow and calls OS_Error() with the error code OS_ERR_CSEMA_OVERFLOW. a data structure of the type OS_CSEMA needs to be defined in memory and initialized using OS_CREATECSEMA(). Initial count value of the semaphore: 0 <= InitValue <= 216 = 0xFFFF for 8/16-bit CPUs 0 <= InitValue <= 232 = 0xFFFFFFFF for 32-bit CPUs Table 3: OS_CreateCSema() parameter list Additional Information To create a counting semaphore. The value of a semaphore created using this macro is zero. the macro OS_CREATECSEMA() should be used. If the value of the created semaphore should be zero. for any reason. The counter can have a maximum value of 0xFFFF for 8/16-bit CPUs / 0xFFFFFFFF for 32-bit CPUs. Parameter Description pCSema Pointer to a data structure of type OS_CSEMA. Table 4: OS_SignalCSema() parameter list Additional Information OS_SignalCSema() signals an event to a semaphore by incrementing its counter. Table 2: OS_CREATECSEMA() parameter list Additional Information To create a counting semaphore. use the function OS_CreateCSema(). a data structure of the type OS_CSEMA needs to be defined in memory and initialized using OS_CreateCSema(). OS_CreateCSema() Description Creates a counting semaphore with a specified initial count value.

Limit of semaphore count value. The counter is then decremented and program execution continues. the tasks are put into ready state and the task that has the highest priority will become the active task. If one or more tasks are waiting for an event to be signaled to this semaphore. According to the rules of the scheduler. WaitCSema() waits until the counter is incremented by another task. Calling OS_SignalCSemaMax() with a MaxValue of 1 handles a counting semaphore as a binary semaphore.Counting Semaphores Prototype void OS_SignalCSemaMax (OS_CSEMA* OS_UINT Parameter Description pCSema. semaphore not available before timeout. Maximum time until semaphore should be available Table 7: OS_WaitCSemaTimed() parameter list Return value Integer value: 0: Failed. int TimeOut). If the counter is 0. pCSema MaxValue Pointer to a data structure of type OS_CSEMA. OS_SignalCSemaMax() signals an event to a semaphore by incrementing its counter. 1 <= MaxValue <= 216 = 0xFFFF for 8/16-bit CPUs 1 <= MaxValue <= 232 = 0xFFFFFFFF for 32-bit CPUs Table 5: OS_SignalCSemaMax() parameter list Additional Information As long as current value of the semaphore counter is below the specified maximum value. Parameter Description pCSema Pointer to a data structure of type OS_CSEMA. the counter is decremented and program execution continues. the task—of all the tasks waiting for the semaphore— with the highest priority will continue program execution. OS_WaitCSema() Description Decrements the counter of a semaphore. semaphore was available and counter decremented. Table 6: OS_WaitCSema() parameter list Additional Information If the counter of the semaphore is not 0. OS_WaitCSemaTimed() Description Decrements a semaphore counter if the semaphore is available within a specified time. Important This function may not be called from within an interrupt handler. An unlimited number of tasks can wait for a semaphore. PPRTOS-3 57 . a timer or an interrupt handler via a call to OS_SignalCSema(). Prototype void OS_WaitCSema (OS_CSEMA* pCSema). MaxValue ). Prototype int OS_WaitCSemaTimed (OS_CSEMA* pCSema. Parameter Description pCSema TimeOut Pointer to a data structure of type OS_CSEMA. 1: OK.

semaphore was not signaled. or an interrupt handler via a call to OS_SignalCSema(). Prototype int OS_SetCSemaValue (OS_SEMA* pCSema. OS_CSemaRequest() does not wait and does not modify the semaphore counter. OS_GetCSemaValue() Description Returns the counter value of a specified semaphore. Prototype char OS_CSemaRequest (OS_CSEMA* pCSema). Table 9: OS_GetCSemaValue() parameter list Return value The counter value of the semaphore. Parameter Description pCSema Pointer to a data structure of type OS_CSEMA. of all the tasks waiting for the semaphore. WaitCSemaTimed() waits until the semaphore is signaled by another task. Prototype int OS_GetCSemaValue (OS_SEMA* pCSema). a timer. Important This function may not be called from within an interrupt handler. 1: OK. The function returns with error state. the program execution continues but returns a value of 0. Parameter Description pCSema Pointer to a data structure of type OS_CSEMA. Additional information If the counter of the semaphore is not 0. OS_CSemaRequest() Description Decrements the counter of a semaphore. if it is signaled. Because this function never blocks a calling task. The counter is then decremented and program execution continues. Parameter Description pCSema Pointer to a data structure of type OS_CSEMA. OS_UINT Value). OS_SetCSemaValue() Description Sets the counter value of a specified semaphore. If the counter is 0. Table 8: OS_GetCSemaRequest() parameter list Return value 0: Failed. this function may be called from an interrupt handler. Table 10: OS_SetCSemaValue() parameter list IAR PowerPac™ RTOS 58 User Guide PPRTOS-3 . the counter is decremented and program execution continues. semaphore was available and counter was decremented once.Additional Information If the counter of the semaphore is not 0. According to the rules of the scheduler. the task with the highest priority will continue program execution. If the counter is 0. An unlimited number of tasks can wait for a semaphore. the counter is decremented and program execution continues. If the semaphore was not signaled within the specified time.

The debug version of IAR PowerPac RTOS will reflect an error if a deleted semaphore is signaled. PPRTOS-3 59 . Table 11: OS_DeleteCSema() parameter list Additional Information Before deleting a semaphore. Parameter Description pCSema Pointer to a data structure of type OS_CSEMA. OS_DeleteCSema() Description Returns the counter value of a specified semaphore. != 0: In case of error.Counting Semaphores Return value 0: If the value could be set. Prototype void OS_DeleteCSema (OS_CSEMA* pCSema). make sure that no task is waiting for it and that no task will signal that semaphore at a later point.

IAR PowerPac™ RTOS 60 User Guide PPRTOS-3 .

Number of messages: 1 <= x <= 32767.the task could be notified by an event signaled to the task every time a character is placed in the buffer. The number of keys that can be stored in the type-ahead buffer depends only on the size of the mailbox buffer. So a message that is put in first will usually be retrieved first. It simply calls the OS_GetMail() routine for that particular mailbox. As with a keyboard buffer. first out. In this case we would have to disable interrupts every time and in every place that we accessed these variables. task synchronization by the use of semaphores was described. the message size is therefore 1 byte. Another major disadvantage would be that we could not access the buffer from an interrupt handler. a task can easily wait for a key to be pressed without having to poll the buffer. For handling messages larger than 127 bytes. but it is a path full of pitfalls. The message is then retrieved by the task that handles the keyboard input. But doing so would make the program less efficient. but very simply just means “item of data”. The communication to these interrupt handlers is very easy with mailboxes. The buffer behaves like a normal buffer. you do not have to worry about it. you can put something (called a message) in and retrieve it later. Message size: 1 <= x <= 127 bytes. semaphores cannot transfer data from one task to another. Typical applications A keyboard buffer In most programs. you use either a task. For more information. because it is reliable. When detected that a key has been pressed. The message in this case is typically a single byte that holds the key code. because the interrupt handler is not allowed to wait for the resource semaphore.Mailboxes Introduction In the preceding chapters. we could use a resource semaphore every time we accessed the buffer. that key is put into a mailbox that is used as a keyboard buffer. which you define when creating the mailbox. A buffer for serial I/O In most cases. the message size is 1 character. The number of mailboxes is limited only by the amount of available memory. The limitations are normally not a problem. Again. Basics A mailbox is a buffer that is managed by the real-time operating system. These limitations have been placed on mailboxes to guarantee efficient coding and also to ensure efficient management. The advantage of a keyboard buffer is that management is very efficient. On top of that. there is a way out . If we need to transfer data between tasks via a buffer for example. It will become clearer in the typical applications explained in the following section. refer to the Chapter Queues on page 71. serial I/O is done with the help of interrupt handlers. It is also not easy for a task to wait for a character to be placed in a buffer without polling the global variable that contains the number of characters in the buffer. One way out would be the usage of global variables. you may use queues. a software timer or an interrupt handler to check the keyboard. Unfortunately. That is why there is an easier way to do this with a real-time OS: The use of mailboxes. PPRTOS-3 61 . “Message” might sound abstract. This is possible. Mailboxes usually work as FIFO: first in. proven code and you have a type-ahead buffer at no extra cost. Both your task programs and your interrupt handlers store or retrieve data to/from the same mailboxes.

Their singlebyte equivalents OS_PutMail1(). if the mailbox is able to accept one more message. The general functions OS_PutMail(). mailboxes are used simply to hold and transfer single-byte messages. if the mailbox is able to accept one more message. To minimize the overhead caused by the mailbox management of IAR PowerPac RTOS. OS_PutMailCond1(). the interrupt handler that is activated when a new character can be sent retrieves this character with OS_GetMailCond(). or normally with a mailbox used as keyboard buffer. time is very critical. The message size would then be the size of this structure. Retrieves a new single-byte message from a mailbox. if the mailbox is able to accept one more message. A simple way to give commands to this task would be to define a structure for commands.For interrupt-driven sending. This new message will be retrieved first. for example. and OS_GetMailCond1() work exactly the same way as their more universal equivalents and are therefore not described separately. IAR PowerPac™ RTOS 62 User Guide PPRTOS-3 . the interrupt handler that is activated when a new character is received puts it in the mailbox using OS_PutMailCond(). the task places the character(s) in the mailbox using OS_PutMail() or OS_PutMailCond(). The only difference is that they can only be used for single-byte mailboxes. It is recommended to use the single-byte versions if you transfer a lot of single byte-data via mailboxes. Retrieves a new message of a predefined size from a mailbox. OS_PutMailCond1(). if a message is available within a given time. if a message is available. Stores a new single-byte message in a mailbox. and OS_GetMailCond() can transfer messages of sizes between 1 and 127 bytes each. Stores a new single-byte message into a mailbox in front of all other messages. the task receives it using OS_GetMail() or OS_GetMailCond(). Stores a new message of a predefined size in a mailbox. API functions Routine Explanation OS_CREATEMB() OS_PutMail() OS_PutMail1() OS_PutMailCond() OS_PutMailCond1() OS_PutMailFront() OS_PutMailFront1() OS_PutMailFrontCond() OS_PutMailFrontCond1() OS_GetMail() OS_GetMail1() OS_GetMailCond() OS_GetMailCond1() OS_GetMailTimed() Table 1: Mailboxes API overview Macro that creates a new mailbox. variations on some mailbox functions are available for single-byte mailboxes. if a message is available. OS_GetMail(). OS_PutMailCond(). and OS_GetMailCond1() work the same way with the exception that they execute much faster because management is simpler. Stores a new message of a predefined size into a mailbox in front of all other messages. OS_GetMail1(). This is the case. Single-byte mailbox functions In many (if not the most) situations. with a mailbox that takes the character received or sent via serial interface. Stores a new single-byte message in a mailbox. This new message will be retrieved first. Stores a new message of a predefined size in a mailbox. In some of these cases. Retrieves a new message of a predefined size from a mailbox. Stores a new single-byte message into a mailbox in front of all other messages. if the mailbox is able to accept one more message. A buffer for commands sent to a task Assume you have one task controlling a motor. OS_GetMail1(). especially if a lot of data is transferred in short periods of time. For interrupt-driven receiving. Retrieves a new message of a predefined size from a mailbox. The routines OS_PutMail1(). as you might have in applications that control a machine. Retrieves a new single-byte message from a mailbox. Stores a new message of a predefined size into a mailbox in front of all other messages.

MOTORCMD_SIZE. Returns number of messages currently in a specified mailbox. 1. but does not retrieve the message from the mailbox. OS_CREATEMB() Description Macro that creates a new mailbox. (1 <= sizeofMsg <= 127) Maximum number of messages. sizeof(MOTORCMD). The buffer has to be big enough to hold the given number of messages of the specified size: sizeofMsg * maxnoMsg bytes. pMsg).) pMB sizeofMsg maxnoMsg pMsg Pointer to a data structure of type OS_MAILBOX reserved for managing the mailbox. #define MOTORCMD_SIZE 4 char BufferMotor[sizeof(MOTORCMD) * MOTORCMD_SIZE]. &BufferMotor). int Speed[2]. void MOTOR_Init(void) { /* Create mailbox that holds commands messages */ OS_CREATEMB(&MBMotor. char MBKeyBuffer[6]. Prototype void OS_CREATEMB (OS_MAILBOX* unsigned char unsigned int void* Parameter Description pMB. Clears all messages in a specified mailbox. } MOTORCMD . maxnofMsg. OS_MAILBOX MBMotor. } OS_PutMail() / OS_PutMail1() Description Stores a new message of a predefined size in a mailbox. Table 2: OS_CREATEMB() parameter list Example Mailbox used as keyboard buffer: OS_MAILBOX MBKey. } Mailbox used for transferring complex commands from one task to another: /* * Example of mailbox used for transfering commands to a task * that controls 2 motors */ typedef struct { char Cmd.Mailboxes Routine Explanation OS_WaitMail() OS_ClearMB() OS_GetMessageCnt() OS_DeleteMB() Table 1: Mailboxes API overview Waits until a mail is available. sizeof(MBKeyBuffer). functioning as type ahead buffer */ OS_CREATEMB(&MBKey. int Position[2]. Size of a message in bytes. PPRTOS-3 63 . sizeofMsg. void InitKeyMan(void) { /* Create mailbox. &MBKeyBuffer). (1 <= MaxnofMsg <= 32767) Pointer to a memory area used as buffer. Deletes a specified mailbox.

Prototype char OS_PutMailCond (OS_MAILBOX* void* char OS_PutMailCond1 (OS_MAILBOX* const char* Parameter Description pMB. the message is not stored. pMB pMail Pointer to the mailbox. 1. char KEYMAN_StoreCond(char k) { return OS_PutMailCond1(&MBKey. sizeof(MBKeyBuffer). char MBKeyBuffer[6]. void KEYMAN_StoreKey(char k) { OS_PutMail1(&MBKey. pMail). if the mailbox is able to accept one more message.Prototype void OS_PutMail (OS_MAILBOX* void* void OS_PutMail1 (OS_MAILBOX* const char* Parameter Description pMB. pMail). Pointer to the message to store. Example OS_MAILBOX MBKey. Table 4: OS_PutMailCond() / OS_PutMailCond1() overview Return value 0: Success. Important This function may not be called from within an interrupt handler. This function never suspends the calling task. Table 3: OS_PutMail() / OS_PutMail1() parameter list Additional Information If the mailbox is full. 1: Message could not be stored (mailbox is full). char MBKeyBuffer[6]. &k). Example Single-byte mailbox as keyboard buffer: OS_MAILBOX MBKey. Because this routine might require a suspension. the calling task is suspended. message stored. pMB. &MBKeyBuffer).) pMB pMail Pointer to the mailbox. pMail). pMB. Use OS_PutMailCond()/OS_PutMailCond1() instead if you have to store data in a mailbox from within an ISR. Additional Information If the mailbox is full. &k). It may therefore be called from an interrupt routine. /* Store key if space in buffer */ } IAR PowerPac™ RTOS 64 User Guide PPRTOS-3 . /* Store key. pMail). } OS_PutMailCond() / OS_PutMailCond1() Description Stores a new message of a predefined size in a mailbox. wait if no space in buffer */ } void KEYMAN_Init(void) { /* Create mailbox functioning as type ahead buffer */ OS_CREATEMB(&MBKey. it must not be called from an interrupt routine. Pointer to the message to store.

Table 5: OS_PutMailFront() / OS_PutMailFront1() parameter list Additional Information If the mailbox is full. pMB pMail Pointer to the mailbox. } OS_PutMailFrontCond() / OS_PutMailFrontCond1() Description Stores a new message of a predefined size into a mailbox in front of all other messages. Prototype char OS_PutMailFrontCond (OS_MAILBOX* void* char OS_PutMailFrontCond1 (OS_MAILBOX* const char* Parameter Description pMB. This function is useful to store “emergency” messages into a mailbox which have to be handled quick. pMail). This new message will be retrieved first. Prototype void OS_PutMailFront (OS_MAILBOX* void* void OS_PutMailFront1 (OS_MAILBOX* const char* Parameter Description pMB. it must not be called from an interrupt routine.Mailboxes This example can be used with the sample program shown earlier to handle a mailbox as keyboard buffer. Because this routine might require a suspension. &k). if the mailbox is able to accept one more message. char MBCmdBuffer[6]. pMail). Pointer to the message to store. Use OS_PutMailFrontCond()/OS_PutMailFrontCond1() instead if you have to store data in a mailbox from within an ISR. wait if no space in buffer*/ } void KEYMAN_Init(void) { /* Create mailbox for command buffer */ OS_CREATEMB(&MBCmd. Important This function may not be called from within an interrupt handler. OS_PutMailFront() / OS_PutMailFront1() Description Stores a new message of a predefined size at the beginning of a mailbox in front of all other messages. pMail). 1. Example Single-byte mailbox as keyboard buffer: OS_MAILBOX MBCmd. Table 6: OS_PutMailFrontCond() / OS_PutMailFrontCond1() parameter list PPRTOS-3 65 . pMB. the calling task is suspended. pMB. pMail). void KEYMAN_StoreCommand(char k) { OS_PutMailFront1(&MBCmd. &MBCmdBuffer). sizeof(MBCmdBuffer). Pointer to the message to store. /* Store command. It may also be used in general instead of OS_PutMail() to change the FIFO structure of a mailbox into a LIFO structure. The new message will be retrieved first.) pMB pMail Pointer to the mailbox.

This function is useful to store “emergency” messages into a mailbox which have to be handled quick. it may not be called from an interrupt routine. The message size (in bytes) was defined when the mailbox was created. char MBKeyBuffer[6].Return value 0: Success. void OS_GetMail1 (OS_MAILBOX* pMB. Prototype char OS_GetMailCond (OS_MAILBOX * pMB. Additional Information If the mailbox is full. Make sure that it points to a valid memory area and that there is sufficient space for an entire message. It may also be used in general instead of OS_PutMailCond() to change the FIFO structure of a mailbox into a LIFO structure. Table 7: OS_GetMail() / OS_GetMail1() parameter list Additional Information If the mailbox is empty. } OS_GetMailCond() / OS_GetMailCond1() Description Retrieves a new message of a predefined size from a mailbox. Parameter Description pMB Pointer to the mailbox. &c). Pointer to the memory area that the message should be stored at. message stored. the message is not stored. Prototype void OS_GetMail (OS_MAILBOX* pMB. char OS_GetMailCond1 (OS_MAILBOX * pMB. Use OS_GetMailCond/OS_GetMailCond1 instead if you have to retrieve data from a mailbox from within an ISR. char WaitKey(void) { char c. if a message is available. Example OS_MAILBOX MBKey. char* pDest). void* pDest). Table 8: OS_GetMailCond() / OS_GetMailCond1() parameter list IAR PowerPac™ RTOS 66 User Guide PPRTOS-3 . This function never suspends the calling task. void* pDest). Parameter Description pMB pDest Pointer to the mailbox. Because this routine might require a suspension. Important This function may not be called from within an interrupt handler. It may therefore be called from an interrupt routine. OS_GetMail1(&MBKey. 1: Message could not be stored (mailbox is full). the task is suspended until the mailbox receives a new message. char* pDest). return c. OS_GetMail() / OS_GetMail1() Description Retrieves a new message of a predefined size from a mailbox.

Make sure that it points to a valid memory area and that there is sufficient space for an entire message. OS_TIME Timeout). &c) return c. The message size (in bytes) was defined when the mailbox was created. This function never suspends the calling task. Additional Information If the mailbox is empty. Parameter Description pMB pDest Pointer to the mailbox. Maximum time in timer ticks until the requested mail has to be available. therefore valid values are 1 <= Timeout <= 215-1 = 0x7FFF = 32767 for 8/16-bit CPUs 1 <= Timeout <= 231-1 = 0x7FFFFFFF for 32-bit CPUs Timeout Table 9: OS_GetMailTimed() parameter list Return value 0: Success. Make sure that it points to a valid memory area and that there is sufficient space for an entire message. as soon as a mail is available within the given timeout. it is taken out of the mailbox and returned to caller. OS_GetMailCond1(&MBKey. The task continues execution. The message size (in bytes) has been defined upon creation of the mailbox. Additional Information If the mailbox is empty.Mailboxes Parameter Description pDest Pointer to the memory area that the message should be stored at. Prototype char OS_GetMailTimed (OS_MAILBOX* pMB. message retrieved. Table 8: OS_GetMailCond() / OS_GetMailCond1() parameter list Return value 0: Success. but the program execution continues. Example OS_MAILBOX MBKey. destination remains unchanged. Important This function may not be called from within an interrupt handler. 1: Message could not be retrieved (mailbox is empty). Pointer to the memory area that the message should be stored at. void* pDest. no message is retrieved. message retrieved. destination remains unchanged. 0 is returned. /* * If a key has been pressed. It may therefore also be called from an interrupt routine. or after the timeout value has expired. according to the rules of the scheduler. * Otherwise. 1: Message could not be retrieved (mailbox is empty). the task is suspended for the given timeout. if a message is available within a given time. */ char GetKey(void) { char c = 0. } OS_GetMailTimed() Description Retrieves a new message of a predefined size from a mailbox. no message is retrieved. The data type OS_TIME defaults to an integer. PPRTOS-3 67 .

* Otherwise. */ char GetKey(void) { char c = 0. Prototype void OS_ClearMB (OS_MAILBOX* pMB). Table 11: OS_ClearMB() parameter list Example OS_MAILBOX MBKey. 0 is returned. Important This function may not be called from within an interrupt handler. but does not retrieve the message from the mailbox. as soon as a mail is available. Parameter Description pMB Pointer to the mailbox. The task continues execution. Parameter Description pMB Pointer to the mailbox. OS_ClearMB() Description Clears all messages in a specified mailbox. it is taken out of the mailbox and returned to caller.Important This function may not be called from within an interrupt handler. /* * Clear keyboard type ahead buffer */ void ClearKeyBuffer(void) { OS_ClearMB(&MBKey). Table 10: OS_WaitMail() parameter list Additional Information If the mailbox is empty. &c. otherwise the task continues. 10) /* Wait for 10 timer ticks */ return c. according to the rules of the scheduler. OS_GetMailTimed(&MBKey. } OS_WaitMail() Description Waits until a mail is available. the task is suspended until a mail is available. Example OS_MAILBOX MBKey. Prototype void OS_WaitMail (OS_MAILBOX* pMB). IAR PowerPac™ RTOS 68 User Guide PPRTOS-3 . but the mail is not retrieved from the mailbox. /* * If a key has been pressed. } OS_GetMessageCnt() Description Returns the number of messages currently available in a specified mailbox.

return 0. Example OS_MAILBOX MBSerIn. The memory that has been used by the mailbox for the control structure and the buffer can then be reused or reallocated.Mailboxes Prototype unsigned int OS_GetMessageCnt (OS_MAILBOX* pMB). Table 13: OS_DeleteMB() parameter list Additional Information To keep the system fully dynamic. void Cleanup(void) { OS_DeleteMB(MBSerIn). OS_DeleteMB() Description Deletes a specified mailbox. It is the programmer's responsibility to: ● ● make sure that the program no longer uses the mailbox to be deleted make sure that the mailbox to be deleted actually exists (for example. it is essential that mailboxes can be created dynamically. } PPRTOS-3 69 . has been created first). Parameter Description pMB Pointer to the mailbox. This also means there has to be a way to delete a mailbox when it is no longer needed. Prototype void OS_DeleteMB (OS_MAILBOX* pMB). Table 12: OS_GetMessageCnt() parameter list Return value The number of messages in the mailbox. Parameter Description pMB Pointer to the mailbox.

IAR PowerPac™ RTOS 70 User Guide PPRTOS-3 .

when the message is written into the queue. 3 The retrieving function has to delete every message after processing it. Queues enable intertask communication with larger messages or with messages of various sizes. Both the number and size of queues is limited only by the amount of available written into a queue. There are three major differences between queues and mailboxes: 1 Queues accept messages of various size. The message size is not fixed. Retrieves a message from a queue.Queues Introduction In the preceding chapter. The queue behaves like a normal buffer. Retrieves a message from a queue. if one message is available. Deletes the last retrieved message in a queue. you can put something (called a message) in and retrieve it later. 2 Retrieving a message from the queue does not copy the message. Retrieves a message from a queue within a specified time. So a message that is put in first will be retrieved first. first out. This enhances performance because the data is copied only once. PPRTOS-3 71 . Queues work as FIFO: first in. if one message is available or returns without suspension. Returns the number of messages currently in a queue. Any data structure can be API functions Routine Description OS_Q_Create() OS_Q_Put() OS_Q_GetPtr() OS_Q_GetPtrCond() OS_Q_GetPtrTimed() OS_Q_Purge() OS_Q_Clear() OS_Q_GetMessageCnt() Table 1: Queues API Creates and initializes a message queue. but returns a pointer to the message and its size. Deletes all message in a queue. memory. intertask communication using mailboxes was described. Mailboxes can handle small messages with fixed data size only. OS_Q_Create() Description Creates and initializes a message queue. Stores a new message of given size in a queue. the message size is passed as a parameter. When putting a message into a queue. Basics A queue consists of a data buffer and a control structure that is managed by the real-time operating system.

const void* pSrc. Parameter Description pQ pSrc Size Pointer to a data structure of type OS_Q reserved for the management of the message queue. int Len) { return OS_Q_Put(&_MemoryQ. &_acMemQBuffer. static char _acMemQBuffer[MEMORY_QSIZE]. Len)). OS_UINT Size). sizeof(_acMemQBuffer)).Prototype void OS_Q_Create (OS_Q* pQ. Table 4: OS_Q_GetPtr() parameter list IAR PowerPac™ RTOS 72 User Guide PPRTOS-3 . Pointer to the message to store Size of the message to store Table 3: OS_Q_Put() parameter list Return value 0: Success. Table 2: OS_Q_Create() parameter list Example #define MEMORY_QSIZE 10000. This routine never suspends the calling task. Additional Information If the queue is full. Prototype int OS_Q_GetPtr (OS_Q* pQ. Example char MEMORY_Write(char* pData. static OS_Q _MemoryQ. Pointer to a memory area used as data buffer for the queue. message stored. void** ppData). void*pData. } OS_Q_GetPtr() Description Retrieves a message from a queue. OS_UINT Size). Parameter Description pQ ppData Pointer to the queue. } OS_Q_Put() Description Stores a new message of given size in a queue. pData. It may therefore also be called from an interrupt routine. void MEMORY_Init(void) { OS_Q_Create(&_MemoryQ. Size in bytes of the data buffer. Parameter Description pQ pData Size Pointer to a data structure of type OS_Q reserved for the management of the message queue. Prototype int OS_Q_Put (OS_Q* pQ. the function returns a value unequal to 0. 1: Message could not be stored (queue is full). Address of pointer to the message to be retrieved from queue.

it is not removed from the queue. This has to be done by a call of OS_Q_Purge() after the message was processed. This function never suspends the calling task. while (1) { Len = OS_Q_GetPtrCond(&_MemoryQ. It may therefore also be called from an interrupt routine. while (1) { Len = OS_Q_GetPtr(&_MemoryQ. The value of ppData is undefined. Additional Information If the queue is empty. If a message could be retrieved. Example static void MemoryTask(void) { char MemoryEvent. &pData). >0: Size of message that was retrieved from queue. it must not be called from an interrupt routine. Parameter Description pQ ppData Pointer to the queue. Memory_WritePacket(*(U32*)pData. Example static void MemoryTask(void) { char MemoryEvent. Len). The retrieved message is not removed from the queue. char* pData. Sets the pointer to the message that should be retrieved. pData+4. Sets the pointer ppData to the message that should be retrieved. if (Len > 0) { Memory_WritePacket(*(U32*)pData. int Len. OS_Q_Purge(&_MemoryQ). } else { DoSomethingElse(). } } } /* Check message */ /* Process message */ /* Delete message */ PPRTOS-3 73 . Address of pointer to the message to be retrieved from queue. Len). Because this routine might require a suspension. int Len. pData+4. OS_Q_Purge(&_MemoryQ). the function returns 0. &pData). Use OS_GetPtrCond() instead. Prototype int OS_Q_GetPtrCond (OS_Q* pQ. void** ppData). Table 5: OS_Q_GetPtrCond() parameter list Return value 0: No message available in queue. Additional Information If the queue is empty. char* pData. the calling task is suspended until the queue receives a new message. } } /* Get message */ /* Process message */ /* Delete message */ OS_Q_GetPtrCond() Description Retrieves a message from a queue. This has to be done by a call of OS_Q_Purge() after the message was processed. if one message is available.Queues Return value The size of the retrieved message.

OS_Q_GetPtrTimed() Description Retrieves a message from a queue within a specified time if a message is available. the task is suspended for the given timeout. Parameter Description pQ Pointer to the queue. Additional Information If the queue is empty. char* pData. } } } /* Check message */ /* Process message */ /* Delete message */ /* Timeout */ OS_Q_Purge() Description Deletes the last retrieved message in a queue. Address of pointer to the message to be retrieved from queue. void** ppData. Prototype void OS_Q_Purge (OS_Q* pQ). Sets the pointer ppData to the message that should be retrieved. Example static void MemoryTask(void) { char MemoryEvent. The task continues execution. Parameter Description pQ ppData Timeout Pointer to the queue. IAR PowerPac™ RTOS 74 User Guide PPRTOS-3 . int Len. if (Len > 0) { Memory_WritePacket(*(U32*)pData. &pData. after the message is processed. therefore valid values are 1 <= Timeout <= 215-1 = 0x7FFF = 32767 for 8/16-bit CPUs 1 <= Timeout <= 231-1 = 0x7FFFFFFF for 32-bit CPUs Table 6: OS_Q_GetPtrCond() parameter list Return value 0: No message available in queue. 10). Table 7: OS_Q_Purge() parameter list Additional Information This routine should be called by the task that retrieved the last message from the queue. OS_Q_Purge(&_MemoryQ). no message is retrieved. or after the timeout value has expired. according to the rules of the scheduler. >0: Size of message that was retrieved from queue. as soon as a message is available within the given timeout. } else { DoSomethingElse(). Prototype int OS_Q_GetPtrTimed (OS_Q* pQ. pData+4. The data type OS_TIME defaults to an integer. Maximum time in timer ticks until the requested message has to be available. while (1) { Len = OS_Q_GetPtrTimed(&_MemoryQ. Len). OS_TIME Timeout).

Queues

Example
static void MemoryTask(void) { char MemoryEvent; int Len; char* pData; while (1) { Len = OS_Q_GetPtr(&_MemoryQ, &pData); Memory_WritePacket(*(U32*)pData, pData+4, Len); OS_Q_Purge(&_MemoryQ); } } /* Get message */ /* Process message */ /* Delete message */

OS_Q_Clear()
Description
Deletes all message in a queue.

Prototype
void OS_Q_Clear (OS_Q* pQ);
Parameter Description

pQ

Pointer to the queue.

Table 8: OS_Q_Clear() parameter list

OS_Q_GetMessageCnt()
Description
Returns the number of messages currently in a queue.

Prototype
int OS_Q_GetMessageCnt (OS_Q* pQ);
Parameter Description

pQ

Pointer to the queue.

Table 9: OS_Q_GetMessageCnt() parameter list

Return value
The number of messages in the queue.

PPRTOS-3

75

IAR PowerPac™ RTOS

76

User Guide

PPRTOS-3

Task Events
Introduction
Task events are another way of communication between tasks. In contrast to semaphores and mailboxes, task events are messages to a single, specified recipient. In other words, a task event is sent to a specified task. The purpose of a task event is to enable a task to wait for a particular event (or for one of several events) to occur. This task can be kept inactive until the event is signaled by another task, a S/W timer or an interrupt handler. The event can consist of anything that the software has been made aware of in any way. For example, the change of an input signal, the expiration of a timer, a key press, the reception of a character, or a complete command. Every task has a 1-byte (8-bit) mask, which means that 8 different events can be signaled to and distinguished by every task. By calling OS_WaitEvent(), a task waits for one of the events specified as a bitmask. As soon as one of the events occurs, this task must be signaled by calling OS_SignalEvent(). The waiting task will then be put in the READY state immediately. It will be activated according to the rules of the scheduler as soon as it becomes the task with the highest priority of all the tasks in the READY state.

API functions
Routine Description

OS_WaitEvent() OS_WaitSingleEvent() OS_WaitEventTimed() OS_WaitSingleEventTimed() OS_SignalEvent() OS_GetEventsOccurred() OS_ClearEvents()
Table 1: Events API overview

Waits for one of the events specified in the bitmask and clears the event memory after an event occurs. Waits for one of the events specified as bitmask and clears only that event after it occurs. Waits for the specified events for a given time, and clears the event memory after an event occurs. Waits for the specified events for a given time; after an event occurs, only that event is cleared. Signals event(s) to a specified task. Returns a list of events that have occurred for a specified task. Returns the actual state of events and then clears the events of a specified task.

OS_WaitEvent()
Description
Waits for one of the events specified in the bitmask and clears the event memory after an event occurs.

Prototype
char OS_WaitEvent (char EventMask);
Parameter Description

EventMask

The events that the task will be waiting for.

Table 2: OS_WaitEvent() parameter list

Return value
All events that have actually occurred.

PPRTOS-3

77

Example OS_WaitEvent(3). /* Wait for event 1 or 2 to be signaled */ OS_WaitEventTimed() Description Waits for the specified events for a given time. Additional Information If none of the specified events are available. or an interrupt handler within the specified TimeOut time. a S/W timer. Parameter Description EventMask The events that the task will be waiting for. Any bit in the 8-bit event mask may enable the corresponding event. All unmasked events remain unchanged. The first of the specified events will wake the task if the event is signaled by another task. If no event is signaled. Maximum time in timer ticks until the events have to be signaled. OS_WaitSingleEvent() Description Waits for one of the events specified by the bitmask and clears only that event after it occurs. or an interrupt handler. The data type OS_TIME defaults to an integer. the task is suspended. the task is activated after the specified timeout and all actual events are returned and then cleared. 0 if no events were signaled in time.Additional Information If none of the specified events are signaled. Example OS_WaitSingleEvent(3). These events are signaled by another task. the task is suspended for the given time. the task is suspended. /* Wait for event 1 or 2 to be signaled */ For a further example. Any bit in the 8-bit event mask may enable the corresponding event. These events are signaled by another task. The first of the specified events will wake the task. see OS_SignalEvent(). Parameter Description EventMask Timeout The events that the task will be waiting for. Any bit in the 8-bit event mask may enable the corresponding event. The first of the specified events will wake the task. a S/W timer. Table 3: OS_WaitSingleEvent() parameter list Return value All masked events that have actually occurred. Prototype char OS_WaitEventTimed (char EventMask. and clears the event memory after an event occurs. Additional Information If none of the specified events are signaled. OS_TIME TimeOut). a S/W timer or an interrupt handler. IAR PowerPac™ RTOS 78 User Guide PPRTOS-3 . Prototype char OS_WaitSingleEvent (char EventMask). therefore valid values are 1 <= Timeout <= 215-1 = 0x7FFF = 32767 for 8/16-bit CPUs 1 <= Timeout <= 231-1 = 0x7FFFFFFF for 32-bit CPUs Table 4: OS_WaitEventTimed() parameter list Return value The events that have actually occurred within the specified time.

Maximum time in timer ticks until the events have to be signaled. Prototype void OS_SignalEvent (char Event. Prototype char OS_WaitSingleEventTimed (char EventMask. Additional Information If none of the specified events are available. Parameter Description Event The event(s) to signal: 1 means event 1 2 means event 2 4 means event 3 . All unmasked events remain unchanged. /* Wait for event 1 or 2 to be signaled within 10 ms */ OS_SignalEvent() Description Signals event(s) to a specified task. therefore valid values are 1 <= Timeout <= 215-1 = 0x7FFF = 32767 for 8/16-bit CPUs 1 <= Timeout <= 231-1 = 0x7FFFFFFF for 32-bit CPUs Table 5: OS_WaitSingleEventTimed() parameter list Return value The masked events that have actually occurred within the specified time. Multiple events can be signaled as the sum of the single events (for example. The data type OS_TIME defaults to an integer. OS_TASK* pTask). Any bit in the 8bit event mask may enable the corresponding event. the task is activated after the specified timeout and the function returns zero.. only that event is cleared. 0 if no masked events were signaled in time. 10).Task Events Example OS_WaitEventTimed(3. The first of the specified events will wake the task if the event is signaled by another task. Task that the events are sent to. pTask Table 6: OS_SignalEvent() parameter list Additional Information If the specified task is waiting for one of these events. 10). Parameter Description EventMask Timeout The events that the task will be waiting for.. PPRTOS-3 79 . after an event occurs. the task is suspended for the given time. 128 means event 8. OS_TIME TimeOut). 6 will signal events 2 & 3). /* Wait for event 1 or 2 to be signaled within 10 ms */ OS_WaitSingleEventTimed() Description Waits for the specified events for a given time. If no event is signaled. it will be put in the READY state and activated according to the rules of the scheduler. a S/W timer or an interrupt handler within the specified TimeOut time. Example OS_WaitSingleEventTimed(3.

Parameter Description pTask The task who's event mask is to be returned. Stack0). TCB1. Additional Information By calling this function. Table 7: OS_getEventsOccured() parameter list Return value The event mask of the events that have actually occurred. } /* Create Task0 */ If the task was only waiting for a key to be pressed. IAR PowerPac™ RTOS 80 User Guide PPRTOS-3 . /* Notify Task that key was pressed */ } void InitTask(void) { OS_CREATETASK(&TCB0. the actual events remain signaled. The task would then be deactivated until a key is pressed. as in this case. Task0. NULL means current task. /* Data area for tasks (task control blocks) */ void Task0(void) { OS_U8 MyEvent. 0. Stack1[64]. OS_GetMail() could simply be called. while(1) MyEvent = OS_WaitEvent(EVENT_KEYPRESSED | EVENT_SERIN) if (MyEvent & EVENT_KEYPRESSED) { /* handle key press */ } if (MyEvent & EVENT_SERIN) { /* Handle serial reception */ } } } void TimerKey(void) { /* More code to find out if key has been pressed */ OS_SignalEvent(EVENT_SERIN. Prototype char OS_GetEventsOccurred (OS_TASK* pTask). events are a good option. OS_ClearEvents() Description Returns the actual state of events and then clears the events of a specified task. The event memory is not cleared. /* Task stacks */ OS_TASK TCB0.Example The task that handles the serial input and the keyboard waits for a character to be received either via the keyboard (EVENT_KEYPRESSED) or serial interface (EVENT_SERIN): /* * Just a small demo for events */ #define EVENT_KEYPRESSED (1) #define EVENT_SERIN (2) OS_STACKPTR int Stack0[96]. This is one way for a task to find out which events have been signaled. OS_GetEventsOccurred() Description Returns a list of events that have occurred for a specified task. 100. &TCB0). The task is not suspended if no events are available. If the task has to handle multiple mailboxes.

NULL means current task.Task Events Prototype char OS_ClearEvents (OS_TASK* pTask). Table 8: OS_ClearEvents() parameter list Return value The events that were actually signaled before clearing. PPRTOS-3 81 . Parameter Description pTask The task who's event mask is to be returned.

IAR PowerPac™ RTOS 82 User Guide PPRTOS-3 .

the signalling function does not need to know which task is waiting for the event to occur. Compared to a task event. In contrast to task-events. Table 2: OS_EVENT_Create() parameter list Additional Information Before the event object can be used. the reception of a character. Waits for an event with timeout and resets the event after it occurs. if the event object was already created before the call of OS_EVENT_Create(). and then resets the event. Prototype void OS_EVENT_Create (OS_EVENT* pEvent) Parameter Description pEvent Pointer to an event object data structure. or an interrupt handler. OS_EVENT_Create(&HW_Event). it has to be created once by a call of OS_EVENT_Create(). Waits for an event and resets the event after it occurs. or resumes waiting tasks. Deletes the specified event object. Has to be called before the event object can be used. Returns the state of an event object. The purpose of an event object is to enable one or multiple tasks to wait for a particular event to occur. /* Create and initialize event object */ PPRTOS-3 83 . Example OS_EVENT _HW_Event. OS_EVENT_Create() Description Creates an event object and resets the event. the event is set in non-signaled state. event objects are standalone objects which are not owned by any task. or a complete command. a key press. On creation. Sets the event. a S/W timer. The debug version of IAR PowerPac RTOS checks whether the specified event object was already created and calls OS_Error() with error code OS_ERR_2USE_EVENTOBJ. The event can be anything that the software is made aware of in any way. Examples include the change of an input signal. Resets the event to unsignaled state. The tasks can be kept suspended until the event is set by another task. the expiration of a timer. if any. Sets the events. OS_EVENT_Create() must not be called for an event object which was already created before. and the list of waiting tasks is deleted. resumes waiting tasks.Event objects Introduction Event objects are another type of communication and synchronization objects. API functions Routine Description OS_EVENT_Create() OS_EVENT_Wait() OS_EVENT_WaitTimed() OS_EVENT_Set() OS_EVENT_Reset() OS_EVENT_Pulse() OS_EVENT_Get() OS_EVENT_Delete() Table 1: Event object API overview Creates an event object. Therefore.

which has to be created before the call of OS_EVENT_WaitTimed().OS_EVENT_Wait() Description Waits for an event and suspends the calling task as long as the event is not signaled. 1: The event was not signaled and a timeout occurred. Important This function may not be called from within an interrupt handler or software timer. The debug version of IAR PowerPac RTOS will check whether pEvent addresses a valid event object and will call OS_Error() with error code OS_ERR_EVENT_INVALID in case of an error. Maximum time in timer ticks until the event have to be signaled. OS_TIME Timeout) Parameter Description pEvent Timeout Pointer to the event object that the task will be waiting for. Prototype char OS_EVENT_WaitTimed (OS_EVENT* pEvent. IAR PowerPac™ RTOS 84 User Guide PPRTOS-3 . the calling task is suspended until the event object becomes signaled. the calling task is suspended until the event object becomes signaled or the timeout time has expired. /* Wait for event object */ OS_EVENT_WaitTimed() Description Waits for an event and suspends the calling task for a specified time as long as the event is not signaled. pEvent has to address an existing event object. The data type OS_TIME defaults to an integer. the event was signaled within the specified time. Additional Information If the specified event object is already set. the calling task resets the event and continues operation. Prototype void OS_EVENT_Wait (OS_EVENT* pEvent) Parameter Description pEvent Pointer to the event object that the task will be waiting for. the calling task resets the event and continues operation. Example OS_EVENT_Wait(&_HW_Event). Important This function may not be called from within an interrupt handler or software timer. Table 3: OS_EVENT_Wait() parameter list Additional Information If the specified event object is already set. The debug version of IAR PowerPac RTOS will check whether pEvent addresses a valid event object and will call OS_Error() with error code OS_ERR_EVENT_INVALID in case of an error. If the specified event object is not set. pEvent has to address an existing event object. therefore valid values are 1 <= Timeout <= 215-1 = 0x7FFF = 32767 for 8/16-bit CPUs 1 <= Timeout <= 231-1 = 0x7FFFFFFF for 32-bit CPUs Table 4: OS_EVENT_Wait() parameter list Return value 0: Success. which has to be created before the call of OS_EVENT_Wait(). If the specified event object is not set.

all waiting tasks are resumed and the event object is not set to the signaled state. Table 5: OS_EVENT_Set() parameter list Additional Information If no tasks are waiting at the event object. while (1) { OS_Delay (40). /********************************************************************/ /****** HW module ***************************************************/ OS_STACKPTR int _StackHW[128]. If at least one task is already waiting at the event object.. void HW_Init(void). send broadcast to waiting tasks */ HW_Free(). The debug version of IAR PowerPac RTOS will check whether pEvent addresses a valid event object and will call OS_Error() with error code OS_ERR_EVENT_INVALID in case of an error.. } else { /* event was not signaled within tim out time. /* Task stack /* Task-control-block */ */ /****** local data **************************************************/ static OS_EVENT _HW_Event. #include "RTOS. } OS_EVENT_Set() Description Sets an event object to signaled state. Prototype void OS_EVENT_Set (OS_EVENT* pEvent) Parameter Description pEvent Pointer to the event object which should be set to signaled state. /* Init done. TCBLP. OS_TASK TCBHP. /****** local functions *********************************************/ static void _HWTask(void) { /* Initialize HW functionality */ OS_Delay(100). } } PPRTOS-3 85 . handle event */ . void HW_Free(void).Event objects Example if (OS_EVENT_WaitTimed(&_HW_Event. 10) == 0) { /* event was signaled within tim out time. StackLP[128].. which has to be created before a call of OS_EVENT_Create(). or resumes tasks which are waiting at the event object. handle timeout */ . Example The following example uses event objects to synchronize tasks to a hardware initialization function.h" OS_STACKPTR int StackHP[128]. OS_TASK _TCBHW. the event object is set to signaled state.. /* Task stacks */ /* Task-control-blocks */ /********************************************************************/ /****** Interface to HW module **************************************/ void HW_Wait(void). pEvent has to address an existing event object.

/* Initially disable interrupts OS_InitKern(). 25. StackLP). } } static void LPTask(void) { HW_Wait(). while (1) { OS_Delay (50). } */ */ */ */ */ */ OS_EVENT_Reset() Description Resets the specified event object to non-signaled state. "LP Task". which has been created before by a call of OS_EVENT_Create(). HPTask. StackHP). } void HW_Init(void) { OS_CREATETASK(&_TCBHW. /* Initialize OS OS_InitHW(). while (1) { OS_Delay (200). OS_Start(). } } /* Wait until HW module is set up */ /* Wait until HW module is set up */ /********************************************************************* * * main **********************************************************************/ int main(void) { OS_IncDI(). "HWTask". Table 6: OS_EVENT_Reset() parameter list Additional Information pEvent has to address an existing event object. 100. /* Initialize Hardware for OS HW_Init(). Prototype void OS_EVENT_Reset (OS_EVENT* pEvent) Parameter Description pEvent Pointer to the event object which should be reset to non-signaled state./****** global functions ********************************************/ void HW_Wait(void) { OS_EVENT_Wait(&_HW_Event). The debug version of IAR PowerPac RTOS will check whether pEvent addresses a valid event object and will call OS_Error() with the error code OS_ERR_EVENT_INVALID in case of an error. } void HW_Free(void) { OS_EVENT_Set(&_HW_Event). /* Initialize HW module /* You need to create at least one task before calling OS_Start() OS_CREATETASK(&TCBHP. } /********************************************************************/ /********************************************************************/ static void HPTask(void) { HW_Wait(). _StackHW). LPTask. "HP Task". 50. OS_SendString("Start project will start multitasking !\n"). IAR PowerPac™ RTOS 86 User Guide PPRTOS-3 . OS_EVENT_Create(&_HW_Event). OS_CREATETASK(&TCBLP. _HWTask. /* Start multitasking return 0.

Table 7: OS_EVENT_Pulse() parameter list Additional Information If any tasks are waiting at the event object. /* Reset event object to non-signaled state */ OS_EVENT_Pulse() Description Signals an event object and resumes waiting tasks. Prototype unsigned char OS_EVENT_Get (OS_EVENT* pEvent). It is your responsibility to make sure that: ● ● the program no longer uses the event object to be deleted the event object to be deleted actually exists (has been created first) PPRTOS-3 87 . the actual state of the event object remains unchanged. This also means there has to be a way to delete an event object when it is no longer needed. The event object remains un-signaled. Parameter Description pEvent Pointer to the event object which should be pulsed. Parameter Description pEvent Pointer to an event object which should be deleted. OS_EVENT_Get() Description Returns the state of an event object. The debug version of IAR PowerPac RTOS will check whether pEvent addresses a valid event object and will call OS_Error() with error code OS_ERR_EVENT_INVALID in case of an error. Prototype void OS_EVENT_Delete (OS_EVENT* pEvent). Table 8: OS_EVENT_Get() parameter list Return value 0: Event object is not set to signaled state 1: Event object is set to signaled state. Parameter Description pEvent Pointer to an event object who’s state should be examined. the tasks are resumed. which has been created before by a call of OS_EVENT_Create(). it is essential that event objects can be created dynamically. The debug version of IAR PowerPac RTOS will check whether pEvent addresses a valid event object and will call OS_Error() with the error code OS_ERR_EVENT_INVALID in case of an error. then resets the event object to non-signaled state. pEvent has to address an existing event object. Additional Information By calling this function. Table 9: OS_EVENT_Delete() parameter list Additional Information To keep the system fully dynamic. OS_EVENT_Delete() Description Deletes an event object. Prototype void OS_EVENT_Pulse (OS_EVENT* pEvent).Event objects Example OS_EVENT_Reset(&_HW_Event). The memory that has been used by the event object’s control structure can then be reused or reallocated.

IAR PowerPac™ RTOS 88 User Guide PPRTOS-3 . The debug version of IAR PowerPac RTOS will check whether pEvent addresses a valid event object and will call OS_Error() with error code OS_ERR_EVENT_INVALID in case of an error. which has been created before by a call of OS_EVENT_Create(). the debug version of IAR PowerPac RTOS calls OS_Error() with error code OS_ERR_EVENT_DELETE. pEvent has to address an existing event object. an event object should not be deleted in a normal application. To avoid any problems. If any task is waiting at the event object which is deleted.● no tasks are waiting at the event object when it is deleted.

Heap type memory management
Introduction
ANSI C offers some basic dynamic memory management functions. These are malloc, free, and realloc. Unfortunately, these routines are not thread-safe, unless a special thread-safe implementation exists in the compiler specific runtime libraries; they can only be used from one task or by multiple tasks if they are called sequentially. Therefore, IAR PowerPac RTOS offer task-safe variants of these routines. These variants have the same names as their ANSI counterparts, but are prefixed OS_; they are called OS_malloc(), OS_free(), OS_realloc(). The threadsafe variants that IAR PowerPac RTOS offers use the standard ANSI routines, but they guarantee that the calls are serialized using a resource semaphore. Heap type memory management is part of the IAR PowerPac RTOS libraries. It does not use any resources if it is not referenced by the application (that is, if the application does not use any memory management API function). Note that another aspect of these routines may still be a problem: the memory used for the functions (known as heap) may fragment. This can lead to a situation where the total amount of memory is sufficient, but there is not enough memory available in a single block to satisfy an allocation request.

API functions
API routine Description

OS_malloc() OS_free() OS_realloc()

Allocates a block of memory on the heap. Frees a block of memory previously allocated. Changes allocation size.

Table 1: Heap type memory manager API overview

PPRTOS-3

89

IAR PowerPac™ RTOS

90

User Guide

PPRTOS-3

Fixed block size memory pools
Introduction
Fixed block size memory pools contain a specific number of fixed-size blocks of memory. The location in memory of the pool, the size of each block, and the number of blocks are set at runtime by the application via a call to the OS_MEMF_CREATE() function. The advantage of fixed memory pools is that a block of memory can be allocated from within any task in a very short, determined period of time.

API functions
All API functions for fixed block size memory pools are prefixed OS_MEMF_.
API routine Description

Create / Delete
OS_MEMF_Create OS_MEMF_Delete Creates fixed block memory pool. Deletes fixed block memory pool.

Allocation
OS_MEMF_Alloc OS_MEMF_AllocTimed OS_MEMF_Request Allocates memory block from a given memory pool. Waits indefinitely if no block is available. Allocates memory block from a given memory pool. Waits no longer than given time limit if no block is available. Allocates block from a given memory pool, if available. Non-blocking.

Release
OS_MEMF_Release OS_MEMF_FreeBlock Releases memory block from a given memory pool. Releases memory block from any pool.

Info
OS_MEMF_GetNumFreeBlocks OS_MEMF_IsInPool OS_MEMF_GetMaxUsed OS_MEMF_GetNumBlocks OS_MEMF_GetBlockSize
Table 1: Memory pools API overview

Returns the number of available blocks in a pool. Returns !=0 if block is in memory pool. Returns the maximum number of blocks in a pool which have been used at a time. Returns the number of blocks in a pool. Returns the size of one block of a given pool.

OS_MEMF_Create()
Description
Creates and initializes a fixed block size memory pool.

Prototype
void OS_MEMF_Create (OS_MEMF* void* OS_U16 OS_U16
Parameter Description

pMEMF, pPool, NumBlocks, BlockSize);

pMEMF pPool

Pointer to the control data structure of memory pool. Pointer to memory to be used for the memory pool. Required size is: NumBlocks * (BlockSize + OS_MEMF_SIZEOF_BLOCKCONTROL).

Table 2: OS_MEMF_Create() parameter list

PPRTOS-3

91

This is a parameter which is used for debugging purpose only.Parameter Description NumBlocks BlockSize Pointer to memory to be used for the memory pool. Table 4: OS_MEMF_Alloc() parameter list Return value Pointer to the allocated block. It is guaranteed to be 0 in release or stack check builds. Before using any memory pool. It is not used in the majority of applications because there is no need to dynamically create/delete memory pools. IAR PowerPac™ RTOS 92 User Guide PPRTOS-3 . Its value has no effect on program execution. The debug version of libraries mark the memory pool as deleted. Table 2: OS_MEMF_Create() parameter list Additional Information OS_MEMF_SIZEOF_BLOCKCONTROL gives the number of bytes used for control and debug purposes. Prototype void OS_MEMF_Delete (OS_MEMF* pMEMF). Table 3: OS_MEMF_Delete() parameter list Additional Information This routine is provided for completeness. Parameter Description pMEMF Pointer to the control data structure of memory pool. it has to be created. The retrieved pointer must be delivered to OS_MEMF_Release() as a parameter to free the memory block. The release and stack check versions do not. The pointer must not be modified. the calling task is suspended until a memory block becomes available. memory pools are created at startup (before calling OS_Start()) and will never be deleted. the memory pool and memory blocks inside this pool can no longer be used. Required size is: NumBlocks * (BlockSize + OS_MEMF_SIZEOF_BLOCKCONTROL). OS_MEMF_Alloc() Description Requests allocation of a memory block. The debug version of libraries keeps track of created and deleted memory pools. but may be remembered in debug builds to allow runtime analysis of memory allocation problems. For most applications it is preferred to have a static memory pool design. Waits until a block of memory is available or the timeout has expired. Waits until a block of memory is available. Prototype void* OS_MEMF_Alloc (OS_MEMF* pMEMF. int Purpose). OS_MEMF_AllocTimed() Description Requests allocation of a memory block. Parameter Description pMEMF Purpose Pointer to the control data structure of memory pool. OS_MEMF_Delete() Description Deletes a fixed block size memory pool. After deletion. Size in bytes of one block. Additional Information If there is no free memory block in the pool.

void* pMemBlock). Pointer to the memory block to free. Continues execution in any case. Prototype void* OS_MEMF_Request (OS_MEMF* pMEMF. This is a parameter which is used for debugging purpose only. The pointer must not be modified. Table 6: OS_MEMF_Request() parameter list Return value !=NULL pointer to the allocated block NULL if no block has been allocated. int Purpose). The retrieved pointer must be delivered to OS_MEMF_Release() as parameter to free the memory block. specified in ticks. Its value has no effect on program execution. Parameter Description pMEMF Purpose Pointer to the control data structure of memory pool. but may be remembered in debug builds to allow runtime analysis of memory allocation problems. Table 7: OS_MEMF_Release() parameter list PPRTOS-3 93 . Its value has no effect on program execution. OS_MEMF_Request() Description Requests allocation of a memory block. the calling task is suspended until a memory block becomes available or the timeout has expired. Additional Information The calling task is never suspended by calling OS_MEMF_Request(). Table 5: OS_MEMF_Alloc_Timed() Return value !=NULL pointer to the allocated block NULL if no block has been allocated.Fixed block size memory pools Prototype void* OS_MEMF_AllocTimed (OS_MEMF* pMEMF. The pointer must not be modified. Time limit before timeout. int Timeout. The retrieved pointer must be delivered to OS_MEMF_Release() as parameter to free the memory block. This is a parameter which is used for debugging purpose only. Additional Information If there is no free memory block in the pool. Parameter Description pMEMF Timeout Purpose Pointer to the control data structure of memory pool. OS_MEMF_Release() Description Releases a memory block that was previously allocated. Parameter Description pMEMF pMemBlock Pointer to the control data structure of memory pool. int Purpose). 0 or negative values are permitted. but may be remembered in debug builds to allow runtime analysis of memory allocation problems. Prototype void OS_MEMF_Release (OS_MEMF* pMEMF.

IAR PowerPac RTOS itself will find the associated memory pool. Parameter Description pMEMF Pointer to the control data structure of memory pool. OS_MEMF_GetBlockSize() Description Information routine to examine the size of one memory block in the pool. OS_MEMF_GetNumBlocks() Description Information routine to examine the total number of available memory blocks in the pool. The memory pool does not need to be denoted. This is the value that was given as parameter during creation of the memory pool. it is activated according to the rules of the scheduler. IAR PowerPac™ RTOS 94 User Guide PPRTOS-3 . If any task is waiting for a fixed memory block. Table 10: OS_MEMF_GetBlockSize() parameter list Return value Size in bytes of one memory block in the specified memory pool. The memory block becomes available for other tasks waiting for a memory block from the pool. The pointer must not be modified between allocation and release. Prototype void OS_MEMF_FreeBlock (void* pMemBlock). it is activated according to the rules of the scheduler. It has the advantage that only one parameter is needed. Table 9: OS_MEMF_GetNumBlocks() parameter list Return value Returns the number of blocks in the specified memory pool. Prototype int OS_MEMF_GetBlockSize (OS_MEMF* pMEMF). This is the value of the parameter when the memory pool was created. OS_MEMF_GetNumFreeBlocks() Description Information routine to examine the number of free memory blocks in the pool. This function may be used instead of OS_MEMF_Release(). If any task is waiting for a fixed memory block. OS_MEMF_FreeBlock() Description Releases a memory block that was previously allocated. Prototype int OS_MEMF_GetNumBlocks (OS_MEMF* pMEMF). The pointer must not be modified between allocation and release. Parameter Description pMEMF Pointer to the control data structure of memory pool.Additional Information The pMemBlock pointer has to be the one that was delivered from any retrieval function described above. The memory block becomes available for other tasks waiting for a memory block from the pool. Table 8: OS_MEMF_FreeBlock() parameter list Additional Information The pMemBlock pointer has to be the one that was delivered form any retrieval function described above. Parameter Description pMemBlock Pointer to the memory block to free.

1: Pointer belongs to the pool. Table 11: OS_MEMF_GetNumFreeBlocks() parameter list Return value The number of free blocks actually available in the specified memory pool. OS_MEMF_IsInPool() Description Information routine to examine whether a memory block reference pointer belongs to the specified memory pool. Pointer to a memory block that should be checked. OS_MEMF_GetMaxUsed() Description Information routine to examine the amount of memory blocks in the pool that were used concurrently since creation of the pool. Table 13: OS_MEMF_IsInPool() parameter list Return value 0: Pointer does not belong to memory pool. Table 12: OS_MEMF_GetMaxUsed() parameter list Return value Maximum number of blocks in the specified memory pool that were used concurrently since the pool was created.Fixed block size memory pools Prototype int OS_MEMF_GetNumFreeBlocks (OS_MEMF* pMEMF). Prototype char OS_MEMF_IsInPool (OS_MEMF* pMEMF. PPRTOS-3 95 . Parameter Description pMEMF Pointer to the control data structure of memory pool. Parameter Description pMEMF pMemBlock Pointer to the control data structure of memory pool. Parameter Description pMEMF Pointer to the control data structure of memory pool. void* pMemBlock). Prototype int OS_MEMF_GetMaxUsed (OS_MEMF* pMEMF).

IAR PowerPac™ RTOS 96 User Guide PPRTOS-3 .

If an overflow is detected. In a multitasking system. some processors use a specific stack area for interrupt service routines (called a hardware interrupt stack). see the CPU & Compiler Specifics manual of IAR PowerPac RTOS documentation. PPRTOS-3 97 . We recommend using OS_EnterIntStack() and OS_LeaveIntStack() even if there is currently no additional benefit for your specific CPU. also interrupt stack size in the debug version). INTERRUPT STACK To reduce stack size in a multitasking environment. see the CPU & Compiler Specifics manual of IAR PowerPac RTOS documentation. the debug and stack check builds of IAR PowerPac RTOS fill the stack with control characters when it is created and check these characters every time the task is deactivated. For details about interrupt stacks. and local variables. After transferring control to the IAR PowerPac RTOS scheduler by calling OS_Start(). a section of the memory that is not reserved for the stack will be overwritten. For details regarding required size of your system stack. For details. Refer to the CPU & Compiler Specifics manual of IAR PowerPac RTOS documentation for details on your processor's stack. a program uses the system stack. OS_Error() is called. In case the CPU already supports hardware interrupt stacks or if a separate interrupt stack is not supported at all. However. The minimum size of a task stack pretty much depends on the CPU and the compiler. If there is no interrupt stack. The stack needs to have a minimum size which is determined by the sum of the stack usage of the routines in the worstcase nesting. IAR PowerPac RTOS may support a separate stack for interrupts by calling the function OS_EnterIntStack() at beginning of an interrupt service routine and OS_LeaveIntStack() at its very end. The location and size of this stack is defined when creating the task. refer to the CPU & Compiler Specifics manual of IAR PowerPac RTOS documentation. because code that uses them might reduce stack size on another CPU or a new version of IAR PowerPac RTOS with support for an interrupt stack for your CPU. the system stack is used only when no task is executed for the following: ● ● IAR PowerPac RTOS scheduler IAR PowerPac RTOS software timers (and the callback). If the stack is too small. every task has to have its own stack. parameters. A “normal” single-task program needs exactly one stack. IAR PowerPac RTOS monitors the stack size (and. Note that defining a larger stack than necessary will waist memory. and calls the failure routine OS_Error() if it detects a stack overflow. except in cases where the CPU has a separate stack for interrupt functions. and a serious program failure is most likely to occur. Interrupt routines also use the stack to save the return address and flag registers. This is the same stack that a non-IAR PowerPac RTOS program for this CPU would use. you will have to add stack requirements of your interrupt service routines to each task stack.Stacks Introduction The stack is the memory area used for storing the return address of function calls. IAR PowerPac RTOS cannot reliably detect a stack overflow. as well as for temporary storage. To detect a stack overflow. Even if the CPU does not support a hardware interrupt stack. if available. these function calls are implemented as empty macros. TASK STACK Each IAR PowerPac RTOS task has a separate stack. SYSTEM STACK Before IAR PowerPac RTOS takes over control (before the call to OS_Start()).

OS_Delay(1000). Prototype int OS_GetStackBase (OS_TCB* pTask). printf("Addr Stack[1] %x". OS_Delay(1000). Table 2: OS_GetStackBase() parameter list Return value The pointer to the base address of the stack. NULL means current task. } OS_GetStackSize() Description Returns the size of a task stack. Prototype int OS_GetStackSize (OS_TCB* pTask). Additional Information This function is only available in the debug and stack check builds of IAR PowerPac RTOS. NULL means current task. Parameter Description pTask The task whose stack size is to be checked. OS_GetStackBase(&TCB[0]). OS_GetStackBase() Description Returns a pointer to the base of a task stack. OS_GetStackBase(&TCB[1]). because only these builds initialize the stack space used for the tasks. Parameter Description pTask The task whose stack base has to be returned. because only these builds initialize the stack space used for the tasks.API functions Routine Description OS_GetStackBase() OS_GetStackSize() OS_GetStackSpace() OS_GetStackUsed() Table 1: Stacks API overview Returns the base address of a task stack. Returns the size of a task stack. IAR PowerPac™ RTOS 98 User Guide PPRTOS-3 . Returns the unused portion of a task stack. Returns the used portion of a task stack. Additional Information This function is only available in the debug and stack check builds of IAR PowerPac RTOS. Example void CheckStackBase(void) { printf("Addr Stack[0] %x". Table 3: OS_GetStackSize() parameter list Return value The size of the task stack in bytes.

which returns the number of unused bytes on the stack. Prototype int OS_GetStackUsed (OS_TCB* pTask). because it can only detect modified bytes on the stack. Additional Information In most cases. because only these builds initialize the stack space used for the tasks. OS_GetStackSpace(&TCB[1]). you can reduce the size of this stack and vice versa. OS_GetStackSpace(&TCB[0]). } OS_GetStackSpace() Description Returns the unused portion of a task stack. Unfortunately. the stack size required by a task cannot be easily calculated. OS_Delay(1000). printf("Size Stack[1] %d".Stacks Example void CheckStackSize(void) { printf("Size Stack[0] %d". However. space used for register storage or local variables is not always modified. Table 4: OS_GetStackSpace() parameter list Return value The unused portion of the task stack in bytes. NULL means current task. Prototype int OS_GetStackSpace (OS_TCB* pTask). In most cases. OS_Delay(1000). Table 5: OS_GetStackUsed() parameter list Return value The used portion of the task stack in bytes. OS_GetStackSize(&TCB[0]). because it takes quite some time to calculate the worst-case nesting and the calculation itself is difficult. be generous with your stack space or use other means to verify that the allocated stack space is sufficient. This function is only available in the debug and stack check builds of IAR PowerPac RTOS. the required stack size can be calculated using the function OS_GetStackSpace(). Important This routine does not reliably detect the amount of stack space left. Example void CheckStackSpace(void) { printf("Unused Stack[0] %d". PPRTOS-3 99 . OS_Delay(1000). If there is a lot of space left. printf("Unused Stack[1] %d". Parameter Description pTask The task whose stack space is to be checked. this routine will detect the correct amount of stack bytes. NULL means current task. Parameter Description pTask The task whose stack space is to be checked. but in case of doubt. OS_GetStackSize(&TCB[1]). } OS_GetStackUsed() Description Returns the used portion of a task stack. OS_Delay(1000).

be generous with your stack space or use other means to verify that the allocated stack space is sufficient. Example void CheckStackUsed(void) { printf("Used Stack[0] %d". because it can only detect modified bytes on the stack. } IAR PowerPac™ RTOS 100 User Guide PPRTOS-3 . Important This routine does not reliably detect the amount of stack space used. If there is a lot of space left. the required stack size can be calculated using the function OS_GetStackUsed(). because it takes quite some time to calculate the worst-case nesting and the calculation itself is difficult. which returns the number of used bytes on the stack. because only these builds initialize the stack space used for the tasks. However. OS_GetStackUsed(&TCB[0]). Unfortunately. you can reduce the size of this stack and vice versa. this routine will detect the correct amount of stack bytes. space used for register storage or local variables is not always modified.Additional Information In most cases. the stack size required by a task cannot be easily calculated. OS_GetStackUsed(&TCB[1]). This function is only available in the debug and stack check builds of IAR PowerPac RTOS. but in case of doubt. In most cases. printf("Used Stack[1] %d". OS_Delay(1000). OS_Delay(1000).

Interrupts This chapter explains how to use interrupt service routines (ISRs) in cooperation with IAR PowerPac RTOS. the program returns to the highest-priority task in the READY state. The latency depends on various factors and differs even on the same computer system. typically up to 3 CPU cycles can be lost before the interrupt request has reached the CPU core. PPRTOS-3 101 . Pipeline fill Most modern CPUs are pipelined. register) is typically the worst case instruction. The CPU requires 15 clock cycles. They can respond very quickly to external events such as the status change on an input. Specific details for your CPU and compiler can be found in the CPU & Compiler specifics manual of the IAR PowerPac RTOS documentation. What are interrupts? Interrupts are interruptions of a program caused by hardware. or ISR. After the ISR is completed. (Push parameters and perm. the CPU saves its registers and executes a subroutine referred to as an interrupt service routine. The CPU will typically complete the current instruction.LR}. CAUSES OF INTERRUPT LATENCIES ● ● ● ● ● The first delay is typically in the hardware: The interrupt request signal needs to be synchronized to the CPU clock. Interrupts effectively allow events to be processed as they occur. This instruction can take a lot of cycles. ISRs are also nestable . It stores 13 32-bit registers on the stack. There are several good reasons for using interrupt routines. In an ARM7 system. modern CPUs (such as ARM) perform a mode switch. push-multiple. The memory system may require additional cycles for wait states. there are in most cases additional cycles required for memory access. Normal interrupts are maskable. a few extra cycles are required to refill the pipeline. Execution of an instruction happens in various stages of the pipeline. but we list a few of them. PC and flag registers) on the stack. Interrupt latency Interrupt latency is the time between an interrupt request and the execution of the first instruction of the interrupt service routine. reception or completion of transmission of a character via serial interface. they can occur at any time unless they are disabled with the CPU's “disable interrupt” instruction. on most systems. In general. which requires less CPU cycles than saving registers. These depend on the type of system used. The value that one is typically interested in is the worst case interrupt latency. The interrupt latency is the sum of a lot of different smaller delays explained below.they can be recognized and executed within other ISRs. divide. the CPU performs a mode switch or pushes registers (typically. After the current instruction is completed. Because the mode switch has flushed the pipeline. or memory-copy instructions are the instructions which require most clock cycles. Depending on the synchronization logic. the expiration of a hardware timer. the instruction STMDB SP!. or other types of events. An instruction is executed when it has reached its final stage of the pipeline.{R0-R11. Every computer system has an interrupt latency. When an interrupt occurs. On top of the cycles required by the CPU. ADDITIONAL CAUSES FOR INTERRUPT LATENCIES There can be additional causes for interrupt latencies.

reading multiple words from memory. If this line is marked as dirty. Interrupts can never be interrupted by other interrupts of the same or lower level of priority. Details are explained in the CPU/MCU/SOC manuals and the CPU & Compiler Specifics manual of IAR PowerPac RTOS. which interrupts are considered high and which interrupts are considered low priority. Interrupt routines. it needs to be written back to main memory. the interrupt with higher priority takes precedence and its ISR is executed first. effectively increasing interrupt latencies for all interrupts. Latencies caused by cache write back. but in a lot of cases a complete line fill needs to be performed. In this case. An RTOS also needs to temporarily disable the interrupts which can call API-functions of the RTOS. a system using IAR PowerPac RTOS will have the same worst-case interrupt latency for high priority interrupts as a system running without IAR PowerPac RTOS. In general. this takes a few instructions. Of course. causing an additional delay. Different priorities have two effects: ● ● If different interrupts occur simultaneously. On most systems. Using IAR PowerPac RTOS. one interrupt disables further interrupts. translation table walks caused by the TLB not containing translations for the handler and/or the data it accesses can increase interrupt latency significantly. some (like IAR PowerPac RTOS) disable only low-priority interrupts and do thereby not affect the latency of high priority interrupts. the FIQ is treated as “High priority interrupt”. A cache miss may cause a line to be replaced. these may not contain the required data. latencies. Even if the interrupts are re-enabled in the ISR. the differences are: Low-priority interrupts ● ● May call IAR PowerPac RTOS API functions Latencies caused by IAR PowerPac RTOS High-priority interrupts ● ● May not call IAR PowerPac RTOS API functions No Latencies caused by IAR PowerPac RTOS (Zero latency) Example of different interrupt priority levels ARM CPUs support normal interrupts (IRQ) and fast interrupt (FIQ). In real-time interrupt handlers. What we mean when we say “Zero interrupt latency” is that the latency of high-priority interrupts is not affected by the RTOS. Application program. especially as they involve potentially slow main memory accesses.● ● ● ● ● ● Latencies caused by cache line fill. the application program can cause additional latencies by disabling interrupts. How many different levels of interrupts there are depend on the CPU and the interrupt controller. IAR PowerPac RTOS distinguishes two different levels of interrupts: High / Low priority interrupts. Latencies caused by MMU translation table walks. Zero interrupt latency Zero interrupt latency in the strict sense is not possible as explained above. Some RTOSes disable all interrupts. not only the required data is loaded from memory. The IAR PowerPac RTOS port specific documentation explains where “the line is drawn”. Translation table walks can take a considerable amount of time. RTOS (Real-time Operating system). latency. causing add. but of course causes add. IAR PowerPac™ RTOS 102 User Guide PPRTOS-3 . High / low priority interrupts Most CPUs support interrupts with different priorities. This can make sense in some situations. If the memory system has one or multiple caches.

IAR PowerPac RTOS has to be informed that an interrupt service routine is running. Interrupt handlers must restore the environment of a task completely. Restores the status of the interrupt flag. Unconditionally enables Interrupt. Routine Description OS_CallISR() OS_CallNestableISR() OS_EnterInterrupt() OS_LeaveInterrupt() OS_IncDI() OS_DecRI() OS_DI() OS_EI() OS_RestoreI() Table 1: Interrupt API overview Interrupt entry function. PPRTOS-3 103 . These rules apply to both single-task programming as well as to multitask programming using IAR PowerPac RTOS. the ISR would continue as soon as the interrupted task became the current task again. Interrupt handlers have to be finished quickly. This leads us to the following rule: ● Interrupt functions that re-enable interrupts or use any IAR PowerPac RTOS function need to call OS_EnterInterrupt() at the beginning. so the ISR has to make sure that all registers modified during interrupt execution are saved at the beginning and restored at the end of the interrupt routine. ADDITIONAL RULES FOR PREEMPTIVE MULTITASKING A preemptive multitasking system like IAR PowerPac RTOS needs to know if the program that is executing is part of the current task or an interrupt handler. If a task switch were to occur during the execution of an ISR.Interrupts Rules for interrupt handlers GENERAL RULES There are some general rules for interrupt handlers. This environment normally consists of the registers only. based on the interrupt disable counter. API functions Before calling any IAR PowerPac RTOS function from within an ISR. Informs IAR PowerPac RTOS that the end of the interrupt routine has been reached. the task switch then occurs in the routine OS_LeaveInterrupt(). Does not change the interrupt disable counter. It should not wait in any form or perform a polling operation. If you debug an interrupt routine. before executing any other command. The end of the ISR is executed at a later point. Disables interrupts. If a higher priority task is made ready by the ISR. This has proven to be the most efficient way of initiating a task switch from within an interrupt service routine. This is because IAR PowerPac RTOS cannot perform a task switch during the execution of an interrupt handler. call either OS_LeaveInterrupt() or OS_LeaveInterruptNoSwitch() as last command. executes task switching within ISR. and before they return. Interrupt entry function supporting nestable interrupts. Intensive calculations should be kept out of interrupt handlers. it can only do so at the end of an interrupt handler. ● ● Interrupt handlers preserve all registers. Increments the interrupt disable counter (OS_DICnt) and disables interrupts. when the interrupted task is made ready again. do not be confused. This is not a problem for interrupt handlers that do not allow further interruptions (which do not enable interrupts) and that do not call any IAR PowerPac RTOS functions. An interrupt handler should only be used for storing a received value or to trigger an operation in the regular program (task). Decrements the counter and enables interrupts if the counter reaches 0. Informs IAR PowerPac RTOS that interrupt code is executing.

OS_CallISR() sets the interrupt priority of the CPU to the user definable ’fast’ interrupt priority level. OS_CallNestableISR() does not alter the interrupt priority of the CPU. Example #pragma interrupt void OS_ISR_Tick(void) { OS_CallISR(_IsrTickHandler). Prototype void OS_CallISR (void (*pRoutine)(void)). } OS_EnterInterrupt() Note:This function may not be available in all ports. Description Parameter pRoutine Pointer to an interrupt routine. OS_CallISR() has to be used to call an interrupt handler because OS_EnterInterrupt() / OS_LeaveInterrupt() may not be available. thus keeping all interrupts with higher priority enabled. Example #pragma interrupt void OS_ISR_Tick(void) { OS_CallNestableISR(_IsrTickHandler). Note:For some specific CPUs. Description Parameter pRoutine Pointer to an interrupt routine. Refer to the CPU specific manual. when the corresponding interrupt should not be interrupted by another IAR PowerPac RTOS interrupt. } OS_CallNestableISR() Description Entry function for use in an IAR PowerPac RTOS interrupt handler. Note:For some specific CPUs OS_CallNestableISR() has to be used to call an interrupt handler because OS_EnterNestableInterrupt() / OS_LeaveNestableInterrupt() may not be available. OS_LeaveNestableInterrupt() Table 1: Interrupt API overview OS_CallISR() Description Entry function for use in an IAR PowerPac RTOS interrupt handler. IAR PowerPac™ RTOS 104 User Guide PPRTOS-3 . Prototype void OS_CallNestableISR (void (*pRoutine)(void)). Nestable interrupts enabled. Table 2: OS_CallISR() parameter list Additional Information OS_CallISR() can be used as an entry function in an IAR PowerPac RTOS interrupt handler. thus disabling further task switches. Disables further interrupts. Fast interrupts are not disabled. Table 3: OS_CallNestableISR() parameter list Additional Information OS_CallNestableISR() can be used as an entry function in an IAR PowerPac RTOS interrupt handler. thus locking any other IAR PowerPac RTOS interrupt.Routine Description OS_EnterNestableInterrupt() Re-enables interrupts and increments the IAR PowerPac RTOS internal critical region counter. Nestable interrupts disabled. when interruption by higher prioritized IAR PowerPac RTOS interrupts should be allowed. Refer to the CPU specific manual.

/* Any functionality could be here */ OS_LeaveInterrupt(). it: ● ● disables task switches keeps interrupts in internal routines disabled.Interrupts Description Informs IAR PowerPac RTOS that interrupt code is executing. It must be used with either OS_LeaveInterrupt() or OS_LeaveInterruptNoSwitch() as the last function called.&Task). EXAMPLE USING OS_ENTERINTERRUPT()/ OS_LEAVEINTERRUPT() Interrupt routine using OS_EnterInterrupt()/OS_LeaveInterrupt(): __interrupt void ISR_Timer(void) { OS_EnterInterrupt(). executes task switching within ISR. it is not executed from within the ISR. This will be the next call of an IAR PowerPac RTOS function or the scheduler interrupt if the program is not in a critical region. OS_LeaveInterrupt() Note:This function may not be available in all ports. Prototype void OS_LeaveInterruptNoSwitch (void). Additional Information If OS_LeaveInterrupt() is used. Additional Information If OS_LeaveInterruptNoSwitch() is used. } OS_LeaveInterruptNoSwitch() Description Informs IAR PowerPac RTOS that the end of the interrupt routine has been reached but does not execute task switching within ISR. Description Informs IAR PowerPac RTOS that the end of the interrupt routine has been reached. it should be the first function to be called in the interrupt handler. it should be the last function to be called in the interrupt handler. If the interrupt has caused a task switch. OS_SignalEvent(1. but at the next possible occasion. it will be executed (unless the program which was interrupted was in a critical region). EXAMPLE USING OS_ENTERINTERRUPT()/ OS_LEAVEINTERRUPT() Interrupt routine using OS_EnterInterrupt()/OS_LeaveInterrupt(): PPRTOS-3 105 . Prototype void OS_EnterInterrupt (void). Additional Information If OS_EnterInterrupt() is used. The use of this function has the following effects. it should be the last function to be called in the interrupt handler. Prototype void OS_LeaveInterrupt (void). If the interrupt has caused a task switch.

the interrupts have to be temporarily disabled: Bad example: volatile long lvar. OS_IncDI() / OS_DecRI() The following functions are actually macros defined in RTOS. In certain sections of the program. use OS_IncDI() and OS_DecRI(). then OS_DecRI(). you could also use the pair OS_DI() and OS_RestoreI(). They have the disadvantage that they do not work with routines because the status of OS_DICnt is not actually changed. but are macros in reality). void routine (void) { lvar ++. maskable interrupts are normally enabled. lvar ++. it can be necessary to disable interrupts for short periods of time to make a section of the program an atomic operation that cannot be interrupted. } OS_IncDI() increments the interrupt disable counter which is used for the entire OS and is therefore consistent with the rest of the program in that any routine can be called and the interrupts will not be switched on before the matching OS_DecRI() has been executed. } Enabling / disabling interrupts from C During the execution of a task.&Task). } The problem with disabling and re-enabling interrupts is that functions that disable/enable the interrupt cannot be nested. they only look like functions. you may also safely use the compiler-provided intrinsics to disable interrupts. As long as you only call IAR PowerPac RTOS functions with interrupts enabled. Increments the interrupt disable counter (OS_DICnt) and disables interrupts. OS_DecRI(). If you do not use these recommended IAR PowerPac RTOS functions. These functions can still be used. as in the example above. and they should therefore be used with great care. OS_IncDI() Short for Increment and Disable Interrupts. Example volatile long lvar.__interrupt void ISR_Timer(void) { OS_EnterInterrupt(). These are a bit more efficient because the interrupt disable counter OS_DICnt is not modified twice. because this could lead to long interrupt latency times (the longer interrupts are disabled. but it is recommended to use the functions that IAR PowerPac RTOS offers (to be precise. OS_SignalEvent(1. We recommend disabling interrupts only for short periods of time. In case of doubt. An example would be the access to a global volatile variable of type long on an 8/16-bit CPU. so they execute very quickly and are very efficient./* Any functionality could be here */ OS_LeaveInterrupt(). Decrements the counter and enables interrupts if the counter reaches 0. however. Your C compiler offers two intrinsic functions for enabling and disabling interrupts. you should not call routines when interrupts are disabled. you may run into a problem if routines which require a portion of the code to run with disabled interrupts are nested or call an OS routine. IAR PowerPac™ RTOS 106 User Guide PPRTOS-3 . if possible. the higher the interrupt latency). Also. If you need to disable interrupts for a short moment only where no routine is called. To make sure that the value does not change between the two or more accesses that are needed. It is important that they are used as a pair: first OS_IncDI(). but only checked once. void routine (void) { OS_IncDI().h. OS_DecRI() Short for Decrement and Restore Interrupts.

if (--OS_DICnt==0) OS_EI(). } { OS_ASSERT_DICnt(). void routine (void) { OS_DI(). based on the interrupt disable counter. OS_DI(). OS_DICnt++. These are known as nested interrupts. OS_EI() Short for Enable Interrupts. because it does not take the interrupt disable counter into account. if (OS_DICnt==0) OS_EI(). Example volatile long lvar. } Definitions of interrupt control macros (in RTOS.h) #define OS_IncDI() #define OS_DecRI() #define OS_RestoreI() { OS_ASSERT_DICnt(). Re-enabling interrupts in an interrupt handler allows the execution of further interrupts with equal or higher priority than that of the current interrupt. } Nesting interrupt routines By default. } { OS_ASSERT_DICnt(). Refrain from using this function directly unless you are sure that the interrupt enable count has the value zero. Restores the status of the interrupt flag.Interrupts OS_DI() / OS_EI() / OS_RestoreI() OS_DI() Short for Disable Interrupts. Disables interrupts. lvar++. you may re-enable interrupts inside an ISR by using OS_EnterNestableInterrupt() and OS_LeaveNestableInterrupt() within the interrupt handler. OS_RestoreI() Short for Restore Interrupts. interrupts are disabled in an ISR because the CPU disables interrupts with the execution of the interrupt handler. illustrated in the diagram below: Task ISR 1 ISR 2 ISR 3 Interrupt 1 Interrupt 2 Interrupt 3 Time For applications requiring short interrupt latency. OS_RestoreI(). Does not change the interrupt disable counter. PPRTOS-3 107 .

NMIs should be used with great care and may under no circumstances call any IAR PowerPac RTOS routines. IAR PowerPac RTOS needs to know that another ISR is still active and that it may not perform a task switch. OS_LeaveNestableInterrupt() Note:This function may not be available in all ports. As it is important that IAR PowerPac RTOS keeps track of the status of the interrupt enable/disable flag. thus disabling further task switches. OS_LeaveNestableInterrupt() disables interrupts right before ending the interrupt routine again. thus re-enabling task switches if the counter has reached zero again. Re-enabling interrupts will make it possible for an IAR PowerPac RTOS scheduler interrupt to shortly interrupt this ISR. Prototype void OS_LeaveNestableInterrupt (void). Description Disables further interrupts. the enabling and disabling of interrupts from within an ISR has to be done using the functions that IAR PowerPac RTOS offers for this purpose. Prototype void OS_EnterNestableInterrupt (void). meaning it can interrupt these atomic operations. Additional Information This function should be the first call inside an interrupt handler when nested interrupts are required. then decrements the IAR PowerPac RTOS internal critical region count. The function OS_EnterNestableInterrupt() is implemented as a macro and offers the same functionality as OS_EnterInterrupt() in combination with OS_DecRI(). Additional Information This function is the counterpart of OS_EnterNestableInterrupt(). but is more efficient. Description Re-enables interrupts and increments the IAR PowerPac RTOS internal critical region counter. In this case. The routine OS_EnterNestableInterrupt() enables interrupts within an ISR and prevents further task switches. IAR PowerPac™ RTOS 108 User Guide PPRTOS-3 . and has to be the last function call inside an interrupt handler when nested interrupts have earlier been enabled by OS_EnterNestableInterrupt(). Therefore. Example Refer to the example for OS_LeaveNestableInterrupt(). resulting in smaller and faster code. but is more efficient. resulting in smaller and faster code. thus restores the default condition. therefore it is not really recommended to enable interrupts within an interrupt handler. a non-maskable interrupt (NMI) cannot be disabled. However. OS_EnterNestableInterrupt() Note:This function may not be available in all ports. Non-maskable interrupts (NMIs) IAR PowerPac RTOS performs atomic operations by disabling interrupts. The function OS_LeaveNestableInterrupt() is implemented as a macro and offers the same functionality as OS_LeaveInterrupt() in combination with OS_IncDI().Nested interrupts can lead to problems that are difficult to track.

is incremented so that the routine can be nested. } */ OS_LeaveRegion() Description Indicates to the OS the end of a critical region. Using the macro indicates to IAR PowerPac RTOS the beginning of a critical region. A critical region counter (OS_RegionCnt). it will be performed right after the region is left. meaning that no task switch and no execution of software timers are allowed except in situations where the active task has to wait. the critical region ends. Additional Information OS_EnterRegion() is not actually a function but a macro. preemptions are switched off. A typical example for a critical region would be the execution of a program section that handles a time-critical hardware access (for example writing multiple bytes into an EEPROM where the bytes have to be written in a certain amount of time). Prototype void OS_EnterRegion (void). Effectively. OS_EnterRegion() Description Indicates to the OS the beginning of a critical region. so it does not hurt but does not do any good either to declare them as such. A critical region can be defined anywhere during the execution of a task. If this counter reaches 0 again. Critical regions can be nested. disabling interrupts will disable preemptive task switches. The counter will be decremented by a call to the routine OS_LeaveRegion(). API functions Routine Description OS_EnterRegion() OS_LeaveRegion() Table 1: Critical regions API overview Indicates to the OS the beginning of a critical region. which is 0 by default. /* this code will not be interrupted by the OS OS_LeaveRegion(). However. Example void SubRoutine(void) { OS_EnterRegion(). however. the scheduler will be switched on again after the outermost loop is left. Software timers and interrupts are executed as critical regions anyhow.Critical Regions Introduction Critical regions are program sections during which the scheduler is switched off. If a task switch becomes due during the execution of a critical region. or a section that writes data into global variables used by a different task and therefore needs to make sure the data is consistent. it behaves very much like a function but is much more efficient. Interrupts are still legal in a critical region. Indicates to the OS the end of a critical region. Interrupts are not disabled using OS_EnterRegion(). PPRTOS-3 109 .

Additional Information OS_LeaveRegion() is not actually a function but a macro. Usage of the macro indicates to IAR PowerPac RTOS the end of a critical region. A critical region counter (OS_RegionCnt). it behaves very much like a function but is much more efficient. IAR PowerPac™ RTOS 110 User Guide PPRTOS-3 . If this counter reaches 0 again.Prototype void OS_LeaveRegion (void). which is 0 by default. However. Example Refer to the example for OS_EnterRegion(). is decremented. the critical region ends.

so the difference between two measurements could theoretically be inaccurate by up to two ticks. Low-resolution measurement The system time variable OS_Time is measured in ticks. Each measurement can potentially be up to 1 tick less than the actual time. Introduction IAR PowerPac RTOS supports two basic types of run-time measurement which may be used for calculating the execution time of any section of your code. This means that the actual system time can potentially be more than what a low-resolution function will return (for example. and the first value is subtracted from the second to obtain the time it took for the code to execute. Low-resolution measurements use a time base of ticks.Time measurement IAR PowerPac RTOS supports 2 types of time measurement: ● ● Low resolution (using a time variable). PPRTOS-3 111 . The basic idea behind low-resolution measurement is quite simple: The system time is returned once before the section of code to be timed and once after. The length of a cycle depends on the timer clock frequency. The low-resolution functions OS_GetTime() and OS_GetTime32() are used for returning the current contents of this variable. because the system time must be measured twice. if an interrupt actually occurs at 1. Consider the following: with a normal tick of 1 ms. the system will still have measured only 1 tick as having elapsed).4 ticks. The term low-resolution is used because the time values returned are measured in completed ticks. or ms. The problem becomes even greater with runtime measurement. High resolution (using a hardware timer). while highresolution measurements are based on a time unit called a cycle. Both are explained in this chapter. or once every ms. the variable OS_Time is incremented with every tick-interrupt.

The following diagram illustrates how low-resolution measurement works. OS_GetTime32() Description Returns the current system time in ticks as a 32-bit value. Return value The system variable OS_Time as a 16. it is the lower 16 bits of the OS_Time variable. and the second call returns 5. The OS_Time variable is a 32-bit value. However with a tick of 1 ms. We can see that the section of code actually begins at 0. the first call to OS_GetTime() returns 0. IAR PowerPac™ RTOS 112 User Guide PPRTOS-3 . Therefore. In some cases. Prototype int OS_GetTime (void).5 ms and ends at 5. Returns the current system time in ticks as a 32-bit value. Additional Information This function returns the system time as a 16-bit value on 8/16-bit CPUs. API FUNCTIONS Routine Description OS_GetTime() OS_GetTime32() Returns the current system time in ticks.5) = 4.5 ms 5. low-resolution measurement may be fully sufficient for your needs. OS_GetTime() => 0 Code to be timed OS_GetTime() => 5 OS_Time 0. if the return value is 32-bit. which means that its actual execution time is (5.2 ms 0 ms 1 ms 2 ms 3 ms 4 ms 5 ms 6 ms For many applications. The measured execution time of the code would therefore result in (5 . Table 1: Low-resolution measurement API overview OS_GetTime() Description Returns the current system time in ticks. and as a 32-bit value on 32-bit CPUs.2 .0. it may be more desirable than high-resolution measurement due to its ease of use and faster computation time. If the return value is 16-bit. it is simply the entire contents of the OS_Time variable.7 ms.0) = 5 ms.or 32-bit integer value.2 ms.

7 ms.000.5 ms 5. Data structure All high-resolution routines take as parameter a pointer to a data structure of type OS_TIMING. This means that with each tick-interrupt. it is typically about 1 µs. OS_GetTime() => 0 Code to be timed OS_GetTime() => 5 OS_Time 0. it is typically more common to use the function OS_Timing_Getus().000 . The measured execution time of the code in this example would therefore be (52. While system resolution depends on the CPU used.700 µs. Look at the illustration below.000.000 cycles. Additional Information This function always returns the system time as a 32-bit value. which corresponds to 4. Although the function OS_Timing_GetCycles() may be used for returning the execution time in cycles as above.000 cycles.5.000 cycles (both values are kept track of internally). an internal count is kept of the number of cycles that have been completed. while the call to OS_Timing_End() calculates the ending value at 52. The number of cycles per tick is therefore (10 MHz / 1 kHz) = 10. which returns the value in microseconds (µs).000) = 47. the return value would be 4. In the above example. Instead of measuring the number of completed ticks at a given time. the timer restarts at 0 and counts up to 10. Return value The system variable OS_Time as a 32-bit integer value. defined as follows: #define OS_TIMING OS_U32 PPRTOS-3 113 .2 ms 0 ms 1 ms 2 ms 3 ms 4 ms 5 ms 6 ms The call to OS_Timing_Start() calculates the starting value at 5. which measures the execution time of the same code used in the low-resolution calculation. the return value is simply the entire contents of the OS_Time variable. Because the OS_Time variable is also a 32-bit value. making high-resolution measurement about 1000 times more accurate than lowresolution calculations. For this example. we assume that the CPU has a timer running at 10 MHz and is counting up.Time measurement Prototype U32 OS_GetTime32 (void). High-resolution measurement High-resolution measurement allows for fine-tuning of time measurement.

Parameter Description pCycle Pointer to a data structure of type OS_TIMING. Prototype void OS_Timing_End (OS_TIMING* pCycle). IAR PowerPac™ RTOS 114 User Guide PPRTOS-3 . Table 5: OS_Timing_Getus() parameter list Additional Information The execution time in microseconds (µs) as a 32-bit integer value. Returns the execution time of the code between OS_Timing_Start() and OS_Timing_End() in cycles. Marks the end of a code section to be timed. Returns the execution time of the code between OS_Timing_Start() and OS_Timing_End() in microseconds. Table 4: OS_TimingEnd() parameter list Additional Information This function must be used with OS_Timing_Start(). Prototype OS_U32 OS_Timing_Getus (OS_TIMING* pCycle). Prototype void OS_Timing_Start (OS_TIMING* pCycle). Table 2: High-resolution measurement API overview OS_TimingStart() Description Marks the beginning of a section of code to be timed. OS_Timing_GetCycles() Description Returns the execution time of the code between OS_Timing_Start() and OS_Timing_End() in cycles. OS_Timing_Getus() Description Returns the execution time of the code between OS_Timing_Start() and OS_Timing_End() in microseconds. Parameter Description pCycle Pointer to a data structure of type OS_TIMING. OS_TimingEnd() Description Marks the end of a section of code to be timed. Table 3: OS_TimingStart() parameter list Additional Information This function must be used with OS_Timing_End(). Parameter Description pCycle Pointer to a data structure of type OS_TIMING.API FUNCTIONS Routine Description OS_TimingStart() OS_TimingEnd() OS_Timing_Getus() OS_Timing_GetCycles() Marks the beginning of a code section to be timed.

} /* * Measure the execution time with hi resolution and return it in us */ OS_U32 BenchmarkHiRes(void) { OS_U32 t. tHi = BenchmarkHiRes(). Example The following sample demonstrates the use of low-resolution and high-resolution measurement to return the execution time of a section of code: #include "RTOS. /* Task-control-blocks */ volatile int Dummy. } /* Burn some time */ /* * Measure the execution time with low resolution and return it in ms (ticks) */ int BenchmarkLoRes(void) { int t. OS_Timing_Start(&t). return t. while (1) { tLo = BenchmarkLoRes(). return OS_Timing_Getus(&t). PPRTOS-3 115 . /* Execute the user code to be benchmarked */ OS_Timing_End(&t).Time measurement Prototype OS_U32 OS_Timing_GetCycles (OS_TIMING* pCycle). t = OS_GetTime(). OS_U32 tHi. Dummy++). char ac[80]. /* Task stacks */ OS_TASK TCB. /* Execute the user code to be benchmarked */ t = OS_GetTime() .t. Dummy < 11000. Additional Information Cycle length depends on the timer clock frequency. UserCode().h> OS_STACKPTR int Stack[1000]. void UserCode(void) { for (Dummy=0.H" #include <stdio. UserCode(). Table 6: OS_Timing_GetCycles() parameter list Return value The execution time in cycles as a 32-bit integer. } void Task(void) { int tLo. Parameter Description pCycle Pointer to a data structure of type OS_TIMING.

"HP Task". "HiRes: %d us\n". sprintf(ac. /* Start multitasking } */ */ */ */ The output of the sample is as follows: LoRes: HiRes: LoRes: HiRes: LoRes: 7 ms 6641 us 7 ms 6641 us 6 ms IAR PowerPac™ RTOS 116 User Guide PPRTOS-3 .sprintf(ac. OS_Start(). } } /********************************************************** * * main * **********************************************************/ void main(void) { OS_InitKern(). OS_SendString(ac). tLo). /* Initialize OS OS_InitHW(). /* Initialize Hardware for OS /* You need to create at least one task here ! OS_CREATETASK(&TCB. Task. tHi). Stack). OS_SendString(ac). "LoRes: %d ms\n". 100.

OS_TimeDex Basically. as only the documented API functions are guaranteed to remain unchanged in future versions of IAR PowerPac RTOS. These variables are accessible and are not declared constant. the task list and timer list will be checked for a task or timer to activate. Additional Information The time variable has a resolution of one time unit. Introduction Note:Do not change the value of any system variables.System variables The system variables are described here for a deeper understanding of how the OS works and to make debugging easier. for internal use only.OS_TimeDex)) >= 0. PPRTOS-3 117 . If ((int)(OS_Time . but they should only be altered by functions of IAR PowerPac RTOS. Important Do not alter any system variables. Your application should not rely on any of the internal variables. Prototype extern volatile OS_I32 OS_Time. which is normally 1/1000 seconds (1 ms) and is normally the time between two successive calls to the IAR PowerPac RTOS interrupt handler. Instead of accessing this variable directly. Time variables OS_Time Description This is the time variable which contains the current system time in ticks (usually equivalent to ms). After activation. OS_TimeDex will be assigned the time stamp of the next task or timer to be activated. some of these variables can be very useful. OS internal variables and data-structures IAR PowerPac RTOS internal variables are not explained here as they are in no way required to use IAR PowerPac RTOS. especially the time variables. use OS_GetTime() or OS_GetTime32() as explained in the Chapter Time measurement on page 111. However. Contains the time at which the next task switch or timer activation is due.

IAR PowerPac™ RTOS 118 User Guide PPRTOS-3 .

generated by a hardware timer and all options available for it. but it can not handle situations where the interrupt rate is different from the tick rate. Introduction Typically a hardware timer generates periodic interrupts used as a time base for the OS. code size and execution speed. Generating timer interrupts The hardware timer is normally initialized in the OS_InitHW() function which is delivered with the BSP. OS_EnterInterrupt(). Extended IAR PowerPac RTOS tick handler. one of these need to be called. The BSP also includes the interrupt handler which is called by the hardware timer interrupt. it has to be called from an interrupt handler. Tick handler The interrupt service routine used as time base needs to call a tick handler. IAR PowerPac RTOS offers tick handlers with different functionality as well as a way to call a hook function from within the system tick handler. Configures the extended IAR PowerPac RTOS tick handler. The interrupt service routine then calls one of the tick handlers of the OS. or OS_EnterNestableInterrupt() has to be called. OS_TICK_Handle() Description The default IAR PowerPac RTOS timer tick handler which is typically called by the hardware timer interrupt handler.System tick This chapter explains the concept of the system tick.6 interrupts per tick. Prototype void OS_TICK_Handle ( void ). before calling the IAR PowerPac RTOS tick handler PPRTOS-3 119 . which increments the tick count by one every time it is called. This tick handler is small and efficient. OS_TICK_HandleEx() is capable of handling even fractional interrupt rates. This interrupt handler has to call one of the IAR PowerPac RTOS system tick handler functions which are explained in this chapter. API FUNCTIONS Routine Description OS_TICK_Handle() OS_TICK_HandleEx() OS_TICK_Config() Table 1: API functions Standard IAR PowerPac RTOS tick handler. such as 1. Most application use the standard tick handler OS_TICK_Handle(). The reason why there are different tick handlers is simple: They differ in capabilities. There are different tick handlers available. Additional Information The IAR PowerPac RTOS tick handler must not be called by the application.

OS_EnterInterrupt() or OS_EnterNestableInterrupt() has to be called before calling the IAR PowerPac RTOS tick handler. For other ratios. OS_LeaveNestableInterrupt(). before the IAR PowerPac RTOS timer is started. the ratio is defined by calling the OS_TICK_Config(). OS_TICK_HandleEx(). OS_LeaveNestableInterrupt(). It can be used in situations where the basic timer-interrupt interval (tick) is a multiple of 1 ms and the time values used as parameter for delays still should use 1 ms as the time base. Prototype void OS_TICK_Config ( unsigned FractPerInt. } Assuming the hardware timer runs at a frequency of 500 Hz. This should be done during OS_InitHW(). unsigned FractPerTick ). it has to be called from an interrupt handler. the IAR PowerPac RTOS tick handler configuration function OS_TICK_Config() should be called as demonstrated in the Example section of OS_TICK_Config(). Refer to OS_TICK_Config() on page 120 about how to configure OS_TICK_HandleEx(). Fractional value per tick. } OS_TICK_HandleEx() Description An alternate tick handler which may be used instead of the standard tick handler. thus interrupting the system every 2 ms. OS_TICK_HandleEx() needs to be used. OS_TICK_Config() Description Configures the tick to interrupt ratio. meaning one interrupt increments the tick count (OS_Time) by one. Table 2: OS_TICK_Config() parameter list Additional Information The “normal” tick handler OS_TICK_Handle() assumes a 1:1 ratio. Additional Information The IAR PowerPac RTOS tick handler must not be called by the application.Example /* Example of a timer interrupt handler */ /********************************************************************* * * OS_ISR_Tick */ __interrupt void OS_ISR_Tick(void) { OS_EnterNestableInterrupt(). IAR PowerPac™ RTOS 120 User Guide PPRTOS-3 . Prototype void OS_TICK_HandleEx ( void ). Parameter Description FractPerInt FractPerTick Fractional value per interrupt. Example /* Example of a timer interrupt handler using OS_HandleTickEx */ /********************************************************************* * * OS_ISR_Tick */ __interrupt void OS_ISR_Tick(void) { OS_EnterNestableInterrupt(). OS_TICK_Handle().

System tick

Tick frequency is 1kHz, meaning one 1 equals 1ms and interrupt frequency is 500Hz, meaning 1 interrupt every 2 ms. In this case parameters have the following values:
/********************************************************************* * * _ConfigTickHandler */ static void _ConfigTickHandler() { unsigned FractPerInt; unsigned FractPerTick; FractPerInt = 2; FractPerTick = 1; OS_TICK_Config(FractPerInt, FractPerTick); }

Note that fractional values are supported, such as tick is 1 ms, where an interrupt is generated every 1.6ms. This means that FractPerInt and FractPerTick are:
FractPerInt = 16; FractPerTick = 10;

or
FractPerInt = 8; FractPerTick = 5;

Hooking into the system tick
There are various situations in which it can be desirable to call a function from the tick handler. Some examples are:
● ● ●

Watchdog update Periodic status check Periodic I/O update

The same functionality can be achieved with a high-priority task or a software timer with 1 tick period time.

Advantage of using a hook function
Using a hook function is much faster than performing a task switch or activating a software timer, because the hook function is directly called from the IAR PowerPac RTOS timer interrupt handler and does not cause a context switch.

API FUNCTIONS
Routine Description

OS_TICK_AddHook() OS_TICK_RemoveHook()
Table 3: API functions

Adds a tick hook handler. Removes a tick hook handler.

OS_TICK_AddHook()
Description
Adds a tick hook handler.

Prototype
void OS_TICK_AddHook ( OS_TICK_HOOK * pHook, OS_TICK_HOOK_ROUTINE * pfUser );
Parameter Description

pHook pfUser

Pointer to a structure of OS_TICK_HOOK. Pointer to an OS_TICK_HOOK_ROUTINE function.

Table 4: OS_TICK_AddHook() parameter list

PPRTOS-3

121

Additional Information
The hook function is called directly from the interrupt handler. The function therefore should execute as fast as possible. The function called by the tick hook must not re-enable interrupts.

OS_TICK_RemoveHook()
Description
Removes a tick hook handler.

Prototype
void OS_TICK_RemoveHook ( OS_TICK_HOOK * pHook );
Parameter Description

pHook

Pointer to a structure of OS_TICK_HOOK.

Table 5: OS_TICK_RemoveHook() parameter list

Additional Information
The function may be called to dynamically remove a tick hook function which was installed by a call of OS_TICK_AddHook().

IAR PowerPac™ RTOS

122 User Guide

PPRTOS-3

Configuration of target system (BSP)
This chapter explains the target system specific parts of IAR PowerPac RTOS, also called BSP (board support package). If the system is up and running on your target system, there is no need to read this chapter.

Introduction
You do not have to configure anything to get started with IAR PowerPac RTOS. The start project supplied will execute on your system. The file RTOSINIT.c is provided in source code and can be modified to match your target hardware needs. It is compiled and linked with your application program.

Hardware-specific routines
Routine Description

OS_InitHW()

Initializes the hardware timer used for generating interrupts. IAR PowerPac RTOS needs a timer-interrupt to determine when to activate tasks that wait for the expiration of a delay, when to call a software timer, and to keep the time variable upto-date. The idle loop is always executed whenever no other task (and no interrupt service routine) is ready for execution. Reads the timestamp in cycles. Cycle length depends on the system. The IAR PowerPac RTOS timer-interrupt handler. When using a different timer, always check the specified interrupt vector.

OS_Idle() OS_GetTime_Cycles() OS_ISR_Tick()
Table 1: Hardware specific routines

Configuration defines
For most embedded systems, configuration is done by simply modifying the following defines, located at the top of the RTOSInit.c file:
Define Description

OS_FSYS

System frequency (in Hz). Example: 20000000 for 20MHz.

Table 2: Configuration defines overview

How to change settings
The only file which you may need to change is RTOSInit.c. This file contains all hardware-specific routines. The one exception is that some ports of IAR PowerPac RTOS require an additional interrupt vector table file (details can be found in the CPU & Compiler Specifics manual of IAR PowerPac RTOS documentation).

SETTING THE SYSTEM FREQUENCY OS_FSYS
Relevant defines:

PPRTOS-3

123

the basic time unit can be made 1 ms by using the configuration function OS_TICK_Config(). CHANGING THE TICK FREQUENCY Relevant defines: OS_FSYS As noted above. the value of the time variable OS_Time will no longer be equivalent to multiples of 1 ms. these modes may be used for saving power consumption. However. Different (lower or higher) interrupt rates are possible. The interrupt frequency is therefore normally 1 kHz. STOP / HALT / IDLE modes Most CPUs support power-saving STOP. Using these types of modes is one possible way to save power consumption during idle times. OS_FSYS defines the clock frequency of your system in Hz (times per second). you may modify the OS_Idle() routine. the basic time unit does not have to be 1 ms.c.c. it might just as well be 100 µs or 10 ms or any other value. USING A DIFFERENT TIMER TO GENERATE THE TICKINTERRUPTS FOR IAR POWERPAC RTOS Relevant routines: OS_ InitHW() IAR PowerPac RTOS usually generates 1 interrupt per ms. you must modify OS_InitHW() to initialize the appropriate timer. Refer to the CPU & Compiler Specific guide of IAR PowerPac RTOS documentation for details about your processor. or as long as other interrupts will activate tasks.OS_FSYS For most systems it should be sufficient to change the OS_FSYS define at the top of RTOSInit.c. If you have to use a different timer for your application. If you choose an interrupt frequency different from 1 kHz. IAR PowerPac™ RTOS 124 User Guide PPRTOS-3 . The value of OS_FSYS is used for calculating the desired reload counter value for the system timer for 1000 interrupts/sec. Refer to Tick handler on page 119 for detailed information. or tick. making the timer-interrupt. This is done by a timer initialized in the routine OS_InitHW(). Because 1 ms is an appropriate value for most applications. or IDLE modes. read the comments in RTOSInit. which is part of the hardware-dependant module RTOSInit. For details about initialization. IAR PowerPac RTOS usually generates 1 interrupt per ms. As long as the timer-interrupt will wake up the system with every IAR PowerPac RTOS tick. to switch the CPU to power-saving mode during idle times. normally equal to 1 ms. If required. HALT.

For each project configuration you have to explicitly enable the plug-in in the debugger section of the project options: The IAR PowerPac RTOS C-SPY plug-in is now available in debugging sessions and may be accessed from the main menu. PPRTOS-3 125 . Note that if you are not running a debugging session. If a certain part is not available. the IAR PowerPac RTOS C-SPY plug-in is not loaded during debugging. Overview During your debugging session. the IAR PowerPac RTOS menu is not available. Enabling the C-SPY plug-in module By default. the IAR PowerPac RTOS C-SPY plug-in is accessible from the IAR Embedded Workbench IDE main menu. From the menu you may activate the individual windows that provide IAR PowerPac RTOS related information. The amount of information available depends on the IAR PowerPac RTOS build used during debugging. the respective menu item is either greyed out or the window column shows a N/A. The sections below describe these individual windows.RTOS-aware debugging This chapter describes the IAR PowerPac RTOS C-SPY plug-in and its capabilities in greater detail.

The number of messages in a mailbox and the maximum number of messages as mailbox can hold. The event mask of a task. The buffer behaves like a normal buffer. and the available stack space. The message buffer address. you can put something (called a message) in and retrieve it later. this column displays the number of remaining time slices and the number of time slice reloads. waiting tasks etc. Table 4: Mailboxes window items IAR PowerPac™ RTOS 126 User Guide PPRTOS-3 . This window shows the mailboxes and provides information about the number of messages. this column displays the timeout value and in parentheses the point in time when the delay will be finished. as well as the value of the current stack bottom pointer. that is their address and name. The task status as a short text. The task control block address that uniquely identifies a task. It retrieves its information directly from the IAR PowerPac RTOS task list. If available. If a task is delayed. The list of tasks that are waiting for a mailbox. The number of task activations. If available.Task list The Task List window lists all current tasks. the task name is displayed here. The individual columns are described below: Column Description * Id Name Status Timeout Events Stack Info Activations Round Robin A green arrow points at the currently active task. Table 3: Task list window items Mailboxes A mailbox is a buffer that is managed by the real-time operating system. The size of an individual message in bytes. Column Description Id Messages Message size pBuffer Waiting tasks The mailbox address. If round robin scheduling is available. this column shows the amount of used stack space.

Shows whether the timer is active or not. Table 6: Resource Semaphores window items PPRTOS-3 127 . The time period the timer runs. Table 5: Timers window items Resource semaphores Resource semaphores are used to manage resources by avoiding conflicts caused by simultaneous use of a resource. This window provides information about available resources. Counts the number of semaphore uses. Column Description Id Hook Time Period Active The timer’s address.RTOS-aware debugging Timers A software timer is an object that calls a user-specified routine after a specified delay. when the timer finishes waiting. The address and name of the owner task. The time delay and the point in time. Lists the tasks (address and name) that are waiting at the semaphore. This window provides information about active software timers. Column Description Id Owner Use counter Waiting tasks The resource semaphore address. The function (address and name) that is called after the timeout.

or if they are longer than the default you may increase that value. the IAR PowerPac RTOS C-SPY plug-in imposes certain limits on the amount of information retrieved from the target.System information A running IAR PowerPac RTOS contains a number of system variables that are available for inspection. However. This window lists the most important ones. the settings are restored to their default values on plug-in reload. your changes are applied immediately and should become noticeable after the next window update. This dialog box allows you to tweak these limits in a certain range. After changing settings and clicking the OK button. IAR PowerPac™ RTOS 128 User Guide PPRTOS-3 . to avoid endless requests in case of false values in the target memory. Settings To be safe. for example when hitting the next breakpoint. for example if your task names are no longer than 32 characters you may set the Maximum string length to 32.

/* Avoid further task switches */ OS_DICnt =0. while (OS_Status). This routine is shipped as source code as part of the module OS_Error. Note:When modifying the OS_Error() routine. If IAR PowerPac RTOS detects a runtime error. The error code is passed to the function as parameter. after re-enabling interrupts. the first statement needs to be the disabling of scheduler via OS_EnterRegion(). /* Allow interrupts so we can communicate */ OS_EI(). PPRTOS-3 129 . If you look at the OS_Error() routine. you will see that it is more complicated than necessary. Simply reset this variable to 0 using your in circuit-emulator.c. These are: ● ● ● ● ● Usage of uninitialized data structures Invalid pointers Unused resource that has not been used by this task before OS_LeaveRegion() called more often than OS_EnterRegion() Stack overflow (this feature is not available for some processors) Which runtime errors that can be detected depend on how much checking is performed. It simply disables further task switches and then. OS_Status = ErrCode. Unfortunately. The actual error code is assigned to the global variable OS_Status.Debugging Runtime errors Some error conditions can be detected during runtime. the last statement needs to be the infinite loop. but there is a difference). it calls the following routine: void OS_Error(int ErrCode). Most of the time. looking at this part of the program will make the problem clear. } When using an emulator. you should set a breakpoint at the beginning of this routine or simply stop the program after a failure. You can modify the routine to accommodate your own hardware. The program then waits for this variable to be reset. additional checking costs memory and speed (it is not that significant. this could mean that your target hardware sets an error-indicating LED or shows a little message on the display. loops forever as follows: Example /* Run time error reaction */ void OS_Error(int ErrCode) { OS_EnterRegion(). and you can easily step back to the program sequence causing the problem.

The interrupt disable counter (OS_DICnt) is out of range (0-15). Default interrupt handler called. Task control block invalid. Possible reasons may be that one mailbox data structure was overwritten.List of error codes Value Define Explanation 100 101 120 121 128 129 130 132 133 135 OS_ERR_ISR_INDEX OS_ERR_ISR_VECTOR OS_ERR_STACK OS_ERR_CSEMA_OVERFLOW OS_ERR_INV_TASK OS_ERR_INV_TIMER OS_ERR_INV_MAILBOX OS_ERR_INV_CSEMA OS_ERR_INV_RSEMA OS_ERR_MAILBOX_NOT1 Index value out of bounds during interrupt controller initialization or interrupt installation. Illegal function call in an interrupt service routine: A routine that may not be called from within an ISR has been called from within an ISR. The mailbox is not in the list of mailboxes as expected. Control block for counting semaphore invalid. OS_Unuse() has been called before OS_Use(). OS_ERR_LEAVEINT OS_ERR_DICNT Error in OS_LeaveInterrupt(). OS_DeleteRSema() was called on a resource semaphore which is claimed by a task. not initialized or overwritten. Stack overflow or invalid stack. 154 156 160 OS_ERR_INTERRUPT_DISABLED OS_ERR_RESOURCE_OWNER OS_ERR_ILLEGAL_IN_ISR 161 OS_ERR_ILLEGAL_IN_TIMER Table 1: Error code list IAR PowerPac™ RTOS 130 User Guide PPRTOS-3 . not initialized or overwritten. Illegal function call in an interrupt service routine: A routine that may not be called from within a software timer has been called from within a timer. not initialized or overwritten. The counter is affected by the following API calls: OS_IncDI() OS_DecRI() OS_EnterInterrupt() OS_LeaveInterrupt() OS_Delay() or OS_DelayUntil() called from inside a critical region with interrupts disabled. 136 137 138 140 OS_ERR_MAILBOX_DELETE OS_ERR_CSEMA_DELETE OS_ERR_RSEMA_DELETE OS_ERR_MAILBOX_NOT_IN_LIST 142 150 151 152 153 OS_ERR_TASKLIST_CORRUPT OS_ERR_UNUSE_BEFORE_USE OS_ERR_LEAVEREGION_BEFORE_ENTERREG OS_LeaveRegion() has been called before ION OS_EnterRegion(). Timer control block invalid. not initialized or overwritten. not initialized or overwritten. One of the following 1-byte mailbox functions has been used on a multi. but interrupt vector not initialized. OS_Unuse() has been called from a task which does not own the resource.byte mailbox: OS_PutMail1() OS_PutMailCond1() OS_GetMail1() OS_GetMailCond1(). OS_DeleteCSema() was called on a counting semaphore with waiting tasks. Counting semaphore overflow. OS_DeleteMB() was called on a mailbox with waiting tasks. Mailbox control block invalid. Control block for resource semaphore invalid. The OS internal task list is destroyed.

c. Nested call of OS_Suspend() exceeded OS_MAX_SUSPEND_CNT OS_Resume() called on a task that was not suspended. that had no memory block allocated (all available blocks were already free before). Pointer to memory block does not belong to memory pool on Release Pointer to memory block is already free when calling OS_MEMF_Release(). OS_Rx interrupt handler for embOSView is nested. same pointer was released twice. OS_MEMF_Release() was called for a memory pool. Timer control block has been initialized by calling a create function twice. Disable nestable interrupts. PPRTOS-3 131 . Mailbox control block has been initialized by calling a create function twice. An OS_EVENT object was created twice. This error can only occur when IAR PowerPac RTOS was compiled without round robin support. Fixed size memory pool has been initialized by calling a create function twice. Task control block has been initialized by calling a create function twice. Possibly. Fixed size memory block control structure not created before use. Resource semaphore has been initialized by calling a create function twice.Debugging Value Define Explanation 162 OS_ERR_ILLEGAL_OUT_ISR IAR PowerPac RTOS timer tick handler or UART handler for embOSView was called without a call of OS_EnterInterrupt(). An OS_EVENT object was deleted with waiting tasks 170 171 172 174 175 176 180 190 191 192 OS_ERR_2USE_TASK OS_ERR_2USE_TIMER OS_ERR_2USE_MAILBOX OS_ERR_2USE_CSEMA OS_ERR_2USE_RSEMA OS_ERR_2USE_MEMF OS_ERR_NESTED_RX_INT OS_ERR_MEMF_INV OS_ERR_MEMF_INV_PTR OS_ERR_MEMF_PTR_FREE 193 OS_ERR_MEMF_RELEASE 194 OS_ERR_POOLADDR 195 200 201 202 OS_ERR_BLOCKSIZE OS_ERR_SUSPEND_TOO_OFTEN OS_ERR_RESUME_BEFORE_SUSPEND OS_ERR_TASK_PRIORITY 210 211 212 OS_ERR_EVENT_INVALID OS_ERR_2USE_EVENTOBJ OS_ERR_EVENT_DELETE Table 1: Error code list (Continued) The latest version of the defined error table is part of the comment just before the OS_Error() function declaration in the source file OS_Error. An OS_EVENT object was used before it was created. Counting semaphore has been initialized by calling a create function twice. OS_MEMF_Create() was called with a memory pool base address which is not located at a word aligned base address OS_MEMF_Create() was called with a data block size which is not a multiple of processors word size. OS_CreateTask() was called with a task priority which is already assigned to another task.

IAR PowerPac™ RTOS 132 User Guide PPRTOS-3 .

25 bytes * 9 . memory model. Segger uses these programs to benchmark the IAR PowerPac RTOS performance. configuration. You can use these examples to evaluate the benchmark results. IAR PowerPac RTOS runs on 8/16/32-bit CPUs. Depending on which features are being used. Example programs for both methods are supplied in the \Example directory of your IAR PowerPac RTOS shipment. PPRTOS-3 133 . compiler. optimization.11 bytes * 0 bytes * Depends on CPU.). toolchain. Benchmarking IAR PowerPac RTOS is designed to perform fast context switches. compiler.Performance and resource usage This chapter covers the performance and resource usage of IAR PowerPac RTOS. Module Memory type Memory requirements IAR PowerPac RTOS kernel IAR PowerPac RTOS kernel Mailbox Binary and counting semaphores Resource semaphore Timer Event Table 1: IAR PowerPac RTOS memory requirements ROM RAM RAM RAM RAM RAM RAM 1100 . optimization. etc. This section describes two different methods to calculate the execution time of a context switch from a task with lower priority to a task with a higher priority. configuration. The actual performance and resource usage depends on many factors (CPU. The following table shows the memory requirements for the different modules. Note. even single-chip systems with less than 2 Kbytes ROM and 1 Kbyte RAM can be supported by IAR PowerPac RTOS. that the actual performance depends on many factors (CPU. Introduction High performance combined with low resource usage has always been a major design consideration.1600 bytes * 18 .). The first method uses port pins and requires an oscilloscope. It explains how to benchmark IAR PowerPac RTOS and information about the memory requirements in typical systems which can be used to obtain sufficient estimates for most target systems.15 bytes * 3 bytes 4 .5 bytes * 9 . The second method uses the high-resolution measurement functions. Memory requirements The memory requirements of IAR PowerPac RTOS (RAM and ROM) differ depending on the used features of the library. and library model used Performance The following section shows how to benchmark IAR PowerPac RTOS using the supplied example programs. clock speed. etc. memory model.

// Start measurement OS_Resume(&TCBHP). All sources are compiled with IAR Embedded Workbench version 4. 99. StackLP[128]. // Initialize Hardware for OS LED_Init().187us All example performance values in the following section are determined with the following system configuration: ATMEL AT91SAM7S256 running with 48 MHz clock speed. The following source code is excerpt from MeasureContextSwitchingTime_Scope. StackHP). HPTask. The example program executes in of flash memory. TCBLP. // Stop measurement } } /********************************************************************* * * LPTask */ static void LPTask(void) { while (1) { OS_Delay(100).562us 7. // Syncronize to tick to avoid jitter // // Display measurement overhead // LED_SetLED0().The following table gives an overview about the variations of the context switch time depending on the memory type and the CPU mode: Target Memory CPU mode Time ATMEL AT91SAM7S256 ATMEL AT91SAM7S256 ATMEL AT91SAM7S256 ATMEL AT91SAM7S256 Table 2: IAR PowerPac RTOS context switch times Flash Flash RAM RAM Thumb ARM ARM Thumb 7. } IAR PowerPac™ RTOS 134 User Guide PPRTOS-3 . 100.c uses the LED. // // Perform measurement // LED_SetLED0(). "LP Task".875us 5. "HP Task". // Start multitasking return 0. This allows measuring the context switch time with an oscilloscope.c module to set and clear a port pin. OS_Start(). OS_CREATETASK(&TCBLP. // Initially disable interrupts OS_InitKern(). // Initialize OS OS_InitHW(). // Resume high priority task to force task switch } } /********************************************************************* * * main */ int main(void) { OS_IncDI().h" #include "LED. StackLP). MEASUREMENT WITH PORT PINS AND OSCILLOSCOPE The example file MeasureCST_Scope.h" static OS_STACKPTR int StackHP[128].c: #include "RTOS. LPTask.40A using Thumb mode with high optimization level. // Task stacks // Task-control-blocks /********************************************************************* * * HPTask */ static void HPTask(void) { while (1) { OS_Suspend(NULL). // Initialize LED ports OS_CREATETASK(&TCBHP. static OS_TASK TCBHP. // Suspend high priority task LED_ClrLED0(). LED_ClrLED0().896us 6.

tAB Voltage [V] A B C D tAB tCD Time [t] Example measurements for AT91SAM7S and ARM code in RAM Task switching time has been measured with the parameters listed below: Application program: MeasureCST_Scope. because the signal also contains the overhead of switching the LED on and off.9232MHz = 20.40A (4. The context switching time tCS is calculated as follows: tCS = tCD . The real context switch time is shorter. There are switching points to determine: ● ● ● ● ● A = LED is switched on for overhead measurement B = LED is switched off for overhead measurement C = LED is switched on right before context switch in low-priority task D = LED is switched off right after context switch in high-priority task D = LED is switched off right after context switch in high-priority task The time needed to switch the LED on and off in subroutines is marked as time tAB.Performance and resource usage Oscilloscope analysis The context switch time is the time between switching the LED on and off. The picture below shows a simplified oscilloscope signal with an active-low LED signal (low means LED is illuminated).866ns PPRTOS-3 135 .9232MHz CPU clock cycle (tCycle): tCycle = 1 / fCPU = 1 / 47.501) CPU frequency (fCPU): 47.c Hardware: AT91SAM7S256 processor with 48MHz Program is executing in RAM ARM mode is used Compiler used: IAR Embedded Workbench V4.40. the context switch time is the time between rising and falling edge of the signal. The time of this overhead is also displayed on the oscilloscope as a small peak right before the task switch time display and has to be subtracted from the displayed context switch time. If the LED is switched on with an active high signal. The time needed for a complete context switch including the time needed to switch the LED on and off in subroutines is marked as time tCD. If the LED is switched on with an active low signal. the signal polarity is reversed.1.

866ns IAR PowerPac™ RTOS 136 User Guide PPRTOS-3 .6ns / 20.9232MHz CPU clock cycle (tCycle): tCycle = 1 / fCPU = 1 / 47.15Cycles = 283Cycles => 283Cycles (5.501) CPU frequency (fCPU): 47.tAB = 298Cycles .40A (4.9us @48MHz).c Hardware: AT91SAM7S256 processor with 48MHz Program is executing in FLASH Thumb mode is used Compiler used: IAR Embedded Workbench V4.1.866ns = 14.40.9232MHz = 20. Example measurements for AT91SAM7S and Thumb code in FLASH Task switching time has been measured with the parameters listed below: Application program: MeasureCST_Scope. The number of cycles calculates as follows: CyclesAB = tAB / tCycle =312ns / 20. The number of cycles calculates as follows: CyclesCD = tCD / tCycle = 6217.977Cycles => 298Cycles Resulting context switching time and number of cycles The time which is required for the pure context switch is: tCS = tCD .952Cycles => 15Cycles tCD is measured as 6217.6ns.Measuring tAB and tCD tAB is measured as 312ns.866ns = 297.

The number of cycles calculates as follows: CyclesAB = tAB / tCycle =436.973Cycles => 384Cycles Resulting context switching time and number of cycles The time required for the pure context switch is: tCS = tCD .Performance and resource usage Measuring tAB and tCD tAB is measured as 436. Refer to section High-resolution measurement on page 113 for detailed information about the IAR PowerPac RTOS high-resolution measurement. PPRTOS-3 137 .tAB = 384Cycles . The number of cycles calculates as follows: CyclesCD = tCD / tCycle = 8012ns / 20.c uses a high resolution timer to measure the context switch time from a low priority task to a high priority task and display the results on stdout.8ns.21Cycles = 363Cycles => 363Cycles (7. The example MeasureContextSwitchingTime_HRTimerCSpy.8ns / 20.933Cycles => 21Cycles tCD is measured as 8012ns.866ns = 383.866ns = 20. Measurement with high-resolution timer The context switch time may be measured with the high-resolution timer.56us @48MHz).

static OS_TASK TCBHP.3u usec\r\n".h" static OS_STACKPTR int StackHP[128]. // Suspend high priority task OS_Timing_End(&_Time).h" #include "stdio. TCBLP.OS_Timing_GetCycles(&MeasureOverhead).%. v / 1000. // Task stacks // Task-control-blocks // Timer values /********************************************************************* * * HPTask */ static void HPTask(void) { while (1) { OS_Suspend(NULL). printf("Context switch time: %u. static OS_U32 _Time. IAR PowerPac™ RTOS 138 User Guide PPRTOS-3 .#include "RTOS. } } The example program calculates and subtracts the measurement overhead itself. // // Perform measurements in endless loop // while (1) { OS_Delay(100). // Syncronize to tick to avoid jitter OS_Timing_Start(&_Time). v = OS_ConvertCycles2us(1000 * v). // Time for Measure Overhead OS_U32 v. // OS_Timing_End(&MeasureOverhead). Use the C-SPY terminal I/O window to check the results. so there is no need to do this. StackLP[128]. v % 1000). // Resume high priority task to force task switch v = OS_Timing_GetCycles(&_Time) . // Stop measurement } } /********************************************************************* * * LPTask */ static void LPTask(void) { OS_U32 MeasureOverhead. // Start measurement OS_Resume(&TCBHP). // // Measure overhead for time measurement so we can take this into // account by subtracting it OS_Timing_Start(&MeasureOverhead).

C routines and reentrance Normally. Everything else has to be thought about carefully. However. it is recommended to use a resource semaphore to avoid this kind of problem. PPRTOS-3 139 . the compiler may have options that force it to generate non-reentrant code. the C compiler generates code that is fully reentrant. although it is possible to do so under certain circumstances. If for some reason you need to have nonreentrant routines in your program that can be used from more than one task. A routine is in use from the moment it is called until it returns or the task that has called it is terminated. they are fully reentrant. Assembly routines and reentrance As long as assembly functions access local variables and parameters only. It is recommended not to use these options. All routines supplied with your real-time operating system are fully reentrant.Reentrancy Reentrance All routines that can be used from different tasks at the same time have to be fully reentrant.

IAR PowerPac™ RTOS 140 User Guide PPRTOS-3 .

Limitations The following limitations exist for IAR PowerPac RTOS: Maximum number of tasks: Maximum number of priorities: Maximum number of semaphores: Maximum number of mailboxes: Maximum number of queues: Maximum size of queues: Maximum number of timers Task specific event flags: limited by available RAM only 255 limited by available RAM only limited by available RAM only limited by available RAM only limited by available RAM only limited by available RAM only 8 bits / task If you need to make changes to IAR PowerPac RTOS. the full source code is optionally available. PPRTOS-3 141 .

IAR PowerPac™ RTOS 142 User Guide PPRTOS-3 .

bat and modify the _TOOLPATH_ variable. The object version offers the full functionality of IAR PowerPac RTOS including all supported configuration of the compiler. different compile options give you full control of the generated code. The \RTOS\Src\GenOSSrc folder contains all IAR PowerPac RTOS source files.Source code of kernel and library Introduction IAR PowerPac RTOS is available in two versions: 1 Object version: Object code + hardware initialization source. the debug libraries as described and the source code for idle task and hardware initialization. Batch files for building the library from the command line are provided. because the _TOOLPATH_ variable in BuildLibs. Nothing else should require changes Major compile time switches Many features of IAR PowerPac RTOS may be modified by compile-time switches. the object version does not allow source-level debugging of the library routines and the kernel. you should not modify any of the files in the CPU folder. or has to be passed as parameters during the library build process. However. The batch files are located under <ToolchainDir>\ARM\PowerPac\RTOS\Src\. An example workspace for building a library is also available. If you have changed the default installation path of IAR PowerPac RTOS the batch build will fail. PPRTOS-3 143 . All of them are predefined to reasonable values in the distribution of IAR PowerPac RTOS. You should be able to build the library without any error or warning messages. To start the batch build click BuildLibs. You can debug the entire system and even modify it for new memory models or other CPUs.bat. The \RTOS\Src\CPU folder contains all CPU and compiler specific source code and header files used for building the IAR PowerPac RTOS libraries. The compile-time switches must be changed in RTOS. The full source version gives you the ultimate options: IAR PowerPac RTOS can be recompiled for different data sizes. making it possible to optimize the system for versatility or minimum memory requirements. IAR PowerPac RTOS Normally.bat points to the main directory of your compiler relative to the default installation path of IAR PowerPac RTOS. IAR PowerPac RTOS sources have to be recompiled with the modified switches. It also contains DOS batch files that can be used for rebuilding the complete set of the IAR PowerPac RTOS libraries. 2 Full source version: Complete source code. The IAR PowerPac RTOS libraries can only be built if you have purchased a source code version of IAR PowerPac RTOS. The source code distribution of IAR PowerPac RTOS contains the following additional files: ● ● ● The \Src\ folder contains all source code part of the distribution. Building IAR PowerPac RTOS libraries IAR PowerPac RTOS is shipped with different prebuilt libraries. Open BuildLibs. the internal data structures are not explained in detail. Because this document describes the object version.h.

Ensure that none of your tasks ever run on the same priority when you disable round robin scheduling.OS_RR_SUPPORTED This switch defines whether round robin scheduling algorithm is supported. IAR PowerPac™ RTOS 144 User Guide PPRTOS-3 . that tasks are never suspended on any synchronization object or claim any resource semaphores when they are terminated. Even though the overhead is minimal and execution time is not affected significantly. you have to enable this switch (define it to be unequal to 0) to enable termination of tasks which are suspended on synchronization objects or claim resource semaphores. If you never use round robin scheduling and all of your tasks run on different individual priorities. When using an 8-bit CPU. Note:By default. For 8-bit CPUs it is disabled. this switch is activated for 16. you may disable round robin scheduling by defining this switch to 0. This will save RAM and ROM and will also speed up the task-switching process. Disabling this switch will save some RAM in the task control structure and will also speed up the wait functions for synchronization objects. you may define this switch to zero when you do not terminate tasks in your application.and 32-bit CPUs. OS_SUPPORT_CLEANUP_ON_TERMINATE IAR PowerPac RTOSIf enabled. it allows termination of tasks which are claiming resource semaphores or are suspended on any synchronization object. or if your application ensures. All IAR PowerPac RTOS versions enable round robin scheduling by default.

This feature can be used for changing priorities in a way so that basically every desired algorithm can be implemented. What interrupt priorities can I use for the interrupts my program uses? Any. One way would be to have a task control task with a priority higher than that of all other tasks that dynamically changes priorities.FAQ (frequently asked questions) Q: A: Can I implement different priority scheduling algorithms? Yes. that is any internal timer. which means that task priorities can be changed while the system is running (using OS_SetPriority()). but it could also be an external signal. the prioritycontrolled round-robin algorithm is perfect for real-time applications. Q: A: Q: A: PPRTOS-3 145 . the system is fully dynamic. Can I use a different interrupt source for IAR PowerPac RTOS? Yes. Normally. any periodical signal can be used.

IAR PowerPac™ RTOS 146 User Guide PPRTOS-3 .

Used when a task must wait for something that can be signaled more than once. An item of data (sent to a mailbox. Short for microprocessor. that task will be executed before the interrupted task is returned to. or other container for data). A data buffer managed by the RTOS. A scheduling system in which each task is allowed to run until it gives up the CPU. used for sending messages to a task or interrupt handler. The task that is currently executing is called the active task. A section of code which must be executed without interruption. Like a mailbox. Central Processing Unit. Non-Maskable Interrupt. The routine is called automatically by the processor when an interrupt is acknowledged. Every task in an RTOS has a priority.Glossary Active Task Only one task can execute at any given time. or messages of individual size. to a task or an interrupt handler. queue. but the interrupted task will be returned to and finished first. The “brain” of a microcontroller. The execution of multiple software routines independently of one another. The OS divides the processor's time so that the different routines (tasks) appear to be happening simultaneously. but used for sending larger messages. an ISR can make a higher priority task ready. A message sent to a single. A scheduling system in which the highest priority task that is ready will always be executed. A type of semaphore that keeps track of multiple resources. Queue PPRTOS-3 147 . Interrupt Service Routine. Example: Watchdog timer-interrupt. Cooperative multitasking Counting semaphore CPU Critical region Event ISR Mailbox Message Multitasking NMI Preemptive multitasking Processor Priority Priority inversion A situation in which a high priority task is delayed while it waits for access to a shared resource which is in use by a lower priority task. The CPU core of a controller The relative importance of one task to another. the part of a processor that carries out instructions. The task then becomes ready. If an ISR makes a higher priority task ready. An interrupt that cannot be masked (disabled) by software. ISRs must preserve the entire context of a task (all registers). specified task that something has occurred. The lower priority task temporarily gets the highest priority until it releases the resource.

Resource Anything in the computer system with limited availability (for example memory. The program section of an RTOS that selects the active task. return addresses. Resource semaphore RTOS Scheduler Semaphore Software timer Stack A data structure used for synchronizing tasks. A type of semaphore used for managing resources by ensuring that only one task has access to a resource at a time. and other information that needs to be maintained across function calls. computation time). ISRs are used for realtime parts of the software. An area of memory with FIFO storage of parameters. timers. Superloop Task Tick Timeslice IAR PowerPac™ RTOS 148 User Guide PPRTOS-3 . A multitasking system allows multiple tasks to execute independently from one another. Real-time Operating System. The time (number of ticks) for which a task will be executed until a round-robin task change may occur. A program running on a processor. automatic variables. their relative priorities. A data structure which calls a user-specified routine after a specified delay. A program that runs in an infinite loop and uses no real-time kernel. Essentially. each task normally has its own stack. The OS timer interrupt. anything used by a task. In multitasking systems. based on which tasks are ready to run. Usually equals 1 ms. and the scheduling system being used.

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 24 OS_CreateTask() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 61 single-byte . . . . . . . . . . . . . . . of embOS . . . 87 OS_EVENT_Pulse() . . . . . . . . . . . . . . . 13 cooperative multitasking . . . . . . 56 OS_CREATEMB() . . . 28 OS_DeleteCSema() . . . . . . . . . . . . . . . . . . . . . . . . . . .16. . . . . . . . . . . . . . . . . . . . . . . 11 embOS features . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .17. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 106 OS_DelayUntil() . . . . . . . . . . . . . 20. . . . . . . . . . . . 107 Non-maskable interrupts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 107 Interrupt level . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 27 OS_CREATETASK() . . . . . . . . . . . . . . . . . . . 123 Configuration. . . . . . . . . . . . . . . . . . . . . . . . . . . 117 Interrupt control macros . . . . . . . . . . . . . . . . . . . 55 Critical regions . . . . . . . . . . . . . of embOS .119. . . . . 9 N Nesting interrupts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 14 preemptives multitasking. . . . . . . . . . . . . . . . . . . . . . . . . . . 15 D Debug version. 2 Counting Semaphores . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11 Error codes . . . . . . 143 different builds of . . . . . . . . . . . . . . . . . . . . . . . . . .Index Index C C startup . . . . . . . . . . . . . 26 OS_CREATETIMER() . . . . . . 44 OS_DecRI() . . . . . . . . . . . . . . . 141 PPRTOS-3 149 . 63 OS_CREATERSEMA() . . . . 108 OS_EnterRegion() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . of embOS . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 109 OS_EVENT_Create() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 104 OS_ClearEvents() . . . . . . . 130 runtime errors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 113 low-resolution . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 80 OS_ClearMB() . . . . . . . . . . . . . . . 87 OS_EVENT_Get() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 51 OS_CreateTaskEx() . . 9 I Internal data-structures . . . 85 E edition. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 38. . . . . . 104 OS_CallNestableISR() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 41. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 123–124 copyright notice . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 62 Measurement . . . . . . . . . . . . . . . . . 83–88 G guidelines. . . . . . . . . . . . . . . . . . . . . . . . . . . 24 OS_CallISR() . . . . . . . . . . . . . . . . . . . . . . . . . . 55 OS_CreateCSema() . . . . 109–110 M Mailboxes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 106 interrupt handler . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 28 OS_Delay() . . . . . . . 130 Events . . . . 21 Debugging . . . . . 91–95 Multitasking systems . . . . . . of this guide . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13 Interrupts . . . . . . 19 Configuration defines . .129–131 error codes . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 91 Memory pools . . 2 document conventions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 43 OS_CreateTimer() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 47 OS_DI() . . . . . . . . . . . . . . . . . . . . . . . . . . 39. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 83 OS_EVENT_Delete() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2 embOS building libraries of . 143 Limitations. . . . . . . . . . 13 Interrupt service routines . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 111 high-resolution . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 86 OS_EVENT_Set() . . . . . . . . . . . . . 103 L Libraries. . . . . . . . . . . . . . . . . 87 OS_EVENT_Reset() . . . . . . . . . . . . . . . . . 69 OS_DeleteTimer() . . . . . . . . . . 25 OS_CREATETASK_EX() . . . . . . . . . . . . . . . 21 features of . . . . . . . . . . . . . . 61–69 basics . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . reading. . 129 disclaimer . . . . . . . . . . . . . 107 OS_EnterInterrupt() . . . . . . . . . . . . . . . . . . . . . . . . . . . .101–108 enabling/disabling . . . . . . . . . . . . . . . . . . . . . . . . . 77–81. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 108 O OS . . . . . . . . . . . . . . . . . . . . . . . . . . 111 Memory management fixed block size . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 104–105 OS_EnterNestableInterrupt() . . 59 OS_DeleteMB() . . . . . . . . 107 OS_EI() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 68 OS_CREATECSEMA() . . . . . . building . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .

. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 79 OS_WaitSingleEvent() . . . . . . . . . . . 64 OS_PutMailCond1() . . 63 OS_Q_Clear() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 120 OS_TICK_HandleEx() . 31 OS_GetpCurrentTimer() . . . . . 65 OS_PutMailFrontCond1() . . . . . . . . . . . . . . . . . . . . . . 107 OS_Resume() . . . . . . . . . 95 OS_MEMF_Release(). . . . . . . . . . . . . . . . . . . . . . . . . . . . 57 OS_WaitCSema() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 93 OS_PutMailCond() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 67 OS_GetMail(). . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 68 OS_GetpCurrentTask() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 47 OS_GetTimerValue() . . . . . . . . . . . 123 OS_ISR_Tick() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 64 IAR PowerPac™ RTOS OS_PutMailFrontCond() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 57 OS_WaitEventTimed() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 123 OS_GetCSemaValue() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 120 OS_TICK_Handle() . . . . . . . . . 66 OS_GetMessageCnt() . . . . . . . . . . . . . . . . 32 OS_GetTimerPeriod() . . . . . . . . . . . . . . . 123 OS_IncDI() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 45 OS_Start() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 121 OS_TICK_Config() . . . . . . . . . . . . . . . . . 46 OS_SetTimeSlice() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 114 OS_Timing_GetCycles() . . . . . . . . . . . . 94 OS_MEMF_GetMaxUsed() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 42. . . . . . . . . . . . . . . . . .42. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 20 OS_StopTimer() . . . . . . . . . . . . . . . . . . 33 OS_SetTimerPeriod() . . . . . . 66 OS_GetMail1() . . . . . . . . . . . . . . . . . . . . . . 112 OS_Idle() . . . . . . . . . . . . . . . . . . 35 OS_Yield() . . . . . . . . . . . . . . . 84 OS_EVENT_Wait(). . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 47 OS_GetTimerStatus() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 89 OS_Request() . 54 OS_GetStackBase() . . . . . . . . . . . . . . . . . . . . . . . . 114 OS_TimingStart() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 114 OS_Unuse() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 34 OS_Terminate() . . . . . . . . . . . . . . . . . . . . . . . . . . . 48 OS_GetPriority() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 78 OS_WaitEvent() . . . . . . . . . . . . . . . 65 OS_PutMailFront() . . . . . . . . . . . . . . . . . 105 OS_LeaveInterrupt() . . . . . . . . . . . . 52 OS_USE() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 41. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 54 OS_GetSemaValue() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 35 150 User Guide PPRTOS-3 . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 33 OS_SetTaskName() . . . 29 OS_free() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 51 OS_WaitCSemaTimed() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 80 OS_GetMailCond() . . . . . . . . . . . . 112 OS_GetTime_Cycles() . . . . . . . . . 65 OS_PutMailFront1() . . . . . . . . . . . . . . . . . 72 OS_Q_Purge() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 92 OS_MEMF_FreeBlock() . . . . 78 OS_WakeTask() . . . . . . . . . . . . . . . . 40. . . 73 OS_Q_GetPtrTimed() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 56 OS_SignalEvent() . . . 68 OS_WaitSingleEventTimed() . . . . . . . . . . . . . . . . . . . . . . . . 72 OS_realloc() . . 71 OS_Q_GetMessageCnt() . 117 OS_TimingEnd() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 40 OS_Suspend() . . . . . . . . 31 OS_GetTaskID() . . . . 39. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 123 OS_GetTime32() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 84 OS_ExtendTaskContext() . . . 106 OS_InitHW() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 94 OS_MEMF_GetNumFreeBlocks() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 31 OS_GetResourceOwner . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 94 OS_MEMF_IsInPool() . . . . . . . . . . . . . . . . . . . . . . . .42. . . . 89 OS_MEMF_AllocTimed() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 98 OS_GetStackSize() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 109 OS_malloc() . . . . . . . . . 98 OS_GetStackSpace() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 74 OS_Q_GetPtr() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 58 OS_SetPriority() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 32 OS_RetriggerTimer() . . . . . . . . . . . . . . . . . . . . . . . . . . . 92 OS_MEMF_Create() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 66 OS_GetMailCond1() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 122 OS_Time . . . . . . . . . . . . . . . . 123 OS_IsTask() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 58 OS_GetEventsOccurred() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 91 OS_MEMF_Delete() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 63 OS_PutMail1() . . . . . . . . . . . . . . . . . . . . . . . . . . . 34 OS_TICK_AddHook() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 119 OS_TICK_RemoveHook(). . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 95 OS_MEMF_GetNumBlocks() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 89 OS_FSYS . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 75 OS_Q_Create() . . . 92 OS_MEMF_Alloc() . 66 OS_GetMailTimed() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 117 OS_TimeDex . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 75 OS_Q_GetPtrCond() . . . . . . . . . . 99 OS_GetStackUsed() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 40. . 79 OS_StartTimer() . . . . . . 65 OS_PutMail() . . . . . . . . . . . . . . . . 32 OS_LeaveInterruptNoSwitch() . . . . . . . .OS_EVENT_WaitTimed() . . 114 OS_Timing_Getus() . . . . . . 105 OS_LeaveNestableInterrupt() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 108 OS_LeaveRegion() . . . . 33 OS_SignalCSema() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 93 OS_MEMF_Request() . . . . . . . . . 45 OS_SetCSemaValue() . . . . . . . . . . . . . . 47 OS_GetTime() . . . . . . . . . . . . . . . . . . . . . . 53 OS_RestoreI() . . . . . . . . . . . . . . . . . . . . . . 77 OS_WaitMail(). . . . . . . . 74 OS_Q_Put() . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 99 OS_GetSuspendCnt() . . . . . . . . . . . . . . . . . . . . . 94 OS_MEMF_GetBlockSize() . . .

. . . . 17 PPRTOS-3 151 . of this guide . . . . . . . . . . . . . . . . . . . . . . . . . . . 123 version. . . . . . . . . . 17 Counting. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . of embOS . . . . . . . . . . . . . . . . . . . . . . . . . . 21 Resource semaphores . . . . . . . . . . . . . . 37 Stack . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23 Task routines . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . IAR Embedded Workbench . . . . . . . . 13 switching . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2 Time variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .c configuration .15–16 RTOSInit. . . . . . .Index P part number. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . of this guide . . . . . . . . . . . . . . . . 17 Syntax. . . 139 registered trademarks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .23–35 Tasks . . . . . . . . . . . . . . . . . . . . .17. . . . . . . . . . . . . . 9 System variables . . . . . 16 Priority inversion . . . . . . . . 111–116 trademarks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17 TCB . . . . . . . . . . . . . . . . . . . . . . 17 Stacks switching . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 71–75 R reading guidelines . . . . . . . . . . . . . . . 129 S Scheduler . . 16 global variables . . . . . . . . . . . 117 T Task communication . . . . . . . . . . . . . . . . . . . . . . . 16 publication date. . . . . . . . 2 V Vector table file . . . . . . . . . . . 13 status . . . . . . . . . . . . . . . . . 15 Priority . . 13 single-task systems . . . . 17 Superloop . . . . . . . . . . . 16 multitasking systems . . . . . . . . . . . . . . . . . . . . . . . . conventions used . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2 Q Queues . . . . . . . . . . . . . . . . . 2 Release version. . . . . . . . . . . . . . . . . . . . . . . . . . 97–100 Stack pointer . . . . . 18 superloop . . . . . . . . .37–43 Software timers API overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 123 Runtime errors . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15 Semaphores . . 117 Time-related routines . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13 Switching stacks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 13 communication . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2 Preemptive multitasking . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16 Task control block . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 49 Round-robin .17. . . . 9 Reentrance . . . . . . . . . . . . . . . . . .49–54 Software timer . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .55–59 Resource. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 17. . . . . . . . . . . . . . . . . . . . . .

Sign up to vote on this title
UsefulNot useful