connecting simulink to osek

12
Connecting Simulink to OSEK: Automatic Code Generation for Real-Time Operating Systems with TargetLink Lutz Köster, Thomas Thomsen, Ralf Stracke dSPACE Translation of “Von Simulink nach OSEK: Automatische Codegenerierung für Echtzeitbetriebssysteme mit TargetLink“ , published on the occasion of the congress Embedded Intelligence 2001, Nuremberg, Feb 14 - 16. dSPACE

Upload: others

Post on 12-Sep-2021

17 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: Connecting Simulink to OSEK

Connecting Simulink to OSEK:Automatic Code Generation

forReal-Time Operating Systems

with TargetLink

Lutz Köster, Thomas Thomsen, Ralf StrackedSPACE

Translation of“Von Simulink nach OSEK:

Automatische Codegenerierung für Echtzeitbetriebssystememit TargetLink“ ,

published on the occasion ofthe congress Embedded Intelligence 2001,

Nuremberg, Feb 14 - 16.

dSPACE

Page 2: Connecting Simulink to OSEK
Page 3: Connecting Simulink to OSEK

3

Connecting Simulink to OSEK: Automatic Code Generation forReal-Time Operating Systems with TargetLink

Lutz Köster, Thomas Thomsen, Ralf StrackedSPACE

.

ABSTRACT

This paper describes how one further step towardsintegrating the complete software development processof embedded real-time systems in Simulink andStateflow is achieved. Automatic code generation inproduction quality is already possible with dSPACE'sTargetLink. The next step is true integration of real-timeoperating systems into the code generation process.The OSEK standard is applied for this purpose andbriefly described at the beginning. The article thenfocuses on concepts and techniques used by TargetLinkto achieve OSEK-compliant code generation. It isshown, how operating system functions and propertiesare specified on a block diagram level, how code ofdifferent sample rates is bundled into different tasks,how tasks can communicate among each other and howall this can be simulated on a target system. The paperalso gives striking evidence of how powerful standardscan boost tool development and how they can helpintegrate different tool systems, which had beencompletely separated before.

INTRODUCTION

The software development of embedded systems isincreasingly being done with the help of simulation toolsthat are programmed with executable block-diagramspecifications. One of the most popular tool suites isMATLAB, Simulink and Stateflow from The MathWorks,which became the de-facto standard in the embeddedsystems industry. In 1999, dSPACE introducedTargetLink to the market, which extends Simulink andStateflow with a production quality code generator.TargetLink is able to produce ANSI-C code andprocessor/compiler-specific C code that is highlyreadable and small enough for resource-limited,embedded real-time systems. Since then, automaticcode generation with TargetLink has been proven in awide range of control applications. dSPACE now widensthe scope of code generation with the next version ofTargetLink by supporting OSEK-compliant real-timeoperating systems.

Modern ECUs, as they are used in automobiles andaircrafts, typically contain 3 distinguished software layers(see Figure 1). The highest layer is the application codeand contains signal processing, control strategies,failsafe and diagnostic functions. Simulink and Statefloware perfectly suited to specify and simulate thesefunctions. TargetLink then can be used to automaticallygenerate production code.

The lowest level is the hardware abstraction layer (HAL),which contains basic I/O routines, interrupt serviceroutines, device drivers and communication handlers.Block diagram specifications do not offer significantadvantages for this layer - they are directly programmedin C or assembly. Many of these routines are readilyavailable from external sources or are generated withthe help of processor-specific configuration tools.

In-between these layers is the real-time operatingsystem (RTOS), which is responsible for schedulingtasks and managing intertask communication andprocessor resources. Real-time operating systems forembedded systems are commercially available from avariety of vendors. They, too, typically come with aconfiguration tool and a system generator that

Figure 1: ECU software layers

Page 4: Connecting Simulink to OSEK

4

automatically builds the real-time kernel according to theuser's specification. In recent years, the OSEK standardemerged to standardize the Application ProgramInterface (API) and functionality of real-time operatingsystems. This makes it possible to connect codegenerators to kernel builders and to make the generatedcode compatible to the real-time kernel.

OSEK: GOALS AND CONCEPTS

The goal of the OSEK specification is to support theportability and reusability of application software. Toachieve this goal, the OSEK working groups definedabstract and application-independent user interfaces inthe areas of the real-time operating system,communication and network management. Theseinterfaces are also independent of hardware andnetwork. Different applications require different featuresof a real-time operating system. Small microcontrollershave only small amounts of memory, so ROM and RAMusage must be very economical. Bigger systems mayneed special features of the operating system and thelimitations concerning memory usage may be lessstringent. These different cases demand a scaleable andconfigurable real-time operating system.

The OSEK specification provides a pool of services andprocessing mechanisms, but leaves a certain amount offlexibility to allow optimal adaptation to differentmicrocontrollers.

For clarity it shall be repeated that OSEK itself is not anoperating system product. It only specifies a certain APIand behavior. There are several commercial OSproducts available on the market that are compliant tothe OSEK standard. Hereafter, they are referred to asOSEK operating system implementations.

The main benefits of the OSEK standard are:• Savings in costs by reducing development time.• Enhanced software quality because well-tested

software modules can be reused in differentapplications.

• Because OSEK is scalable, the specification of theoperating system allows optimal adjustment to thespecific application and thus reduces memory usagein small systems.

• The portability and reusability of application softwarefor different hardware platforms and possibly also fordifferent OSEK-compliant real-time operating systemimplementations.

The OSEK specification describes a static real-timeoperating system where all operating system objectssuch as tasks, events, messages and resources arecreated at compile time. These objects are defined, andtheir attributes are described offline with the help of theOSEK Implementation Language (OIL). OSEK definesseveral mandatory standard attributes - like the priorityof the object “TASK” - which must be implemented by allOSEK operating system implementations. Some of themare defined to ensure scalability of the operating system.

However, the OSEK operating system developer isallowed to define additional implementation specificattributes for the OSEK objects.

The application software can be subdivided into tasksaccording to their real-time requirements. For memoryefficiency reasons, OSEK distinguishes between basicand extended tasks. Basic tasks can assume the states‘running’, ‘ready’ or ‘suspended’. A task is running if theprocessor is assigned to it. At any one point in time, onlyone task can be in the running state. A task is ready, ifall the requirements for transition to the running state aremet, but the CPU is assigned to another task. Thescheduler decides when a ready task becomes arunning task. The ready task can interrupt a running taskif the priorities and preemptibilities allow this; otherwise,it has to wait until all tasks with higher priorities havefinished. In the suspended state, the task is passive.Before it can enter the ready state, it must be activated.In addition to basic tasks, extended tasks can enter a‘waiting’ state where they wait for at least one eventbefore continuing execution.

The functionality of the operating system is subdividedinto different conformance classes to ensure scalability.In the two basic conformance classes, only basic taskscan be used. The two extended conformance classesallow the usage of basic and extended tasks.

An OSEK operating system uses priority-basedscheduling. In addition, the priority ceiling protocol isincluded for resource handling. The use of the OSEKobject resource is similar to the use of semaphores inother operating systems, except that the priority ceilingprotocol avoids deadlocks during resource occupation.Resources can be used to manage concurrent accessesof tasks and interrupt service routines with differentpriorities to shared resources like memory or hardware.

OSEK defines counters and alarms to process recurringevents. Alarms are assigned to counters that count timeticks or other recurring signals such as angle-basedencoder interrupts. An alarm triggers an event oractivates a task whenever the counter reaches apredefined value. When the alarm is specified as beingcyclic, the associated task is called periodically, forexample, at certain sample times or certain crankshaftangles. Single alarms can be used, for example, totrigger a task some defined time after a certain eventhas occurred.

OSEK also defines message-based communicationbetween tasks (intertask communication). Messages canbe sent between tasks inside one ECU or they are usedfor communication between tasks on different ECUs.

For extended tasks the event mechanism can be usedfor task synchronization. An extended task can wait foran event until it is set by another extended task, a basictask, an alarm or an ISR (interrupt service routine). Afterthe event is set, the waiting task leaves the ‘waitingstate’ and enters the ‘ready state’.

Page 5: Connecting Simulink to OSEK

5

The processing of interrupts is supported in OSEK bydifferent categories of ISRs. Category 1 ISRs are notallowed to call any OSEK API function. They areabsolutely independent of the operating system. ISRs ofcategory 2 are allowed to call API functions at any placeinside the ISR, whereas category 3 ISRs are divided intotwo sections: in the first section no calling of any APIfunction is allowed, in the second section it is. Thissecond section must be nested by the special macrosEnterISR() and LeaveISR().

MODELING REAL-TIME (OSEK) APPLICATIONSIN SIMULINK / TARGETLINK

GENERAL MODELING STYLES

In recent years, Matlab/Simulink/Stateflow has becomea standard tool for modeling and offline simulation incontrol design. It is optimally tailored to the needs of thecontrol engineer and provides a powerful set of blocklibraries and toolboxes. The range of applications whereMatlab/Simulink/Stateflow is used is constantly growing.In addition to the classic offline simulation of dynamicsystems, the tool is used as the specification basis for allphases of the electronic control unit's moderndevelopment cycle. As a graphical and executablespecification, it replaces the classic, verbally-orientedapproaches. With this extended usage come newrequirements that formerly were not important. Inconjunction with highly efficient automatic productioncode generation, Matlab/Simulink/Stateflow now is usedto describe the complete application software. Here thereal-time operating system plays an important role, andOSEK is becoming increasingly popular in theautomotive field. The new version of dSPACE's codegenerator TargetLink provides seamless integration ofOSEK-conformant operating systems into theMatlab/Simulink/Stateflow environment and the codegenerated from it. In contrast to many CASE tools thathave their origin directly in software development, wheretasks, messages, resources, etc. are a natural part ofthe world, the classic domain ofMatlab/Simulink/Stateflow is function design, which hasa completely different abstraction level. Automatic codegeneration for real-time operating systems out ofMatlab/Simulink/Stateflow has to deal with the problemof mapping Simulink's modeling concepts onto availableoperating system services and providing newspecification options - e.g. by new blocks - to supportimportant operating system features. The codegenerator must be able to produce a proper real-timeimplementation for an unchanged Simulink model by awell-considered default behavior, and provide all theoptions necessary to optimally adjust the code toparticular user needs.

A real-time application based on a (multitasking) real-time operating system (RTOS) is divided into differentsoftware units that are called by the RTOS. These tasksusually combine parts of the software with common real-

time requirements such as timing, priority etc. They canbe called by the RTOS automatically at certain times, oractivated by hardware or software events. Simulinkmodels initially do not contain tasks but are built up fromother components. The code generator has to mapthese structures onto the RTOS software units.

A Simulink model usually is divided into hierarchicalsubsystems. The functional blocks of these subsystemsare executed either cyclically with a certain sample rateor driven by certain events. While Simulink generallyallows blocks with different sample rates to be mixedarbitrarily, production code generation reasonablyrequires that blocks with the same sample rate arecombined to form system units.

Figure 2 shows a typical Simulink/Stateflow diagram thatcontains cyclic and event-driven parts. In an enginecontrol application, for example, the electric throttlecontrol algorithm executes periodically and theignition/injection part is driven by crankshaft events.Generating code implementing this model as a real-time(OSEK) application contains the following steps.

The 10-millisecond and the 100-millisecond subsystemsare implemented as separate operating system TASKS.The corresponding functions in the C code must beextended by the necessary task declarations. The RTOSmust be configured in such a way that these tasks arecalled periodically with the specified rate. In an OSEKapplication, this is realized by alarms that are defined,assigned to timers and initialized properly at systemstartup.

The crankshaft synchronous subsystem is alsoimplemented as a separate task. It usually is assigneddirectly to a corresponding hardware event. Thestatechart in Figure 2 only serves to generate theappropriate trigger in the offline simulation. It has to be

Figure 2: Typical Simulink/Stateflow diagram

Page 6: Connecting Simulink to OSEK

6

ignored by the code generator. The user thereforeplaces the statechart outside the focus of the codegenerator, thus no code will be generated for thestatechart. This is an important concept. Simulinkmodels usually contain parts that specify the controllerand additional parts that are only needed for simulatingthe controller, e.g. plant subsystems for closed-loopsimulations. The code generator only works on thecontroller part of the model. In Figure 2, this is markedby the dashed rectangle.

Generally, asynchronous functions are modeled astriggered subsystems. If triggered subsystems areimplemented as separate tasks, they must be activatedby the source which releases the trigger. FC_System inFigure 2 is activated by code that is automaticallygenerated into task 100ms. If the trigger comes fromoutside the scope of the code generator, as forCrankshaft, the user must assign task activation to theproper source manually, e.g. to a hardware interrupt.

The data connections between the subsystems/tasksmust be handled carefully by the code generator. It mustbe considered that tasks may interrupt each otherrequiring that some data accesses must be protected toavoid inconsistencies. As a result, the code generatorsometimes creates local copies of global data for furtherprocessing. Data connections that cross the border ofthe code generator's scope - e.g., to pass data to handwritten code within the same ECU or to send data via abus to different ECUs - must be established, forexample, by operating system messages or by serviceroutines that access data resources.

Finally, an offline description of the application has to begenerated as the input to the tool that builds the tailoredreal-time kernel. This is done via the OIL file (OSEKImplementation Language), which is part of the OSEKspecification.

The following sections describe the different stepsmentioned above in greater detail.

TASKS

As described in the previous section, the Simulink modelis partitioned into tasks. If the user makes no specificinput, TargetLink uses a default partitioning. However,by means of special blocks (the task block, which isdescribed later), the user can completely determinewhich subsystems are assigned to which tasks.

By default, TargetLink groups together all the model'speriodic subsystems that have the same sample rate inseparate tasks. Triggered subsystems with commontrigger sources are combined, and their code is assignedeither to the trigger source's task where this is within thecode generator's scope (FC_System in Figure 2 isassociated to task 100ms ) or to a separate task.(Crankshaft in Figure 2).

By placing a special task block in a subsystem, the codegenerator's default task partitioning can be overruled.

The task block explicitly assigns a subsystem to acertain task. FC_System in Figure 3 will now beimplemented as a separate task. Its trigger source in100ms will not directly call the code of FC_System anymore, but will only produce the OSEK 'activateTask'command for the corresponding task; when it will bescheduled depends on task priorities andpreemptibilities.

As shown in Figure 3, it is also possible to assignseveral subsystems to one common task. The code for100ms and 10ms will now be included in the commonTask B. This combined task is scheduled periodically atten milliseconds, which is the highest commondenominator of both the sample rates involved. Acounter encapsulates the code of 100ms and executes itupon execution of every 10th task. Note, that the worstcase execution time must be less than 10 ms.Therefore, in most cases only subsystems with thesame sample rate are assigned to the same task.

The possibility of combining subsystems distributed overthe model to create common tasks allows a feature-oriented modeling style. It is not necessary to partitionthe model at the highest level with regards to samplerates or membership in certain events. Instead, themodel can be divided into parts belonging to the samehigh level functionality. An electronic control unit usuallycontains dozens of so-called features (e.g., throttlecontrol, idle speed control, EGR, injection, etc.) that aredeveloped by different teams. They form separatesubsystems at the topmost model level. Any of themmay contain parts that are executed at different samplerates. Bundling these parts (processes) of the samesample rate to one task avoids scheduling overhead.

The task block not only serves as a mean to assignsubsystems to certain tasks, but also provides aninterface to specify attributes of the corresponding task.Figure 4 shows the dialog which opens when the taskblock is double-clicked. The current subsystem can beassigned to an existing task, or a new task can be

Figure 3: Task block to define separate tasks

Page 7: Connecting Simulink to OSEK

7

created. The standard OSEK attributes such as priority,number of activations, full preemptive or non-preemptive, used resources or owned events, etc. canbe specified. Some of these settings influence only thegenerated OIL description and not the actual C sourcecode, others - such as priority and schedule - are usedby the code generator to optimize the code, e.g., fordata exchange, which will be shown in a later section ofthis paper. Figure 4 shows two tabs in the task block'sdialog: OSEK Standard and OSEK XYZ. OSEK itselfrequires a set of attributes that each RTOS vendor hasto provide, but allows additional implementation-specificsettings. For several commercially available operatingsystems, these specific options can also be selectedfrom TargetLink via the OSEK XYZ tab of the taskdialog. However, this does not limit the use of TargetLinkfor these supported OSEK products. A later section willshow how TargetLink can interact with any other desiredproducts and the corresponding operating systemconfiguration tools.

When tasks are created, either by the code generator'sdefault mechanism or by explicit user requests, thenecessary declarations are generated into the C sourcecode (e.g. TASK(T_100ms) { ...), and the taskactivation itself is initiated. Activation of periodic tasks isassigned to automatically generated OSEK alarms thatare initialized at system startup. Triggered tasks areactivated by code that is included in the task of thetrigger source. If this source is outside the scope of thecode generator, a piece of code (macro) that performsthis activation is generated, and the user must assign itto the trigger source, e.g., an interrupt.

INTERTASK COMMUNICATION

In Simulink, data exchange is modeled by signal lines. Ina task-driven preemptive environment, data exchangebecomes a more complex issue. One important job of anRTOS is to manage the communication between tasks.Inter-ECU communication is data exchange betweensoftware distributed to different physical hardware unitsand usually is handled by some kind of network layer.Intra-ECU communication is connections between tasksrunning on the same processor. While the former alwaysrequires operating system services (OSEK messages),the latter can optionally be implemented without OSinteraction.

Figure 5 shows a scenario where tasks with differentsample rates, priorities and preemptibilities exchangedata. Task A sends signal1 and signal2 to Task B.Global variables that can be accessed by both tasks areusually used for this data exchange. Since Task A ispreemptive (in OSEK terms SCHEDULE = FULL) andTask B has a higher priority, it may happen that Task Ais interrupted after signal1 has already been updated,but while signal2 still has its old value. Consequently,Task B would work with values for signal1 and signal2from different time steps. This inconsistency can lead tounwanted behavior and normally has to be avoided. Inthis example Task A is responsible for implementing amechanism that is suited to protect againstinconsistencies. One possible way is to use local copiesfor signal1 and signal2. At the end of Task A there is onecompact block of code that copies this localrepresentation to the corresponding global variables. Itstill has to be ensured that Task A is not interruptedduring this copying procedure. This can be done bydisabling interrupts or by using the OSEK serviceresource. The introduction of local working copies

Figure 4: Task block dialog

Figure 5: Communication between Tasks

Page 8: Connecting Simulink to OSEK

8

ensures that this time critical section is as short aspossible.

It depends on the task settings and the related question'who can be interrupted by whom' to determine if thesender or the receiver is responsible for implementationof inconsistency protection. In Figure 5, signal3 is alsopotentially exposed to an inconsistency. Although it is asingle data line, it represents a vector, and accesses to itcould be interrupted. However, in the particular case ofFigure 5, the sender cannot be interrupted by thereceiver (Task A has a higher priority than Task C) andvice versa (Task C is not preemptive, i.e., SCHEDULE =NON). In this case, both tasks can use the globalvariable for signal3 directly, which is of course the mostefficient way of data exchange.

Operating systems usually provide a means to exchangeprotected information between tasks. OSEK definesmessages as a common interface for protected intra-ECU communication and for inter-ECU communicationbased on a common bus. For data exchange betweentasks on the same ECU, these messages are not alwaysthe most efficient implementation since the automaticallyimplemented inconsistency protection is sometimes notnecessary, as shown in the last example. Per default,TargetLink therefore automatically selects the mostefficient implementation (global variables with or withoutcopies, interrupt lock, resources, etc.) depending on thetask’s priority and preemptibility. This default behaviorcan be overruled by explicit user settings. For instance,this might become necessary if the user cannot ensurethat these task settings will remain unchanged aftercode generation or if a signal goes outside the scope ofthe code generator.

SPECIAL BLOCKS

Special blocks that are not included in the normalSimulink blockset provide a specification interface tospecific OSEK features and reproduce their behavior

during simulation. The Alarm/Counter block is given asan example.As described in the Tasks section, alarms areautomatically used to set up time-periodic tasks. Inaddition, TargetLink provides a special block that makesthe general alarm functionality of OSEK available to theuser. Since each OSEK alarm is assigned to a counter,the TargetLink alarm block is always combined with aspecial counter block that was designed especially forthis purpose (see Figure 7).

Although the alarm and the counter always form a unit,they are divided into two blocks because one countercan have several associated alarms. Code for thecounter itself will usually not be generated because ahardware counter/timer or an operating system counterwill be used. The TargetLink counter will be used foroffline simulation only in this context. The settings in theblock dialog allow simulation settings adjustment to thereal counter behavior and reflect the standardized OSEKattributes for counters. The output signal of the counteris connected to one or more alarms. In the alarm block acounter value specifies when the alarm expires (the firsttime) and the task that is connected to this alarm by a(function call) trigger is activated. Cycle optionallydefines the periodicity of the alarm. Alarms are set up atsystem initialization - e.g., for time-periodic tasks - orwhen a certain event occurs at runtime. The secondcase is modeled by a special input for a trigger that canbe released by any source within the model. Absolute orrelative alarms can be specified. The former expire atabsolute counter values, whereas the latter expire at acertain number of time ticks after the alarm wastriggered.

OSEK CONFIGURATION, TOOL INTERACTION

A typical ECU application consists of several C sourcefiles. Some of them have been generated automatically

Figure 6: Specification of Inter-Task Communication

Figure 7: Alarm / Counter blocks

Page 9: Connecting Simulink to OSEK

9

by TargetLink, others are supplied by handprogrammers. As an input for the System Generator,there is one OIL file describing the complete real-timeapplication, both the automatically generated and thehandwritten parts. The System Generator is a toolprovided by the vendor of the operating system thatanalyzes the OIL file and optimally scales the OS for thespecific application. It generates C files and libraries thatare linked together with the other source files to form thefinal executable program (see Figure 8).

A critical path often is interaction and cooperationbetween the tools involved and the hand programmers.While one part of the application and the correspondingOIL description is supplied by TargetLink, the handprogrammer or any other source delivers an additionalpart. In contrast to the C code that can be derived fromseveral source files, the final OIL description must beone single document. Most OSEK vendors providegraphical tools to conveniently generate the textual OILfile. Such tools are especially useful since all commercialOSEK implementations have a lot of possible options inaddition to the standard. Some option selections are notindependent of others and without tool support, it is easyto produce inconsistencies. On the other hand, the usershould be able to specify most of the attributes for thoseapplication parts that come from Simulink directly in theblock diagram. It has already been pointed out thatsome of these attributes can be used for codeoptimization. TargetLink therefore works with an externalOIL file as the database for the RTOS settings. It canimport and export this data format. Simulink components(e.g., subsystems) can be assigned to OSEK objects(e.g., tasks) that already are in the OIL database, or newentries can be created. The user can choose the mostsuitable tool to enter attributes with. For example, it ispossible to specify the basic, i.e., OSEK standard,attributes of tasks within the TargetLink environment andcomplete the description with the OSEK vendor-specificsettings using the OIL configurator. By using thisexternal database, consistency can be ensured.

Changes made in any tool are automatically applied bythe others.

SIMULATING PRODUCTION CODE FOR OSEK

One of the major strengths of Simulink is that it providesan executable specification. The behavior of thecontroller to be designed can be simulated offline on thePC, often using plant models to close the loop (seeFigure 9).Besides this Floating-Point Simulation Mode of thestandard Simulink environment, TargetLink provides twofurther modes:• Production Code Host Simulation Mode• Production Code Target Simulation Mode

In Production Code Host Simulation Mode, theTargetLink-generated (fixed-point) production code isused for simulation instead of the original Simulinkblocks (software-in-the-loop). Technically, the generatedcode is inserted into an s-function (the Simulink blockthat allows C code to be integrated into simulation) thatreplaces the original controller part of the model. Usingthis simulation mode, the generated code can bevalidated and fixed-point arithmetic effects such asquantization errors, saturation or overflows can betested. The numerical effects that occur on the host PCare virtually the same as on the targetedmicroprocessor.

In Production Code Target Simulation Mode, theTargetLink-generated control algorithm is computed on amicrocontroller that is equivalent to those on theproduction ECUs (processor-in-the-loop). Simulink stillprovides the stimuli, i.e., the input signals for thecontroller, for example, computed by the plant model,and evaluates the outputs. These signals are sent to andreceived from the target microcontroller by the serialinterface of the PC. Again, this is accomplished by an s-function that replaces the original controller. Using theProduction Code Target Simulation Mode, finalverification of the generated production code can bemade under realistic closed-loop operating conditions.The output of the target compiler can be verifiedbecause it is part of the test loop.

These advantages must remain unchanged when codeis generated for OSEK. The original production code,now including OSEK API calls, shall be used for

Figure 8: Tool interaction

Figure 9: Floating-Point Simulation on Host PC

Page 10: Connecting Simulink to OSEK

10

simulation. To achieve this TargetLink provides thefollowing mechanisms.

SIMULATION WITHOUT AN OSEK OPERATINGSYSTEM

Even if no commercial OSEK operating system isavailable on the target, the code must be tested insimulation without any changes. To make that possible,TargetLink creates additional code that implements - in asimple way - all OSEK macros and API functions usedby the generated application code. These OSEK macrosand API functions do not necessarily have to form acomplete real-time operating system. They are tailoredto the special needs of this non real-time closed-loopsimulation.

During simulation, it is known at each time step whichtask is to be executed. For production code targetsimulation, a corresponding 'activate task' command issent to the target (by the s-function). It is not necessaryto have a complete scheduler on the target. A simplescheduler substitute can call the task like an ordinary Cfunction. This is because the effects that task executiontime can have on scheduling cannot be reproducedduring offline simulation. While the task executes on thetarget, the host waits for a response, and the simulationtime is halted. Therefore no other task becomes activeand no preemptive scheduler is needed.

The Production Code Host Simulation Mode is verysimilar to the Production Code Target Simulation Mode.As in production code target simulation, the generatedcode remains unchanged. Unlike target simulation, theproduction code and the simulation frame consisting ofthe generated OSEK API functions and macros are partof the s-function. Instead of sending the input data to thetarget, the s-function calls the simulation frame whichthen activates the tasks.

SIMULATION INCLUDING AN OSEK OPERATINGSYSTEM

The most realistic simulation results can be achieved ifeach software module in the final application is alreadyincluded in the simulation. From this point of view, it isuseful for the original OSEK operating system to be partof the production code target simulation. Thus correctinteraction between the automatically generated codeand the OS can be verified. Since the simulationremains non real-time and the simulation progress of themodel part that remains on the PC - e.g., the plantmodel - determines the simulation time, the operatingsystem on the target must be disconnected from its real-time inputs. The host PC, i.e., Simulink, must providethese stimuli, for example, hardware timer values,interrupts, etc., in accordance with the current simulationtime (see Figure 10).Let us assume an application with two periodic tasks;one with a sample rate of 10ms and the other with a rateof 100ms. Corresponding alarms are assigned to thesystem timer. Whenever the system timer reaches

values that are multiples of 10ms and 100msrespectively, the corresponding task is activated. Forsimulation, the system timer is disconnected from itshardware timebase. Without any host intervention itdoes not count up and target simulation idles. When thesimulation time in Simulink reaches 10ms (20ms,30ms,...), the PC forces the target to set the systemtimer to the corresponding value, and the original OSEKtask activation mechanism starts. After the task hasfinished, the computation results are sent back to thePC. The communication with the host is accomplishedby a low-priority idle task.

Because the system time used on the target is simulatedby Simulink and the host- PC sends input data and timercommands only after the previous simulation step wascompleted, the simulation does not run in real time. Themain benefit of this new kind of simulation is theverification of counter and alarm handling, event andmessage handling, task activation and task interaction.

TARGET SPECIFIC CODE GENERATION FORCOMMERCIAL OSEK IMPLEMENTATIONS

As previously mentioned, the OSEK specification leavesa certain amount of flexibility to allow optimal adaptationto different microcontrollers. As a consequence, differentOSEK vendors implement some functionality in differentways, even if the implementation is for the samemicrocontroller.An example is the API functions for counter access.There is no standard API function to read the systemtime. Therefore, the code for the same applicationappears slightly different for different OSEKimplementations. Wherever possible, TargetLink usesstandard OSEK API functions in the generated code.But when necessary, TargetLink uses implementation-

Figure 10: Target Simulation with an OSEK OS

Page 11: Connecting Simulink to OSEK

11

specific API functions to ensure efficient and readableapplication code.

Cooperation between major OSEK vendors anddSPACE ensures the best TargetLink support for thedifferent OSEK implementations.

Another area of incompatibility is the possible OILattributes for OSEK objects. Here the OS vendorsusually provide a lot more options than described in thestandard. For example, tasks have several additionalattributes and the user might want to specify theseattributes at the same place where an individualspecifies the standard attributes, i.e., in the TargetLinkTask block. TargetLink therefore provides a mechanismto identify these extensions to the standard and let theuser enter the desired options. The key for this feature isagain the OIL file. OSEK dictates that each vendordescribes even the non-standard attributes by name andpossible values in OIL syntax. TargetLink analyzes thisdescription and provides the necessary GUI where theuser can, for example, specify the stack mechanism fora task.

When the user wants to port an application from oneOSEK implementation to another, TargetLinkautomatically replaces the implementation-specific APIcalls (such as the counter accesses) and the specificOIL attributes. This increases portability. AlthoughOSEK was specified mainly to facilitate the reuse ofsoftware, these jobs would have to be done manually ifno automatic code generator were available.

CONCLUSION

A steadily increasing number of developmentdepartments from different automotive areas are usingMatlab/Simulink, one of the standard tools for the controlengineer, as a specification basis for the entiredevelopment cycle of electronic control units. This ismade possible in particular by the availability of toolssuch as TargetLink, which can automatically generateproduction-ready C code that has proven itself equal tohandwritten programs. For the implementation of

complete applications, the connection to a real-timeoperating system, in particular to the widespread OSEKstandard, is of elementary importance. This paper hasshown how TargetLink maps the basic modelingconcepts of Simulink onto the OSEK functionality. Thefunction developers can continue working in their familiarenvironment, which has proven its suitability ininnumerable applications all over the world, andadditionally get the flexibility and adaptability necessaryfor embedded software development. Some extensionsto the standard Simulink blockset that make all importantOSEK services and properties available in the modeland that are optimally adjusted to the Simulinkphilosophy were introduced. It was shown, despite somedivergent opinions, that Simulink together with thedescribed environment extension is very well suited tomodeling embedded software systems.

REFERENCES

[1] OSEK/VDX Operating System, Version 2.1,May 2000

[2] OSEK/VDX System Generation OIL: OSEKImplementation Language, Version 2.2, July 2000

[3] OSEK/VDX Communication, Version 2.2.1,September 2000

[4] TargetLink Production Code Generation Guide,dSPACE GmbH Paderborn Germany, May 2000

[5] Simulink User’s Guide, The MathWorks, Nattick, MAUSA 1999

[6] H. Hanselmann, U. Kiffmeier, L. Köster, M. Meyer,“Automatic Generation of Production Quality Codefor ECUs”, SAE 99, March 1-4, Detroit

CONTACT

Dr. Lutz Köster Lead Engineer SoftwaredSPACE GmbH Technologiepark 2533100 Paderborn [email protected] http://www.dspace.de

OSEK/VDX Homepage: http://www.osek-vdx.org/

Page 12: Connecting Simulink to OSEK

USA and Canada

dSPACE Inc.28700 Cabot Drive . Suite 1100Novi . MI 48377Tel.: +1 248 567 1300Fax: +1 248 567 [email protected]

FrancedSPACE SARLParc BurospaceBâtiment 17Route de la Plaine de Gisy91573 Bièvres CedexTel.:+33 1 6935 5060Fax:+33 1 6935 [email protected]

Headquarters in Germany

dSPACE GmbHTechnologiepark 2533100 PaderbornTel.: +49 5251 1638-0Fax: +49 5251 [email protected]

United KingdomdSPACE Ltd.2nd Floor Westminster HouseSpitfire CloseErmine Business ParkHuntingdonCambridgeshire PE29 6XYTel.: +44 1480 410700Fax: +44 1480 [email protected]

dSPACE