4
RTOS EMBEDDED SYSTEMS are usually microcontroller-based systems that represent a class of reliable and dependable dedicated computer systems designed for specific purposes. Microcontrollers are used in most electronic devices in an endless variety of ways. For example, it is estimated that there are more than 50 microcontrollers used in intelligent appliances in a modern average household in Europe. Some applications areas are in telephone systems, microwaves, washing machines, cookers, digital TVs, remote control units, Hi-Fi equipment, PCs, MP3 players, mobile phones and so on. Some microcontroller-based embedded systems are required to respond to external events in the shortest possible time and such systems are often referred to as real-time embedded systems. It is important to understand that not all embedded systems are real-time and, also, not all real-time systems are embedded. For example, most of embedded automotive systems can be classified as real-time systems. Various specialized control functions in a vehicle, such as engine control, brake and clutch control are examples of real-time systems. Most complex real-time systems require a number of tasks to be processed independently and this requires some form of scheduling and task control mechanisms. For example, consider an extremely simple real- time system which must flash an LED at required intervals and at the same time look for a key input from a keyboard. One solution would be to scan the keyboard in a loop at regular intervals while flashing the LED at the same time. Although this approach may work for a simple example, in most complex real- time systems, a real-time operating system (RTOS) or a multi-processing approach are usually employed. Multi-processing is beyond the scope of this article and this approach requires the use of more than one processor (e.g. more than one microcontroller) and is generally used in parallel computing applications where very high-speed processing, as well as multitasking, are required. The Basic Principles of an RTOS An RTOS is a program that manages system resources, schedules the execution of various tasks in the system and provides services for inter-task synchronization and messaging. There are many books and sources of reference that describe the operation and principles of various RTOS systems. Every RTOS consists of a kernel that provides the low level functions, mainly the scheduling, creation of tasks and inter-task resource management. Most complex RTOSs also provide file-handling services, disk input-output operations, interrupt servicing, network management and user management. A task is an independent thread of execution in a multitasking system, usually with its own local set of data. A multitasking system consists of a number of independent tasks, each running its own code and communicating with each other in order to have orderly access to shared resources. The simplest RTOS consists of a scheduler that determines the execution order of the tasks in the system. Each task has its own context consisting of the state of the CPU and associated registers. The scheduler switches from one task to another one by performing a context switching where the context of the running process is stored and context of the next process is loaded appropriately so that execution can continue properly with the next task. The time taken for the CPU to perform Professor Dr Dogan Ibrahim, lecturer at the Near East University in Cyprus, describes the design of a C-based, simple multitasking RTOS, using PIC microcontrollers µ RTOS: Simple Multitasking with Microcontrollers Figure 1: Co-operative scheduling Figure 2: Round-robin scheduling Figure 3: Pre-emptive scheduling 20 June 10 - Electronics World

microcontroller_RTOS

  • Upload
    vknr

  • View
    3

  • Download
    0

Embed Size (px)

DESCRIPTION

8 bit schedular

Citation preview

  • RTOS

    EMBEDDED SYSTEMS areusually microcontroller-based systems thatrepresent a class of reliable and dependablededicated computer systems designed forspecific purposes. Microcontrollers are used inmost electronic devices in an endless varietyof ways. For example, it is estimated thatthere are more than 50 microcontrollers usedin intelligent appliances in a modern averagehousehold in Europe. Some applications areasare in telephone systems, microwaves,washing machines, cookers, digital TVs,remote control units, Hi-Fi equipment, PCs,MP3 players, mobile phones and so on.

    Some microcontroller-based embeddedsystems are required to respond to externalevents in the shortest possible time and suchsystems are often referred to as real-timeembedded systems. It is important tounderstand that not all embedded systemsare real-time and, also, not all real-timesystems are embedded. For example, most ofembedded automotive systems can beclassified as real-time systems. Variousspecialized control functions in a vehicle, suchas engine control, brake and clutch controlare examples of real-time systems.

    Most complex real-time systems require anumber of tasks to be processedindependently and this requires some form ofscheduling and task control mechanisms. Forexample, consider an extremely simple real-time system which must flash an LED atrequired intervals and at the same time lookfor a key input from a keyboard. One solutionwould be to scan the keyboard in a loop atregular intervals while flashing the LED at thesame time. Although this approach may workfor a simple example, in most complex real-time systems, a real-time operating system(RTOS) or a multi-processing approach areusually employed. Multi-processing is beyondthe scope of this article and this approachrequires the use of more than one processor

    (e.g. more than onemicrocontroller) and isgenerally used in parallelcomputing applicationswhere very high-speedprocessing, as well asmultitasking, are required.

    The Basic Principles ofan RTOS

    An RTOS is a programthat manages systemresources, schedules theexecution of various tasksin the system and providesservices for inter-tasksynchronization andmessaging. There are manybooks and sources ofreference that describe theoperation and principles ofvarious RTOS systems.

    Every RTOS consists of akernel that provides the lowlevel functions, mainly thescheduling, creation oftasks and inter-taskresource management.Most complex RTOSs alsoprovide file-handlingservices, disk input-outputoperations, interruptservicing, networkmanagement and usermanagement.

    A task is an independent thread ofexecution in a multitasking system, usuallywith its own local set of data. A multitaskingsystem consists of a number of independenttasks, each running its own code andcommunicating with each other in order tohave orderly access to shared resources. Thesimplest RTOS consists of a scheduler thatdetermines the execution order of the tasks in

    the system. Each task has its own contextconsisting of the state of the CPU andassociated registers. The scheduler switchesfrom one task to another one by performinga context switching where the context of therunning process is stored and context of thenext process is loaded appropriately so thatexecution can continue properly with the nexttask. The time taken for the CPU to perform

    Professor Dr Dogan Ibrahim, lecturer at the Near East University in Cyprus, describesthe design of a C-based, simple multitasking RTOS, using PIC microcontrollers

    RTOS: Simple Multitaskingwith Microcontrollers

    Figure 1: Co-operative scheduling

    Figure 2: Round-robin scheduling

    Figure 3: Pre-emptive scheduling

    20 June 10 - Electronics World

  • RTOS

    context switching is known as the contextswitching time and is negligible compared tothe actual execution times of the tasks.

    Although there are many variations ofscheduling algorithms in use, the three mostcommonly used algorithms are: Co-operative scheduling Round-robin scheduling Pre-emptive scheduling.

    The type of scheduling algorithm to beused depends on the nature of theapplication and, in general, most applicationsuse either one of the above algorithms, or acombination of them, or a modified versionof these algorithms.

    Co-operative scheduling (see Figure 1) isperhaps the simplest algorithm where tasksvoluntarily give up the CPU usage when theyhave nothing useful to do or when they arewaiting for some resources to becomeavailable. This algorithm has the disadvantagethat certain tasks can use excessive CPUtimes, thus not allowing some otherimportant tasks to run when needed. Co-operative scheduling is used in simplemultitasking systems with no time criticalapplications. A variation of the pure co-operative scheduling is to prioritize the tasksand run the highest priority computable taskwhen the CPU becomes available.

    Round-robin scheduling (see Figure 2)allocates each task an equal share of the CPUtime. Tasks are in a circular queue and whena tasks allocated CPU time expires, the task isremoved and placed at the end of the queue.This type of scheduling can not besatisfactory in many real-time applicationswhere each task can have varying amount ofCPU requirements depending on thecomplexity of processing involved. Onevariation of the pure round-robin schedulingis to provide a priority-based scheduling,where tasks with the same priority levelsreceive equal amounts of CPU time.

    Pre-emptive scheduling is themost commonly used schedulingalgorithm in real-time systems.Here, the tasks are prioritized andthe task with the highest priorityamong all other tasks gets theCPU time (see Figure 3). If a taskwith a priority higher than thecurrently executing task becomesready to run, the kernel saves thecontext of the current task andswitches to the higher priority taskby loading its context. Usually thehighest priority task runs tocompletion or until it becomesnon-computable, for example bywaiting for a resource to becomeavailable. At this point thescheduler determines the task withthe highest priority that can runand loads the context of this task.Although the pre-emptivescheduling is very powerful, care isneeded, as an error inprogramming can place a highpriority task in an endless loopand, thus, not release the CPU toother tasks. Some multitaskingsystems employ a combination ofround-robin and pre-emptivescheduling. In such systems, timecritical tasks are usually prioritizedand run under pre-emptivescheduling, whereas the non-timecritical tasks run under round-robinscheduling, sharing the left CPUtime among themselves.

    So far, we have said nothingabout how various tasks worktogether in an orderly manner. Inmost applications, data andcommands must flow betweenvarious tasks so that the tasks canco-operate and work together.

    www.electronicsworld.co.uk 21

    Figure 4: Programlisting of RTOS

  • RTOS

    22 June 10 - Electronics World

    One very simple way of doing this is throughshared data held in RAM where every task canaccess. Modern RTOS systems, however,provide local task memories and inter-task-communication tools such as mailboxes andpipes so that data can be passed securely andreliably between tasks. In addition, tools suchas event flags, semaphores and mutexes areusually provided for task, as well as inter-tasksynchronization purposes.

    RTOS Systems for PIC MicrocontrollersThere are several commercially available,

    shareware and open-source RTOS systems forthe PIC microcontroller family. Brief details ofsome popular RTOS systems are given in thissection.

    Salvo (www.pumpkininc.com) is a low-cost,event-driven, priority-based, multitasking RTOSdesigned for microcontrollers with limitedprogram and data memories. It can be used formany microcontrollers, including the 8051family, ARM, Atmel AVR, M68HC11, MS430,PIC microcontroller family and others. Salvo iswritten in ANSI C and supports a large numberof compilers, including Keil C51, Hi-Tech 8051,Hi-ech PICC-18, Microchip MPLAB C18 andmany others. A demo version (Salvo Lite) isavailable for evaluation purposes. The SE andLE versions are for systems requiring smallernumber of tasks with less features, while thePro version is the top model aimed forprofessional applications. The Pro versionsupports unlimited number of tasks withpriorities, event flags, semaphores, binarysemaphores, message queues and many morefeatures.

    CCS is a C compiler developed anddistributed by Custom Computer Services Inc(www.ccsinfo.com) for the PICmicrocontrollers. There are several versions ofthe compiler depending on the type ofmicrocontroller used in the target design. ThePCW models of the compiler support built-in

    RTOS. The provided RTOS is co-operative andrequires no interrupt features. The RTOSprovides a number of functions to start andterminate a task, to send messages betweentasks, to synchronize tasks using semaphoresand so on. When a task is scheduled to run,control of the processor is given to that task.When the task is complete, or does not needthe processor any more, control returns to adispatch function, which gives control of theprocessor to the next scheduled task. Becausethe RTOS does not use interrupts and is notpre-emptive, the user must make sure that atask does not run forever.

    CMX-Tiny+ (www.cmx.com) supports alarge number of microcontrollers, including thePIC24 and dsPIC family. This is a pre-emptiveRTOS, supporting a large number of featuressuch as event flags, messages, cyclic timers,semaphores and so on. This RTOS can beconfigured to operate as a co-operativescheduler if required. Although CMX-Tiny+ is ahighly sophisticated RTOS, it has thedisadvantage that the cost is relatively highand it is not available for lower members ofthe PIC family.

    PICos18 (www.picos18.com) is an open-source pre-emptive RTOS for the PIC18microcontrollers, developed under the GPLlicense. The full documentation and the sourcecode is provided free of charge for peoplewishing to use the product.

    MicroC/OS-II (http://micrium.com) is a low-cost priority based pre-emptive RTOS which hasbeen ported to many microcontrollers includingthe PIC microcontrollers. This RTOS isdeveloped in ANSI C with full source-code anddocumentation provided, and is used overhundreds of real-time products all over theworld. MicroC/OS-II is a highly sophisticatedRTOS, providing semaphores, mailboxes,event flags, timers, memory management,queues and so on.

    FreeRTOS (www.freertos.org) is an open-

    source royalty-free RTOS that can bedownloaded and used in commercialapplications. This RTOS has been ported tomany microcontrollers, including the PICfamily of microcontrollers. FreeRTOS is pre-emptive but can be configured for co-operative or hybrid operations. The softwaresupports interrupts, queues, mailboxes, binary

    Figure 5: PIC18 microcontrollerstack structure

    Figure 6: A simpleRTOS multitaskingexample

  • RTOS

    semaphores, counting semaphores, mutexesand so on.

    Finally, OSA-RTOS (http://picosa.narod.ru) isa freeware RTOS for PIC microcontrollersdistributed under the BSD license. This RTOSis compatible with a large number of Ccompilers, including the Microchip C18,mikroC and CCS. The full source code andthe documentation are available from thewebsite. OSA is a co-operative multitaskingRTOS, offering many features such assemaphores, events, data queues, mutexes,memory pools, system services and manymore.

    Development of the RTOSThis section describes the development of a

    simple, yet effective RTOS for micro-controllers, called the RTOS. AlthoughRTOS has been primarily developed for thePIC18 series of microcontrollers, it is writtenusing the C language and, thus, it should bepossible to modify and adapt it for othertypes of microcontrollers.

    One of the classical approaches to RTOSdesign is to use Task Control Blocks (TCBs). ATCB is basically a structure that stores theessential information about a task, such asthe return address, CPU registers, task state,local event flags, etc. RTOS has beendesigned to have a simple architecture andthus is not based on TCBs.

    RTOS uses a round-robin type schedulerwith the addition of allocating variable CPUtime to individual tasks. Thus, for pure round-robin type applications all tasks can beconfigured to have the same CPU timeallocations. Task durations, however, can beconfigured if desired so that tasks can beallocated different maximum CPU times.

    Task scheduling in RTOS is based on 1mstimer interrupts where context switchingoccurs within the timer interrupt serviceroutine. Data flow between the tasks can beachieved using common variables declared atthe beginning of the program. In addition,task synchronization tools are not provided inthis simple RTOS.

    Figure 4 shows the program listing ofRTOS. The code is based on the mikroClanguage from mikroElektronika(www.mikroe.com), which is currently one ofthe popular C language compilers for PICmicrocontrollers.

    Each task in RTOS is organized as a Cfunction, running forever in a loop. The first

    thing a task does is to call kernel functionInitTask which saves the task return address inan array called TStack. In addition, themaximum allocated duration of each task (inms) is also stored in array TTime. The programcounter of a PIC18 microcontroller is 24-bitswide and is stored in three 8-bit stackregisters TOSL, TOSH and TOSU after aprocedure call or an interrupt (see Figure 5).These registers are accessed by RTOS duringthe saving and restoring of task returnaddresses.

    In an application, the main programinitially calls all the tasks in turn so that theirreturn addresses can be saved. Thenfunction StartTasks is called. This functioncalls to SetUpTmrInt to configure timerTMR0 so that timer interrupts can begenerated every milliseconds for the kernel.In addition, the return address of Task 0 ispushed onto the stack and a RETURN isexecuted so that task execution starts fromTask 0. At the core of the kernel we havethe timer interrupt service routine (ISR). TheISR determines the next task to run andperforms the necessary context switching.The following operations are carried outwithin the ISR: Timer register TMR0 is reloaded for one

    millisecond interrupts; Current CPU registers W, STATUS and BSR

    are saved; If allocated duration of current task has not

    expired, then timer interrupts are re-enabled and ISR passes control back to thesame task with no context changing;

    Otherwise, the return address of currenttask is saved in array TStack;

    Task number of the next task is determinedand its return address is pushed ontoprocessor stack;

    CPU registers W, STATUS and BSR of nexttask are restored;

    Timer interrupts are re-enabled and ISRpasses CPU control to the next task.

    Using RTOSHere is an example to show how RTOS

    can be used in a simple multitaskingapplication. An LEDs is connected to port pinsRB0 of a PIC18F452 microcontroller, operatedfrom a 8MHz crystal. Similarly, port pins RB1and RB2 are connected to push-buttonswitches such that logic 0 is applied to thecorresponding microcontroller pin when aswitch is pressed. Three tasks named TASK0,

    TASK1 and TASK2 are created (see Figure 6)with the following functions:

    TASK 0: This task flashes the LED connectedto port pin RB0 as long as a Flag isset.

    TASK 1: This task clears the Flag whenbutton connected to RB1 is pressed,thus stops the flashing.

    TASK 2: This task sets the Flag when buttonconnected to RB2 is pressed, thus re-starts the flashing.

    Each task initially calls to function InitTaskwith its task number and maximum durationand then enters its endless loop. Task0flashes the LED as long as the Flag variable isset. Task1 and Task2 both wait in a whileloop until either switch RB1 or RB2 ispressed. Pressing RB1 clears the Flag and,thus, the flashing stops. Similarly, pressingRB2 sets the Flag and, as such, the flashing isre-started by Task0. Notice that a Macrocalled SwapTask can be used to stopexecution of the current task and passcontrol to the next task, i.e. it can be used toforce a context switching when a task hascompleted its execution or it has nothing elseuseful to do.

    The main program initially calls to all thetasks so that their return addresses are savedand then calls to function StartTasks to startexecution from Task0. Notice that variableFlag is used as a shared variable and thus itmust be declared at the beginning of theprogram.

    Simple and Effective RTOSThe development of a simple, yet effective

    RTOS system for the PIC18 series ofmicrocontrollers has been described.Although there are several commerciallyavailable microcontroller RTOS systems, someare expensive, or use too many resources ofthe target microcontroller. The RTOSdescribed in this paper (RTOS) is simple anduses only a timer and very small RAMmemory of the target microcontroller. Itshould be possible to use the RTOS in manysmall real-time multitasking applications. Thecode given in Figure 4 is configured for threetasks, 8MHz clock frequency and 1msscheduling time. These parameters can easilybe changed to suit any other application.

    www.electronicsworld.co.uk 23