12.07.2015 Views

Download - Czech Technical University in Prague

Download - Czech Technical University in Prague

Download - Czech Technical University in Prague

SHOW MORE
SHOW LESS

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

<strong>Czech</strong> <strong>Technical</strong> <strong>University</strong> <strong>in</strong> <strong>Prague</strong>Faculty of Electrical Eng<strong>in</strong>eer<strong>in</strong>gDepartment of Control Eng<strong>in</strong>eer<strong>in</strong>gMASTER THESISRTW target for L<strong>in</strong>ux with CANopensupportAuthor: Bc. Lukáš HamáčekSupervisor: Ing. Libor Waszniowski, Ph.D. <strong>Prague</strong>, 2009


PoděkováníTímto bych rád poděkoval všem, kteří mi přispěli cennými radami a pomocí při vypracovánídiplomové práce, zejména mému vedoucímu <strong>in</strong>g. Liboru Waszniowskému, PhD.Zvláštní poděkování patří také mé rod<strong>in</strong>ě, která mi během celého studia poskytovalapodporu jak materialní tak duševní.


AbstractThe goal of this master thesis was to create the support of CANopen communicationprotocol <strong>in</strong> L<strong>in</strong>ux target for the Real Time Workshop tool of Matlab. First of all,the toolset (target) for Real Time Workshop was prepared to enable code generation,compilation and execution at the MPC5200 based s<strong>in</strong>gle-board computer runn<strong>in</strong>g L<strong>in</strong>uxoperat<strong>in</strong>g system. The architecture and particular scripts of this target are described <strong>in</strong>the first part of this thesis. The ma<strong>in</strong> task of this work was <strong>in</strong>tegration of CanFestival,the open source implementation of the CANopen stack, <strong>in</strong>to the code automatically generatedfrom the Simul<strong>in</strong>k model. The CANopen blockset, provid<strong>in</strong>g protocol API <strong>in</strong> theSimul<strong>in</strong>k model, has been developed for this reason. The CANopen blockset is described<strong>in</strong> the second part of this thesis. Moreover, examples of us<strong>in</strong>g the target and the blocksetare attached to simplify the quick start of us<strong>in</strong>g these tools.AbstraktCílem této diplomové práce bylo vytvořit podporu komunikace po protokolu CANopenv kódu generovaném pomocí nástroje Real Time Workshop, který je součástí programuMatlab. Dokument popisuje nejprve takzvaný target, což je sada nástrojů umožňujícígenerování, překlad a spustění kódu na cílové platformě tvořené počítačem BOA5200s operačním systémem L<strong>in</strong>ux. Hlavní část diplomové práce se poté zaměřuje na <strong>in</strong>tegraciovladače protokolu CANopen do kódu generovaného z Matlabu. K tomuto účeluje vytvořena sada Simul<strong>in</strong>kových bloků (CANopen blockset), která zpřístupňuje rozhraníovladače pro použití v modelu Simul<strong>in</strong>ku. Obě části práce jsou doplněny ukázkovýmiaplikacemi pro rychlé pochopení práce s nástroji.5


Contents1 Introduction 91.1 Work motivation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 101.2 Employed technologies . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 101.2.1 BOA 5200 computer . . . . . . . . . . . . . . . . . . . . . . . . . . 101.2.2 Matlab - Simul<strong>in</strong>k . . . . . . . . . . . . . . . . . . . . . . . . . . . . 111.2.3 Matlab - Real Time Workshop . . . . . . . . . . . . . . . . . . . . . 111.2.4 CANopen protocol . . . . . . . . . . . . . . . . . . . . . . . . . . . 111.2.5 CanFestival driver . . . . . . . . . . . . . . . . . . . . . . . . . . . 121.3 Solution concept . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 121.3.1 Embedded target creation . . . . . . . . . . . . . . . . . . . . . . . 121.3.2 CANopen blockset . . . . . . . . . . . . . . . . . . . . . . . . . . . 131.3.3 Simulation support of CANopen blocks . . . . . . . . . . . . . . . . 132 L<strong>in</strong>ux ERT Target 152.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 162.2 Target <strong>in</strong>stallation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 172.2.1 Installation prerequisites . . . . . . . . . . . . . . . . . . . . . . . . 172.2.2 M<strong>in</strong>GW environment <strong>in</strong>stallation . . . . . . . . . . . . . . . . . . . 172.2.3 L<strong>in</strong>ux ERT Target <strong>in</strong>stallation . . . . . . . . . . . . . . . . . . . . . 182.2.4 BOA mach<strong>in</strong>e preparation . . . . . . . . . . . . . . . . . . . . . . . 192.3 Target architecture . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 232.3.1 Target configuration scripts . . . . . . . . . . . . . . . . . . . . . . 232.3.2 Code generat<strong>in</strong>g scripts . . . . . . . . . . . . . . . . . . . . . . . . . 252.4 Generated code . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 282.4.1 Ma<strong>in</strong> function . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 282.4.2 Makefile . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 312.4.3 Script go and the build process . . . . . . . . . . . . . . . . . . . . 333 CANopen blockset 343.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 353.1.1 Simulation capabilities . . . . . . . . . . . . . . . . . . . . . . . . . 353.1.2 Blockset parts . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 353.2 Installation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 373.2.1 Object Dictionary editor <strong>in</strong>stallation . . . . . . . . . . . . . . . . . 373.2.2 CANopen blockset <strong>in</strong>stallation . . . . . . . . . . . . . . . . . . . . . 373.2.3 CANopen support <strong>in</strong> the target . . . . . . . . . . . . . . . . . . . . 373.2.4 Updat<strong>in</strong>g CanFestival version . . . . . . . . . . . . . . . . . . . . . 383.3 EDS file and Object Dictionary . . . . . . . . . . . . . . . . . . . . . . . . 396


3.3.1 CanFestival OD editor . . . . . . . . . . . . . . . . . . . . . . . . . 393.4 CANopen node block . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 403.4.1 Block parameters . . . . . . . . . . . . . . . . . . . . . . . . . . . . 403.4.2 ObjectDictionary class and EDS file parser . . . . . . . . . . . . . . 433.4.3 Block functionality . . . . . . . . . . . . . . . . . . . . . . . . . . . 433.4.4 Simulation capabilities . . . . . . . . . . . . . . . . . . . . . . . . . 443.4.5 Block code generation . . . . . . . . . . . . . . . . . . . . . . . . . 443.5 Callbacks block . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 453.5.1 Block parameters . . . . . . . . . . . . . . . . . . . . . . . . . . . . 453.5.2 Block functionality . . . . . . . . . . . . . . . . . . . . . . . . . . . 493.5.3 Simulation capabilities . . . . . . . . . . . . . . . . . . . . . . . . . 493.5.4 Block code generation . . . . . . . . . . . . . . . . . . . . . . . . . 503.6 Callback parameters parser blocks . . . . . . . . . . . . . . . . . . . . . . . 513.6.1 Parser blocks parameters . . . . . . . . . . . . . . . . . . . . . . . . 513.6.2 Simulation capabilities . . . . . . . . . . . . . . . . . . . . . . . . . 513.6.3 Emergency callback parameters parser block . . . . . . . . . . . . . 523.6.4 Heartbeat error callback parameters parser block . . . . . . . . . . 523.6.5 Slave boot up callback parameters parser block . . . . . . . . . . . 533.7 SYNC message generator block . . . . . . . . . . . . . . . . . . . . . . . . 543.7.1 Block parameters . . . . . . . . . . . . . . . . . . . . . . . . . . . . 553.7.2 Block code generation . . . . . . . . . . . . . . . . . . . . . . . . . 553.8 Asynchronous operations block . . . . . . . . . . . . . . . . . . . . . . . . 563.8.1 SDO transfers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 563.8.2 Block <strong>in</strong>puts and outputs . . . . . . . . . . . . . . . . . . . . . . . 563.8.3 Block parameters . . . . . . . . . . . . . . . . . . . . . . . . . . . . 573.8.4 Block code generation . . . . . . . . . . . . . . . . . . . . . . . . . 623.8.5 Simulation capabilities . . . . . . . . . . . . . . . . . . . . . . . . . 623.9 Function call offset block . . . . . . . . . . . . . . . . . . . . . . . . . . . . 633.9.1 Block code generation . . . . . . . . . . . . . . . . . . . . . . . . . 643.10 Asynchronous rate transition block . . . . . . . . . . . . . . . . . . . . . . 653.10.1 Block code generation . . . . . . . . . . . . . . . . . . . . . . . . . 664 Conclusion 67A Target usage example 70A.1 Model target configuration . . . . . . . . . . . . . . . . . . . . . . . . . . . 70A.2 Model creation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 71A.3 Code build<strong>in</strong>g and execution . . . . . . . . . . . . . . . . . . . . . . . . . . 72B CANopen blockset usage example 74B.1 Def<strong>in</strong>ition of the control problem . . . . . . . . . . . . . . . . . . . . . . . 74B.2 Creation of the node Object Dictionary . . . . . . . . . . . . . . . . . . . . 75B.3 Creation of the Simul<strong>in</strong>k model . . . . . . . . . . . . . . . . . . . . . . . . 76B.3.1 CANopen callbacks . . . . . . . . . . . . . . . . . . . . . . . . . . . 77B.3.2 Creat<strong>in</strong>g the controller . . . . . . . . . . . . . . . . . . . . . . . . . 79B.4 Generat<strong>in</strong>g and compil<strong>in</strong>g the code . . . . . . . . . . . . . . . . . . . . . . 807


C Blockset common use cases 82C.1 Synchronous master node . . . . . . . . . . . . . . . . . . . . . . . . . . . 82C.2 Synchronous slave node . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 83C.3 Synchronous CANopen sensor . . . . . . . . . . . . . . . . . . . . . . . . . 84C.4 Asynchronous CANopen node . . . . . . . . . . . . . . . . . . . . . . . . . 86C.5 Model with two CANopen nodes . . . . . . . . . . . . . . . . . . . . . . . 88D Abbreviations 90E Attached CD content 918


Chapter 1Introduction9


1.1 Work motivationAs an <strong>in</strong>troduction to this work I will write a few words about code generation and Iwill try to expla<strong>in</strong> the ga<strong>in</strong> of code generation from a model. I will focus on control systemapplications executed by an embedded computer. Applications <strong>in</strong> control eng<strong>in</strong>eer<strong>in</strong>ghave some common features. The application is based on runn<strong>in</strong>g periodic task or tasksthat conta<strong>in</strong> new output calculation <strong>in</strong> each step. It means that all the applications havesimilar architecture and code generation is reasonable <strong>in</strong> this case.The automated code generation technique became very popular because it has a lot ofadvantages over the manual programm<strong>in</strong>g. Firstly, the code generation enables very fastapplication design. While hav<strong>in</strong>g the required hardware supported by the code generationtool, the application can be done <strong>in</strong> a few hours. Moreover, the correct work<strong>in</strong>g of theapplication kernel is ensured and does not need to be tested anymore.The other significant advantage is that code generation isolates low level programm<strong>in</strong>gfrom application design. Professional control system eng<strong>in</strong>eer is then able to create embeddedcontroller without hav<strong>in</strong>g extensive programm<strong>in</strong>g skills.F<strong>in</strong>ally, all the code fragments that appear <strong>in</strong> the f<strong>in</strong>al program are written just oncewhile develop<strong>in</strong>g the code generation tool. It faces to more reliable code which is writtenmore rigorously as it is expected to be used <strong>in</strong> many applications.Very popular application for control systems design is Matlab-Simul<strong>in</strong>k which createsenvironment for controller tun<strong>in</strong>g and simulation. Real Time Workshop [Mat] is a partof Matlab which provides tools for code generation from the Simul<strong>in</strong>k model. Real TimeWorkshop def<strong>in</strong>es C-language code representation of each block of Simul<strong>in</strong>k block libraryand places it <strong>in</strong>to the proper part of model source while generat<strong>in</strong>g the code. Moreover,ma<strong>in</strong> function of the generated application ensures model synchronization and communicationwith orig<strong>in</strong>al Simul<strong>in</strong>k model via TCP connection.The code generation obviously depends on the target platform def<strong>in</strong>ed by computertype and operat<strong>in</strong>g system. Real Time Workshop supports several platforms, however,processor PowerPC 5200, which is used at the Department of Control Eng<strong>in</strong>eer<strong>in</strong>g is notsupported. The support for BOA5200 computer (equipped by PowerPC 5200 processor)[AM] and L<strong>in</strong>ux operat<strong>in</strong>g system was prepared by Pavel Jelínek <strong>in</strong> his master thesis[Jel08].The BOA computer is equipped by the CAN bus port [CiAa]. The aim of this workis to create Simul<strong>in</strong>k support for CANopen protocol communication [CiAb] and enablecode generation of real-time application us<strong>in</strong>g CANopen communication.1.2 Employed technologiesThe follow<strong>in</strong>g section describes briefly the hardware, software and protocols used <strong>in</strong>this thesis.1.2.1 BOA 5200 computerBOA5200 is s<strong>in</strong>gle-board embedded computer based on the PowerPC 5200 processor.It is equipped by 128MB of RAM, 32MB of FLASH memory and Ethernet, RS232 andtwo CAN peripherals. This computer is runn<strong>in</strong>g L<strong>in</strong>ux 2.6 hav<strong>in</strong>g SocketCan [Ber] CANdriver <strong>in</strong>cluded <strong>in</strong> its kernel <strong>in</strong> our application. The file system image <strong>in</strong>cludes SSH server10


to enable us<strong>in</strong>g SSH connection and file transfers from the host computer to BOA. Imagesof both L<strong>in</strong>ux kernel and file system have been already prepared <strong>in</strong> [Jel08].1.2.2 Matlab - Simul<strong>in</strong>kSimul<strong>in</strong>k is a part of Matlab software which provides graphical user <strong>in</strong>terface for numericalsimulations. It conta<strong>in</strong>s basic blocks that provide signal rout<strong>in</strong>g, simple mathematicaloperations and data display <strong>in</strong>to charts. Simul<strong>in</strong>k is enhanced by blocksets like ControlSystem Blockset, Aerospace Blockset and many others. These blocksets provide blocks ofmore sophisticated functions.Simulation model is created by connect<strong>in</strong>g particular blocks together. This model isthen simulated <strong>in</strong> discrete or cont<strong>in</strong>uous sample time by Simul<strong>in</strong>k eng<strong>in</strong>e.Simul<strong>in</strong>k provides also the possibility to create new blocks. The user def<strong>in</strong>ed blockfunctionality is written <strong>in</strong> so called S-function which conta<strong>in</strong>s the code that should beperformed at the <strong>in</strong>itialization phase, simulation step, and so on. This S-function is attachedto the S-function block <strong>in</strong> the Simul<strong>in</strong>k model. The user <strong>in</strong>terface of the block canbe customized by the block mask.Note The blockset has been developed and tested at the Matlab version 2008a. However,it should work at the newer versions as well.1.2.3 Matlab - Real Time WorkshopReal Time Workshop is a Matlab tool which is able to generate C language code fromthe Simul<strong>in</strong>k model. This code can be compiled with any C compiler and while runn<strong>in</strong>git performs the same operations as the Simul<strong>in</strong>k model dur<strong>in</strong>g simulation. The generatedcode is equipped by feature called External mode. It is possible to connect from theSimul<strong>in</strong>k model to the runn<strong>in</strong>g generated application via TCP and the External mode.The simulation <strong>in</strong> Simul<strong>in</strong>k can be then performed <strong>in</strong> the same way as without generatedcode with the difference that it is physically runn<strong>in</strong>g the external program and the dataexchange and control signals are transfered via the External mode.It is obvious that code generation and compilation is platform dependent. It meansthat code generated for PC and W<strong>in</strong>dows will not work at embedded computer runn<strong>in</strong>gL<strong>in</strong>ux and vice versa. The tool which customizes the code while generat<strong>in</strong>g and preparesMakefile for its compilation is called target.1.2.4 CANopen protocolCANopen protocol [Wik] is designed to enhance CAN bus communication protocol.It creates <strong>in</strong> fact the application layer to the CAN protocol accord<strong>in</strong>g to the OSI model(Open System for Interconnection). CANopen uses CAN messages to transmit its dataand def<strong>in</strong>es mean<strong>in</strong>g of particular message IDs.CANopen network consists of particular nodes (devices). Each node is def<strong>in</strong>ed by itsObject Dictionary (OD). This dictionary is a data structure which keeps all the <strong>in</strong>formationabout communication, node and device sett<strong>in</strong>gs as well as the state variables of thedevice. It means, for example, that the CANopen thermometer has the current temperaturevalue stored <strong>in</strong> its OD. Read CANopen protocol description at [CiAb] for detail11


<strong>in</strong>formation.1.2.5 CanFestival driverCanFestival is an open-source driver for CANopen network. This implementation ofCANopen stack has been chosen due to the fact that it supports L<strong>in</strong>ux OS as well asthe SocketCan CAN bus driver used by our L<strong>in</strong>ux kernel. The driver code architecture isobviously well-considered and I have not noticed any serious limitations <strong>in</strong> us<strong>in</strong>g it. On theother hand, the driver is still <strong>in</strong> development and it yields a lot of problems. The authorteam has not released any official version of the driver for a long time. It means that theonly way how to obta<strong>in</strong> the current version is the CVS checkout. However, the code <strong>in</strong>the CVS repository is cont<strong>in</strong>uously chang<strong>in</strong>g and not only by fix<strong>in</strong>g bugs and add<strong>in</strong>g newfeatures but by chang<strong>in</strong>g exist<strong>in</strong>g API functions as well. Moreover, the changes and thecode itself are not documented very well. It makes follow<strong>in</strong>g the current driver versionabsolutely impossible.Approximately <strong>in</strong> the same time as I started work<strong>in</strong>g on this project, my colleaguestarted customiz<strong>in</strong>g the driver to be used at 16-bit micro-controller without operat<strong>in</strong>gsystem. On the basis of experience with CanFestival described above, we decided to stopupdat<strong>in</strong>g the driver from CVS repository and fix a stable version <strong>in</strong> our repository. It doesnot mean that updat<strong>in</strong>g CanFestival version used by CANopen blockset is not possible.It would just need more effort than pure update of repository. Read section 3.2.4 for more<strong>in</strong>formation about updat<strong>in</strong>g CanFestival version.1.3 Solution conceptThe master thesis goal is to create CANopen protocol support <strong>in</strong>to Real Time Workshopto enable generat<strong>in</strong>g applications us<strong>in</strong>g CANopen communication from Simul<strong>in</strong>kmodel. The application has to be compatible with the BOA5200 computer runn<strong>in</strong>g L<strong>in</strong>ux.Solv<strong>in</strong>g a few tasks allows reach<strong>in</strong>g the goal. First of all, the target has to be preparedto enable generat<strong>in</strong>g, build<strong>in</strong>g and execut<strong>in</strong>g the code at the BOA computer. Then,the CANopen blockset has to be created to provide CANopen API to be used <strong>in</strong> Simul<strong>in</strong>kmodel. CANopen blocks provide high level simulation of data exchange and eventsoccurrence and generation of code <strong>in</strong>terfac<strong>in</strong>g the CANopen stack.1.3.1 Embedded target creationThe target customiz<strong>in</strong>g the code generated by Real Time Workshop to be used at theBOA computer have been prepared by Pavel Jelínek [Jel08]. The target is supplementedby a set of tools that provide code compilation <strong>in</strong> W<strong>in</strong>dows and upload<strong>in</strong>g the programexecutable <strong>in</strong>to the BOA mach<strong>in</strong>e. MSYS environment runn<strong>in</strong>g <strong>in</strong> W<strong>in</strong>dows is used toexecute cross-compiler based on GCC, which compiles generated code and creates L<strong>in</strong>uxexecutable. This executable file is transfered by SCP to BOA mach<strong>in</strong>e and started viaSSH connection.The tools described above are already done and work<strong>in</strong>g properly. However, the targetfor Real Time Workshop is of type GRT (Generic Real-time Target) which uses basic typeReal Time Workshop for code generation. Matlab provides enhanced version of this tool12


called Real Time Workshop Embedded Coder generat<strong>in</strong>g optimized code. The target basedon ERT (Embedded Real-time Target) has to be used to enable generat<strong>in</strong>g code by RTWEmbedded Coder. Creation of this target for the desired platform is the first goal of thisthesis. Moreover, the documentation of compiler tools and environments should be jo<strong>in</strong>twith the new target documentation to provide unified user guide. The target creationand the unified documentation are described <strong>in</strong> the chapter L<strong>in</strong>ux ERT Target 2 of thisdocument.1.3.2 CANopen blocksetThe ma<strong>in</strong> idea of CANopen [CiAb] support is to <strong>in</strong>tegrate CanFestival driver [LOLb]<strong>in</strong>to the code generated by ERT target and create Simul<strong>in</strong>k blocks that provide API ofparticular driver functions. The <strong>in</strong>tegration itself means <strong>in</strong> fact enhanc<strong>in</strong>g the generatedMakefile so that the driver libraries are l<strong>in</strong>ked together with the generated code whilebuild<strong>in</strong>g the executable file. If the appropriate driver header files are <strong>in</strong>cluded <strong>in</strong>to thegenerated code, driver functions can be used.To implement the driver API <strong>in</strong> Simul<strong>in</strong>k it is necessary to create blocks that will generatecode mak<strong>in</strong>g the driver to do the required operations. Each block can add its code<strong>in</strong>to the model Start and Term<strong>in</strong>ate function to perform the necessary sett<strong>in</strong>gs. The ma<strong>in</strong>function of each block is placed <strong>in</strong> its Output function which is performed periodically <strong>in</strong>the simulation steps or asynchronously after some event occurrence.Additionally, the driver itself has to be <strong>in</strong>itialized and started. The CANopen nodeblock (section 3.4) will be created to control the driver. This block will be the ma<strong>in</strong>block of the blockset and it will have to be used just once for each CANopen node <strong>in</strong> themodel (the blockset will support creation of more nodes as BOA has 2 CAN ports). Thisblock will read the EDS file def<strong>in</strong><strong>in</strong>g the node behavior and set the block configurationaccord<strong>in</strong>g to the file content. Moreover, <strong>in</strong>puts and outputs of the block will match thePDO data messages mapp<strong>in</strong>g and provide direct access to synchronously transfered dataobjects.Support for synchronization messages generation will be provided by a special blockwhich will send the message <strong>in</strong> each simulation step. Asynchronous events like node statechange, emergency message reception, etc. are handled by callback functions <strong>in</strong> CanFestivaldriver. Callbacks block will convert these functions to Simul<strong>in</strong>k function call signalsthat will activate particular Function call subsystems. Callbacks parameters will be providedby parameters parser blocks to the model.The blocks described above provide the ord<strong>in</strong>ary work<strong>in</strong>g of the node. Asynchronousoperations like SDO messages, Network management, etc. will be supported by anAsynchronous block (section 3.8). This block will perform a def<strong>in</strong>ed set of asynchronousoperations. It will be designed ma<strong>in</strong>ly for use <strong>in</strong> the function call subsystem to handleevents.1.3.3 Simulation support of CANopen blocksThe ma<strong>in</strong> goal of CANopen blockset project is to create a tool for code generationfor model us<strong>in</strong>g CANopen communication. However, it is very useful to provide at leasta basic simulation capability to enable controller tun<strong>in</strong>g just <strong>in</strong> Simul<strong>in</strong>k while design<strong>in</strong>gthe embedded device. There are a few ways how to handle the simulation. They differs<strong>in</strong> the level of CANopen network simulation.13


The most universal way of network simulation is the simulation of CAN bus and thecomplete message traffic. This would enable to simulate all the CANopen features <strong>in</strong>clud<strong>in</strong>gNetwork management, emergency messages and so on. On the other hand, thissimulation support would take a lot of work on someth<strong>in</strong>g which is not a goal of theproject at all as we do not want to create CANopen network simulator.The other way is based on simulation <strong>in</strong>puts and outputs of particular blocks. Itmeans that if some block reads some value from network communication and providesit at his output, a simulation <strong>in</strong>put will be created and its value will be used <strong>in</strong>stead ofthe received message <strong>in</strong> case of simulation. Almost all data transfers can be simulatedus<strong>in</strong>g this method, however, the nodes do not use any object dictionary to store theirvalues. It means that the data <strong>in</strong>tegrity between nodes <strong>in</strong> the model is not ensured dur<strong>in</strong>gsimulation.The compromise solution is to enhance the previous method by stor<strong>in</strong>g object dictionarycontent of each node <strong>in</strong>to the Matlab workspace. CANopen node and Asynchronousblocks will work with these data objects. The remote node can be simulated by us<strong>in</strong>gextra CANopen node block, which will create its OD <strong>in</strong> the workspace and other blockcan simulate read<strong>in</strong>g or writ<strong>in</strong>g to the remote node OD. Simulation of this type will beused <strong>in</strong> the blockset. Read particular sections <strong>in</strong> block descriptions to learn more aboutthe simulation.14


Chapter 2L<strong>in</strong>ux ERT Target15


2.1 IntroductionReal Time Workshop embedded coder is a Matlab tool which provides the code generationof any Simul<strong>in</strong>k model. This is very useful for quick application development.User can create, for example, some controller model <strong>in</strong> Simul<strong>in</strong>k and just click Generatecode to get source code of the controller <strong>in</strong> C language. Obviously, the code has to becustomized for particular hardware and eventually operat<strong>in</strong>g system (Target with uppercase T ). This customization of generated code is controlled by targets (target with lowercase t). Matlab conta<strong>in</strong>s a set of targets. Each target def<strong>in</strong>es some platform (Target)which it is designed for (PC + W<strong>in</strong>dows, Unix, etc.).L<strong>in</strong>ux ERT target is based on generic Unix target and is design to control code generationfor Target platform BOA5200 computer [AM] and L<strong>in</strong>ux. This computer is equippedby two CAN peripherals [CiAa], so the target conta<strong>in</strong>s support for CANopen blockset. Itis Simul<strong>in</strong>k blockset which <strong>in</strong>tegrates the CANopen [CiAb] driver to the generated codeand enables the user to develop embedded applications us<strong>in</strong>g CANopen communication.However, the blockset is described <strong>in</strong> a separate documentation. The simple diagram ofReal Time Workshop pr<strong>in</strong>ciple is shown <strong>in</strong> the figure 2.1.W<strong>in</strong>dowsEthernetBOA5200TCP connectionExternal modeL<strong>in</strong>ux ERT TargetCode generationC source files and MakefileL<strong>in</strong>uxBuild<strong>in</strong>gL<strong>in</strong>ux executableMSYSSCP copyStart via SSHL<strong>in</strong>ux executableHardware peripheralsFigure 2.1: Real Time Work Target pr<strong>in</strong>cipleThis document describes everyth<strong>in</strong>g which is necessary to know for gett<strong>in</strong>g startedwork<strong>in</strong>g with the target. The first chapter 2.2 describes the target <strong>in</strong>stallation and <strong>in</strong>stallationof all support<strong>in</strong>g tools like compilers on W<strong>in</strong>dows host PC. Additionally, theBOA software equipment is def<strong>in</strong>ed and its preparation is described. The architecture ofthe target itself, <strong>in</strong>clud<strong>in</strong>g particular files description (section 2.3), and generated codeappearance (section 2.4) is expla<strong>in</strong>ed later <strong>in</strong> the document. F<strong>in</strong>ally a simple tutorial(section A) on us<strong>in</strong>g the target is attached to make the first steps with target as easy aspossible.16


2.2 Target <strong>in</strong>stallationThe L<strong>in</strong>ux ERT Target is designed to be used <strong>in</strong> W<strong>in</strong>dows operat<strong>in</strong>g system. However,the Target mach<strong>in</strong>e BOA5200 [DoCE] is runn<strong>in</strong>g OS L<strong>in</strong>ux so that the generatedcode has to be compiled for L<strong>in</strong>ux and PowerPC processor (BOA5200 is based on thePowerPC5200). This type of compilation is called cross-compilation. The tool cha<strong>in</strong> forbuild<strong>in</strong>g programs for BOA target was prepared at the Department of Control Eng<strong>in</strong>eer<strong>in</strong>gat CTU [DoCE]. Pavel Jelínek has ported this tool cha<strong>in</strong> for work<strong>in</strong>g at M<strong>in</strong>GWenvironment as a part of his Master thesis [Jel08]. I have just used the complete parts toenable compilation and execution of code generated by this target.In the aim of creation the complete documentation for the target, I will describe particularsteps of <strong>in</strong>stallation everyth<strong>in</strong>g needed for the work with target and BOA computer.2.2.1 Installation prerequisitesFor work with L<strong>in</strong>ux ERT target you have to have PC with Matlab <strong>in</strong>stalled. Theblockset has been developed and tested at the Matlab version 2008a. However, it shouldwork at the newer versions as well. The target was developed and tested <strong>in</strong> the Matlab ofrelease 2008a. The Matlab <strong>in</strong>stallation has to conta<strong>in</strong> Simul<strong>in</strong>k and Real Time WorkshopEmbedded Coder tools. The target distribution should conta<strong>in</strong> <strong>in</strong>stallation files of M<strong>in</strong>GWenvironment, compiler tool cha<strong>in</strong> and BOA L<strong>in</strong>ux image. Bellow is the list of all filesnecessary to <strong>in</strong>stall and use the target. These files should be attached to the targetdistribution.ˆ Tftpd32-3.22-setup.exeˆ gcc-powerpc-603e-l<strong>in</strong>ux-gnu-addw<strong>in</strong>.tarˆ gcc-powerpc-603e-l<strong>in</strong>ux-gnu.tarˆ M<strong>in</strong>GW-5.1.3.exeˆ m<strong>in</strong>ires-1.01-1-MSYS-1.0.11.tar.bz2ˆ MSYS-1.0.10.exeˆ openssh-4.6p1-MSYS-1.0.11.tar.bz2ˆ openssl-0.9.8e-3-MSYS-1.0.11.tar.bz2ˆ zlib-1.2.3-MSYS-1.0.11.tar.bz2ˆ MPC5200-2007.02.01-redbootROMRAM.srecˆ myfs.jffs2ˆ zImage.elf2.2.2 M<strong>in</strong>GW environment <strong>in</strong>stallationM<strong>in</strong>GW is a collection of freely available and freely distributable W<strong>in</strong>dows specificheader files and import libraries, augment<strong>in</strong>g the GNU Compiler Collection (GCC ) andits associated tools (GNU b<strong>in</strong>utils) [m<strong>in</strong>]. It is supplemented by MSYS which is a M<strong>in</strong>imalSYStem provid<strong>in</strong>g a POSIX compatible Bourne shell environment, with a small collectionof UNIX command l<strong>in</strong>e tools [m<strong>in</strong>]. These tools together provide the W<strong>in</strong>dows compatibleenvironment of GNU utilities for application build<strong>in</strong>g and necessary file management.There are steps of M<strong>in</strong>GW <strong>in</strong>stallation and its setup to fit all our needs <strong>in</strong> the follow<strong>in</strong>gtext. All the files mentioned bellow should be present nearby this document <strong>in</strong> softwarefolder. If their are not, it is no problem to download them from the Internet. Moreover,you may want to use newer versions of the programs that will have been probably released.17


Note I recommend to <strong>in</strong>stall everyth<strong>in</strong>g just <strong>in</strong>to C:\ or <strong>in</strong>to folder without space ordiacritic marks <strong>in</strong> its path at least. This could raise some problems.1. Run M<strong>in</strong>GW-5.1.3.exe and <strong>in</strong>stall M<strong>in</strong>GW <strong>in</strong> its m<strong>in</strong>imal configuration. No languagesupport is necessary. Note that this <strong>in</strong>staller will download M<strong>in</strong>GW from theInternet dur<strong>in</strong>g <strong>in</strong>stallation.2. Run MSYS-1.0.10.exe and <strong>in</strong>stall MSYS. Proceed the post-<strong>in</strong>stall guide started atthe end of the <strong>in</strong>stallation.3. Unpack m<strong>in</strong>ires-1.01-1-MSYS-1.0.11.tar.bz2 to the MSYS <strong>in</strong>stallation folder (e.g.C:/MSYS/1.0 ).4. Unpack openssh-4.6p1-MSYS-1.0.11.tar.bz2 to the MSYS <strong>in</strong>stallation folder.5. Unpack openssl-0.9.8e-3-MSYS-1.0.11.tar.bz2 to the MSYS <strong>in</strong>stallation folder.6. Unpack zlib-1.2.3-MSYS-1.0.11.tar.bz2 to the MSYS <strong>in</strong>stallation folder.Note Unpack<strong>in</strong>g .tar.bz2 archives <strong>in</strong> W<strong>in</strong>dows can be done e.g. <strong>in</strong> Total Commander[Ghia] while hav<strong>in</strong>g the proper packer plug<strong>in</strong> <strong>in</strong>stalled [Ghib]. The other way ho to unpackthese archives is to just copy them <strong>in</strong> the proper location <strong>in</strong> W<strong>in</strong>dows, run MSYS consoleand unpack them by the tar command.$ tar −xjf soubor . tar . bz2$ tar −xvf soubor . tarCross-compiler <strong>in</strong>stallationThe work<strong>in</strong>g M<strong>in</strong>GW and MSYS environment with SSH communication support is<strong>in</strong>stalled now. Steps of <strong>in</strong>stallation the cross compiler for PowerPC mach<strong>in</strong>e and L<strong>in</strong>uxwill mentioned bellow. The tool cha<strong>in</strong> creation and customization is described <strong>in</strong> [Jel08]and [DoCE]. I will describe just us<strong>in</strong>g the prepared archives here.1. Unpack gcc-powerpc-603e-l<strong>in</strong>ux-gnu.tar to the M<strong>in</strong>GW <strong>in</strong>stallation folder.2. Unpack gcc-powerpc-603e-l<strong>in</strong>ux-gnu-addw<strong>in</strong>.tar to the M<strong>in</strong>GW <strong>in</strong>stallation folder.3. Add the compiler path to the system paths by add<strong>in</strong>g the follow<strong>in</strong>g l<strong>in</strong>e at the endof the file /etc/profile.exportPATH=$PATH : / m<strong>in</strong>gw / usr / b<strong>in</strong>2.2.3 L<strong>in</strong>ux ERT Target <strong>in</strong>stallationInstallation of the L<strong>in</strong>ux ERT Target itself is very simple. Just unpack the l<strong>in</strong>ux ert -target.zip somewhere and run l<strong>in</strong>ux ert target setup.m script <strong>in</strong> Matlab. It will add thetarget path <strong>in</strong>to Matlab paths. The target should be visible <strong>in</strong> the Simulation configurationdialog Real Time Worshop pane of the Simul<strong>in</strong>k model after restart<strong>in</strong>g Matlab. Thiswill <strong>in</strong>stall just the target without CANopen blockset which has to be <strong>in</strong>stalled separately.Without hav<strong>in</strong>g the blockset <strong>in</strong>stalled, the CANopen support option must not be enabled.18


2.2.4 BOA mach<strong>in</strong>e preparationThe target is designed to work with BOA5200 computer [AM] based on PowerPCprocessor. From the software po<strong>in</strong>t of view, there has to be OS L<strong>in</strong>ux with SSH supportand SocketCan [Ber] CAN bus driver <strong>in</strong>stalled. The SSH support is secured by add<strong>in</strong>gDropBear SSH server [Joh] <strong>in</strong>to L<strong>in</strong>ux file system. The SocketCan driver is <strong>in</strong>cluded <strong>in</strong>the L<strong>in</strong>ux kernel. Creation of the L<strong>in</strong>ux kernel and file system is described <strong>in</strong> [Jel08] and[DoCE] aga<strong>in</strong>. The L<strong>in</strong>ux target should be supplemented by prepared L<strong>in</strong>ux kernel andfile system image and I will only describe the steps of <strong>in</strong>stall<strong>in</strong>g these images <strong>in</strong>to theBOA computer.The images will be transfered via TFTP service which is much faster than serial bus.We will set up the network connection and <strong>in</strong>stall TFTP server now. First of all, <strong>in</strong>stallthe TFTP server by runn<strong>in</strong>g the file Tftpd32-3.22-setup.exe, start it and set its workdirectory to the directory BOA5200 of the target distribution.We will configure the BOA network connection now. First, connect the BOA computerto the host PC by RS232 cable. Open W<strong>in</strong>dows Hyperterm<strong>in</strong>al with this configuration:Baud Rate: 38400, Bits: 8, Parity: No, Stop Bits: 1 and turn the BOA on. Someth<strong>in</strong>gshould be written at the console. Wait until the <strong>in</strong>formation about execut<strong>in</strong>g the bootscript appears and press Ctrl+C to avoid the script execution. Now the RedBoot consoleshould be active.RedBoot [Hat] is a software started just after computer power up and it is used toma<strong>in</strong>ta<strong>in</strong> the flash memory and boot the operat<strong>in</strong>g system. It is required to have RedBootsoftware <strong>in</strong> version 2007-02-01 or later to run L<strong>in</strong>ux kernel 2.6. You can recognize thecurrent RedBoot version from console output after BOA power up. If RedBoot versionof your BOA is 2007-02-01 or later, you can skip the RedBoot update section. You willhave to configure your RedBoot to connect to the network. The best way how to do it isto follow the steps later <strong>in</strong> this chapter.Updat<strong>in</strong>g RedBootThe follow<strong>in</strong>g paragraph summarizes the steps of updat<strong>in</strong>g RedBoot accord<strong>in</strong>g to[DoCE] or [Jel08]. You should have your BOA runn<strong>in</strong>g the RedBoot console and theTFPT server started at our host computer. Note, that the RedBoot console is not casesensitive, but the image names are! M<strong>in</strong>d the RedBoot image name case.1. Type this command to the consoleRedBoot> load −v −b 0 x100000MPC5200 −2007.02.01 − redbootROMRAM . srec2. After f<strong>in</strong>ish<strong>in</strong>g the transfer save the new RedBoot image to the flash memory andreset the computer by typ<strong>in</strong>g these commandsRedBoot> fis cr RedBootRedBoot> resetNow, the computer should started with the new RedBoot version. Avoid runn<strong>in</strong>g theboot script and cont<strong>in</strong>ue with <strong>in</strong>stall<strong>in</strong>g the L<strong>in</strong>ux19


Install<strong>in</strong>g L<strong>in</strong>ux kernel and file systemTo <strong>in</strong>stall L<strong>in</strong>ux at the BOA computer it is necessary to store kernel and file systemimages <strong>in</strong>to the flash memory and set up the RedBoot to boot L<strong>in</strong>ux after startup. Thefollow<strong>in</strong>g steps describe the file transfer us<strong>in</strong>g TFTP and their storage <strong>in</strong>to the memory.1. Format BOA flash and clear RAM by these commandsRedBoot> fis <strong>in</strong>itRedBoot> mfill −b 0 x100000 −l 0 xFF0000 −p 0 xFFFFFFFF2. Transfer the file system image myfs.jffs2 by typ<strong>in</strong>g this command.RedBoot> load −v −r −b 0 x100000myfs . jffs23. After successful f<strong>in</strong>ish of the transfer save the image <strong>in</strong>to the flash memory.RedBoot> fis cr JFFS2 −l 0 xFF00004. Transfer the kernel image zImage.elf by typ<strong>in</strong>g this command.RedBoot> load −v −b 0 xFF0000zImage . elf5. After successful f<strong>in</strong>ish of the transfer save the image to the flash memory.RedBoot> fis cr L<strong>in</strong>uxThe L<strong>in</strong>ux kernel and file system are stored <strong>in</strong> the flash memory and L<strong>in</strong>ux can bestarted by typ<strong>in</strong>g follow<strong>in</strong>g commands.RedBoot> fis load L<strong>in</strong>uxRedBoot> execIt is possible to write these commands to the RedBoot boot script and enable automaticstart<strong>in</strong>g of L<strong>in</strong>ux. This is described <strong>in</strong> the next paragraph.Configur<strong>in</strong>g RedBootRedBoot configuration can be performed by typ<strong>in</strong>g fconfig command <strong>in</strong> the RedBootconsole. It starts simple configuration dialog. The follow<strong>in</strong>g list<strong>in</strong>g shows the examplesett<strong>in</strong>gs. I have added comment l<strong>in</strong>es started by # to expla<strong>in</strong> particular values.RedBoot> fconfig# enable boot scriptRun script at boot : true# old boot script commandsBoot script :. . fi lo L<strong>in</strong>ux. . exEnter script , term<strong>in</strong>ate with empty l<strong>in</strong>e20


# load<strong>in</strong>g L<strong>in</strong>ux image from flash>> fi lo L<strong>in</strong>ux# execut<strong>in</strong>g the image>> ex>># timeout before start<strong>in</strong>g the boot script <strong>in</strong> RedBootBoot script timeout (1000 ms resolution ) : 5# dynamic IP address assignment ( DHCP ) is disabledUse BOOTP for network configuration : false# IP address of the network routerGateway IP address : 1 9 2 . 1 6 8 . 1 2 3 . 2 5 4# IP address of BOA computer , will be used by SSH connectionLocal IP address : 1 9 2 . 1 6 8 . 1 2 3 . 1 9 9Local IP address mask : 2 5 5 . 2 5 5 . 2 5 5 . 0# IP address of the computer runn<strong>in</strong>g TFTP serverDefault server IP address : 1 9 2 . 1 6 8 . 1 2 3 . 1 0 1FEC Network hardware address [ MAC ] : 0 x00 : 0 x00 : 0 x00 : 0 x00 : 0 x00 : 0 x03GDB connection port : 9000Force console for special debug messages : falseUpdate RedBoot non−volatile configuration − cont<strong>in</strong>ue ( y/n ) ? y# reset the TargetRedBoot> resetWith this configuration BOA will set its IP address permanently and start L<strong>in</strong>ux.M<strong>in</strong>d that it is necessary to set the same IP address <strong>in</strong> the L<strong>in</strong>ux configuration file oncemore accord<strong>in</strong>g to the next paragraph.Customiz<strong>in</strong>g L<strong>in</strong>uxSome more sett<strong>in</strong>gs is necessary to perform <strong>in</strong> the L<strong>in</strong>ux itself to make network connectionand SSH server work<strong>in</strong>g. First of all edit /etc/<strong>in</strong>it.d/config-eth0 by vi editor whichis <strong>in</strong>stalled <strong>in</strong> the BOA file system and change the IP address to match the local addressconfigured <strong>in</strong> RedBoot.Then generate the keys for SSH server by typ<strong>in</strong>g follow<strong>in</strong>g set of commands.$ cd / etc / ssh$ / usr / local / b<strong>in</strong> / . / dropbearkey −t rsa −f dropbear_rsa_host_key$ / usr / local / b<strong>in</strong> / . / dropbearkey −t dss −f dropbear_dss_host_keyYou can change the supervisor password by typ<strong>in</strong>g the command passwd root.We will create user profile for execut<strong>in</strong>g the generated programs at the BOA mach<strong>in</strong>e.However, sett<strong>in</strong>g thread priority <strong>in</strong> the ma<strong>in</strong> function (see section 2.4.1) requires rootauthority, so the program will work but all the threads will have the same priority whichis not optimal especially <strong>in</strong> the multitask<strong>in</strong>g mode. The solution is to execute the programfrom the root profile. The follow<strong>in</strong>g set of commands creates user called rtw and set thefolder /home/rtw to be its home folder.$ cd /$ mkdir home$ cd home$ mkdir rtw$ adduser −h / home / rtw rtw$ chown rtw : rtw rtwAfter the next boot up, the network should work correctly and it should be possibleto connect to BOA computer via SSH service as both root and rtw user.F<strong>in</strong>ally, the CAN ports have to be configured to use 1Mbps bit rate and to be turnedon after the L<strong>in</strong>ux boot up. To do this create script called can <strong>in</strong> /etc/<strong>in</strong>it.d with thefollow<strong>in</strong>g content.21


#!/ b<strong>in</strong> /shecho 660000 >/sys / class / net / can0 / can_baudrateecho 660000 >/sys / class / net / can1 / can_baudrateifconfig can0 upifconfig can1 upTo run the script while L<strong>in</strong>ux is boot<strong>in</strong>g enable can script execution by typ<strong>in</strong>g chmoda+x /etc/<strong>in</strong>it.d/can and add the follow<strong>in</strong>g l<strong>in</strong>e <strong>in</strong>to /etc/<strong>in</strong>ittab.: : once : / etc / <strong>in</strong>it . d/ can22


2.3 Target architectureI will describe particular files of the ERT target <strong>in</strong> this chapter. What the files doand when they are called are the ma<strong>in</strong> th<strong>in</strong>gs that is necessary to know to understandthe target architecture. It is usual to name all the target files with the prefix same as thetarget name. It means that <strong>in</strong> our case all the files has the prefix l<strong>in</strong>ux ert target.The diagram of all the target scripts is <strong>in</strong> the figure 2.2. It shows the process of targetselection and configuration customization by user <strong>in</strong> the upper part. The code generationprocess is shown <strong>in</strong> the lower part of the figure.2.3.1 Target configuration scriptsThis group of scripts performs the target <strong>in</strong>tegration <strong>in</strong>to Matlab environment andcustomization of the configuration dialog. It also def<strong>in</strong>es the variables used by codegenerator and set them to the default values.l<strong>in</strong>ux ert target.tlcThe basic file of the whole target is l<strong>in</strong>ux ert target.tlc which def<strong>in</strong>es the appearance ofthe Simulation configuration dialog of the Simul<strong>in</strong>k model while the target is chosen for thecode generation. This file was created by customization of matlabroot/rtw/c/ert/ert.tlcfile which def<strong>in</strong>es the generic ERT target and is set to be an <strong>in</strong>heritor of it. It meansthat it <strong>in</strong>herits the sett<strong>in</strong>gs of the generic ERT target and adds the specific features ofthe L<strong>in</strong>ux ERT target.sl customization.mThis file conta<strong>in</strong>s the sl customization function which adds TCP/IP communicationsupport for external mode <strong>in</strong>to the target. It has to be placed somewhere <strong>in</strong> the Matlabpath and it is <strong>in</strong>voked by Simul<strong>in</strong>k dur<strong>in</strong>g the startup.l<strong>in</strong>ux ert target select callback handler.mSelect callback script is called after select<strong>in</strong>g the target <strong>in</strong> configuration dialog. Thisscript set up default values of configuration and disables some of them to be changed byuser. The aim of this is to set up as much as possible of the configuration automaticallyand disable the user to set unsupported values.l<strong>in</strong>ux ert target canopen support callback handler.mThis is the callback script after chang<strong>in</strong>g the value of Enable CANopen support <strong>in</strong>the Real Time Workshop/CANopen support configuration pane. It tries to search theCanFestival lib and <strong>in</strong>clude folders. They are placed <strong>in</strong> the CANopen blockset folder andif it is correctly <strong>in</strong>stalled (the blockset folder is <strong>in</strong> the Matlab path), it should be found.The search<strong>in</strong>g is based on file called cfpo<strong>in</strong>terfile.txt which is placed <strong>in</strong> the canfestivalblockset subfolder. Its only purpose is the path search<strong>in</strong>g.The canfestival/<strong>in</strong>clude folder conta<strong>in</strong>s the header files of CF API that are necessary forcompilation of program us<strong>in</strong>g CanFestival. The folder has to be added <strong>in</strong>to <strong>in</strong>clude path forcompilation <strong>in</strong> Makefile if the CANopen blockset support is enabled. The canfestival/libfolder conta<strong>in</strong>s the CanFestival libraries that are necessary for program l<strong>in</strong>k<strong>in</strong>g. If the23


l<strong>in</strong>ux_ert_target.tlcThe ma<strong>in</strong> file of the ERT target.Keeps the appearance ofthe Configuration dialog.TargetselectedAdds menucategoriesSimulation ConfigurationTarget selectedKeeps the sett<strong>in</strong>gs of generatedtarget and simulation.Configuration dialog for usercustomization._select_callback_handler.mDefault values of Simulation configurationsparameters are set.Some options are disabled if it is not allowedto be changed by user.Fills default configurationsl_customization.mAfter selection of the ERT targetadds the TCP/IP external modecomunication support.Generate codeCANopen support disabledRTWoptionsCANopen supportenabledCanFestival buildfrom source_canopen_support_callback_handler.mIt searches the Matlab path for cfpo<strong>in</strong>terfile.txtand determ<strong>in</strong>e the CanFestival <strong>in</strong>clude and libfolders <strong>in</strong> CANopen blockset._cfbulid_callback_handler.mDisables CF library path Edit box and enablesCF source folder <strong>in</strong>sertion <strong>in</strong> Setup dialog.model.rtw_s<strong>in</strong>gletask<strong>in</strong>g_ma<strong>in</strong>.tlc_multitask<strong>in</strong>g_ma<strong>in</strong>.tlcFile conta<strong>in</strong><strong>in</strong>g <strong>in</strong>formation fromconfiguration dialog and RTWoptions of the model and its blocks.S<strong>in</strong>gletask<strong>in</strong>g ma<strong>in</strong>function generation script.Solver and tasks<strong>in</strong>formationMultitask<strong>in</strong>g ma<strong>in</strong>function generation script.S<strong>in</strong>gletask<strong>in</strong>gSolver modeMultitask<strong>in</strong>gSolver model<strong>in</strong>ux_ert_target.tmf_make_rtw_hook.mlogger.tlc_generate_ma<strong>in</strong>.tlcMakefile templateParticular sections of this file are calleddur<strong>in</strong>g the TLC process. Additionalcode costumization can be done here.Script generat<strong>in</strong>gLogger modul.Ma<strong>in</strong> functiongeneration script.model.mkProjekt Makefileadapt_code.mRewrites paths <strong>in</strong>toUnix formatlogger.c + .hLogger modul.ert_ma<strong>in</strong>.cFile conta<strong>in</strong>ig theMa<strong>in</strong> function.l<strong>in</strong>ux_ert_target_go.mThis file generates the go script.Copied fromERT folder_wrap_make_cmd_hook.mThis file is called dur<strong>in</strong>g TLC processand generates projekt make processbatch file._code_template.cgtTemplate of sourcefiles banners.gopthread_period.c + .hmodel.bat*.c + *.h filesScript go performesthe make process andprogram startup.Periodic thread library.Make process batch file.Model code is atomaticallygenerated <strong>in</strong>to a setof source files.LegendMa<strong>in</strong> TLC file Config dialog callbacks RTW configuration Code generat<strong>in</strong>g scripts Generated filesFigure 2.2: Target architecture with scripts call<strong>in</strong>g diagram24


Build CanFestival from source option is enabled this libraries are not used and they areobta<strong>in</strong>ed by compilation the CanFestival source code.l<strong>in</strong>ux ert target cfbuild callback handler.mThis callback function is <strong>in</strong>voked by chang<strong>in</strong>g the Build CanFestival from source optionand it only switches between <strong>in</strong>sertion of CanFestival library folder or source code folder.Moreover, it enables or disables CAN message console logg<strong>in</strong>g option as the CanFestivalhas to be built from source to turn it on.2.3.2 Code generat<strong>in</strong>g scriptsThis group of scripts is used by Real Time Workshop dur<strong>in</strong>g the code generation.The code generation has predef<strong>in</strong>ed some scripts that are called <strong>in</strong> specified phases of theprocess.Before describ<strong>in</strong>g the target scripts I will mention the model.rtw file (model is generallythe name of the model so that it may be called differently). This file is generated automaticallyat the beg<strong>in</strong>n<strong>in</strong>g of the TLC process and it conta<strong>in</strong>s all the <strong>in</strong>formation aboutmodel, its blocks and simulation sett<strong>in</strong>g necessary for program generation, compilationand execution.l<strong>in</strong>ux ert target generate ma<strong>in</strong>.tlcThis is the TLC script which generates the ma<strong>in</strong> function file ert ma<strong>in</strong>.c accord<strong>in</strong>gto solver mode and sample times sett<strong>in</strong>gs of the model. This file is registered <strong>in</strong> theReal Time Workshop/Templates pane <strong>in</strong> the Simulation configuration. It is set by l<strong>in</strong>uxert target select callback handler.m script and the user change is disabled.This script creates the ert ma<strong>in</strong>.c source file and calls TLC function for s<strong>in</strong>gle ormulti-task<strong>in</strong>g solver mode. F<strong>in</strong>ally, it calls TLC script for generation of the system loggermodule.l<strong>in</strong>ux ert target s<strong>in</strong>gletask<strong>in</strong>g ma<strong>in</strong>.tlcThis script generates the content of the ert ma<strong>in</strong>.c file for the s<strong>in</strong>gletask<strong>in</strong>g mode. Allthe model code is executed from a s<strong>in</strong>gle thread runn<strong>in</strong>g at the base sample time. Thes<strong>in</strong>gle task<strong>in</strong>g mode differs accord<strong>in</strong>g to the number of sample times used <strong>in</strong> the model.S<strong>in</strong>gletask<strong>in</strong>g-s<strong>in</strong>glerate mode means that just one sample time is used. S<strong>in</strong>gletask<strong>in</strong>gmultiratemode means that more sample times are used <strong>in</strong> the model but everyth<strong>in</strong>ghas to be executed from a s<strong>in</strong>gle thread. It is handled by the rate scheduler which isautomatically generated <strong>in</strong>to the model.c file and the ma<strong>in</strong> function is the same for boths<strong>in</strong>gle and multi rate case.Read <strong>in</strong> Code generation chapter for more <strong>in</strong>formation about the s<strong>in</strong>gletask<strong>in</strong>g ma<strong>in</strong>function.l<strong>in</strong>ux ert target multitask<strong>in</strong>g ma<strong>in</strong>.tlcThis script generates the content of the ert ma<strong>in</strong>.c file for the multitask<strong>in</strong>g mode.The multitask<strong>in</strong>g mode is only reasonable (and allowed as well) for the model with moredifferent sample times. The multitask<strong>in</strong>g mode is realized <strong>in</strong> the way that each of thesample times has separate thread where its loop is runn<strong>in</strong>g. The cycles of each loop is25


controlled by the ma<strong>in</strong> loop runn<strong>in</strong>g at the base sample time (the greatest common divisorof all sample times).Read <strong>in</strong> Code generation chapter for more <strong>in</strong>formation about the multitask<strong>in</strong>g ma<strong>in</strong>function.logger.tlcThe logger module of the generated code performs runtime logg<strong>in</strong>g of the programevents. It supports two types of logg<strong>in</strong>g - console output and log file output. Both typescan be disabled or set onto three different levels accord<strong>in</strong>g to the amount of logged messages.This is set <strong>in</strong> the Real Time Workshop/Runtime logg<strong>in</strong>g pane <strong>in</strong> the configurationdialog. This file generates the source and header files of the logger module.l<strong>in</strong>ux ert target.tmfThis file is the template of the Makefile used for build<strong>in</strong>g the generated program.The result of this is the Makefile model.mk, where model is the name of the model.The template is based on the generic template for Unix ERT target which can be found<strong>in</strong> matlabroot/rtw/c/ert/ert unix.tmf. The template is only changed to enable l<strong>in</strong>k<strong>in</strong>gCanFestival driver <strong>in</strong>to the program. L<strong>in</strong>k<strong>in</strong>g of the driver is subject to the Real TimeWorkshop/CANopen support sett<strong>in</strong>gs <strong>in</strong> the Simulation configuration.If the CANopen support is disabled, the Makefile does not need any parts of the driverfor l<strong>in</strong>k<strong>in</strong>g. If it is enabled and it is not required to build the driver from its source code,it adds <strong>in</strong>clude folder to the <strong>in</strong>clude paths and lib folder to the libraries for l<strong>in</strong>k<strong>in</strong>g. Thesefolders are set <strong>in</strong> the configuration dialog. If build<strong>in</strong>g the driver from source is required( configure) and make commands are applied at the <strong>in</strong>serted source folder. Then thelibraries obta<strong>in</strong>ed by actual compilation are used for the f<strong>in</strong>al l<strong>in</strong>k<strong>in</strong>g.l<strong>in</strong>ux ert target make rtw hook.mFile with this name is called dur<strong>in</strong>g the code generation process if it exist <strong>in</strong> the targetpath. It conta<strong>in</strong>s sections that are called <strong>in</strong> a different moments of the generation.It performs several tasks. It rewrites CanFestival folders paths <strong>in</strong>to old DOS format byrtw alt pathname Matlab function. This command removes spaces and diacritical marksfrom the given paths.The copy<strong>in</strong>g of several source files and libraries is performed after the TLC process.The source and header files of periodic thread library are copied <strong>in</strong>to generated codefolder. If the CANopen support is enabled and build CanFestival is not required threelibrary files of CanFestival driver are copied there as well.F<strong>in</strong>ally there are executed to scripts <strong>in</strong> the exit section. The script adapt code.m customizesgenerated Makefile for runn<strong>in</strong>g <strong>in</strong> MSYS environment and the script l<strong>in</strong>ux ert target -go.m generates the go script.adapt code.mThis script customizes already generated Makefile model.mk for runn<strong>in</strong>g <strong>in</strong> the MSYSenvironment. It rewrites all backslashes \ with slashes /. All the paths are rewritten<strong>in</strong>to the Unix format this way. However, there are some backslashes <strong>in</strong> the Makefile used26


as l<strong>in</strong>e cont<strong>in</strong>uation mark that have to be kept. It is secured <strong>in</strong> the way that all thesebackslashes are represented by BACKSLASH keyword <strong>in</strong> the Makefile template. Afterrewrit<strong>in</strong>g the paths this keyword is replaced by regular \ mark.l<strong>in</strong>ux ert target go.mThis script creates the go script and place it <strong>in</strong>to the work<strong>in</strong>g directory. This script isthe only user <strong>in</strong>terface of program compilation and execution. Its content differs accord<strong>in</strong>gto the sett<strong>in</strong>gs <strong>in</strong> Real Time Workshop/Target configuration pane. There is set <strong>in</strong> thisdialog whether the project should be just compiled, compiled and copied onto the Targetmach<strong>in</strong>e or executed at the Target mach<strong>in</strong>e as well. Information about the Target mach<strong>in</strong>eIP address is used as well. Moreover if CANopen support is enabled the script <strong>in</strong>serts<strong>in</strong>to the go script commands for copy<strong>in</strong>g the canfestival dynamic library onto the Targetcomputer.l<strong>in</strong>ux ert target wrap make cmd hook.mThe model.bat file is generated by Real Time Workshop. This file conta<strong>in</strong>s the executioncommand of make program. This is done automatically, but if there is the l<strong>in</strong>uxert target wrap make cmd hook.m script <strong>in</strong> the target path, it is called <strong>in</strong>stead andthe model.bat content can be customized.l<strong>in</strong>ux ert target code template.cgtThis file conta<strong>in</strong>s template for source file banner of all the generated .h and .c files.It is used by Real Time Workshop while generat<strong>in</strong>g the files.27


2.4 Generated codeThis chapter describes the code generated by Real Time Workshop us<strong>in</strong>g L<strong>in</strong>ux ERTtarget. The folder model l<strong>in</strong>ux ert rtw is created <strong>in</strong> the work<strong>in</strong>g folder and all the generatedfiles are placed <strong>in</strong>to it. Generally, there are several types of generated files. First of allthe file ert ma<strong>in</strong>.c with ma<strong>in</strong> function conta<strong>in</strong>s the code used for model synchronization.Additionally the files conta<strong>in</strong><strong>in</strong>g the code of all the blocks used <strong>in</strong> the model are generated.The <strong>in</strong>terface between the step synchronization <strong>in</strong> the ma<strong>in</strong> function and calculations ofthe model blocks is created <strong>in</strong> the file model.c. This is an <strong>in</strong>terface between L<strong>in</strong>ux ERTtarget specific code (ma<strong>in</strong> function) and general block code generated by RTW automaticallyas well.F<strong>in</strong>ally the Makefile (model.mk) and make execution batch file (model.bat) are generated.In the work<strong>in</strong>g directory, the go script is created to enable the user to run build<strong>in</strong>gand execution of the code by a s<strong>in</strong>gle command.2.4.1 Ma<strong>in</strong> functionThe ma<strong>in</strong> function is completely generated by the target and is customized accord<strong>in</strong>gto the solver mode and sample times sett<strong>in</strong>g of the Simul<strong>in</strong>k model. The target support allthe solver modes (s<strong>in</strong>gletask<strong>in</strong>g - s<strong>in</strong>glerate, s<strong>in</strong>gletask<strong>in</strong>g - multirate and mutlitask<strong>in</strong>g).However, the base part of the ma<strong>in</strong> file is always the same.The base part of the ma<strong>in</strong> file conta<strong>in</strong>s three functions. The ma<strong>in</strong> function whichperforms the basic sett<strong>in</strong>g of the simulation and creates two threads runn<strong>in</strong>g the ma<strong>in</strong> loopand rt OneStep functions. The ma<strong>in</strong> loop thread is set to have the highest priority and itproduces the base sample time steps. The ma<strong>in</strong> loop controls the execution of step functionus<strong>in</strong>g a semaphore. There may be more step function threads <strong>in</strong> case of multitask<strong>in</strong>g mode.Ma<strong>in</strong> loopEach simulation <strong>in</strong>dependently of the solver mode has just one base sample time. Thisbase sample time is the greatest common divisor of all used sample times of the model.The ma<strong>in</strong> loop function is started <strong>in</strong> a thread with the highest priority and it is liable forgenerat<strong>in</strong>g the base step <strong>in</strong>tervals with as high precision as possible.The tim<strong>in</strong>g is realized by periodic thread implemented <strong>in</strong> pthread periodic library createdby Pavel Píša at the Department of Control Eng<strong>in</strong>eer<strong>in</strong>g at CTU [Píš05]. This libraryhas a very simple API for creation periodic timer and wait<strong>in</strong>g for the timer expiration.It is secured by the period timer that the ma<strong>in</strong> loop cycle is executed just <strong>in</strong> the basesample time frequency. The most important code of the ma<strong>in</strong> loop is shown <strong>in</strong> the figure2.3.The step cycle waits for unblock<strong>in</strong>g the step semaphore. This semaphore is unblocked<strong>in</strong> each ma<strong>in</strong> loop cycle. From the step cycle the mode step function placed <strong>in</strong> the automaticallygenerated model.c file is called. This function conta<strong>in</strong>s the code of simulationstep calculations.\* sett<strong>in</strong>g the priority is just pseudo code here *\set_thread_priority ( MAX_PRIORITY ) ;\* start = actual time , period = base sample time *\pthread_make_periodic_np ( pthread_self ( ) , &start , &period ) ;28


w h i l e ( ! f<strong>in</strong>ished ) {\* wait<strong>in</strong>g f o r timer expiration *\pthread_wait_np ( ) ;\* check<strong>in</strong>g the overrun *\sem_getvalue(&step_semaphore , &step_sem_value ) ;i f ( step_sem_value ) {rtmSetErrorStatus ( test2_M , ” Overrun ” ) ;break ;}\* perform<strong>in</strong>g the step *\sem_post(&step_semaphore ) ;sem_post(&step_semaphore ) ;\* external mode communication *\rtExtModeCheckEndTrigger ( ) ;}Overrun check<strong>in</strong>gFigure 2.3: Ma<strong>in</strong> loop cycleIt is obvious from the simulation synchronization pr<strong>in</strong>ciple that if the execution of themodel code called from the rt OneStep function took more time than is the sample time,the real time feature of the simulation would be violated, an overrun would occur. It isnot possible to guarantee that the code would be fast enough and so it is necessary tocheck the overrun occurrence at least.


Ma<strong>in</strong> loop threadSet thread priority to MAXCreate periodic timerWhile loopWait for timerCheck for overrunIf sem > 0 thenOverrun Error!Release semaphoresem=1rt_OneStep threadSet thread priority to MAX -1While loopTake semaphoresem=1Call model_step()Take semaphoresem=0model_step()Model simulationStep codeRelease semaphoresem=2F<strong>in</strong>al stepRelease semaphoreRelease semaphoreert_ma<strong>in</strong>.cmodel.cFigure 2.5: Overrun check<strong>in</strong>grequired to be s<strong>in</strong>gletask<strong>in</strong>g is called s<strong>in</strong>gletask<strong>in</strong>g - multirate. The ma<strong>in</strong> function is thesame as <strong>in</strong> the classic s<strong>in</strong>gletask<strong>in</strong>g mode and the rate schedul<strong>in</strong>g of the particular sampletimes is performed <strong>in</strong> the model.c file. The diagram is shown <strong>in</strong> the figure 2.6. Note thatdouble us<strong>in</strong>g of semaphores (described <strong>in</strong> Overrun check<strong>in</strong>g paragraph) is abandoned <strong>in</strong>this figure to simplify the diagram.Multitask<strong>in</strong>g caseUsually if more than one sample times are used <strong>in</strong> the model, the multitask<strong>in</strong>g solvermode is chose. The advantage over the s<strong>in</strong>gletask<strong>in</strong>g - multirate case is that each sampletime operations are runn<strong>in</strong>g <strong>in</strong> the separate thread. The threads are generated <strong>in</strong>to theert ma<strong>in</strong>.c file. Each conta<strong>in</strong>s the loop which is synchronized by a semaphore.The rate schedul<strong>in</strong>g is controlled by the ma<strong>in</strong> loop with call<strong>in</strong>g scheduler functionsfrom model.c. The ma<strong>in</strong> loop is runn<strong>in</strong>g at the highest (base) sample time. It calls themodel SetEventsForThisBaseStep(eventFlags) function <strong>in</strong> each cycle. It fills the array oflogical variables evenFlags so that it conta<strong>in</strong>s an <strong>in</strong>formation whether particular sampletime cycle is scheduled <strong>in</strong>to this base time cycle or not. This decision have been made <strong>in</strong>the last base sample cycle by call<strong>in</strong>g the rate scheduler <strong>in</strong>side the model.c file.While hav<strong>in</strong>g the <strong>in</strong>formation whether to run particular sample time steps or not, appropriatesemaphores are released. Base sample time (always numbered as 0) is performed<strong>in</strong> each ma<strong>in</strong> loop cycle. The diagram of function calls <strong>in</strong> multitask<strong>in</strong>g model is shown<strong>in</strong> the figure 2.7. Note that double us<strong>in</strong>g of semaphores (described <strong>in</strong> Overrun check<strong>in</strong>gparagraph) is abandoned <strong>in</strong> this figure to simplify the diagram.30


Ma<strong>in</strong> loop threadSet thread priority to MAXCreate periodic timerWhile loopWait for timerCheck overrunRelease semaphoreF<strong>in</strong>al stepRelease semaphoreGet EventFlagsfor the base stepRate schedulermodel_step()Schedule ratesCall model_step0()model_step0()Model simulationHighest frequencycodemodel_step1()Model simulationSecond highestfrequency codert_OneStep threadSet thread priority to MAX -1If EventFlags[1] == 1If EventFlags[2] == 1model_step2()While loopTake semaphoreModel simulationThird highestfrequency codeCall model_step()ert_ma<strong>in</strong>.cmodel.cFigure 2.6: S<strong>in</strong>gletask<strong>in</strong>g - multirate model synchronizationThread priority assignmentSeparation of the model code <strong>in</strong>to threads accord<strong>in</strong>g to sample times was described<strong>in</strong> the previous paragraphs. The schedul<strong>in</strong>g of these threads is managed by operat<strong>in</strong>gsystem, L<strong>in</strong>ux <strong>in</strong> this case. The schedul<strong>in</strong>g priority can be set to particular threads. Thenthe preemptive scheduler is able to <strong>in</strong>terrupt runn<strong>in</strong>g thread <strong>in</strong> case that some thread withhigher priority is ready to run. The highest priority at all is set to the thread runn<strong>in</strong>gthe ma<strong>in</strong> loop 2.4.1. The second highest priority is then set to the thread runn<strong>in</strong>g thebase sample time step (rt OneStep). Although both loops runs at the same frequency, thema<strong>in</strong> loop controls the synchronization and needs to have the highest priority to checkthe eventual overrun.Priorities of rt OneStepX threads are set to match the step sample time order <strong>in</strong> themultitask<strong>in</strong>g case. It means that threads runn<strong>in</strong>g faster sample times are set to havehigher priority. But still the highest priority is always set to the ma<strong>in</strong> loop.2.4.2 MakefileThe Makefile model.mk (model is the model name) is created by fill<strong>in</strong>g the templatel<strong>in</strong>ux ert target.tmf. Parameters stored <strong>in</strong> the RTW options configured <strong>in</strong> Simulation31


Ma<strong>in</strong> loop threadSet thread priority to MAXCreate periodic timerWhile loopWait for timerGet EventFlagsCheck overrun0Release semaphore0rt_OneStep0 threadSet thread priority to MAX -1While loopTake semaphore0Call model_step0()Get EventFlagsfor the base stepRate schedulermodel_step0()Model simulationHighest frequencycodeEventFlag[1] == 1Check overrun1Release sem1EventFlag[2] == 1Check overrun2Release sem2rt_OneStep1 threadSet thread priority to MAX -2While loopTake semaphore1Call model_step1()model_step1()Model simulationSecond highestfrequency codeF<strong>in</strong>al stepRelease semaphore0Release semaphore1Release semaphore2rt_OneStep2 threadSet thread priority to MAX -3While loopTake semaphore2Call model_step2()model_step2()Model simulationThird highestfrequency codeert_ma<strong>in</strong>.cmodel.cFigure 2.7: Multitask<strong>in</strong>g model diagramconfiguration dialog are filled <strong>in</strong>to prepared variables of the Makefile. CANopen supportvariables were added to the general RTW options. These variables are used <strong>in</strong> the Makefileto control the compilation of code us<strong>in</strong>g CanFestival API and the compilation of the driveritself. CANopen support variables and their usage <strong>in</strong> the Makefile is shown <strong>in</strong> the table2.1.Real Time Workshop forwards CanFestival paths and Matlab paths from the configurationto the Makefile. The problem is that W<strong>in</strong>dows uses backslash as folder separatorand L<strong>in</strong>ux and MSYS too the classic slash. All the paths forwarded to the Makefile has tobe rewritten to the Unix format. MSYS is able to work with W<strong>in</strong>dows address beg<strong>in</strong>n<strong>in</strong>gwith the disk identifier, the only th<strong>in</strong>g which is necessary to be changed <strong>in</strong> the pathsare the slashes. It means that if Matlab path C:\MATLAB\R2008a is rewritten <strong>in</strong>toC:/MATLAB/R2008a, it works <strong>in</strong> MSYS environment.The Matlab path is customized by l<strong>in</strong>ux ert target wrap make cmd hook.m script. TheCanFestival address are rewritten <strong>in</strong> the l<strong>in</strong>ux ert target make rtw hook.m script <strong>in</strong> thesection called just before TLC process.32


RTW variable Values Influence on the Makefile0 No CanFestival parts are compiled or l<strong>in</strong>kedCANOPEN SUPPORT1 CanFestival headers and libraries are usedCANFESTIVAL BUILD01CF libraries are copied from library pathCF source path compiled and libraries usedCANFESTIVAL INCLUDE Path Folder with CF header filesCANFESTIVAL LIB Path Folder with precompiled CF librariesCANFESTIVAL SOURCE Path CF source folder prepared to make commandCANFESTIVAL CONSOLE01No CanFestival driver console outputCAN messages logg<strong>in</strong>g (–debug=MSG option)Table 2.1: CANopen variables <strong>in</strong> the Makefile2.4.3 Script go and the build processThis script is generated <strong>in</strong>to the work<strong>in</strong>g directory. It conta<strong>in</strong>s commands for build<strong>in</strong>gthe generated program, copy<strong>in</strong>g to the Target mach<strong>in</strong>e and start<strong>in</strong>g it. The sett<strong>in</strong>g of theTarget IP address and other connection <strong>in</strong>formation can be customized <strong>in</strong> the Real TimeWorkshop/Target pane of the Simulation configuration.33


Chapter 3CANopen blockset34


3.1 IntroductionThe CANopen blockset provides Simul<strong>in</strong>k API of the CANopen communication protocol[CiAb]. It is designed ma<strong>in</strong>ly for generat<strong>in</strong>g the code by L<strong>in</strong>ux Embedded Real TimeTarget which is customized for L<strong>in</strong>ux OS and BOA5200 computer [AM]. The blockset<strong>in</strong>tegrates CanFestival driver [LOLb] <strong>in</strong>to the code generated by the target. Particularblocks provide particular API functions of the driver to be used <strong>in</strong> Simul<strong>in</strong>k model. Itimplements entire CanFestival API which enables to create CANopen node with commonfeatures.Note The blockset has been developed and tested at the Matlab version 2008a. Itshould work at the newer versions as well.3.1.1 Simulation capabilitiesThe blockset has the simulation support as well, but it is designed only to enablerunn<strong>in</strong>g the simulation dur<strong>in</strong>g the embedded controller tun<strong>in</strong>g <strong>in</strong> Simul<strong>in</strong>k. It does notsimulate CANopen network and its communication at all. The simulation support is realizedma<strong>in</strong>ly by the simulation <strong>in</strong>puts and outputs of the blocks that are used to obta<strong>in</strong>data from the model <strong>in</strong>stead of the CANopen network dur<strong>in</strong>g the simulation.Moreover, CANopen node and CANopen asynchronous blocks works with Object dictionaryobject stored <strong>in</strong> Matlab workspace and use it for data exchange. This featureenables to simulate asynchronous data transfers via SDO messages. F<strong>in</strong>ally, simulationof CANopen event callbacks <strong>in</strong>clud<strong>in</strong>g parameters pars<strong>in</strong>g is supported as well. On theother hand, Network management, Heartbeat service or Network synchronization are notsimulated at all. Read simulation capabilities of particular blocks to learn more aboutthis topic.While simulat<strong>in</strong>g the model <strong>in</strong> Simul<strong>in</strong>k some simulation blocks are always added.While generat<strong>in</strong>g the code all model blocks are generated <strong>in</strong>clud<strong>in</strong>g these used just forthe simulation. You can use Environment controller switch to avoid generat<strong>in</strong>g parts ofthe model connected to simulation ports. See blockset usage tutorial <strong>in</strong> section B.3.2 forexample of do<strong>in</strong>g this.3.1.2 Blockset partsParticular blocks of the blockset are def<strong>in</strong>ed <strong>in</strong> model file l<strong>in</strong>ux ert target blockset.mdl.This model is a library and is set to be part of Simul<strong>in</strong>k Library Browser by the code <strong>in</strong>file slblocks.m. It secures that the blockset will be visible <strong>in</strong> the browser and its blockswill be usable <strong>in</strong> Simul<strong>in</strong>k models. Read [Mat] to understand the follow<strong>in</strong>g text aboutblockset parts well.Block maskThe block user <strong>in</strong>terface enabl<strong>in</strong>g the parameters sett<strong>in</strong>gs is realized by the blockmask. The mask def<strong>in</strong>es the appearance of the block and forwards the parameters tothe block S-function. If some more complex code is necessary to process the parametersor customize the block appearance, callbacks on parameter change are stored outsidethe model <strong>in</strong> mask callbacks folder. This folder is added <strong>in</strong>to Matlab path by blockset<strong>in</strong>stallation script. This simplifies the code ma<strong>in</strong>tenance and enables code re-usage.35


Block S-functionEach block has just one S-Function which is written <strong>in</strong> C language. The S-functionsare then compiled <strong>in</strong>to MEX file with the extension .mexw32. The S-function is a set ofcallback functions <strong>in</strong> fact. There are functions perform<strong>in</strong>g block ports and sample timesett<strong>in</strong>gs, writ<strong>in</strong>g code <strong>in</strong>to .rtw file while generat<strong>in</strong>g code and perform<strong>in</strong>g the simulation<strong>in</strong> Simul<strong>in</strong>k environment as well.Block TLC scriptEach block has the TLC (Target Language Compiler) script called by the same nameas its S-function. TLC scripts are stored <strong>in</strong> subfolder tlc c and are reliable for the codegeneration. Similarly to the S-function, the TLC script is based on callback functionsthat are called by the Real Time Workshop while generat<strong>in</strong>g code. The code for generat<strong>in</strong>gsource files and their content is placed <strong>in</strong> the proper callback functions. Thereare more TLC scripts than is the number of blocks, however just the ma<strong>in</strong> ones are calledautomatically by RTW and the other are used as libraries and called from the ma<strong>in</strong>scripts.Block helpThe block help is realized by HTML script with the same name as the S-function.The help files are l<strong>in</strong>ked to the block mask so that the help is accessible directly by blockhelp button. The help is based on parameters description which is the same as Blockparameters sections <strong>in</strong> this document. Images used <strong>in</strong> help pages are stored <strong>in</strong> help imgsubfolder.CanFestival driverThe blockset is based on CanFestival driver for the CANopen network. It is possibleeither build the CanFestival from source while generat<strong>in</strong>g code or us<strong>in</strong>g prepared libraries.The libraries are stored <strong>in</strong> the canfestival/lib subfolder of the blockset and are used whileBuild CanFestival from source option <strong>in</strong> model configuration is disabled. In the same wayCanFestival header files are handled. They are prepared <strong>in</strong> folder canfestival/<strong>in</strong>clude and<strong>in</strong> case of build<strong>in</strong>g CanFestival, the headers from the source folder are used <strong>in</strong>stead.ObjectDictionary classAn <strong>in</strong>stance of the ObjectDictionary class is created by each CANopen node block used<strong>in</strong> the model. It is stored <strong>in</strong> the workspace and keeps the node Object dictionary. The ODcontent is read from the EDS file and parsed by the EDS parser which is a part of the classcalled from the class constructor. This Matlab class is def<strong>in</strong>ed <strong>in</strong> the ObjectDictionary.mfile <strong>in</strong> the blockset folder.36


3.2 InstallationThis chapter describes <strong>in</strong>stallation of the CANopen blockset and all the other programsnecessary to work with the blockset. As the blockset is designed to be used with the L<strong>in</strong>uxERT Target, it is supposed to have this target already <strong>in</strong>stalled accord<strong>in</strong>g to its help. Thetarget distribution conta<strong>in</strong>s all the necessary tools for work<strong>in</strong>g with the Target computer[AM] and generat<strong>in</strong>g code for this platform.3.2.1 Object Dictionary editor <strong>in</strong>stallationFor creat<strong>in</strong>g the CANopen node <strong>in</strong> Simul<strong>in</strong>k model it is essential to have the EDSfile and source files of the Object Dictionary prepared (see section 3.3). Creation of theEDS file and generation of the source files has to be performed by the Object DictionaryEditor distributed with the CanFestival driver sources. It is also available <strong>in</strong> the blocksetdistribution <strong>in</strong> the subfolder canfestival/objdictgen.The editor needs to have Python, WxPython and Gnosis Utils <strong>in</strong>stalled for runn<strong>in</strong>g.The follow<strong>in</strong>g <strong>in</strong>stallation files should be available <strong>in</strong> the blockset distribution or you candownload the current versions from the appropriate web sites.ˆ python-2.6.1.msiˆ wxPython2.8-w<strong>in</strong>32-unicode-2.8.9.2-py26.exeˆ Gnosis Utils-1.2.2.w<strong>in</strong>32.exeWhile hav<strong>in</strong>g the <strong>in</strong>stallation file prepared you can <strong>in</strong>stall the Python environment byrunn<strong>in</strong>g them one after another. Then the Object Dictionary Editor can be started byrunn<strong>in</strong>g objdictedit command <strong>in</strong> Matlab command l<strong>in</strong>e. Exist<strong>in</strong>g .od file can be passedas a function parameter. Read section 3.3 for more <strong>in</strong>formation about work<strong>in</strong>g with theeditor and EDS files.3.2.2 CANopen blockset <strong>in</strong>stallationThe <strong>in</strong>stallation of the blockset itself is very simple. It has to be just unpackedsomewhere and the canopen blockset setup.m script has to be performed from the Matlabcommand l<strong>in</strong>e. The script just adds the blockset folder and subfolders to the Matlabsearch path.3.2.3 CANopen support <strong>in</strong> the targetThe blockset can be used only with the L<strong>in</strong>ux ERT Target. To enable the blocksetusage <strong>in</strong> the target the CANopen support option has to be checked <strong>in</strong> the model configuration<strong>in</strong> the Real Time Workshop/CANopen support pane. If the blockset is properly<strong>in</strong>stalled the paths of CanFestival libraries and <strong>in</strong>cludes will be automatically filled <strong>in</strong>after check<strong>in</strong>g this option.The menu offers compil<strong>in</strong>g CanFestival from the source as well. However, the path ofthe source folder is not filled automatically. The CanFestival sources should be distributedtogether with the target as well or it can be obta<strong>in</strong>ed from the CanFestival web sides[LOLb] (see section 3.2.4 for more <strong>in</strong>formation). If the build<strong>in</strong>g is required, the targetwrites commands for CanFestival compilation <strong>in</strong>to the Makefile. It performs the configure37


script on the source folder first. The follow<strong>in</strong>g parameters are used to set up the desiredtarget platform.. / configure −−timers=unix −−can=socket −−cc=powerpc −603e−l<strong>in</strong>ux−gnu−gcc −−arch=ppc −−os=←↪l<strong>in</strong>ux −−target=unixMoreover, if the CAN message console logg<strong>in</strong>g option is enabled the –debug=MSGparameter is added. Then the make command is applied to the CanFestival source folderand the libraries are copied <strong>in</strong>to the generated code folder to be used by l<strong>in</strong>ker. If you arestart<strong>in</strong>g work with the driver, visit [DoCE] to learn the very basics <strong>in</strong> us<strong>in</strong>g it.3.2.4 Updat<strong>in</strong>g CanFestival versionThe current version of CanFestival can be obta<strong>in</strong>ed from project CVS repository (visit[LOLb] for the <strong>in</strong>formation about the repository). Now, you can set Build CanFestivalfrom source option <strong>in</strong> the configuration parameters of your model and fill the new Can-Festival folder. The target is prepared to configure and build the CF source, however,there are some problems that have to solved before start<strong>in</strong>g the code generation.Firstly, the drivers/can socket/can socket.c file of CF source <strong>in</strong>cludes some headers ofSocketCan driver distribution. This headers are placed <strong>in</strong> the <strong>in</strong>clude/l<strong>in</strong>ux folder of ourlocal CanFestival source. Copy this folder <strong>in</strong>to the new CF source <strong>in</strong>clude folder and youwill not have to <strong>in</strong>stall SocketCan driver.In the time you decide to update the CanFestival, the driver API will have been probablychanged. It means that you will have to change the particular TLC scripts of theblockset to generate the API function calls accord<strong>in</strong>g to the current prototypes. Visit[LOLa] doxygen sites for the <strong>in</strong>formation about the current driver API.F<strong>in</strong>ally, you will have to rebuild your Object dictionary created <strong>in</strong> the old version ofobjdictedit as it will not be probably compatible. You have to load your .od file <strong>in</strong>to thenew objdictedit and build the dictionary by the menu command once more.After perform<strong>in</strong>g the steps described above, the blockset should work with the newCanFestival version correctly. However, accord<strong>in</strong>g to my experience with us<strong>in</strong>g the driver,I do not believe it very much. While <strong>in</strong>tegrat<strong>in</strong>g the driver I had to solve some problemsand fix some bugs. I could not wait until the bugs were fixed by the authors <strong>in</strong> the repositorybecause some changes <strong>in</strong> driver API would be made as well.The most significant bug or may be chaos is <strong>in</strong> the endianity solution. It has beenchanged many times, so it is not possible to follow changes until these days very well.Macros called UNS16 LE and UNS32 LE are applied to OD entries to switch the valuebytes <strong>in</strong>to little endian form. However, this causes that CANopen message IDs of littleendian are compared with masks of big endian at mach<strong>in</strong>e us<strong>in</strong>g big endian notation andso the IDs are not recognized. Practically, it means that some messages def<strong>in</strong>ed to besent are not sent and received messages are not processed. If you noticed such problems,have a look at the endianity solution and messages proceed<strong>in</strong>g <strong>in</strong> the current version.38


3.3 EDS file and Object DictionaryThe CANopen network is based on particular nodes. Each node has its own ObjectDictionary (OD) [CiAb] which keeps all the configuration variables of the node and theattached device as well as the data def<strong>in</strong><strong>in</strong>g the state of the device. Some entries (<strong>in</strong>dices)of the OD have mean<strong>in</strong>g def<strong>in</strong>ed by the CANopen standard, some are device specific. TheOD fully def<strong>in</strong>es the behavior of the node <strong>in</strong> the network.The content of the Object Dictionary can be saved <strong>in</strong> a text EDS file (Electronic DataSheet). Many universal CANopen devices supports load<strong>in</strong>g its configuration from suchEDS file. The ma<strong>in</strong> block of the blockset does it as well. The custom EDS file can becreated by CanFestival OD editor.3.3.1 CanFestival OD editorCanFestival OD editor is a Python script called objdictedit.py which can be found <strong>in</strong>CanFestival source folder <strong>in</strong> objdictgen subfolder. It can be started by runn<strong>in</strong>g objdicteditcommand <strong>in</strong> Matlab command l<strong>in</strong>e. Exist<strong>in</strong>g .od file name can be passed as a functionparameter. Python and WxPython have to be <strong>in</strong>stalled accord<strong>in</strong>g to section 3.2 to runit properly. The editor has graphical user <strong>in</strong>terface for creat<strong>in</strong>g or customiz<strong>in</strong>g ObjectDictionary. The OD can be then exported <strong>in</strong>to EDS file and C language source and headerfiles that conta<strong>in</strong> the C structure representation of the OD and have to be l<strong>in</strong>ked withthe generated code.The Node name is specified <strong>in</strong> the OD editor. This name is used as a node identifier<strong>in</strong> the model <strong>in</strong> case of us<strong>in</strong>g more than one nodes. The name has to be the same as thename of EDS file and .c and .h source files. These files are then placed <strong>in</strong> the model folderand the name is set to all the CANopen blocks that should work with this dictionary.The example of us<strong>in</strong>g OD files with OD (node) name myOD is shown <strong>in</strong> the figure 3.1.In case of us<strong>in</strong>g more than one CANopen node block <strong>in</strong> the model, EDS, .c and .hfiles with the unique name has to be created for each node.BuilddictionaryOD editor (objdictedit.py)Node name = myODExportTo EDSfileReadconfigurationCANopen node blockOD name = myODSimul<strong>in</strong>k modelmyOD.hmyOD.cmyOD.edsModel folderL<strong>in</strong>ux ERT targetCodegenerationBuild<strong>in</strong>gModel sourcesModel executableFigure 3.1: Pr<strong>in</strong>ciple of creat<strong>in</strong>g and us<strong>in</strong>g OD <strong>in</strong> the CANopen node39


3.4 CANopen node blockThe CANopen node block is the ma<strong>in</strong> block of the CANopen blockset. It keeps theObject Dictionary content of the node and it has to be used just once for each nodecreated <strong>in</strong> the model. The dependency of each other block on the ma<strong>in</strong> block and ODname match is checked. This block uses its Object Dictionary name parameter as a basename of EDS file. It reads the EDS file and fills the block mask accord<strong>in</strong>g to its content(see section 3.4.2). F<strong>in</strong>ally, it adds the OD .c and .h files to the model source to be l<strong>in</strong>kedwith generated code (see section 3.3).The block is def<strong>in</strong>ed <strong>in</strong> l<strong>in</strong>ux ert target blockset.mdl file and support files are mentioned<strong>in</strong> the table 3.1.S-function sourceS-function mexHelp fileTLC scriptsMask callbackscanopen.ccanopen.mexw32canopen help.htmlcanopen.tlc (ma<strong>in</strong>)cf canopen.tlccanopen mask edsFile.mcanopen mask generateSYNC.mcanopen mask <strong>in</strong>itialisation.mcanopen mask loadMapp<strong>in</strong>g.mcanopen mask modelSYNC.mTable 3.1: Block files3.4.1 Block parametersThe follow<strong>in</strong>g text describes particular parameters of the block mask. It is the help ofus<strong>in</strong>g the block <strong>in</strong> the model. The parameters are configured <strong>in</strong> the block mask which isshown <strong>in</strong> the figure 3.2.Node IDNode ID is the ID of the local CANopen node (1 - 127).CAN board numberBOA5200 computer is equipped with two CAN ports. By sett<strong>in</strong>g CAN board parameteryou choose which of these ports to use.CAN bit rateBit rate of used CAN bus can be set <strong>in</strong>to predef<strong>in</strong>ed values only.Object Dictionary nameName of the CanFestival OD of this node. It is either the name of .eds, .c, .h Can-Festival files and the OD structure identifier def<strong>in</strong>ed there. The EDS file and the ObjectDictionary def<strong>in</strong>ition .c and .h files can be edited and generated by CanFestival Objdicteditand have to be placed <strong>in</strong> the model directory. The name of the dictionary <strong>in</strong>cluded40


Figure 3.2: Mask of the CANopen node block<strong>in</strong> these files has to be the same as the name of these files. The reason is that all theOD variables use the name as prefix. For example: the CanFestival OD name is myNode.Then <strong>in</strong>sert myNode <strong>in</strong> the edit array and place OD files myNode.eds, myNode.c andmyNode.h <strong>in</strong>to the model directory.While more than one CANopen node blocks are used <strong>in</strong> the model this identifierdeterm<strong>in</strong>es which model block belongs to each CANopen node.Load I/O mapp<strong>in</strong>g from EDS fileIf checked the cells of <strong>in</strong>put and output mapp<strong>in</strong>g are filled automatically accord<strong>in</strong>g tothe RPDOs a TPDOS mapp<strong>in</strong>g read from EDS file.Input/output mapp<strong>in</strong>gInput mapp<strong>in</strong>g def<strong>in</strong>es which entries of Object Dictionary are connected to block<strong>in</strong>puts. Output mapp<strong>in</strong>g def<strong>in</strong>es which entries of Object Dictionary are connected toblock outputs.The only accessible entries are the Manufacturer specific variables def<strong>in</strong>ed <strong>in</strong> EDS.These entries are generated by OD editor (see section 3.3.1) as variables <strong>in</strong>to the C code.The entries are accessed just through these variables <strong>in</strong> IO mapp<strong>in</strong>g. The variables havethe name which they are represented by <strong>in</strong> the code.41


Input/output mapp<strong>in</strong>g is an array of <strong>in</strong>puts/outputs of the block <strong>in</strong> the follow<strong>in</strong>g form.{{ OD_<strong>in</strong>dex , OD_sub<strong>in</strong>dex or −1, Entry_data_type , ' Entry name ' } , . . . }Example{{8193 , −1, 7 , ' c p d v e l o c i t y ' } , {8195 , −1, 5 , ' cpd controlword ' }}This array is filled automatically by OD entries mapped <strong>in</strong>to RPDO (output mapp<strong>in</strong>g)and TPDO (<strong>in</strong>put mapp<strong>in</strong>g). The array can be modified by user. To return to the defaultvalues check the Load I/O mapp<strong>in</strong>g from EDS file option. Accord<strong>in</strong>g to the <strong>in</strong>put/outputmapp<strong>in</strong>g the number of block <strong>in</strong>puts and outputs is set. Each <strong>in</strong>put is supplied by simulationoutput and each output is supplied by simulation <strong>in</strong>put. In case of simulation these<strong>in</strong>puts/outputs are used for obta<strong>in</strong><strong>in</strong>g values <strong>in</strong>stead of PDO communication. Simulationsupport has to be enabled to create simulation I/O.Sample timeThe sample time and offset of the block I/O refresh <strong>in</strong> seconds. It is set <strong>in</strong> the formof Sample time = [sampleTime offset]. In the case that just a s<strong>in</strong>gle number is set, it isconsidered to be a sample time and the offset is set to 0.M<strong>in</strong>d that it has noth<strong>in</strong>g <strong>in</strong> common with the CANopen SYNC messages. This is justsynchronization of the block <strong>in</strong>puts and outputs (block Update and Output functions).Simulation supportThe block is ma<strong>in</strong>ly useful for generat<strong>in</strong>g code, but it is also able to perform simulationof synchronous communication. If Simulation support is checked simulation output iscreated to each data <strong>in</strong>put and simulation <strong>in</strong>put to each data output. While simulat<strong>in</strong>gvalues from simulation <strong>in</strong>puts are copied to data outputs and from <strong>in</strong>puts are the valuescopied to correspond<strong>in</strong>g simulation outputs.Heartbeat producer periodHeartbeat service sett<strong>in</strong>g is load from EDS file and it is displayed by the GUI just forthe <strong>in</strong>formation, but cannot be changed here. Heartbeat producer period is the <strong>in</strong>terval(milliseconds) <strong>in</strong> which the heartbeat message is sent by the local node. If it is set tozero, no messages are produced. This sett<strong>in</strong>g is load from the Object Dictionary <strong>in</strong>dex1017 hex.Heartbeat consumer nodes and timeoutsThis <strong>in</strong>formation is load from the EDS file at the <strong>in</strong>dex 1016 hex of the Object Dictionary.It def<strong>in</strong>es the nodes (heartbeat producers) that should be monitored and the periodsof heartbeat messages they are send<strong>in</strong>g. It is displayed as a cell array of pairs node ID andperiod <strong>in</strong> milliseconds. If the array is empty no heartbeat consumer is established. Thissett<strong>in</strong>gs cannot be changed us<strong>in</strong>g this GUI. If some node does not send the message <strong>in</strong> thegiven <strong>in</strong>terval, the Heartbeat error callback is called. Therefor the CANopen callbacksblock should be used to handle this error while us<strong>in</strong>g Heartbeat service.42


3.4.2 ObjectDictionary class and EDS file parserWhile hav<strong>in</strong>g the Object Dictionary name <strong>in</strong>serted <strong>in</strong> the CANopen block mask, theappropriate EDS file is loaded. It is given to the ObjectDictionary class constructor whichuses EDS parser do read the EDS file. The resulted OD object is placed <strong>in</strong>to the objDictstructure <strong>in</strong> the field with the same name as the OD name. This structure is stored <strong>in</strong>the Matlab workspace and all used CANopen blocks have their ODs <strong>in</strong> it. The OD objectkeeps all the <strong>in</strong>dices of the given EDS file, their default values and data types (bothCanFestival and Matlab representation).3.4.3 Block functionalityThe CANopen node block generates the code controll<strong>in</strong>g the CANopen driver (Can-Festival) and the local CANopen node as it is the ma<strong>in</strong> block of the blockset. It meansthat it starts the driver at the simulation startup and stops it at the simulation term<strong>in</strong>ation.After the startup the local node state is set to Initialisation and accord<strong>in</strong>g to theCANopen standard [CiAb] it switches to the Pre-operational state automatically. However,it is necessary to switch the state to Operational manually to start the CANopennode function. There is shown the diagram of the block functionality <strong>in</strong> the figure 3.3.Output and Update functions of the model are performed <strong>in</strong> each simulation step. Thisblock copies particular entries of the Object Dictionary to its output ports <strong>in</strong> the Outputfunction and updates its OD by new <strong>in</strong>puts <strong>in</strong> the Update function. Read appropriateparagraph <strong>in</strong> the Block parameters section for more <strong>in</strong>formation about mapp<strong>in</strong>g <strong>in</strong>putand output block ports on the OD entries.model_start()●Initialize and start CANopen driver●Set local state to Initialisation(it will be set to preOperational automatically)Simulation startmodel_output()Blocksampletime●Copy OD entriesto the block output portsmodel_update()●Copy block <strong>in</strong>put portsto the OD entriesSimulation f<strong>in</strong>ishmodel_term<strong>in</strong>ate()●Set local state to Stopped●Stop CANopen driverFigure 3.3: CANopen node block functionality <strong>in</strong> the model functions43


Called by RTWDur<strong>in</strong>g TLC processcanopen.tlcBlockTypeSetup()●Adds post EMCY callbackparams structure <strong>in</strong>to modelheader filecf_canopen.tlcgenerateCanopenFiles()●Generates functions forInitialization, start<strong>in</strong>g andStopp<strong>in</strong>g the CANopenDriver and local nodeBlockInstanceSetup()●Creates %.c file●Creates %.h file●Calls function generat<strong>in</strong>gFiles contentStart()Term<strong>in</strong>ate()Output()Update()●Writes bodies of theseFunctions <strong>in</strong>to modelfunctionsGenerated files%.h●Header file of CANopenNode functions%.c●Source file of CANopenNode functionsmodel.c●Model <strong>in</strong>itialisation andStep functionsFigure 3.4: TLC function call diagram <strong>in</strong> CANopen block code generation3.4.4 Simulation capabilitiesIf the simulation directly <strong>in</strong> Simul<strong>in</strong>k is required, the Simulation support option <strong>in</strong>the block mask has to be checked. While hav<strong>in</strong>g this option checked simulation <strong>in</strong>putsand outputs of the block are created. The ObjectDictionary object is created <strong>in</strong> Matlabworkspace. This object is stored <strong>in</strong> objDict structure <strong>in</strong> the field of the same nameas is the OD name parameter. It means that if the OD name is e.g. controller, theproper ObjectDictionary is stored <strong>in</strong> the field objDict.controller <strong>in</strong> the workspace. Ineach simulation step, entries of this OD are updated by block <strong>in</strong>put values and the blockoutputs are read from the OD object as well. It means <strong>in</strong> fact that the Object Dictionaryrealizes the block state. This data object <strong>in</strong> the workspace is used for data exchange byCANopen asynchronous blocks dur<strong>in</strong>g the simulation.3.4.5 Block code generationWhile generat<strong>in</strong>g the code, TLC functions of canopen.tlc file are called by Real TimeWorkshop [Mat] as it is demonstrated <strong>in</strong> the figure 3.4. Except writ<strong>in</strong>g <strong>in</strong>to default modelfunctions, the pair of .h and .c files is created. These files have name given by blockidentifier which is build from block name <strong>in</strong> Simul<strong>in</strong>k (e.g. files CANopennode1.c andCANopennode1.h are created for the block called CANopen node 1 ). This code moduleis added to the model sources and is l<strong>in</strong>ked with the model code. It conta<strong>in</strong>s the functionperform<strong>in</strong>g the CanFestival driver <strong>in</strong>itialization, CANopen node startup and term<strong>in</strong>ationand are called from model.c <strong>in</strong> the proper time of model execution.44


3.5 Callbacks blockThis blocks creates the API of CANopen event callbacks implemented <strong>in</strong> CanFestivaldriver. It allows the user to handle asynchronous events like Emergency message reception,synchronization or Heartbeat error. Read section 3.5.1 for more <strong>in</strong>formation.Each callback function is performed <strong>in</strong> separate thread with priority lower than thepriority of periodic model threads. It means that long duration of callbacks executioncannot break the model synchronization.This block implements SS OPTION ASYNCHRONOUS option <strong>in</strong> its S-function. Itsays to Simul<strong>in</strong>k that subsystems connected to the block output port are asynchronouslyexecuted. Us<strong>in</strong>g Asynchronous rate transition block (see section 3.10) at each <strong>in</strong>put andoutput of these subsystems is required and checked by Simul<strong>in</strong>k eng<strong>in</strong>e.The block is def<strong>in</strong>ed <strong>in</strong> l<strong>in</strong>ux ert target blockset.mdl file and support files are mentioned<strong>in</strong> the table 3.2.S-function sourceS-function mexHelp fileTLC scriptsMask callbackcanopen callbacks.ccanopen callbacks.mexw32canopen callbacks help.htmlcanopen callbacks.tlc (ma<strong>in</strong>)callbacks.tlccallbacks mask <strong>in</strong>itialisation.mTable 3.2: Block files3.5.1 Block parametersThis section describes the parameters of Callbacks block and possibilities of usage aswell. The mask of the block with parameter sett<strong>in</strong>gs dialog is shown <strong>in</strong> the figure 3.5.Figure 3.5: CANopen callbacks block maskObject dictionary nameThe Object dictionary name is used to say the block which OD it should work withif more than one CANopen node blocks are used <strong>in</strong> the model. The OD name has to bethe same as the OD name of the appropriate CANopen ma<strong>in</strong> block.45


Callbacks connected to function call portsYou can def<strong>in</strong>e the callbacks of CANopen node that are to be used as function callports of the block. The callbacks and correspond<strong>in</strong>g function calls can be used for activationof another block for example Asynchronous operations block or even the ma<strong>in</strong>CANopen node block. It is def<strong>in</strong>ed by the cell of the list of callback names (and sometimesconfiguration parameters) to be used by the port. The syntax of the cell is:{{ ' callback1 name ' } , { ' callback2 name ' , { ' params ' }} , . . . }Example{{ 'SYNC ' } , { 'EMCY' } , { 'OD' ,{ ' 1800 ' , ' 1 ' }} , { ' I n i t i a l i s a t i o n ' }}The function call output port of the block is created (always the first output port) andits width is set to be the same as the number of def<strong>in</strong>ed callbacks. If us<strong>in</strong>g more than onecallbacks the Demux Simul<strong>in</strong>k block has to be connected on the output port and split thesignals <strong>in</strong>to appropriate number of outputs. The number of Demux outputs has to be setby user manually and fit the number of def<strong>in</strong>ed callbacks. F<strong>in</strong>ally, on the Demux portsany Function call subsystems can be connected.Additionally some callbacks are supplemented by a parameter or parameters. Forexample EMCY callback has 3 parameters def<strong>in</strong><strong>in</strong>g the received EMCY message: nodeID, Error code and Error register content. These parameters are stored <strong>in</strong>to the globalmemory while execut<strong>in</strong>g the callback and can be accessed by appropriate parser block.For example EMCY callback parameters can be decoded by EMCY parser block. Thisparser block should be placed <strong>in</strong> the function call subsystem connected to the appropriatecallback. All the supported callbacks are described <strong>in</strong> the follow<strong>in</strong>g text.SYNC messages callbackThis callback is called after SYNC message reception or transmission. No parameteris set to the callbacks parameters port.{ 'SYNC ' }EMCY messages callbackThis callback is called after emergency message reception. This callback has three parametersdef<strong>in</strong><strong>in</strong>g the received EMCY message: node ID (UINT8), Error code (UINT16),Error register (UINT8). Use EMCY parser block to get these parameters from the memory.{ 'EMCY' }46


TPDO messages callbackFigure 3.6: Work<strong>in</strong>g with callbacks and their parametersThis callback is called after PDO transmission. No parameter is set to the callbacksparameters port.{ 'TPDO ' }Initialisation state callbackThis callback is called after enter<strong>in</strong>g the Initialisation state by local node. No parameteris set to the callbacks parameters port.{ ' I n i t i a l i s a t i o n ' }PreOperational state callbackThis callback is called after enter<strong>in</strong>g the PreOperational state by local node.parameter is set to the callbacks parameters port.No{ ' PreOperational ' }Operational state callbackThis callback is called after enter<strong>in</strong>g the Operational state by local node. No parameteris set to the callbacks parameters port.47


{ ' O p e r a t i o n a l ' }Stopped state callbackThis callback is called after enter<strong>in</strong>g the Stopped state by local node. No parameteris set to the callbacks parameters port.{ ' Stopped ' }Slave boot up callbackThis callback is called after reception of Slave boot up message (COBID = 0x700 +NodeID). This callback has one parameter def<strong>in</strong><strong>in</strong>g the node ID (UINT8). Use SlaveBootupparser block to get the value from the memory.{ ' slaveBootup ' }Heartbeat error callbackThis callback is called after detection of CANopen heartbeat error. This callback hasone parameter def<strong>in</strong><strong>in</strong>g the node ID (UINT8). Use Heartbeat error parser block to getthe value from the memory.The heartbeat service has to be def<strong>in</strong>ed <strong>in</strong> EDS file used for node configuration. Thissett<strong>in</strong>g can be done <strong>in</strong> Object Dictonary editor (see section 3.3.1). If the node is set to bea heartbeat producer, the heartbeat request is sent to the network with the given period.If some node does not aswer it <strong>in</strong> the def<strong>in</strong>ed timeout, the heartbeat error callback iscalled at the producer node.{ ' h e a r t b e a t E r r o r ' }OD entry callbackThis callback is called after change of data <strong>in</strong> the def<strong>in</strong>ed OD entry. It can be set toany exist<strong>in</strong>g OD entry. No parameter is set to the callbacks parameters port.The callback has to be predef<strong>in</strong>ed <strong>in</strong> CanFestival Objdictedit by check<strong>in</strong>g the Havecallback option of the appropriate OD entry!{ 'OD' , { ' <strong>in</strong>dex ' , ' sub<strong>in</strong>dex ' }}Simulation supportThe block is ma<strong>in</strong>ly useful for generat<strong>in</strong>g code, but it is also able to perform simulationof CANopen events activat<strong>in</strong>g the callbacks. If Simulation support is checked simulation<strong>in</strong>put is created. This <strong>in</strong>put has as many signals as def<strong>in</strong>ed callbacks number. If one ofthe boolean signals is set, particular callback is activated.48


3.5.2 Block functionalityThe Callback block does not perform any periodic tasks. It does not have output andupdate functions <strong>in</strong> the generated code. Its only function is to register required callbacks atthe program startup. This registration saves po<strong>in</strong>ters to generated callback functions <strong>in</strong>toCanFestival structure. If some callback is activated by the driver, code of the connectedsubsystem is called by the callback function (figure 3.7). Callback parameters are stored<strong>in</strong>to the global memory structure and can be accessed by the appropriate parser block(section 3.6). Read section 3.5.1 for exact <strong>in</strong>formation about particular callback types.model_start()●Register callbacks function po<strong>in</strong>tersIn CanFestivalCanFestival driverEventoccuredsubsystem1_output()emcy_parser_output()●Read EMCY param structuresubsystem2_output()●Subsystem 2 output codeCallbackcalledpost_emcy_callback()●Create EMCY param structure●Calls connected subsystemsync_callback()●Calls connected subsystemmodel.cCANopencallbacks.cFigure 3.7: Example of block code function while hav<strong>in</strong>g Emergency and Sync callbacksemployed3.5.3 Simulation capabilitiesSimulation capabilities of these block are very simple. While the Simulation supportoption is enabled, a s<strong>in</strong>gle <strong>in</strong>put port is created. Its width is the same as the number ofdef<strong>in</strong>ed callbacks. Each <strong>in</strong>put signal is a trigger of particular callback function call. It islogical <strong>in</strong>put that activates particular function call when enabled.The callback parameters can be employed <strong>in</strong> the simulation by enabl<strong>in</strong>g the simulationsupport of particular parameters parser blocks (see section 3.6). Then the simulation<strong>in</strong>puts of that blocks are created and the parameter values can be passed via signals.49


3.5.4 Block code generationThis block uses two TLC scripts - canopen callbacks.tlc and callbacks.tlc. The scriptscreates the pair of header and source files called by the block identifier which is basedon the block label <strong>in</strong> the model. It means that each block has its own source files. Thecallback functions are generated <strong>in</strong>to these files and the code for callbacks registration isplaced <strong>in</strong>to the model start function. The diagram of TLC functions calls is shown <strong>in</strong> thefigure 3.8.Called by RTWDur<strong>in</strong>g TLC processcallbacks.tlccanopen_callbacks.tlcStart()●Register callbacks <strong>in</strong>toCanFestivalBlockInstanceSetup()●Adds %.h fileTo common <strong>in</strong>cludesOutputs()●Generates callbackFunctions and function callsTo subsystemsparseRTWcallbacks()●Parses callbacks parametercellregisterRTWcallbacks()●Generates registration coderegisterODcallbacks()●Generates registration codegenerateRTWcallbacks()●Generate callbacks functionsgenerateODcallbacks()●Generate callbacks functionsGenerated files%.h●Header file of callbacksfunctions%.c●Source file of callbacksfunctionsFigure 3.8: Diagram of block code generation50


3.6 Callback parameters parser blocksA group of blocks that parses callback parameters provided by Callbacks block (seesection 3.5) was created to enable work<strong>in</strong>g with parameters of CANopen driver callbacks.These blocks are designed to be placed <strong>in</strong> function call subsystem activated from thecallback block. The Callbacks block stores the callback parameters <strong>in</strong>to the global memorywhile process<strong>in</strong>g a callback hav<strong>in</strong>g parameters (EMCY, Slave boot up and Heartbeaterror). The parser block can read these parameters from the global memory and setthem to its output ports. If there is more than one CANopen node def<strong>in</strong>ed <strong>in</strong> the model,each can have its own callbacks and parsers block. They are determ<strong>in</strong>ed by their Objectdictionary name parameter. The dependency of the parsers on the Callbacks block ischecked.For more <strong>in</strong>formation about the callbacks and the events that activate the callbacksread Callbacks block section 3.5 and CanFestival driver documentation [LOLb].3.6.1 Parser blocks parametersAll the parser blocks has the same two mask parameters. Its the reason for describ<strong>in</strong>gthe parameters generally for all the block together.Object dictionary nameThe Object dictionary name is used to say the block which OD it should work withif more than one CANopen node blocks are used <strong>in</strong> the model. The OD name has to bethe same as the OD name of the appropriate CANopen ma<strong>in</strong> and callbacks blocks.Simulation supportWhile the Simulation support option is checked three <strong>in</strong>put ports are created. Eachof these ports corresponds to one of the outputs. In case of Simul<strong>in</strong>k simulation values ofthe simulation <strong>in</strong>puts are copied to the output ports <strong>in</strong> each block step.3.6.2 Simulation capabilitiesWhile hav<strong>in</strong>g the Simulation support mask option enable <strong>in</strong> some parser block, simulation<strong>in</strong>put ports are created. Each of these <strong>in</strong>puts corresponds to some block output portand callback parameter as well. In case of Simul<strong>in</strong>k simulation, values from the simulation<strong>in</strong>puts are copied to the outputs <strong>in</strong> the block Output function. Together with callbackevent simulation by Callbacks block the event execution can be completely simulated <strong>in</strong>the Simul<strong>in</strong>k.51


3.6.3 Emergency callback parameters parser blockThis block parses the Emergency message parameters. It can be used only <strong>in</strong> theco-operation with the CANopen callbacks block (with the same Object Dictionary name)hav<strong>in</strong>g the EMCY callback employed. The parser block is designed to be placed <strong>in</strong> functioncall subsystem connected to the appropriate callback of the Callbacks block.The block has three outputs accord<strong>in</strong>g to the number of EMCY callback parameters.These outputs provide values of last received EMCY message processed by the CANopencallbacks block. This Callbacks block writes message parameters to the global memoryand activates the EMCY callback function call.The block is def<strong>in</strong>ed <strong>in</strong> l<strong>in</strong>ux ert target blockset.mdl file and support files are mentioned<strong>in</strong> the table 3.3.S-function sourceS-function mexHelp fileTLC scriptsemcy parser.cemcy parser.mexw32emcy parser help.htmlemcy parser.tlcTable 3.3: Block files3.6.4 Heartbeat error callback parameters parser blockThis block parses the Heartbeat error event parameters. It can be used only <strong>in</strong> theco-operation with the CANopen callbacks block (with the same Object Dictionary name)hav<strong>in</strong>g the Heartbeat error callback employed (see section 3.5.1).The parser block is designed to be placed <strong>in</strong> function call subsystem connected to theappropriate callback of the Callbacks block. The block has a s<strong>in</strong>gle output accord<strong>in</strong>g tothe number of Heartbeat error callback parameters. This output provides the value of thelast Heartbeat error event processed by the CANopen callbacks block. The parameteris the node ID of the node which produced the error. The Callbacks block writes theparameter to the global memory and activates the Heartbeat error callback function call.The block is def<strong>in</strong>ed <strong>in</strong> l<strong>in</strong>ux ert target blockset.mdl file and support files are mentioned<strong>in</strong> the table 3.4.S-function sourceS-function mexHelp fileTLC scriptsheartbeat error parser.cheartbeat error parser.mexw32heartbeat error parser help.htmlheartbeat error parser.tlcTable 3.4: Block files52


3.6.5 Slave boot up callback parameters parser blockThis block parses the Slave boot up message parameters. It can be used only <strong>in</strong> theco-operation with the CANopen callbacks block (with the same Object Dictionary name)hav<strong>in</strong>g the Slave boot up callback employed. The parser block is designed to be placed<strong>in</strong> function call subsystem connected to the appropriate callback of the Callbacks block.The block has a s<strong>in</strong>gle output accord<strong>in</strong>g to the number of Slave boot up message callbackparameters. This output provides the value of the last Slave boot up message processed bythe CANopen callbacks block. The parameter is the node ID of the node which producedthe message. The Callbacks block writes message parameter to the global memory andactivates the Slave boot up callback function call.The block is def<strong>in</strong>ed <strong>in</strong> l<strong>in</strong>ux ert target blockset.mdl file and support files are mentioned<strong>in</strong> the table 3.5.S-function sourceS-function mexHelp fileTLC scriptsslave boot up parser.cslave boot up parser.mexw32slave boot up parser help.htmlslave boot up parser.tlcTable 3.5: Block files53


3.7 SYNC message generator blockThis block can be used for generat<strong>in</strong>g SYNC messages <strong>in</strong> the CANopen network.The SYNC generation can be performed by the CanFestival driver automatically if itis correctly set <strong>in</strong> the Object Dictionary. However, the automatical SYNC generationhas one big disadvantage that it is not synchronized with the model sample time. Itmeans that the time offset between the network synchronization and the model step isnot known. This is solved <strong>in</strong> the way that the automated SYNC generation is disabledand it is performed by SYNC generator block if it is used <strong>in</strong> the model. If the SYNCgenerator block for the given Object Dictionary is not placed <strong>in</strong> the model, the SYNCgeneration is performed automatically by the CanFestival driver accord<strong>in</strong>g to the ODsett<strong>in</strong>gs. It means of course that if neither the SYNC generator is used nor the SYNCgeneration is def<strong>in</strong>ed <strong>in</strong> OD, no SYNC generation is performed and the node is consideredto be the SYNC slave.This block calls the driver command for send<strong>in</strong>g SYNC message <strong>in</strong> its Output functionif the node state is Operational. It secures the synchronization of the model with theCANopen network communication. SYNC message ID is usually 80 hex, however, it ispossible to change it by the block parameter. The message ID is stored <strong>in</strong>to the ObjectDictionary at the model startup. The block functionality diagram is shown <strong>in</strong> the figure3.9.model_start()●Disable automated SYNC generation●Write SYNC ID <strong>in</strong>to the local Object DictionaryBlocksampletimemodel_output()Simulation start●If local state = Operationalthen send SYNCFigure 3.9: Function diagram of SYNC message generator blockAs described above, generat<strong>in</strong>g SYNC messages by the separate block is very useful,however it is necessary to th<strong>in</strong>k about the Simul<strong>in</strong>k work <strong>in</strong> this case. Functions ofparticular blocks are performed <strong>in</strong> each simulation step. If a group of blocks has the samesample time, all the blocks are performed one after another <strong>in</strong> the same step functionand the order of blocks is established just by the co<strong>in</strong>cidence. It means that some verysmall time delay can occur, which could be unwanted <strong>in</strong> case of SYNC messages thatsynchronize all the network. Call<strong>in</strong>g the block code as soon as possible after the timertick is ensured by implement<strong>in</strong>g SS OPTION PLACE ASAP <strong>in</strong> the S-function as well.The block is def<strong>in</strong>ed <strong>in</strong> l<strong>in</strong>ux ert target blockset.mdl file and support files are mentioned<strong>in</strong> the table 3.6.54


S-function sourceS-function mexHelp fileTLC scriptssync generator.csync generator.mexw32sync generator help.htmlsync generator.tlc3.7.1 Block parametersTable 3.6: Block filesThe follow<strong>in</strong>g text describes the parameters of the SYNC generator block.Object dictionary nameThe Object dictionary name is used to say the block which OD it should work with.The OD name has to be the same as the OD name of the appropriate CANopen ma<strong>in</strong>block.Sample timeBlock sample time and offset can be set <strong>in</strong> the same way as <strong>in</strong> each Simul<strong>in</strong>k block.Itis set <strong>in</strong> the standard Simul<strong>in</strong>k format [sampleTime offset]. If it is just a s<strong>in</strong>gle number,the offset is considered to be 0.SYNC message IDThe ID of the generated SYNC message. The default value is 0x80 (80 hex, 128 dec).It is not recommended to change it <strong>in</strong> the CANopen network, because it is def<strong>in</strong>ed byCANopen standard. The ID number has to be set <strong>in</strong> the C language form (0x prefix forhex numbers).3.7.2 Block code generationThis block has a s<strong>in</strong>gle TLC script sync generator.tlc which generates its code dur<strong>in</strong>gthe TLC process. It does not generate any files. It just writes the code for SYNC messageID setup <strong>in</strong>to the model start function and the code for SYNC message send<strong>in</strong>g <strong>in</strong>to themodel output function.55


3.8 Asynchronous operations blockThis block realizes a group of asynchronous transmissions def<strong>in</strong>ed by the parameter.It performs all the transmissions <strong>in</strong> the given order <strong>in</strong> its Output function. The block isuseful for network management or asynchronous communication. It is designed ma<strong>in</strong>ly tobe placed <strong>in</strong> the function call subsystem and called <strong>in</strong> some CANopen event callback (seesection 3.5). In this case the block sample time has to be set to -1 (<strong>in</strong>herited). However,it is possible to set the periodic sample time and run the block periodically straight <strong>in</strong> themodel. As an example of the common usage we can mention this block connected to thePre-operational callback and perform<strong>in</strong>g sett<strong>in</strong>g the node state to Operational or may besend<strong>in</strong>g Start-Node command to other nodes as well.The block is def<strong>in</strong>ed <strong>in</strong> l<strong>in</strong>ux ert target blockset.mdl file and support files are mentioned<strong>in</strong> the table 3.7.S-function sourceS-function mexHelp fileTLC scriptscf asyn.ccf asyn.mexw32cf asyn help.htmlcf asyn.tlcTable 3.7: Block files3.8.1 SDO transfersMost of the operations that are supported by this block do not need to wait for theend of the message transfer. It means that they are local operations that are performedimmediately or CANopen transfers that are not confirmed and so do not wait for theanswer. The only confirmed service of the CANopen protocol is SDO (Service DataObject). This service provides confirmed read<strong>in</strong>g or writ<strong>in</strong>g to the remote object dictionaryand are used ma<strong>in</strong>ly for the node setup and not for the regular data transfer.This service is supported by operations readNetworkDict and writeNetworkDict <strong>in</strong> thisblock. The answer to the message is handled by the CanFestival driver and a callbackfunction is called at the end of the transfer. It is necessary to wait for this callbackand read the transfer result. If the answer is not delivered <strong>in</strong> time, the timeout error isannounced so no <strong>in</strong>f<strong>in</strong>ite blockage can occur. You can avoid wait<strong>in</strong>g for the answer bysett<strong>in</strong>g appropriate parameter (see section 3.8.3). However, while read<strong>in</strong>g the networkdictionary, it will always wait for the result as the required value is there.The pr<strong>in</strong>ciple of this block work while some SDO transfers are used is shown <strong>in</strong> thefigure 3.10. If no SDO transfers are used, the checkSDO function is not necessary and allthe code is performed <strong>in</strong> a s<strong>in</strong>gle function and <strong>in</strong> a s<strong>in</strong>gle iteration.3.8.2 Block <strong>in</strong>puts and outputsThe block has one <strong>in</strong>put port and two output ports. The <strong>in</strong>put port is a vector of widthgiven by the highest value X of the <strong>in</strong>putX mark used <strong>in</strong> the operation def<strong>in</strong>ition cell. Ifthe highest <strong>in</strong>put used is 5, the width of <strong>in</strong>put port is set to 6 (0..5). The data output iscreated <strong>in</strong> the same way accord<strong>in</strong>g to the highest outputX value used. The second outputport is the error output. Its width is the same as the number of def<strong>in</strong>ed operation. Eachsignal of the port keeps the error code of the particular operation. The order is the same56


subsystem_output() ormodel_output()●Call CANopenasynchronous()model.cCANopenasynchronous()While f<strong>in</strong>ished! || ~errorCall perform functionWait for SDO resultendPerformOperationsBlockUntil SDOCANopenasynchronous_perform()●Perform def<strong>in</strong>ed operationsCanFestival driver_CheckSDOAndCont<strong>in</strong>ue()●SDO answer receivedSDO answercallback●Check SDO transfer resultCANopensynchronous.cSDOtransferf<strong>in</strong>ishedFigure 3.10: Asynchronous block function diagramas the order of def<strong>in</strong>ed sequence. The error code 0 means that the operations term<strong>in</strong>atedcorrectly. See operations description bellow to get <strong>in</strong>formation about particular errorcodes.Us<strong>in</strong>g block <strong>in</strong>put/output as operation parameterYou can use <strong>in</strong>putX mark as an operation parameter (X is the number of signal <strong>in</strong>the <strong>in</strong>put port vector < 0, N >). This will read the value of particular field <strong>in</strong> <strong>in</strong>put portvector and use it as the function parameter. In the same way outputX can be used <strong>in</strong>operations of read<strong>in</strong>g OD to copy the value to the output port <strong>in</strong>stead of some <strong>in</strong>ternalvariable.3.8.3 Block parametersBlock mask parameters are described <strong>in</strong> the follow<strong>in</strong>g section.Object dictionary nameThe Object dictionary name is used to say the block which OD it should work withif more than one CANopen node blocks are used <strong>in</strong> the model. The OD name has to bethe same as the OD name of the appropriate CANopen ma<strong>in</strong> block.Do not wait for SDO transfer resultIn case of SDO transfer, the block waits for the answer before cont<strong>in</strong>uation. This canbe over outweighed by check<strong>in</strong>g the Do not wait for SDO transfer result check box. M<strong>in</strong>dthat <strong>in</strong> case of readNetworkDict the program always wait for the answer (value)!57


Cont<strong>in</strong>ue the transfer sequence <strong>in</strong> case of errorYou can check the Cont<strong>in</strong>ue the transfer sequence <strong>in</strong> case of error for ignor<strong>in</strong>g theoperation failure and perform<strong>in</strong>g the sequence to the end.Sample timeThe sample time and offset of the block I/O refresh <strong>in</strong> seconds. It is set <strong>in</strong> the formof [sampleTime offset]. In the case that just a s<strong>in</strong>gle number is set, it is considered to bea sample time and the offset is set to 0.The sample time sett<strong>in</strong>g can be used to run the block periodically, however, the blockis designed ma<strong>in</strong>ly to perform the asynchronous operations <strong>in</strong> CANopen event callback.In this case the sample time should be set to <strong>in</strong>herited (-1) and the block should be placed<strong>in</strong> Function call subsystem.Simulation supportIn contrast to other blocks the Simulation support option does not create any simulation<strong>in</strong>puts of the block. It enables or disables us<strong>in</strong>g Matlab workspace objects for dataexchange dur<strong>in</strong>g simulation. This feature makes the simulation slow. It is recommendedto disable this option while simulation of asynchronous operations is not required.Operation parameters cellThe cell conta<strong>in</strong>s cells of particular operations of the order which they should beperformed <strong>in</strong>. The cell of one operation then conta<strong>in</strong>s a str<strong>in</strong>g of operation type and a cellof particular parameters. The operation type name corresponds to the function name ofparticular CanFestival function. Each operation type has different number of parameters.All the parameters are set as str<strong>in</strong>gs even if it is a number. Numbers are written <strong>in</strong> thesame form as <strong>in</strong> C language (e.g. 100, 0x10). Various data sources and dest<strong>in</strong>ation canbe used by the operations. First of all, it can be the pair of <strong>in</strong>dex and sub<strong>in</strong>dex <strong>in</strong> case ofaccess<strong>in</strong>g the Object dictionary. Then, it can be a block <strong>in</strong>put or output represented by<strong>in</strong>putX or outputX str<strong>in</strong>g. F<strong>in</strong>ally, it can be a constant number or almost anyth<strong>in</strong>g whichis the user sure to be def<strong>in</strong>ed <strong>in</strong> the generated code. For example it can be a variabledef<strong>in</strong>ed <strong>in</strong> the Manufacturer specific section of Object dictionary.{{ op1 \ _Name , { op1 \ _Parameter1 , op1 \ _Parameter2 }} ,{ op2 \ _Name , { op2 \ _Parameter1 , op2 \ _Parameter2 , op2 \ _Parameter3 }}}Example{{ ' sendPDOevent ' } ,{ ' writeNetworkDict ' , { ' 3 ' , ' 0 x1802 ' , ' 1 ' , ' <strong>in</strong>put2 ' , 'UNS8 ' }} ,{ ' masterSendNMTstateChange ' , { ' 3 ' , 'NMT\ S t a r t \ Node ' }} ,{ ' w r i t e L o c a l D i c t ' , { ' 0 x1802 ' , ' 1 ' , ' 255 ' , 'UNS32 ' }} ,{ ' writeNetworkDict ' , { ' 4 ' , ' 0 x1803 ' , ' 1 ' , ' 255 ' , 'REAL64 ' }}}58


Supported operationsThe follow<strong>in</strong>g text describes the asynchronous operations of CANopen protocol which aresupported by this block.Variable copyThis just copies the value, variable or block <strong>in</strong>put <strong>in</strong>to the target variable or blockoutput. While us<strong>in</strong>g variable name it has to be def<strong>in</strong>ed <strong>in</strong> the CanFestival node sourcefile generated by Objdictedit. The variable set may be used before PDO event operationto start the transmission of PDOs which are transmitted just after its value change.This is a simplified version of read/writeLocalDict operation which works only for thevariables def<strong>in</strong>ed <strong>in</strong> the node source. This operation always f<strong>in</strong>ishes with error code 0.Example{ ' VarCopy ' , { ' var8192 \ 0 ' , ' var8193 \ 1 ' }}copies the value of variable var8192 0 to variable var8193 1, or{ ' VarCopy ' , { ' 0 x15 ' , ' output2 ' }}copies the constant 0x15 to the block output 2, or{ ' VarCopy ' , { ' <strong>in</strong>put3 ' , ' var8192 \ 0 ' }}copies the value of the <strong>in</strong>put signal 3 <strong>in</strong>to variable var8192 0.PDO eventThis operation <strong>in</strong>vokes PDO transmission of PDOs that are to be sent after datachange. Only PDOs that satisfy this condition are transmitted. This operation alwaysf<strong>in</strong>ishes with error code 0.Example{ ' sendPDOevent ' }Set local node stateThis operation sets local CANopen node state. The states can be Initialisation, Stopped,Operational or Pre-operational. M<strong>in</strong>d that the names are case sensitive!! This operationalways f<strong>in</strong>ishes with error code 0.See the CANopen protocol documentation for more <strong>in</strong>formation.59


Example{ ' s e t S t a t e ' , { ' O p e r a t i o n a l ' }}Set remote node stateThis operation sets the state of remote CANopen node with given ID. The states canbe NMT Reset Node, NMT Reset Communication, NMT Stop Node, NMT Start Node orNMT Enter PreOperational. M<strong>in</strong>d that the names are case sensitive!! This operationalways f<strong>in</strong>ishes with error code 0.Example{ ' masterSendNMTstateChange ' , { ' 3 ' , 'NMT\ S t a r t \ Node ' }}Write to local dictionaryThis operation writes value <strong>in</strong>to local Object Dictionary. The parameters of the operationare these: <strong>in</strong>dex, sub<strong>in</strong>dex, value, value data type. If the given OD entry has nosub<strong>in</strong>dices set the sub<strong>in</strong>dex parameter <strong>in</strong>to ’-1’. This operation always f<strong>in</strong>ishes with errorcode 0. The data types are specified us<strong>in</strong>g these str<strong>in</strong>gs:INTEGER8, INTEGER16, INTEGER24, INTEGER32, INTEGER40, INTEGER48, IN-TEGER56, INTEGER64UNS8, UNS16, UNS32, UNS24, UNS40, UNS48, UNS56, UNS64REAL32, REAL64Example{ ' w r i t e L o c a l D i c t ' , { ' 0 x1802 ' , ' 1 ' , ' 255 ' , 'UNS32 ' }}{ ' w r i t e L o c a l D i c t ' , { ' 0 x1802 ' , ' 1 ' , ' <strong>in</strong>put0 ' , 'UNS32 ' }}Read entry of the local dictionaryThis operation reads an entry of the local Object Dictionary. The parameters of theoperation are these: <strong>in</strong>dex, sub<strong>in</strong>dex, target variable, value data type. If the given ODentry has no sub<strong>in</strong>dices set the sub<strong>in</strong>dex parameter <strong>in</strong>to ’-1’. This operation always f<strong>in</strong>isheswith error code 0. The data types are specified us<strong>in</strong>g these str<strong>in</strong>gs:INTEGER8, INTEGER16, INTEGER24, INTEGER32, INTEGER40, INTEGER48, IN-TEGER56, INTEGER64UNS8, UNS16, UNS32, UNS24, UNS40, UNS48, UNS56, UNS64REAL32, REAL64Example60


{ ' r e a d L o c a l D i c t ' , { ' 0 x1802 ' , ' 1 ' , ' var1 ' , 'UNS32 ' }}{ ' r e a d L o c a l D i c t ' , { ' 0 x1803 ' , ' 0 ' , ' output1 ' , 'UNS32 ' }}Write entry of the network dictionaryThis operation writes value <strong>in</strong>to Object Dictionary of remote node. The parametersof the operation are these: node ID, <strong>in</strong>dex, sub<strong>in</strong>dex, value, value data type. If the givenOD entry has no sub<strong>in</strong>dices set the sub<strong>in</strong>dex parameter <strong>in</strong>to ’-1’. The data types arespecified us<strong>in</strong>g these str<strong>in</strong>gs:INTEGER8, INTEGER16, INTEGER24, INTEGER32, INTEGER40, INTEGER48, IN-TEGER56, INTEGER64UNS8, UNS16, UNS32, UNS24, UNS40, UNS48, UNS56, UNS64REAL32, REAL64The SDO transfer uses confirmation. If the Do not wait for SDO transfer result checkbox is unchecked the operation waits for the remote node confirmation of the SDO andchecks the errors. In case of error the SDO abort code is written to the error output portof the block. See CANopen specification for more <strong>in</strong>formation about SDO error codes.Example{ ' writeNetworkDict ' , { ' 4 ' , ' 0 x1803 ' , ' 1 ' , ' 255 ' , 'REAL64 ' }}Read entry of the remote node dictionaryThis operation reads an entry of the remote node Object Dictionary. The parametersof the operation are these: nodeID, <strong>in</strong>dex, sub<strong>in</strong>dex, target variable, value data type. Ifthe given OD entry has no sub<strong>in</strong>dices set the sub<strong>in</strong>dex parameter <strong>in</strong>to ’-1’. The datatypes are specified us<strong>in</strong>g these str<strong>in</strong>gs:INTEGER8, INTEGER16, INTEGER24, INTEGER32, INTEGER40, INTEGER48, IN-TEGER56, INTEGER64UNS8, UNS16, UNS32, UNS24, UNS40, UNS48, UNS56, UNS64REAL32, REAL64After send<strong>in</strong>g the SDO read command to the remote node, the program has to wait forthe SDO answer with the requested value. The Do not wait for SDO transfer result checkbox has no <strong>in</strong>fluence on the wait time <strong>in</strong> the case of read<strong>in</strong>g! In case of error the SDOabort code is written to the error output port of the block. See CANopen specificationfor more <strong>in</strong>formation about SDO error codes.Example{ ' readNetworkDict ' , { ' 2 ' , ' 0 x1802 ' , ' 1 ' , ' var1 ' , 'UNS32 ' }}{ ' readNetworkDict ' , { ' 4 ' , ' 0 x1803 ' , ' 0 ' , ' output1 ' , 'UNS32 ' }}61


SleepGenerates the sleep command which makes the current thread wait for the givenamount of seconds. M<strong>in</strong>d that the thread may be the sample time loop thread <strong>in</strong> casethat the block is not called <strong>in</strong> the Function call subsystem activated by Callbacks block.This operation always f<strong>in</strong>ishes with error code 0.Example{ ' s l e e p ' , { ' 5 ' }}USleepGenerates the usleep command which makes the current thread wait for the givenamount of microseconds. M<strong>in</strong>d that the thread may be the sample time loop thread <strong>in</strong>case that the block is not called <strong>in</strong> the Function call subsystem activated by Callbacksblock. This operation always f<strong>in</strong>ishes with error code 0.Example{ ' u s l e e p ' , { ' 100 ' }}3.8.4 Block code generationThe block code is generated by the cf asyn.tlc script. All the blocks of this typehave the common header file called cf asyn.h. Each block has its own source file calledby the same name as its name <strong>in</strong> Simul<strong>in</strong>k model. See the figure 3.11 for the graphicalrepresentation.3.8.5 Simulation capabilitiesThe block supports Simul<strong>in</strong>k simulation of data transfer operations (readLocalDict,writeLocalDict, readNetworkDict, writeNetworkDict). The other operations def<strong>in</strong>ed <strong>in</strong> thecell are ignored <strong>in</strong> simulation mode. Local dictionary operations reads or writes valuesto the ObjectDictionary object stored <strong>in</strong> the objDict.(odName) structure <strong>in</strong> the Matlabworkspace. This object is created and used by the CANopen block so that the dataexchange is ensured.In case of network dictionary operations (SDO transfers), the block tries to f<strong>in</strong>d theObject Dictionary of the node with the given ID <strong>in</strong> the objDict structure. If the properobject exists (CANopen node block of this OD is used <strong>in</strong> the model), it reads or writesthe data <strong>in</strong> the same way as <strong>in</strong> the local node case.This feature makes the simulation process very slow. It is recommended to disableSimulation support option <strong>in</strong> the parameters if asynchronous operation simulation is notrequired.62


Called by RTWDur<strong>in</strong>g TLC processcf_asyn.tlcBlockTypeSetup()●Generates the commonheader fileBlockInstanceSetup()●Generates source fileof the concrete blockGenerated filescf_asyn.h●Common header file of allAsyn. blocks%.c●Source file of block codeOutputs()●Calls the block functiongetPortNumber()●Parses I/O data portsIdentifiers of the param. cellFigure 3.11: Block code generation process3.9 Function call offset blockThis block is not a part of CANopen blockset at all. It does not need CANopensupport enabled <strong>in</strong> the model and it can be used with general function call blocks ofSimul<strong>in</strong>k. It is designed to be called from with<strong>in</strong> the function call subsystem. It thenwaits for the given time and activates its own function call port. The tim<strong>in</strong>g is realizedby periodic thread [Píš05] and is performed <strong>in</strong> a separate thread to avoid model block<strong>in</strong>g(figure 3.12). This block has a s<strong>in</strong>gle parameter which is a value of required offset <strong>in</strong>seconds.subsystem_output() ormodel_output()●Create Functioncalloffset_wait_thread()model.cStart threadfunctionFunctioncalloffset_wait_thread()●Set timer to Offset time●Wait for timer●Activate function call port●Exit threadFunctioncalloffset_wait_thread.cFigure 3.12: Function call offset code functionalityThe block is def<strong>in</strong>ed <strong>in</strong> l<strong>in</strong>ux ert target blockset.mdl file and support files are mentioned<strong>in</strong> the table 3.8.S-function sourceS-function mexHelp fileTLC scriptsfc offset.cfc offset.mexw32fc offset help.htmlfc offset.tlcTable 3.8: Block files63


3.9.1 Block code generationWhile generat<strong>in</strong>g the model code fc offset.tlc script is called (figure 3.13). It createscommon header file of all blocks of this type and one source file for each of them.Called by RTWDur<strong>in</strong>g TLC processfc_offset.tlcBlockTypeSetup()●Generates the commonheader fileGenerated filesfc_offset.h●Common header file of allFC offset blocksBlockInstanceSetup()●Writes <strong>in</strong>stance declarations<strong>in</strong>to common header fileFunctioncalloffset.c●Source file of block codeOutputs()●Calls generateWaitThread()●Writes thread createcommand <strong>in</strong>to model outputgenerateWaitThread()●Generates thread functionwith wait<strong>in</strong>g codeFigure 3.13: Function call offset code generation64


3.10 Asynchronous rate transition blockThis block is not a part of CANopen blockset at all. It does not need CANopen supportenabled <strong>in</strong> the model and it can be used with general function call blocks of Simul<strong>in</strong>k.This block has to be used while connect<strong>in</strong>g synchronous and asynchronous section of themodel by a data signal. It creates a critical section and ensures data <strong>in</strong>tegrity.In case of simulation it just copies <strong>in</strong>put data <strong>in</strong>to the state vector <strong>in</strong> its Updatefunction and sets the data onto the output port <strong>in</strong> its Output function. It means that itneeds two sample hits to get the value from <strong>in</strong>put to output. Its sample time should beset to the sample time of appropriate synchronous section of the model. While generat<strong>in</strong>gcode it locks these data transfers by mutex.The block supports all data types and any port width. The output port type andwidth is set automatically accord<strong>in</strong>g to the <strong>in</strong>put signal.model_<strong>in</strong>itialisation()●Set state vector of the block to zeros.Block stepblock_output()●Lock mutex●Copy state vector tooutput port●Unlock mutexblock_update()●Lock mutex●Copy <strong>in</strong>put port to thestate vector●Unlock mutexFigure 3.14: Asynchronous rate transition block functionalityThe block is def<strong>in</strong>ed <strong>in</strong> l<strong>in</strong>ux ert target blockset.mdl file and support files are mentioned<strong>in</strong> the table 3.9.S-function sourceS-function mexHelp fileTLC scriptsasync rate transition.casync rate transition.mexw32async rate transition help.htmlasync rate transition.tlcTable 3.9: Block files65


3.10.1 Block code generationWhile generat<strong>in</strong>g the model code async rate transition.tlc script is called (figure 3.15).It writes def<strong>in</strong>itions <strong>in</strong>to common model header file and Output and Update code <strong>in</strong>to theproper place accord<strong>in</strong>g to block usage <strong>in</strong> the model.Called by RTWDur<strong>in</strong>g TLC processrate_transition.tlcBlockTypeSetup()●Writes common <strong>in</strong>cludesGenerated filesmodel.h●Common model header fileBlockInstanceSetup()●Def<strong>in</strong>es block mutex objectsmodel.c●Model source file with stepfunctionsOutputs()Update()InitializeConditions()●Generates block functionsFigure 3.15: Asynchronous rate transition block code generation66


Chapter 4ConclusionI will summarize the work and describe achieved results at the end of the thesis. Thema<strong>in</strong> goal of the thesis was creation of the CANopen protocol support for code generatedfrom Simul<strong>in</strong>k by Real Time Workshop.The generated code has to be customized to be used at embedded hardware. Thedesired platform (computer BOA 5200 and L<strong>in</strong>ux operat<strong>in</strong>g system) is supported byL<strong>in</strong>ux GRT target prepared <strong>in</strong> [Jel08]. I decided to redesign the GRT (Generic RealTime Target) to the ERT type of target. The ERT (Embedded Real Time Target) targetuses enhanced optimization features of Real Time Workshop Embedded Coder for codegeneration. Moreover, the new L<strong>in</strong>ux ERT Target is designed to generate multi-task<strong>in</strong>gapplication and work with CANopen driver. The target controls the code generation andprepares scripts for code compilation. The compilation itself is performed by a tool cha<strong>in</strong>created <strong>in</strong> [Jel08].L<strong>in</strong>ux ERT target featuresˆ Supports BOA5200 computer runn<strong>in</strong>g L<strong>in</strong>ux operat<strong>in</strong>g systemˆ Generates s<strong>in</strong>gle-task<strong>in</strong>g (s<strong>in</strong>gle-rate and multi-rate) and multi-task<strong>in</strong>g applicationsˆ Precise simulation steps tim<strong>in</strong>g us<strong>in</strong>g periodic threadsˆ Task threads priorities assignment accord<strong>in</strong>g to task sample timesˆ Simulation step overrun check<strong>in</strong>gˆ Optional CANopen support, CANopen driver does not have to be l<strong>in</strong>kedˆ Adapts W<strong>in</strong>dows paths to be used <strong>in</strong> MSYS environment (supports paths <strong>in</strong>clud<strong>in</strong>gspaces as well)The CANopen blockset is based on <strong>in</strong>tegration of CanFestival driver <strong>in</strong>to the codegenerated by Real Time Workshop. The libraries of the driver are l<strong>in</strong>ked together withthe generated code by L<strong>in</strong>ux ERT Target if the CANopen support is enabled.Particular blocks of the blockset provide particular API functions of the driver tothe Simul<strong>in</strong>k environment. The blockset supports both synchronous and asynchronouscommunication and enables asynchronous events handl<strong>in</strong>g. Moreover, the simulationsupport of the ma<strong>in</strong> functions has been created as well. The aim of this was not to createCANopen network simulator for Simul<strong>in</strong>k, but just enable basic functionality simulation67


while tun<strong>in</strong>g embedded controller <strong>in</strong> Simul<strong>in</strong>k.The simulation is provided partially by simulation <strong>in</strong>puts and outputs of the blocksand partially by us<strong>in</strong>g Object Dictionary objects saved <strong>in</strong> Matlab workspace. Such objectis created by each CANopen node block <strong>in</strong> the model and data transfers are simulated bywrit<strong>in</strong>g <strong>in</strong>to OD of the other node. Remote SDO transfers can be simulated as well if theremote node is created <strong>in</strong> the model. To be honest, us<strong>in</strong>g workspace dur<strong>in</strong>g simulationmakes it very time-consum<strong>in</strong>g. The simulation support of each block can be switchedoff and it is reasonable to use it only if it is necessary. While tun<strong>in</strong>g the controller thesimulation of the CANopen node block should be sufficient. The follow<strong>in</strong>g list describesall the capabilities of the blockset.CANopen blockset featuresˆ Integrates CanFestival driver <strong>in</strong>to the code generated by L<strong>in</strong>ux ERT Targetˆ Load<strong>in</strong>g node configuration from EDS fileˆ Possibility to create more then one node <strong>in</strong> a s<strong>in</strong>gle modelˆ Optional program and CAN messages logg<strong>in</strong>gˆ Supported features of CANopen protocol:– PDO transfers (also <strong>in</strong> simulation mode)– SDO transfers (also <strong>in</strong> simulation mode)– NMT for remote nodes control– SYNC generator– Callbacks on driver events: EMCY, SYNC, Heartbeat error, OD entry change,PDO transfer, Slave boot up, Node state change (also <strong>in</strong> simulation mode)– Event parameters read<strong>in</strong>g (also <strong>in</strong> simulation mode)– Heartbeat service support– Asynchronous rate transition block for secured data exchange between synchronousand asynchronous parts of the model– Function call offset blockF<strong>in</strong>ally, I will po<strong>in</strong>t out the th<strong>in</strong>gs that can be enhanced <strong>in</strong> the future. The BOAcomputer is runn<strong>in</strong>g L<strong>in</strong>ux kernel without real-time patch applied. Moreover, the L<strong>in</strong>uxkernel uses 4 milliseconds as the system timer resolution. It means that us<strong>in</strong>g sample timelower than 4ms is not possible at all. On the other hand, applications runn<strong>in</strong>g sample timeof multiples of 4ms should work properly. I have performed some experiments and I havenot noticed any problems while runn<strong>in</strong>g model on sample time of any multiple of 4ms.However, the reliability cannot be guaranteed as it is not a real-time system and goodresults were achieved just due to the high performance of the processor which is not fullyemployed by the simple simulation. Generally, this system is not very suitable for runn<strong>in</strong>gapplications requir<strong>in</strong>g sample time of a few milliseconds. However, the experiences fromanother MPC5200 based computer used at the Department of Control Eng<strong>in</strong>eer<strong>in</strong>g showthat L<strong>in</strong>ux kernel with real-time patch can ensure reliable behavior <strong>in</strong> all situations. Thisis promis<strong>in</strong>g direction for the system improvement.68


Bibliography[AM] Analogue and Micro. Boa5200 specification. http://www.analoguemicro.com/powerpc/BOA5200.pdf.[Ber][CiAa][CiAb]BerliOS. Socketcan driver. http://developer.berlios.de/projects/socketcan/.CiA. Can bus. http://www.can-cia.org/<strong>in</strong>dex.php?id=170.CiA. Canopen network. http://www.can-cia.org/<strong>in</strong>dex.php?id=171.[DoCE] CTU FEE Department of Control Eng<strong>in</strong>eer<strong>in</strong>g. Boa wiki.http://rtime.felk.cvut.cz/hw/<strong>in</strong>dex.php/Boa5200 HOWTO.[Ghia]Ghisler. Total commander. http://download.totalcommander.cz/.[Ghib] Ghisler. Total commander packer plug<strong>in</strong>.http://www.totalcmd.net/plugr<strong>in</strong>g/targzbz2.html.[Hat]Red Hat. Redboot guide. http://ecos.sourceware.org/docs-latest/redboot/redbootguide.html.[Jel08] Pavel Jelínek. Podpora simulace s hardware ve smyčcehttp://dce.felk.cvut.cz/dolezilkova/diplomky/2008/dp 2008 jel<strong>in</strong>ek pavel/dp 2008 jel<strong>in</strong>ek pavel.pdf. Master’s thesis, Faculty of Electrical Eng<strong>in</strong>eer<strong>in</strong>g,<strong>Czech</strong> <strong>Technical</strong> <strong>University</strong>, 2008.[Joh]Matt Johnston. Dropbear ssh. http://matt.ucc.asn.au/dropbear/dropbear.html.[LOLa] LOLITech. Canfestival api documentation. http://www.canfestival.org/api/.[LOLb] LOLITech. Canfestival driver. http://www.canfestival.org/.[Mat] Mathworks. Real time workshop embedded coder documentation.http://www.mathworks.com/access/helpdesk/help/toolbox/ecoder/<strong>in</strong>dex.html.[m<strong>in</strong>][Píš05][Wag][Wik]M<strong>in</strong>gw web. http://www.m<strong>in</strong>gw.org.Pavel Píša. Periodic threads. http://dce.felk.cvut.cz/por/hlavni uloha/motor.html,2005.Wago. Wago 750-348. http://www.wago.com/wagoweb/documentation/<strong>in</strong>dex e.htm.Wikipedia. Canopen. http://en.wikipedia.org/wiki/CANopen.69


Appendix ATarget usage exampleThis chapter describes step by step the process of generat<strong>in</strong>g model code us<strong>in</strong>g L<strong>in</strong>uxERT Target and its execution on the BOA mach<strong>in</strong>e. In the aim of creat<strong>in</strong>g as simpleexample as possible, we will use very simple model without CANopen support. Howeverthe model will use two different sample times to try the multitask<strong>in</strong>g program (see section2.4.1).Before start<strong>in</strong>g the model creation and code generation it is necessary to have theL<strong>in</strong>ux ERT target <strong>in</strong>stalled as well as the M<strong>in</strong>GW environment (see section 2.2). TheBOA mach<strong>in</strong>e has to be configured accord<strong>in</strong>g to section 2.2.4 and turned on.A.1 Model target configurationFirst of all create a folder called lets say ert example and new Simul<strong>in</strong>k model (calledert model.mdl) <strong>in</strong>side it. Click Simulation/Configuration parameters <strong>in</strong> the model menu.In Real Time Workshop section click Browse and choose l<strong>in</strong>ux ert target.tlc from the givenlist (see figure A.1). The target conta<strong>in</strong>s callback after its choice. The default sett<strong>in</strong>gsis loaded <strong>in</strong> this callback function so that some simulation parameters are set automatically.Nevertheless we will have a look at the sett<strong>in</strong>gs important for the code generation.Click on the Solver pane <strong>in</strong> the configuration dialog. The fundamental step size is sethere. It is the sample period of the ma<strong>in</strong> loop (see section 2.4.1). If it is set to the valueauto it is calculated automatically as a greatest common divisor of all sample times used<strong>in</strong> the model. The other important option is the Task<strong>in</strong>g mode. It is recommended tokeep the auto value as well. Then the s<strong>in</strong>gletask<strong>in</strong>g mode is chosen if just one sampletime is used or multitask<strong>in</strong>g for more sample times.The other important sett<strong>in</strong>g is the External mode configuration <strong>in</strong> Real Time Workshop/Interfacepane (figure A.2). The external mode provides the TCP connection betweenSimul<strong>in</strong>k and the model runn<strong>in</strong>g on the Target mach<strong>in</strong>e and transfers the simulationsignals to the Simul<strong>in</strong>k w<strong>in</strong>dow dur<strong>in</strong>g the simulation progress. The MEX-file argumentshave follow<strong>in</strong>g mean<strong>in</strong>g: 192.168.123.199 is the IP address of the BOA module, 1 enablesthe communication state messages and 17725 is the communication port of TCP connection.Previous paragraph described the external mode sett<strong>in</strong>gs which is <strong>in</strong> fact the communicationsett<strong>in</strong>gs on the side of host computer. There is the configuration of BOAmodule side communication <strong>in</strong> Real Time Workshop/Target pane. This dialog conta<strong>in</strong>s70


Figure A.1: Model configuration to use L<strong>in</strong>ux ERT Target<strong>in</strong>formation like name and password of the user which should be used for log<strong>in</strong> to the BOAcomputer (use root accord<strong>in</strong>g to the section 2.2.4 to avoid authority problems), BOA IPaddress and model executive options. This options have to conta<strong>in</strong> parameters -w -port17725 to enable external mode and set its port to 17725.The last option def<strong>in</strong>es what operations should be done with the generated code. Itcan be just generated and compiled or copied to the BOA Target or f<strong>in</strong>ally executed theretoo. We will set it to the compile copy execute option.The next configuration pane is called CANopen support. The support of CANopenblockset is configured here. However we do not want to use it and so we will keep thesupport disabled.The last pane is Runtime logg<strong>in</strong>g. You can set the console and file event logg<strong>in</strong>g levelhere.The target configuration is f<strong>in</strong>ished now. Press Apply to store the values and switchto the model w<strong>in</strong>dow.A.2 Model creationWhile hav<strong>in</strong>g the configuration done we have to create the Simul<strong>in</strong>k model itself tohave someth<strong>in</strong>g to be generated. As we want to have a simple model but us<strong>in</strong>g two sampletimes, we will create two discrete s<strong>in</strong>us wave generators. Output values of these generatorswill be cut by saturation blocks and displayed by scopes.To do this open Simul<strong>in</strong>k Library and drag two S<strong>in</strong>e Wave blocks from Sources sectionto the model. Set the sample time of the first S<strong>in</strong>e wave to 0.2. Then set the sample timeof the second S<strong>in</strong>e wave to [0.5 0.1] (0.1 is the time offset of the block).Now drag two Saturation blocks from the Discont<strong>in</strong>uous section and two Scope blocksfrom the S<strong>in</strong>ks section to the model and connect everyth<strong>in</strong>g accord<strong>in</strong>g to the figure A.4.71


Figure A.2: External mode sett<strong>in</strong>gsThe sett<strong>in</strong>gs of these blocks can be left as it is.Now switch back to the Configuration dialog and press Generate code <strong>in</strong> the Real TimeWorkshop pane. The code generation will start and after it f<strong>in</strong>ishes, model l<strong>in</strong>ux ert targetfolder will be created <strong>in</strong> the work<strong>in</strong>g directory. This folder conta<strong>in</strong>s generated files andMakefile prepared to be build (see section 2.4).A.3 Code build<strong>in</strong>g and executionWhile hav<strong>in</strong>g the code generated run the MSYS console and open the model folder<strong>in</strong> it. The go script (see section 2.4.3) is created there. This script conta<strong>in</strong>s commandsfor build and execution of the code accord<strong>in</strong>g to Real Time Workshop/Target pane of theconfiguration dialog. We have chosen compile copy execute option. It means that the goscript will first compile the code and obta<strong>in</strong> model executable. Then it will be copied tothe BOA mach<strong>in</strong>e and f<strong>in</strong>ally executed.Note It is possible to use real W<strong>in</strong>dows paths <strong>in</strong> MSYS but with slash <strong>in</strong>stead of backslashas folder separator (e.g. C:/work/ert example).Run the go script. If the build<strong>in</strong>g f<strong>in</strong>ishes successfully the ert model executable filewill be created. The connection with the BOA mach<strong>in</strong>e is established, the executable issend and started at the Target computer. If no error either <strong>in</strong> build<strong>in</strong>g or communicationoccurs, the program should be runn<strong>in</strong>g now. Switch to the model, set Simulation/Externalto enable external mode and click Connect To Target. While the connection is establishedthe Start real-time code button should become enabled. Click it and start the simulation.You can open the scopes and check the process. To f<strong>in</strong>ish the simulation click the Stopbutton. Then the code runn<strong>in</strong>g at the Target term<strong>in</strong>ates and has to be started aga<strong>in</strong> to72


Figure A.3: Target sett<strong>in</strong>gsS i n e W a v eS a t u r a t i o nS c o p eS i n e W a v e 1S a t u r a t i o n 1S c o p e 1Figure A.4: Example modelrun the simulation once more. It can be started by go script or manually after connect<strong>in</strong>gto the BOA via SSH by the follow<strong>in</strong>g commands.$ ssh root@192 . 1 6 8 . 1 2 3 . 1 9 9$ . / model −tf <strong>in</strong>f −w −port 17725This is end of the example. M<strong>in</strong>d that after mak<strong>in</strong>g any change of the model, the codehas to be regenerated and the go script has to be performed as well to build the programand start at the BOA.73


Appendix BCANopen blockset usage exampleThis tutorial describes step by step the creation of a simple controller with CANopencommunication. This example is called controller and all the files used <strong>in</strong> this tutorialshould be available <strong>in</strong> the blockset distribution.Note The CANopen blockset and this example as well are based on model us<strong>in</strong>g L<strong>in</strong>uxERT Target. It is essential to be familiar with us<strong>in</strong>g it before start<strong>in</strong>g us<strong>in</strong>g the blockset.Perform<strong>in</strong>g the target tutorial first will help you.BOA5200Ball & BeamBeamangleBallpositionL<strong>in</strong>uxGenerated controllerCANopenWagoFigure B.1: Control exampleB.1 Def<strong>in</strong>ition of the control problemImag<strong>in</strong>e that you have Ball and Beam model and you want to control the ball positionat the beam (figure B.1). The output of the system is the ball position measured asvoltage and you can control the beam angle by chang<strong>in</strong>g the motor <strong>in</strong>put voltage. Itmeans that the model is the SISO (S<strong>in</strong>gle-Input S<strong>in</strong>gle-Output) system described by thefollow<strong>in</strong>g discrete transfer function with sample time T s = 0.05s.G = 0.000304z2 + 0.00096z + 0.00018z 3 − 2.364z 2 + 1.731z − 0.3665This system will be controlled by filtered PD controller with follow<strong>in</strong>g transfer functionand the same sample time as the system.C =5.76z − 5.452z − 0.740874


We will use BOA5200 computer [AM] to implement the controller. The <strong>in</strong>terfacebetween model analogue <strong>in</strong>put and output and the computer CAN peripheral will berealized by Wago distributed IO <strong>in</strong> version 750 with CANopen support [Wag]. We haveWago 750-348 ma<strong>in</strong> module and Wago 750-459 (4 analogue <strong>in</strong>puts) and Wago 750-559 (4analogue outputs). However, we will use just one <strong>in</strong>put and one output as the model isSISO. This device uses one PDO message to transfer all 4 <strong>in</strong>puts and one for all 4 outputs.This is the PDO number 2 which has message ID 280hex + NodeID <strong>in</strong> the direction fromWago to controller and ID 300hex + NodeID <strong>in</strong> the opposite direction. We will set theWago node ID to 2.After def<strong>in</strong><strong>in</strong>g the task we can start with the controller design. It is necessary to havethe L<strong>in</strong>ux ERT Target and CANopen blockset correctly <strong>in</strong>stalled (see section 3.2).B.2 Creation of the node Object DictionaryFirst of all, we have to create CANopen node object dictionary <strong>in</strong> OD editor (objdictedit.py)and generate the necessary files (see section 3.3.1). Open the OD editor and createa new project. Fill the setup dialog accord<strong>in</strong>g to the figure B.2. This says that the nodewill be master <strong>in</strong> the CANopen network, the Object Dictionary will be called controllerand the node will use Heartbeat service to secure the network functionality. Click OKafter hav<strong>in</strong>g this filled.Figure B.2: Creat<strong>in</strong>g new Object DictionaryWe will set up the Heartbeat service now. Open Edit/DS-301 profile, move <strong>in</strong>dex0x1016 (Consumer Heartbeat Time) to the right pane and click OK. Open CommunicationParameters <strong>in</strong> the ma<strong>in</strong> w<strong>in</strong>dow. Indices 0x1016 and 0x1017 should be available there. Setthe value of 0x1017 (Producer Heartbeat Time) to 1000ms (0x03E8). This will produce theHeartbeat message every second. Additionally, set the value of <strong>in</strong>dex 0x1016 (ProducerHeartbeat Time) to 0x00020064. This says that if the answer from the node ID 2 (Wago)was not received <strong>in</strong> 100ms (0x64), the Heartbeat error should be announced. We willhandle this error by the appropriate callback <strong>in</strong> the model.We will use one SDO message to configure the Wago behavior and we have to registerit <strong>in</strong> the OD now. Click SDO parameters and add a SDO client. Set its sub<strong>in</strong>dices 1(Transmit SDO) and 2 (Receive SDO) to 0x602 and 0x582.75


Next, we will create <strong>in</strong>ternal node variables <strong>in</strong> Manufacturer specific section. First,create two variables beam angle and ball position that will represent the <strong>in</strong>put and outputof the model. However, PDOs def<strong>in</strong>ed <strong>in</strong> Wago conta<strong>in</strong>s values of all 4 analogue <strong>in</strong>putsand outputs so that we have to create variables that will be mapped onto the rest of themessage. Create 3 more variables for the 3 <strong>in</strong>puts and 3 more variables for 3 outputs.Set the data type of all the created variables to UNSIGNED16. The variable def<strong>in</strong>itionshould look like <strong>in</strong> the figure B.3.Figure B.3: Costume variables def<strong>in</strong>ition <strong>in</strong> Object dictionaryF<strong>in</strong>ally, we have to def<strong>in</strong>e receive and transmit PDO messages and their mapp<strong>in</strong>g onthe variables. Add one Receive PDO <strong>in</strong> the Receive PDO parameters section. Then, setits ID to 0x282 and the Transmission type to 0x01 (synchronized by SYNC messages).Now, click on the Receive PDO mapp<strong>in</strong>g section, add one mapp<strong>in</strong>g object and add 4sub<strong>in</strong>dices by right-click<strong>in</strong>g the s<strong>in</strong>gle entry. Choose variables created as <strong>in</strong>puts <strong>in</strong> themapp<strong>in</strong>g objects value column. First object should be the variable represent<strong>in</strong>g the ballposition as the first <strong>in</strong>put of the Wago module (figure B.4). Create Transmit PDO <strong>in</strong> thesame way as the Receive PDO and use 0x302 message ID. Use output variables <strong>in</strong> themapp<strong>in</strong>g with the beam angle variable at the first position.The Object Dictionary is completely def<strong>in</strong>ed now. Save it as controller.od and clickFile/Export to EDS file and File/Build Dictionary. This will produce controller.eds,controller.c and controller.h files. You can close the OD editor now and cont<strong>in</strong>ue bycreat<strong>in</strong>g the Simul<strong>in</strong>k model.B.3 Creation of the Simul<strong>in</strong>k modelCreate a new model <strong>in</strong> Simul<strong>in</strong>k and save it with the name model.mdl (model namehas to be different from OD name). Place controller.eds, controller.c and controller.h filescreated <strong>in</strong> the previous section <strong>in</strong>to the model folder.First of all, we will set the target <strong>in</strong> Simulation/Configuration parameters menu.Choose L<strong>in</strong>ux ERT target (l<strong>in</strong>ux ert target.tlc file) <strong>in</strong> the Real Time Workshop menu.Then, check Enable CANopen blockset support option <strong>in</strong> the CANopen support pane. Libraryand <strong>in</strong>clude folders should be determ<strong>in</strong>ed automatically, if the target is <strong>in</strong>stalledcorrectly. F<strong>in</strong>ally, enable and set the external mode parameters <strong>in</strong> Target and Interface76


Figure B.4: Receive PDO mapp<strong>in</strong>g onto <strong>in</strong>ternal variablespane accord<strong>in</strong>g to your BOA and network sett<strong>in</strong>gs. See L<strong>in</strong>ux ERT Target documentationfor more <strong>in</strong>formation about this.We will create the model itself now. Open the Simul<strong>in</strong>k Library Browser and dragthe CANopen node block from L<strong>in</strong>ux ERT Target blockset/CANopen blockset section <strong>in</strong>tothe model. Open Block parameters dialog and set it accord<strong>in</strong>g to the figure B.5. If you<strong>in</strong>sert the OD name (controller) and click Load I/O mapp<strong>in</strong>g from EDS file the mapp<strong>in</strong>gis loaded automatically <strong>in</strong> the way that each variable mapped <strong>in</strong>to some PDO is used as<strong>in</strong>put or output of the block. However, we need only one <strong>in</strong>put and one output variableso that you can delete the 3 more entries <strong>in</strong> both cells. The block sample time will be0.05s as the rest of the model and the network communication as well. F<strong>in</strong>ally, enable theSimulation support to create the simulation <strong>in</strong>put and output. This will enable test<strong>in</strong>gthe controller just <strong>in</strong> the Simul<strong>in</strong>k without us<strong>in</strong>g hardware.After hav<strong>in</strong>g the ma<strong>in</strong> block configured, we can employ other CANopen blocks. Firstly,drag the SYNC generator block to the model and set its OD name to controller and sampletime to [0.05 0.04]. This will produce SYNC messages <strong>in</strong> the CANopen network with theperiod of 0.05s delayed 0.04s after the model update. It means <strong>in</strong> fact that the modelupdate will be performed 0.01s after the SYNC message so that the data transfers aresurely f<strong>in</strong>ished.B.3.1CANopen callbacksWe need to handle some asynchronous events of the CANopen network. To do this wewill use CANopen callbacks block. Drag it to the model and set it to provide three typesof callbacks - Boot up of the Wago device, Heartbeat error occurrence and stopp<strong>in</strong>g thelocal node at the end of the simulation (figure B.6).Accord<strong>in</strong>g to the sett<strong>in</strong>gs the Callbacks block has one output port of the width 3.It means that the port has to be split by Demux block <strong>in</strong>to 3 separate signals first.The output port is the function call port that should be used to trigger Function callsubsystem. The callback parameters are stored <strong>in</strong> the global memory by the block andcan be processed by appropriate parsers. Drag 3 Function-Call subsystem blocks <strong>in</strong>to themodel and connect their triggers to the 3 output signals of the Callbacks blocks. Thenopen each subsystem and create there the code handl<strong>in</strong>g particular event.77


Figure B.5: CANopen node block parametersFirst function call subsystem will be connected to the first Callback block outputsignal that is Slave boot up event. This callback has a s<strong>in</strong>gle parameter - ID of the nodewhich booted up. To get this parameter we have to place Slave boot up parser block <strong>in</strong>tothe subsystem and display its <strong>in</strong>put value.We will perform Wago device <strong>in</strong>itialization and start both nodes after reception ofthe boot up message from Wago. CANopen asynchronous block is designed to do suchoperations. Drag this block to the subsystem and open the parameters dialog. The ODname is controller aga<strong>in</strong> and the Operations parameter cell should conta<strong>in</strong> the follow<strong>in</strong>gtext.{{ ' writeNetworkDict ' , { ' 2 ' , ' 0 x1801 ' , ' 2 ' , ' 1 ' , 'UNS8 ' }} , { ' masterSendNMTStateChange ' , ←↪{ ' 2 ' , 'NMT\ S t a r t \ Node ' }} , { ' s e t S t a t e ' , { ' O p e r a t i o n a l ' }}}The first operation sends SDO message to the Wago and enables PDO transmissionafter SYNC message reception. The second operation sets Wago <strong>in</strong>to Operational stateand the last sets local node to Operational state as well. It is a good idea to check SDOtransfer failure. To do this split error output of the block <strong>in</strong>to 3 signals and displaythe value of the first one by the Display block. The subsystem content is shown <strong>in</strong> thefigure B.7. Moreover, it is necessary to <strong>in</strong>sert Asynchronous rate transition block betweenthe subsystem outputs and displays to ensure data <strong>in</strong>tegrity between synchronous andasynchronous part of the model. Set the sample time of rate transitions to 0.05 as is thesynchronous model sample time.78


Figure B.6: Callbacks block parametersThe second callback is activated after Heartbeat error. To handle it place Heartbeaterror parser block <strong>in</strong>to the appropriate function call subsystem and set its OD name tocontroller aga<strong>in</strong>. Display its output at the Display block. It will show the ID of the nodewhich produced the heartbeat error (did not answer on the server request). Do not forgetabout the Asynchronous rate transition block.The last subsystem will perform what should be done after stopp<strong>in</strong>g the local node atthe end of the simulation. We will stop Wago by the CANopen asynchronous block andthe masterSendNMTStateChange operation.B.3.2Creat<strong>in</strong>g the controllerWe have already implemented all the required functionality of the CANopen node.Now, we will create the controller which will communicate us<strong>in</strong>g this node. The Wagoanalogue output produces signal of voltage <strong>in</strong> range < 0V ; 10V >. This is, however,transmitted <strong>in</strong> PDO messages <strong>in</strong> data type 16-bit unsigned <strong>in</strong>teger. This data type isused for CANopen node block ports as well. Moreover, controll<strong>in</strong>g the ball roll<strong>in</strong>g at thebeam requires us<strong>in</strong>g negative voltage (this would have to be solved electronically). Wehave to create converter from double value <strong>in</strong> range < −5V ; 5V > to unsigned value <strong>in</strong>range < 0; 65535 > (16-bit) and the same <strong>in</strong> the opposite direction. These converters areshown <strong>in</strong> the figure B.8.We can use LTI system block from Control System Toolbox of Simul<strong>in</strong>k to implementthe controller. Drag this block to the model and set its parameter to the controller discretetransfer function.tf ( [ 5 . 7 6 − 5 . 4 5 2 ] , [ 1 − 0 . 7 4 0 8 ] , 0 . 0 5 )To enable test<strong>in</strong>g the controller <strong>in</strong> Simul<strong>in</strong>k we will create Ball and Beam mathematicalmodel <strong>in</strong> the same way as the controller with the follow<strong>in</strong>g transfer function.tf ( [ 0 . 0 0 0 3 0 4 0.00096 0 . 0 0 0 1 8 ] , [ 1 −2.364 1 . 7 3 1 − 0 . 3 6 6 5 ] , 0 . 0 5 )79


f ( )f u n c t i o nSl a v e b o o t u pp a r s e r" c o n t r o l l e r "N o d e I D1O u t 2S l a v e b o o t u p p a r s e rd a t a i n p u tC A N o p e n a s y n c h r o n o u s" c o n t r o l l e r "d a t a o u t p u te r r o r o u t p u t2O u t 1C A N o p e n a s y n c h r o n o u sFigure B.7: Function call subsystem triggered by Slave boot up callbackD1o u b l eu + 51 / 1 0S a t u r a t i o n B i a sG a i n 12 ^ 1 6G a i nu i n t 1 6D a t a T y p e C o n v e r s i o n1U i n t 1 61U i n t 1 6d o u b l eD a t a T y p e C o n v e r s i o n2 ^ - 1 6G a i n1 0G a i n 1u - 5B i a s1D o u b l eFigure B.8: Signal converter subsystemsNote We do not want to generate code of these blocks used just for the simulation.To avoid generat<strong>in</strong>g the simulation loop use Environment controller blocks to switch theCANopen block simulation <strong>in</strong>put and output between simulation loop (simulation case)and Ground (code generation case).F<strong>in</strong>ally, we can connect the controller with the data types converters <strong>in</strong> the closedcontrol loop us<strong>in</strong>g <strong>in</strong>put and output of the CANopen node block. In the same way thesimulation model will be connected to the simulation I/O. As a reference signal we canuse e.g. Step function. The complete model is <strong>in</strong> the figure B.9 and the colors markssections with the same sample time (right-click the model and enable Format/SampleTime Colors). Now, you can press the Start simulation button and see the simulationresults <strong>in</strong> the scope w<strong>in</strong>dow.B.4 Generat<strong>in</strong>g and compil<strong>in</strong>g the codeTo generate the model code click Generate code button <strong>in</strong> the simulation parameters(or press Ctrl+B). This will generate the necessary files as well as the go script whichperforms the code compilation and copy<strong>in</strong>g <strong>in</strong>to the BOA computer. This is described80


C A N o p e n c a l l b a c k s" c o n t r o l l e r "s l a v e B o o t u p , h e a r t b e a t E r r o r , S t o p p e d ,C A N o p e n c a l l b a c k sc a l l b a c k sf u n c t i o n ( ) O u t 2S l a v e b o o t u pc a l l b a c kO u t 1A s y n c h r o n o u sR a t e T r a n s i t i o nA R T 1A s y n c h r o n o u sR a t e T r a n s i t i o nA R T 2S l a v e b o o t u p p r o d u c e rn o d e I DS D O e r r o r c o d e00f u n c t i o n ( )S t o p p e d s t a t ec a l l b a c kf u n c t i o n ( )I n 1 O u t 1H e a r t b e a t e r r o rc a l l b a c kA s y n c h r o n o u sR a t e T r a n s i t i o nA R T 3H e a r t b e a t e r r o r p r o d u c e rn o d e I D0U i n t 1 6 D o u b l 0e0 0 9 6 0 . 0 0 0 1 8 ] , [ 1 - 2 . 3 6 4 1T y p e c o n v e r t e r 1B a l l a n d B e a m M o d e lD o u b l eU i n t 1 6T y p e c o n v e r t e r 2S Y N C g e n e r a t o r" c o n t r o l l e r "S a m p l e t i m e = [ 0 . 0 5 0 . 0 4 ]S Y N C g e n e r a t o rG r o u n d 2S i mO u tR T WE n v i r o n m e n tC o n t r o l l e rb e a m _ a n g l e s i m _ b e a m _ a n g l eC A N o p e n n o d e" c o n t r o l l e r "I D = 1s i m _ b a l l _ p o s i t i o n b a l l _ p o s i t i o nC A N o p e n n o d eG r o u n d 1 E n v i r o n m e n tC o n t r o l l e r 1U i n t 1 6 D o u b l eT y p e c o n v e r t e r 4S i mO u tR T Wo u t p u tS y s t e m o u t p u tc o n t r o l l e r a c t i o nU i n t 1 6D o u b l e7 6 - 5 . 4 5 2 ] , [ 1 - 0 . 7 4 0 8 ] , 0e r r o r r e f e r e n c eT y p e c o n v e r t e r 3C o n t r o l l e rR e f e r e n c eFigure B.9: F<strong>in</strong>al CANopen node model<strong>in</strong> the L<strong>in</strong>ux ERT Target documentation. While hav<strong>in</strong>g the generated program runn<strong>in</strong>gat the target BOA computer, you can switch to external simulation mode and start thesimulation as usual. It will perform the model control process <strong>in</strong> the real hardware <strong>in</strong>steadof the simulation LTI model as before.81


Appendix CBlockset common use casesThe follow<strong>in</strong>g section briefly describes a set of simple demo models distributed togetherwith the blockset. The demos show the blockset used for creat<strong>in</strong>g the common CANopennode types. Each demo conta<strong>in</strong>s the Simul<strong>in</strong>k model prepared for code generation andnecessary Object Dictionary files (.od, .eds, .c and .h files). The Object Dictionary iscreated <strong>in</strong> OD editor (see section 3.3.1) and it can be modified by runn<strong>in</strong>g the Matlabcommand objdictedit(’odName.od’).It is necessary to customize the target sett<strong>in</strong>gs <strong>in</strong> configuration parameters beforestart<strong>in</strong>g the code generation of the demo model. There are some options <strong>in</strong> the RealTime Workshop pane that have to be filled accord<strong>in</strong>g to your computer, BOA mach<strong>in</strong>eand network configuration. You have to set up the path of CanFestival driver libraries <strong>in</strong>CANopen support pane. It should be filled automatically, so disabl<strong>in</strong>g and enabl<strong>in</strong>g thesupport option should update the paths of library and <strong>in</strong>clude folders. Then, the BOAmach<strong>in</strong>e IP address has to be filled <strong>in</strong> Target and Interface/External mode panes.C.1 Synchronous master nodeThis example shows how to create simple CANopen node with SYNC generator anda s<strong>in</strong>gle <strong>in</strong>put and output transfered by PDOs synchronized by SYNC. This model isexecuted synchronously with SYNC, but it <strong>in</strong>serts a unit delay <strong>in</strong>to the system as it usesthe received data for output calculation just <strong>in</strong> the next step (after the next SYNC). Seefigure C.1 for the task pr<strong>in</strong>ciple.offsetTsCANSYNC RPDO TPDOSYNC RPDO TPDOCPUSYNCgen.CANopen blockoutput = 2*<strong>in</strong>putk k+1SYNCgen.Figure C.1: Gantt diagram of example functionality82


Object dictionary name used by all blocks is sync master od. It is the name of .eds,.c, .h files as well. These files were prepared <strong>in</strong> the OD editor. The only def<strong>in</strong>ition whichis necessary to be done <strong>in</strong> the editor is the registration of a s<strong>in</strong>gle RPDO and a s<strong>in</strong>gleTPDO. The transmission type of these messages is 1 (transfered after SYNC). A s<strong>in</strong>gle<strong>in</strong>put variable of type 8-bit unsigned <strong>in</strong>teger is mapped <strong>in</strong>to the RPDO and a s<strong>in</strong>gle outputvariable of the same type is mapped <strong>in</strong>to the TPDO.SYNC generator’s sample time is set to 1s. It means that it generates SYNC messageonce per second. The ma<strong>in</strong> block uses the same sample time delayed by offset 0.1s. Itmakes the block to be execute just 0.1s after SYNC which means that synchronous PDOswill have been surely transfered before the block execution.Callbacks block registers the PreOperational callback. It activates the function callsubsystem after the local node boot up. The Asynchronous block is placed <strong>in</strong> this subsystemand switches the local node <strong>in</strong>to the Operational mode. See figure C.2 for theSimul<strong>in</strong>k realization of this task us<strong>in</strong>g CANopen blockset.S Y N C g e n e r a t o r" s y n c _ m a s t e r _ o d "S a m p l e t i m e = 1S Y N C g e n e r a t o rC A N o p e n c a l l b a c k s" s y n c _ m a s t e r _ o d "p r e O p e r a t i o n a l ,C A N o p e n c a l l b a c k sc a l l b a c k so u t p u tC A N o p e n n o d e" s y n c _ m a s t e r _ o d "I D = 1C A N o p e n n o d ei n p u tf u n c t i o n ( )P r e O p e r a t i o n a lc a l l b a c kC o n v e r t2C o n v e r tD a t a T y p e C o n v e r s i o n 1G a i nD a t a T y p e C o n v e r s i o nFigure C.2: Model of CANopen node used as SYNC masterC.2 Synchronous slave nodeThis example shows how to create simple CANopen node hav<strong>in</strong>g s<strong>in</strong>gle <strong>in</strong>put andoutput transfered by PDOs synchronized by SYNC. However, the SYNC messages aregenerated by another node <strong>in</strong> the network. The local node is a SYNC slave. This modeldoes not use any periodic sample time as it is synchronized by SYNC. However, theconstant sample time should be set <strong>in</strong> configuration parameters Solver pane to controlthe program loop. This model <strong>in</strong>serts a unit delay <strong>in</strong>to the system as it uses the receiveddata for output calculation just <strong>in</strong> the next step (after the next SYNC). See figure C.3for the task pr<strong>in</strong>ciple.Object dictionary name used by all blocks is sync slave od. It is the name of .eds, .c,.h files as well. These files were prepared <strong>in</strong> the OD editor. The only def<strong>in</strong>ition which83


offsetTsCANSYNC RPDO TPDOSYNC RPDO TPDOSYNCcallbackCPUOffset block CANopen blockoutput = 2*<strong>in</strong>putk k+1Figure C.3: Gantt diagram of example functionalityis necessary to be done <strong>in</strong> the editor is the registration of a s<strong>in</strong>gle RPDO and a s<strong>in</strong>gleTPDO. The transmission type of these messages is 1 (transfered after SYNC). A s<strong>in</strong>gle<strong>in</strong>put variable of type 8-bit unsigned <strong>in</strong>teger is mapped <strong>in</strong>to the RPDO and a s<strong>in</strong>gle outputvariable of the same type is mapped <strong>in</strong>to the TPDO.Callbacks block registers the PreOperational and SYNC callbacks. The first callbackactivates the function call subsystem after the local node boot up. The Asynchronousblock is placed <strong>in</strong> this subsystem and switches the local node <strong>in</strong>to the Operational mode.The second output of the Callbacks block activates the other function call subsystem afterreception of SYNC message. The ma<strong>in</strong> block and the node calculations are performed <strong>in</strong>this subsystem. The CANopen block’s sample time is set to -1 (<strong>in</strong>herited) as it activatedby the callback. See figure C.4 for the Simul<strong>in</strong>k realization of this task us<strong>in</strong>g CANopenblockset <strong>in</strong>clud<strong>in</strong>g the SYNC callback and offset subsystems content <strong>in</strong> figure C.5.C A N o p e n c a l l b a c k s" s y n c _ s l a v e _ o d " c a l l b a c k sp r e O p e r a t i o n a l , S Y N C ,C A N o p e n c a l l b a c k sf u n c t i o n ( )O u t 1f u n c t i o n ( )S Y N C o f f s e tf u n c t i o n ( )P r e O p e r a t i o n a lc a l l b a c kS Y N C c a l l b a c kFigure C.4: Model of CANopen node as SYNC slaveC.3 Synchronous CANopen sensorThis example shows how to create CANopen node represent<strong>in</strong>g some sensor. Thisdevice measures (generates <strong>in</strong> the example) some value and sends it <strong>in</strong> the PDO just afterreception of SYNC message. This model does not use any periodic sample time as it is84


f ( )f u n c t i o nf ( )f u n c t i o no u t p u tC A N o p e n n o d e" s y n c _ s l a v e _ o d "I D = 1i n p u tF u n c t i o n c a l lo f f s e t1O u t 1C o n v e r tC A N o p e n n o d e2C o n v e r tF u n c t i o n c a l l o f f s e tD a t a T y p e C o n v e r s i o n 1G a i nD a t a T y p e C o n v e r s i o nFigure C.5: Function call offset (left) which delays the node execution (right)synchronized by SYNC. However, the constant sample time should be set <strong>in</strong> configurationparameters Solver pane to control the program loop. The ma<strong>in</strong> block does not performany periodic functionality <strong>in</strong> this use case. It just loads the EDS file and controls theCANopen driver. Its sample time is set to -1 to <strong>in</strong>herit the fundamental sample time ofthe model. See figure C.6 for the task pr<strong>in</strong>ciple.TsCANlatencySYNC TPDO SYNCCPUSYNCcallbackValuemeasurementWrit<strong>in</strong>gto ODAsynchronousPDO transmissionk k+1Figure C.6: Gantt diagram of example functionalityObject dictionary name used by all blocks is sync sensor od. It is the name of .eds, .c,.h files as well. These files were prepared <strong>in</strong> the OD editor. The only def<strong>in</strong>ition which isnecessary to be done <strong>in</strong> the editor is the registration of a s<strong>in</strong>gle TPDO. Its transmissiontype is 255 (transfered after change). After the SYNC reception, the measurement isperformed first and the PDO is sent just after the new value is stored <strong>in</strong>to Object Dictionary.M<strong>in</strong>d, that it is necessary to ensure fast enough value calculation between receptionof SYNC and send<strong>in</strong>g the PDO to preserve the synchronous behavior. A s<strong>in</strong>gle outputvariable of type 8-bit unsigned <strong>in</strong>teger is mapped <strong>in</strong>to the TPDO.Note After writ<strong>in</strong>g the value <strong>in</strong>to OD, the sendPDOevent operation has to be used <strong>in</strong>Asynchronous block to send all asynchronous TPDOs. It is used <strong>in</strong> this example as well.Callbacks block registers the PreOperational and SYNC callbacks. The first callbackactivates the function call subsystem after the local node boot up. The Asynchronousblock is placed <strong>in</strong> this subsystem and switches the local node <strong>in</strong>to the Operational mode.85


The second output of the Callbacks block activates the other function call subsystem afterreception of SYNC message. The counter simulat<strong>in</strong>g the real value measurement is placedthere. Its value is then stored <strong>in</strong>to the OD and the PDO is sent. See figure C.7 for theSimul<strong>in</strong>k realization of this task us<strong>in</strong>g CANopen blockset. There is the SYNC callbacksubsystem content <strong>in</strong> the figure C.8.C A N o p e n c a l l b a c k s" s y n c _ s e n s o r _ o d "p r e O p e r a t i o n a l , S Y N C ,c a l l b a c k sC A N o p e n c a l l b a c k sf u n c t i o n ( )f u n c t i o n ( )C A N o p e n n o d e" s y n c _ s e n s o r _ o d "I D = 1S Y N C c a l l b a c kP r e O p e r a t i o n a lc a l l b a c kC A N o p e n n o d eFigure C.7: Model of CANopen sensorf ( )f u n c t i o nl i mM e a s u r e m e n ts i m u l a t i o nC o n v e r tD a t a T y p e C o n v e r s i o nd a t a i n p u tC A N o p e n a s y n c h r o n o u s" s y n c _ s e n s o r _ o d "C A N o p e n a s y n c h r o n o u s 1d a t a o u t p u te r r o r o u t p u tFigure C.8: Subsystem executed by SYNC callbackC.4 Asynchronous CANopen nodeThis example shows how to create CANopen node which works <strong>in</strong> asynchronous mode.It just waits for the change of its OD entry by received PDO. Then, it reads the value,performs some operation over it and store it <strong>in</strong>to another OD entry. Just after thecalculation, the PDO is transmitted. This model does not use any periodic sample time.The execution is supposed to be aperiodic. However, the constant sample time should beset <strong>in</strong> configuration parameters Solver pane to control the program loop. The ma<strong>in</strong> blockdoes not perform any functionality <strong>in</strong> this use case. It just loads the EDS file and controlsthe CANopen driver. See figure C.9 for the pr<strong>in</strong>ciple of this example. The basic model ofthis example is almost the same as <strong>in</strong> the previous case (see figure C.7). The only changeis that the second callback is not triggered by SYNC but by the OD entry change.Object dictionary name used by all blocks is async change od. It is the name of .eds,.c, .h files as well. These files were prepared <strong>in</strong> the OD editor. The only def<strong>in</strong>ition whichis necessary to be done <strong>in</strong> the editor is the registration of a s<strong>in</strong>gle RPDO and a s<strong>in</strong>gle86


latencyCANRPDOTPDOOD changecallbackCPURead<strong>in</strong>gto ODoutput =2*<strong>in</strong>putWrit<strong>in</strong>gto ODAsynchronousPDO transmissionFigure C.9: Gantt diagram of example functionalityTPDO. The transmission type of these messages is 255 (transfered after value change).A s<strong>in</strong>gle <strong>in</strong>put variable of type 8-bit unsigned <strong>in</strong>teger is mapped <strong>in</strong>to the RPDO and as<strong>in</strong>gle output variable of the same type is mapped <strong>in</strong>to the TPDO.Callbacks block registers the PreOperational and OD change callbacks. The first callbackactivates the function call subsystem after the local node boot up. The Asynchronousblock is placed <strong>in</strong> this subsystem and switches the local node <strong>in</strong>to the Operational mode.The second output of the Callbacks block activates the other function call subsystemafter change of OD <strong>in</strong>dex 2000 hex (the RPDO is mapped there). This entry is read <strong>in</strong>the callback subsystem, multiplied by 2 and stored <strong>in</strong>to the OD entry with <strong>in</strong>dex 2001hex (TPDO mapped variable). The TPDO is transfered after the data change (see thesubsystem content <strong>in</strong> the figure C.10).f ( )f u n c t i o nd a t a i n p u tC A N o p e n a s y n c h r o n o u s" a s y n c _ c h a n g e _ o d "C A N o p e n a s y n c h r o n o u sd a t a o u t p u te r r o r o u t p u tC o n v e r tD a t a T y p e C o n v e r s i o n 12G a i nC o n v e r tD a t a T y p e C o n v e r s i o nd a t a i n p u tC A N o p e n a s y n c h r o n o u s" a s y n c _ c h a n g e _ o d "C A N o p e n a s y n c h r o n o u s 1d a t a o u t p u te r r o r o u t p u tFigure C.10: OD change callback subsystem87


C.5 Model with two CANopen nodesThis example (see figure C.11) shows how to create two CANopen nodes <strong>in</strong> a s<strong>in</strong>glemodel. It can be used for work<strong>in</strong>g with two separate CANopen networks at once. Eachof them is connected to one of CAN ports provided by BOA computer. This examplesimulates the follow<strong>in</strong>g situation. At the first network (CAN port 0) the SYNC masternode synchronously receiv<strong>in</strong>g and transferr<strong>in</strong>g PDOs is created. The node is exactly thesame as <strong>in</strong> sync master example (see section C.1). Data of received RPDO are multipliedby a constant and transmitted <strong>in</strong> the next SYNC period by TPDO. This simulates thefast periodic control loop. Moreover, the device is connected to some supervisor station byanother CANopen network. The second node us<strong>in</strong>g the appropriate CAN port is createdto operate with this network. Its only function is to wait for asynchronous RPDO anduse its value as a multiplication constant <strong>in</strong> the control loop. M<strong>in</strong>d that both nodesare work<strong>in</strong>g <strong>in</strong> the separate networks so that they can have the same node IDs and usemessages hav<strong>in</strong>g the same IDs as well.C A N o p e n c a l l b a c k s" s y n c _ m a s t e r _ o d "p r e O p e r a t i o n a l ,c a l l b a c k so u t p u tC A N o p e n n o d e" s y n c _ m a s t e r _ o d "I D = 1i n p u tC A N o p e n c a l l b a c k sC A N o p e n n o d eS Y N C g e n e r a t o r" s y n c _ m a s t e r _ o d "S a m p l e t i m e = 1S Y N C g e n e r a t o rf u n c t i o n ( )P r e O p e r a t i o n a lc a l l b a c kC o n v e r tD a t a T y p e C o n v e r s i o n 1P r o d u c tC o n v e r tD a t a T y p e C o n v e r s i o nC A N o p e n c a l l b a c k s" a s y n c _ c h a n g e _ o d " c a l l b a c k sP r e O p e r a t i o n a l , O D 0 x 2 0 0 0 _ 0 ,C o n v e r tD a t a T y p e C o n v e r s i o n 2C A N o p e n c a l l b a c k s 1C A N o p e n n o d e" a s y n c _ c h a n g e _ o d "I D = 1f u n c t i o n ( )f u n c t i o n ( )O u t 1A s y n c h r o n o u sR a t e T r a n s i t i o nC A N o p e n n o d e 1P r e O p e r a t i o n a lc a l l b a c k 1O D c h a n g ec a l l b a c kA s y n c h r o n o u s R a t e T r a n s i t i o nFigure C.11: Model with two CANopen nodesEach node has its own Object dictionary (.eds, .c, and .h files as well). The ODname parameter of each block is used to recognize which OD the block works with.The first node OD is called sync master od and it is exactly the same as <strong>in</strong> sync masterexample. The second node OD is called async change od and it is almost the same as<strong>in</strong> the async change example (see section C.4). In contrast to that example, it does notuse any TPDO and its RPDO mapped variable is called async <strong>in</strong>put <strong>in</strong>stead of <strong>in</strong>putto avoid variable name conflict with the other OD while build<strong>in</strong>g. The blocks used <strong>in</strong>both nodes are the same as <strong>in</strong> the mentioned examples. Moreover, at the connection88


l<strong>in</strong>k between asynchronous and synchronous part of the model, the Asynchronous RateTransition block has to be used.89


Appendix DAbbreviationsHIL Hardware In the LoopHW HardWareIO Input OutputISR Interrupt Service Rout<strong>in</strong>eJFFS2 Journale File System version 2M<strong>in</strong>GW M<strong>in</strong>imalist GNU for W<strong>in</strong>dowsMSYS M<strong>in</strong>imal SystemOS Operat<strong>in</strong>g SystemRedBoot Red Hat Embedded Debug and BootstrapRT Real TimeRTW Real Time WorkshopSCP SeCure CopySSH Secure SHellSTF System Target File (TLC)TFTP Trivial File Transfer ProtocolTLC Target Language CompilerCAN Controller Area NetworkEDS Electronic Data SheetPDO Process Data ObjectSDO Service Data ObjectNMT Network ManagementOD Object DictionaryFigure D.1: Abbreviations90


Appendix EAttached CD contentCDCanfestivalCanFestival driver sources <strong>in</strong> current versionboa5200Memory images necessary for BOA mach<strong>in</strong>e preparationcanopen_blockset CANopen blockset <strong>in</strong>stallation foldercanfestivalCanFestival parts used ny blockset<strong>in</strong>clude CanFestival header fileslibCanFestival librariesobjdictgen Object Dictionary editordocBlockset documentationhelp_imgImages used <strong>in</strong> block helpmask_callbacks Scripts called from block maskprivateSupport script of blocksetsrcNot usedtlc_cTLC scripts for blocks code generationDemosDemo applicationcontrollerCANopen blockset exampleert_example L<strong>in</strong>ux ERT target exampledocumentation Documentation LaTex sourcescanopen_blockset CANopen blockset documentationl<strong>in</strong>ux_ert_target L<strong>in</strong>ux ERT Target blockset documentationdp_hamacek Master thesis LaTex sourcesl<strong>in</strong>ux_ert_target L<strong>in</strong>ux ERT Target <strong>in</strong>stallation folderdocL<strong>in</strong>ux ERT Target documentationl<strong>in</strong>ux_ert_target L<strong>in</strong>ux ERT Target scriptsl<strong>in</strong>ux_grt_target L<strong>in</strong>ux GRT Target <strong>in</strong>stallation foldersoftwarePC Software necessary for blockset and BOA usagedp_2008_hamacek_lukas.pdf Master thesis91

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!