313
Cover Programmer’s Guide Version 2.1 CarMaker ®

IPG_CarMaker Programmers Guide

  • Upload
    stuarnt

  • View
    3.770

  • Download
    196

Embed Size (px)

DESCRIPTION

IPG_CarMaker

Citation preview

Page 1: IPG_CarMaker Programmers Guide

Cover

Programmer’s GuideVersion 2.1

CarMaker®

Page 2: IPG_CarMaker Programmers Guide

2

CarMaker Programmer’s Guide Version 2.1.6

The information in this document is furnished for informational use only, may be revisedfrom time to time, and should not be construed as a commitment by IPG Automotive GmbH.IPG Automotive GmbH assumes no responsibility or liability for any errors or inaccuraciesthat may appear in this document.

This document contains proprietary and copyrighted information and may not be copied,reproduced, translated, or reduced to any electronic medium without prior consent, in writ-ing, from IPG Automotive GmbH.

© 1999 - 2006 by IPG Automotive GmbH – www.ipg-automotive.comAll rights reserved.

FailSafeTester, IPG-CAR, IPG-CONTROL, IPG-DRIVER, IPG-ENGINE, IPG-GRAPH, IPG-KINEMATICS, IPG-LOCK, IPG-MOTORCYCLE, IPG-MOVIE, IPG-ROAD, IPG-ROADDA-TA, IPG-TIRE, IPG-TRAILER, IPG-TRUCK are trademarks of IPG Automotive GmbH.

CarMaker, TruckMaker, MotorcycleMaker, MESA VERDE areregistered trademarks of IPG Automotive GmbH.

All other product names are trademarks of their respective companies.

Page 3: IPG_CarMaker Programmers Guide

3

Contents

1 The CarMaker Environment 101.1 CarMaker architectural breakdown . . . . . . . . . . . . . . . . . . . . . . 10

CarMaker user interface programs . . . . . . . . . . . . . . . . . . . . . . 10

CarMaker simulation program . . . . . . . . . . . . . . . . . . . . . . . . . . 10

Data file organisation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11

Program interaction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12

Interaction of HIL systems . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 12

1.2 Inside the CarMaker simulation program . . . . . . . . . . . . . . . . . 14

User accessible modules . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 15

1.3 CarMaker Flow Process Charts . . . . . . . . . . . . . . . . . . . . . . . . 17

Modified Cycle Clock Generation if Oversampling is used . . . . 18

1.4 The main cycle explained . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 21

An pseudo code excerpt from HilMain.c . . . . . . . . . . . . . . . . . . 22

Basic tasks of the main routine . . . . . . . . . . . . . . . . . . . . . . . . . 23

The event loop of the main routine . . . . . . . . . . . . . . . . . . . . . . 23

1.5 A stripped down CM_Main.c . . . . . . . . . . . . . . . . . . . . . . . . . . . 25

1.6 Main Loop . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 26

1.7 SimStart . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 27

1.8 SimStop . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 29

2 Logging Module 302.1 General information . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 30

2.2 Recommended use . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 31

List of functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 31

CarMaker Programmer’s Guide Version 2.1.6

Page 4: IPG_CarMaker Programmers Guide

4

3 Infofile Module 333.1 Infofile format . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 33

3.2 Access functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 34

3.3 Error handling . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 35

3.4 C Function List . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 36

General Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 36

Read Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 40

Write Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 44

Add/Move Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 45

Help Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 47

Additional Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 48

3.5 Tcl/Tk Procedure List . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 48

Library . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 48

ifile . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 48

<handle> . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 49

4 Data Dictionary 534.1 Defining DataDict Variables . . . . . . . . . . . . . . . . . . . . . . . . . . . 53

5 Integrating Simulink models 575.1 Starting Matlab . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 57

5.2 Step-by-step: Integrating a Simulink model . . . . . . . . . . . . . . . . 59

Creating the Simulink model . . . . . . . . . . . . . . . . . . . . . . . . . . . 59

Setting simulation parameters . . . . . . . . . . . . . . . . . . . . . . . . . . 59

Generating and compiling the model C code . . . . . . . . . . . . . . 62

Integrating the model into CarMaker . . . . . . . . . . . . . . . . . . . . . 62

Running the model . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 63

5.3 The CarMaker interface blockset . . . . . . . . . . . . . . . . . . . . . . . 65

Accessing the CarMaker dictionary . . . . . . . . . . . . . . . . . . . . . . 65

Defining CarMaker dictionary variables . . . . . . . . . . . . . . . . . . 66

Accessing C variables . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 68

5.4 The CarMaker target for Real-Time Workshop . . . . . . . . . . . . . 70

Code generation with the CarMaker target . . . . . . . . . . . . . . . . 70

Choosing the right model wrapper . . . . . . . . . . . . . . . . . . . . . . 70

Customizing the wrapper . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 71

Integrating the model library . . . . . . . . . . . . . . . . . . . . . . . . . . . 72

5.5 CarMaker’s tunable parameter interface . . . . . . . . . . . . . . . . . . 74

Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 74

Enabling tunable parameters in a Simulink model . . . . . . . . . . 75

CarMaker Programmer’s Guide Version 2.1.6

Page 5: IPG_CarMaker Programmers Guide

5

Modifying tunable parameters in the model wrapper . . . . . . . . 76

Parameter values in Infofiles . . . . . . . . . . . . . . . . . . . . . . . . . . . 77

Adding tunable parameters to the CarMaker dictionary . . . . . . 78

Known limitations . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 79

Tunable parameter interface functions . . . . . . . . . . . . . . . . . . . 80

5.6 Miscellaneous . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 87

Upgrading to a new CarMaker version . . . . . . . . . . . . . . . . . . . 87

Integration of more than one model . . . . . . . . . . . . . . . . . . . . . 87

Using blocks from the CarMaker for Simulink blockset . . . . . . . 87

CarMaker and Matlab installed on different computers . . . . . . . 87

Troubleshooting . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 89

5.7 Demonstration examples . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 90

Contents of the examples directory . . . . . . . . . . . . . . . . . . . . . . 90

Preparing the examples . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 90

Rebuilding an example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 91

6 CarMaker for Simulink 926.1 CarMaker for Simulink basics . . . . . . . . . . . . . . . . . . . . . . . . . . 93

Creating a new CarMaker project directory . . . . . . . . . . . . . . . . 93

Starting Matlab . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 93

Creating a new model . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 94

Starting the CarMaker GUI . . . . . . . . . . . . . . . . . . . . . . . . . . . . 95

Running a simulation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 95

Switching between several Simulink models . . . . . . . . . . . . . . . 96

Switching between several CarMaker project directories . . . . . 96

Dealing with the start values of your model . . . . . . . . . . . . . . . 96

Working in a non-default model directory . . . . . . . . . . . . . . . . . 97

Upgrading to a new CarMaker version . . . . . . . . . . . . . . . . . . . 97

Troubleshooting . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 97

6.2 Using the C language interface . . . . . . . . . . . . . . . . . . . . . . . . . 99

Rebuilding the model library . . . . . . . . . . . . . . . . . . . . . . . . . . . 99

Identifying which model library you are using . . . . . . . . . . . . . . 99

Integrating model C code built with Real-Time Workshop . . . 100

6.3 The CarMaker for Simulink blockset . . . . . . . . . . . . . . . . . . . . 101

General information . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 101

Utility blocks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 102

CarMaker dictionary blocks . . . . . . . . . . . . . . . . . . . . . . . . . . . 103

General purpose blocks . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 106

CarMaker Programmer’s Guide Version 2.1.6

Page 6: IPG_CarMaker Programmers Guide

6

CarMaker subsystem . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 107

6.4 Demonstration examples . . . . . . . . . . . . . . . . . . . . . . . . . . . . 117

ABSdemo . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 118

BodyCtrl . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 119

ESPTemplate . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 120

SoftABS . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 121

TractCtrl . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 122

UserBrake . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 123

UserPowerTrain . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 124

UserSteer . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 126

UserSteerTorque . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 127

UserTire . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 129

7 CarMaker utilities for Matlab 1307.1 Importing simulation results with cmread . . . . . . . . . . . . . . . . 130

7.2 Accessing CarMaker Infofiles . . . . . . . . . . . . . . . . . . . . . . . . . 132

8 MIO – M-Module Input/Output 1338.1 Supported M-Modules . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 133

M3 / M27 / M43: Binary / Relay Outputs (8/16 channels) . . . . 133

M4: Analog Outputs (4 channels) . . . . . . . . . . . . . . . . . . . . . . 134

M15: Frequency Generator (2 channels) . . . . . . . . . . . . . . . . 135

M31 / M32: Binary Inputs (16 channels) . . . . . . . . . . . . . . . . . 136

M5 / M34 / M35 / M35N: Analog Inputs (16/8 channels) . . . . . 137

M51: Quadruple CAN Interface . . . . . . . . . . . . . . . . . . . . . . . . 138

M62: Analog Outputs (4 channels) . . . . . . . . . . . . . . . . . . . . . 140

M72: Motion Counter . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 141

M77: Quadruple RS232/423 - RS422/485 UART . . . . . . . . . . 142

M392 / M393: Analog Inputs (16/8 channels) . . . . . . . . . . . . . 143

M461/3: Pulse Width and Angle Measurement (4 channels) . 144

8.2 Programming M-Module I/O . . . . . . . . . . . . . . . . . . . . . . . . . . 145

MIO Initialization . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 145

M-Module Carrier Board Configuration . . . . . . . . . . . . . . . . . . 147

M-Module Configuration . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 148

Error Handling . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 149

8.3 Administrative Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 152

Initialization and M-Module Configuration . . . . . . . . . . . . . . . . 152

MIO and M-Module Information . . . . . . . . . . . . . . . . . . . . . . . 154

VME Bus Interrupt Handling . . . . . . . . . . . . . . . . . . . . . . . . . . 155

CarMaker Programmer’s Guide Version 2.1.6

Page 7: IPG_CarMaker Programmers Guide

7

Shared Memory Management . . . . . . . . . . . . . . . . . . . . . . . . 156

Error Handling Functions . . . . . . . . . . . . . . . . . . . . . . . . . . . . 157

8.4 M-Module Function Description . . . . . . . . . . . . . . . . . . . . . . . 159

M3: Binary Outputs (16 channels) . . . . . . . . . . . . . . . . . . . . . 159

M4: Analog Outputs (4 channels) . . . . . . . . . . . . . . . . . . . . . . 159

M5: Analog Inputs (16/8 channels) . . . . . . . . . . . . . . . . . . . . . 161

M15: Frequency Generator (2 channels) . . . . . . . . . . . . . . . . 162

M27: Binary Output (16 channels) . . . . . . . . . . . . . . . . . . . . . 164

M31: Binary Inputs (16 channels) . . . . . . . . . . . . . . . . . . . . . . 165

M32: Binary Inputs (16 channels) . . . . . . . . . . . . . . . . . . . . . . 165

M34: Analog Inputs (16/8 channels) . . . . . . . . . . . . . . . . . . . . 166

M35/M35N: Analog Inputs (16/8 channels) . . . . . . . . . . . . . . . 167

M43: Relay Outputs (8 channels) . . . . . . . . . . . . . . . . . . . . . . 168

M51: Quadruple CAN Interface . . . . . . . . . . . . . . . . . . . . . . . . 169

M62: Analog Outputs (4 channels) . . . . . . . . . . . . . . . . . . . . . 181

M72: Motion Counter . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 182

M77: Quadruple RS232/423 - RS422/485 UART . . . . . . . . . . 188

M392: Analog Inputs (16 channels) . . . . . . . . . . . . . . . . . . . . 192

M393: Analog Inputs (8 channels) . . . . . . . . . . . . . . . . . . . . . 196

M461/3: Pulse Width and Angle Measurement (4 channels) . 198

8.5 mioutil - MIO configuration utility . . . . . . . . . . . . . . . . . . . . . . . 203

Version History . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 204

9 CANiogen – CANdb import tool 2079.1 Overview . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 208

Basic information . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 208

Features . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 209

9.2 Using CANiogen . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 211

The CANiogen Command Line . . . . . . . . . . . . . . . . . . . . . . . . 211

Importing Electronic Control Units (ECU) . . . . . . . . . . . . . . . . 213

Receiving CAN messages and signals of special interest . . . 214

Sending arbitrary CAN messages . . . . . . . . . . . . . . . . . . . . . . 214

Suppressing of I/O variables in the Data Dictionary . . . . . . . . 215

Optimizing the output of CANiogen . . . . . . . . . . . . . . . . . . . . . 215

Disabling range checking of Signal values . . . . . . . . . . . . . . . 216

Naming of generated files, I/O variables and functions . . . . . . 216

Extended features . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 217

9.3 CANiogen’s output . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 219

Output files . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 219

CarMaker Programmer’s Guide Version 2.1.6

Page 8: IPG_CarMaker Programmers Guide

8

The header file IO_CAN.h . . . . . . . . . . . . . . . . . . . . . . . . . . . . 219

The list of generated I/O variables in IO_VarList.txt . . . . . . . . 223

The C module IO_CAN.c . . . . . . . . . . . . . . . . . . . . . . . . . . . . 223

9.4 Integration into CarMaker/HIL . . . . . . . . . . . . . . . . . . . . . . . . . 226

Modifications to IO.c . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 226

Modifications to User.c . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 228

Modifications to the Makefile . . . . . . . . . . . . . . . . . . . . . . . . . . 230

9.5 Version History . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 233

10 APO Messages 236

11 ScriptControl 23711.1 Introduction . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 237

11.2 Using the ScriptControl Window . . . . . . . . . . . . . . . . . . . . . . . 238

11.3 ScriptControl By Example . . . . . . . . . . . . . . . . . . . . . . . . . . . . 239

Example 1 – “Hello World!” . . . . . . . . . . . . . . . . . . . . . . . . . . . 239

Example 2 – Starting a Testrun . . . . . . . . . . . . . . . . . . . . . . . . 239

Example 3 – Subscribing to Quantities . . . . . . . . . . . . . . . . . . 240

Example 4 – Postprocessing and Report Generation . . . . . . . 241

More Examples . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 243

Tcl/Tk Documentation Links . . . . . . . . . . . . . . . . . . . . . . . . . . 243

11.4 ScriptControl Command Reference . . . . . . . . . . . . . . . . . . . . 245

Running a Simulation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 245

Subscribing to Quantities . . . . . . . . . . . . . . . . . . . . . . . . . . . . 248

Clock Timers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 250

Logging . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 252

Accessing CarMaker Parameters in Infofiles . . . . . . . . . . . . . . 255

Managing Simulation Results . . . . . . . . . . . . . . . . . . . . . . . . . 257

Direct Variable Access (DVA) . . . . . . . . . . . . . . . . . . . . . . . . . 261

Executing Matlab Commands . . . . . . . . . . . . . . . . . . . . . . . . . 262

Power Control (KL15) . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 264

FailSafeTester Commands . . . . . . . . . . . . . . . . . . . . . . . . . . . 265

Miscellaneous Commands . . . . . . . . . . . . . . . . . . . . . . . . . . . 268

Deprecated Commands . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 271

12 Working With the FailSafeTester 27412.1 How it Works . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 276

Wiring Topology . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 276

CarMaker Programmer’s Guide Version 2.1.6

Page 9: IPG_CarMaker Programmers Guide

9

Inside the FailSafeTester . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 279

12.2 FailSafeTester Cards . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 282

12.3 Configuring the FailSafeTester . . . . . . . . . . . . . . . . . . . . . . . . 283

FailSafeTester Cards Naming Convention . . . . . . . . . . . . . . . 283

FailSafeTester Configuration Settings . . . . . . . . . . . . . . . . . . . 284

12.4 Addition FailSafeTester Configuration . . . . . . . . . . . . . . . . . . . 286

12.5 FailSafeTester C-functions . . . . . . . . . . . . . . . . . . . . . . . . . . . 287

Add the FST Global Variables . . . . . . . . . . . . . . . . . . . . . . . . . 287

Configure the M51 CAN module . . . . . . . . . . . . . . . . . . . . . . . 287

Add Functions to CarMaker . . . . . . . . . . . . . . . . . . . . . . . . . . 287

12.6 Using the FailSafeTester . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 289

The FailSafeTester GUI . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 289

12.7 FailSafeTester Commands with Mini-Maneuvers . . . . . . . . . . 297

Complete List of FailSafeTester Commands . . . . . . . . . . . . . . 299

Using a Command . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 302

FailSafeTester Example 1 . . . . . . . . . . . . . . . . . . . . . . . . . . . . 304

13 CarMaker Graphical User Interfaces 30513.1 CarMaker Main GUI . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 305

13.2 Car Parameter Editor . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 305

13.3 Instruments . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 305

14 Vehicle Model Exchange 30614.1 Exchange, Step by Step . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 306

Vehicle Model coded in C . . . . . . . . . . . . . . . . . . . . . . . . . . . . 307

Vehicle Model coded in Simulink . . . . . . . . . . . . . . . . . . . . . . . 308

CarMaker Programmer’s Guide Version 2.1.6

Page 10: IPG_CarMaker Programmers Guide

10The CarMaker Environment

CarMaker architectural breakdown

Chapter 1

The CarMaker Environment

1.1 CarMaker architectural breakdown

Let’s first have a look at CarMaker and some of its basic architectural concepts. We’ll takethe perspective of a user whose job it is to build testruns, run simulations with the testrunshe created, and to postprocess the results of these simulations. What he sees when he’sworking with CarMaker will be the basis for a first glance at the CarMaker architecture. Wewill need the concepts explained here later, when we describe the vehicle module, its inter-face and its connection to the outside world in greater detail.

1.1.1 CarMaker user interface programs

The first thing the user will notice is that CarMaker consists of several individual programs.The one program that he almost certainly knows he has to start in order to use CarMaker,is the CarMaker GUI. The CarMaker GUI’s main tasks are to let the user create testruns,edit vehicle parameters and start and stop simulations of testruns.

When simulating a testrun, the user certainly wants to have some kind of feedback of what’sgoing on during the simulation. From within the CarMaker GUI he starts the 3D animationtool IPG-MOVIE, because he wants to see the vehicle driving on the given course. He maystart the online data visualization tool IPG-CONTROL to be able to inspect the time depen-dent behaviour of certain physical quantities of vehicle during the simulation. Or he mightwant to start Instruments to visualize vehicle behaviour using instruments and lights heknows from a car’s dashboard.

IPG-MOVIE, IPG-CONTROL and Instruments are all implemented as individual programs,that can be started from the CarMaker GUI (they may as well be started outside theCarMaker GUI), and which run independently of each other. Together they comprise thegraphical user interface of CarMaker. You find them on the left hand side of Figure 1.1.

1.1.2 CarMaker simulation program

Since the tasks of the programs you read about in the previous section have nothing to dowith any calculation of physical quantities for the simulation, this leads us to the next impor-tant concept of CarMaker. It is the concept of a separately running CarMaker simulation pro-gram. Its task is not to provide any kind of elaborate user interface, but to perform the actual

CarMaker Programmer’s Guide Version 2.1.6

Page 11: IPG_CarMaker Programmers Guide

11The CarMaker Environment

CarMaker architectural breakdown

simulation of a testrun and – in case of CarMaker/HIL – to interface with external hardwarebeing part of the control loop, e.g. a real controller unit. The CarMaker simulation programand possibly connected hardware can be found in the middle and on the right of Figure 1.1.

1.1.3 Data file organisation

Work with CarMaker always takes place in a so called CarMaker project directory thatkeeps the user’s files needed by CarMaker well organized in several subdirectories. A lookat Figure 1.1 shows some typical subdirectories that can be found in a project directory.Each subdirectory serves a special purpose; the following paragraphs give you an impres-sion how file data is used and shared by the individual CarMaker programs.

As we’ve said, the user creates testruns and edits vehicle parameters using the CarMakerGUI. The CarMaker GUI stores testrun data in files in the Data subdirectory.

Each time a simulation is started, the CarMaker simulation program reads informationabout the current testrun from exactly these files in the Data subdirectory. Files needed inaddition to that might be taken from the SimInput subdirectory. During the simulation a logfile and simulation results are written to files in the SimOutput subdirectory.

Also at the start of a simulation, the CarMaker GUI is responsible for providing 3D roadgeometry data to IPG-MOVIE. This becomes necessary if a testrun doesn’t use pre-existingreal-world digitized road data but a course constructed of individual road segments. IPG-MOVIE then reads road geometry data and 3D vehicle geometry data from the Movie sub-directory.

At a later time, for the purpose of postprocessing, IPG-CONTROL or other software like e.g.Matlab can read the simulation results in SimOutput written by the CarMaker simulation pro-gram.

Figure 1.1: Basic CarMaker Architecture

CarMaker GUI

IPG-MOVIE

IPG-CONTROL

Instruments

CarMakerSimulation Program

Data/...

Hardware

SimInput/... SimOutput/... Movie/...

Apo

CarMaker Programmer’s Guide Version 2.1.6

Page 12: IPG_CarMaker Programmers Guide

12The CarMaker Environment

CarMaker architectural breakdown

1.1.4 Program interaction

Having the user interface tools and the simulation program run absolutely independent ofeach other would not make much sense – there needs to be some kind of coordinationbetween them. For the purpose of program interaction, the CarMaker simulation programplays a central role.

The user interface tools connect to the simulation program. They may send commands tothem, like the CarMaker GUI with its “Start simulation!” or “Stop simulation!” commands.These are sent each time the user clicks on the Start or Stop button. The interface toolsmay also request some kind of service, e.g. ask for a list of available quantities and requestregular transmission of quantity values. This is what IPG-CONTROL does in order to dis-play them graphically during the running simulation.

The CarMaker simulation program, in turn, must provide these services. It must react tocommands sent by the CarMaker interface tools. It must register quantities that tools mightwant to receive on a regular basis, e.g. the quantity that contains the current simulationtime, or physical quantities calculated by the vehicle module inside the simulation program.Also, at simulation start, the simulation program sends a special message to IPG-MOVIEtelling it about the current geometry configuration of the vehicle.

Communication between the CarMaker programs is done using standard network commu-nication mechanisms. A special CarMaker module, the Apo library, implements communi-cation services for the CarMaker programs and defines the “language” being used betweenthem. The lightning titled “Apo” in Figure 1.1 should illustrate these facts. For the curious:Apo is an abbreviation of “Applications online”.

1.1.5 Interaction of HIL systems

CarMaker HIL systems use different computers to distribute the applications on. Figure 1.3shows a realtime computer which hosts the CarMaker/HIL application. All models and ser-vices have to meet realtime conditions. Therefore the realtime operating system LynxOS isused on this machine. The realtime system is diskless and shares the disk with the userworksation over network file system.

The user workstation hosts all user interface programs and possibly the LynxOS crossdevelopment kit to generate custom CarMaker/HIL applications for the realtime computer.

All network communication is done by ethernet by the use of the following protokolls:

tftpboot, rarp, DHCP: boot realtime computer over network, determine network adress

rlogin (UNIX) or telnet: remote terminal

NFS: vitual file system

CarMaker Programmer’s Guide Version 2.1.6

Page 13: IPG_CarMaker Programmers Guide

13The CarMaker Environment

CarMaker architectural breakdown

APO: CarMaker communication stack (developed by IPG), based on TCP/IP(UDP and TCP sockets)

Figure 1.3: Programm interaction for HIL systems

APO

DVA

InfoFilesDStore

LogMIO Log

Basic Services

Realtime SystemLinux or Windows

User WorkstationLynxOS

IPG-CAR IPG-DRIVER

IPG-TRAILER

IPG-TIRE

IPG-ROAD

DDict

CarMaker/HIL Application

other Models

IIO

CarMaker GUI

IPG-MOVIE

IPG-CONTROL

Instruments

Custom Panels

LynxOSDev. System

Ethernet

diskless

NFS – network file system

APOvirtualfile system

CarMaker Programmer’s Guide Version 2.1.6

Page 14: IPG_CarMaker Programmers Guide

14The CarMaker Environment

Inside the CarMaker simulation program

1.2 Inside the CarMaker simulation program

As we know from the previous section, the central component within the CarMaker archi-tecture is the CarMaker simulation program. We will now take a closer look at this programto see which modules it consists of and find out about the role that each of these modulesplays within the simulation program. Emphasis will be on the vehicle module; this sectionshould give you an impression how the vehicle module is connected to the surroundingCarMaker environment.

Figure 1.5 shows the basic building blocks of the CarMaker simulation program. The filesand libraries are more or less the same ones that will be linked together when you rebuildthe simulation program. What we can see is that there are four major groups of modules:

user accessible C code modules (at the top)

the CarMaker library libcarmaker.a (left block in the middle)

the vehicle module libcar.a (right block in the middle)

special purpose libraries (at the bottom)

We will examine each group more closely in a moment.

The figure also shows the call hierarchy inside the program: each module calls only func-tions of other modules of the same level or on a lower level.

Figure 1.5: Modules of the CarMaker simulation program

HilUser.c IO.c ...

lib

carm

ak

er.

a

lib

car.

a

Global Variables

CarPower Brake

Ambient DrivMan

DataDict Log ...

Apo Infofile

libipgdriver.a libipgroad.a

Train

...

HilMain.c

CarMaker Programmer’s Guide Version 2.1.6

Page 15: IPG_CarMaker Programmers Guide

15The CarMaker Environment

Inside the CarMaker simulation program

1.2.1 User accessible modules

Here we find all the files the user has direct access to, because they are located in theproject directory’s src subdirectory. The user may add his own modules by modifying theMakefile also found here.

CM_Main.c

This is the main module of the simulation program. It initializes the application and runs theapplication’s main loop. Individual simulations are started and controlled in this module. Allcalls to functions in User.c, IO.c are done within this module, as well as almost all calls tofunctions of the vehicle module. Normally there’s no need for the user to modify this module.

User.c

This and the following module IO.c are the modules the user may taylor to the specificneeds of his application. He is provided with a predefined set of functions that are called atdifferent stages of the simulation and at different points during each simulation step. Thefunctions provided have more or less empty bodies, they do nothing. The idea is that theuser fills the bodies with his own code, adding application specific functionality to theCarMaker simulation program. Possible tasks the user might handle in User.c are the cal-culation of additional physical quantities, e.g. to be used IO.c (which should be kept cleanof such calculations), or the integration of additional model code.

IO.c

This module is intended solely for the task of accessing application specific HIL hardwarecomponents.

The CarMaker library: libcarmaker.a

This library contains nearly all service modules of the simulation program. The code in Hil-Main.c relies heavily on this library to control execution of the program and of the simulation.Initialization, data administration, file i/o, hardware i/o, communications and real-time ser-vices are handled by (not necessarily public) modules of this library. The library provides alot of utility functions available to application specific code written by the user.

Global variables

Internal communication between modules inside the CarMaker simulation program is partlydone using global struct variables. Three of them are central to the simulation: SimCore,Ambient and DrivMan. SimCore belongs to an internal module and contains data pertainingto control and overall functioning of the simulation program, i.e. most of its struct membersdo not represent physical quantities during a simulation. User code should therefore treatthis variable as ‘read only’. To get an idea what the Ambient and DrivMan structs might con-tain, read the description of the concerning modules of the same name below.

Ambient

The Ambient module provides information about environmental conditions of the CarMakervirtual simulation environment, e.g. temperature and wind. Road data is also available here.This information is kept in the Ambient struct, which is mostly used by the vehicle module.

DrivMan

The DrivMan module is responsible of letting the virtual driver perform the maneuversdefined in testrun. This is one of the most important modules inside the simulation programsince its actions directly control the vehicle. The vehicle module should read the DrivMan

CarMaker Programmer’s Guide Version 2.1.6

Page 16: IPG_CarMaker Programmers Guide

16The CarMaker Environment

Inside the CarMaker simulation program

struct to find out which direction the virtual driver wants to the vehicle to go. The virtual driv-er in turn calls the vehicle module to find out about the current state of the vehicle, i.e. itsposition, velocity, etc.

DataDict

The DataDict module organizes all CarMaker quantities into a central data dictionary. Thedictionary contents are shared with the Apo module, providing online quantity access toCarMaker interface tools like IPG-CONTROL. The second task of the DataDict module isto record and write simulation results. The vehicle modules registers quantities, that mightbe of interest to others, in the data dictionary. Availability of certain phyiscal quantities of thevehicle is also prerequisite to animation of the vehicle with IPG-MOVIE.

Log

During a simulation, whenever something happens that the user should know about (e.g.most often some kind of error condition), information about the event should be recorded inthe simulation’s log file. The information is stored persistenly so as to be available for laterevaluation. The CarMaker GUI takes care of notifying the user about important events thatappear in the log file. The log module has a set of functions that allow for writing formattedmessages of different log levels into the logfile of the current simulation. The vehicle moduleuses this functionality to inform the user, if e.g. the vehicle during initialization encountersa critical variable’s value to be completely out of range.

Apo

This is the communications module within CarMaker. It contains all the functions that aCarMaker application might need if it wants to communicate with other CarMaker applica-tions over a network using Apo services. Most of the communication tasks using Apo arealready handled inside libcarmaker.a. The user might want to add some Apo code to Hilus-er.c, e.g. providing services to a user’s interface tool written in the Tcl language. Normally,there’s no need for the vehicle model to make use of the functionility offered by the Apomodule.

Infofile

The infofile module contains functions that are used to access information stored in infofiles,e.g. CarMaker testrun data and vehicle parameters in the Data subdirectory are stored asinfofiles. The vehicle module uses this module to read vehicle parameters from file duringinitialization.

CarMaker Programmer’s Guide Version 2.1.6

Page 17: IPG_CarMaker Programmers Guide

17The CarMaker Environment

CarMaker Flow Process Charts

1.3 CarMaker Flow Process Charts

CarMaker is a multi-threaded application. Hardware IO (if used) and most calculations aredone in the realtime context of the main thread.

Figure 1.7: CarMaker Flow Process Charts

IO_InRead Input Signals

Calc

from IO Hardware

stop

go

Calculation of allModels.One Integration Step

IO_OutWrite Output Signalsto IO Hardware

APOCommunication withUser Front End Tools.GUI, IPG-MOVIE,Instruments, ...

Initialisation

Helper ThreadsLow Priority

CleanupWrite Output Signalsto IO Hardware

LogOutput to stdoutor Log File

DStoreWrite Values ofselected Variablesto Results File

Read TestRun

Main ThreadHigh Priority

TestRun

Very Low Priority

Start/Stop Thread

ModelInitialisation &Parameterization

PreparationCalculatingStart Confitions

Simulation

TestRun Start

Finish

ModelFinish & Cleanup

TestRun Stop

Operating Mode

IdleOperating Mode

1ms

CarMaker Programmer’s Guide Version 2.1.6

Page 18: IPG_CarMaker Programmers Guide

18The CarMaker Environment

CarMaker Flow Process Charts

Even if CarMaker is not running on a realtime computer the pricipals explained here are stillthe same.

Main Thread Restrictions

• Cycle time must allways be less than 1ms!

• No file i/o

• No terminal output (printf...)

• No otherwise blocking operations

• Reading and generation of files is done in seperate threads with lower priority.CarMaker provided Services: Log and DStore

• Parameter files are read in a separate “Testrun Start” Thread.

1.3.1 Modified Cycle Clock Generation if Oversampling is used

Sometimes the cycletime of 1 ms of the main thread is too restricitve and one wants to haveparts of the CarMaker application running with a faster sample time. This can be becausethe acqusition of some input or output signals should be done with a higher frequency than1 kHz. Only those signals are processed in the oversampling thread. The oversampling ratecan only be a multiple of 1ms.

Figure 1.8 shows how the oversampling thread triggers the main thread by sending anevent every n-th cycle. This means that the clock timer moved from the main thread to theoversampling thread and triggers the clockless main thread.

CarMaker Programmer’s Guide Version 2.1.6

Page 19: IPG_CarMaker Programmers Guide

19The CarMaker Environment

CarMaker Flow Process Charts

Data is exchanged between the threads using data buffers containing the values of eachoversample step. It is job of the main thread to process those values, e.g. through multiplecalls (n times) of calculation models (with 1/n ms sample time) requiering or providing thedata.

Figure 1.8: Interactions of oversampling thread and main thread

IO_In

Calc

stop

go

IO_Out

APO

Initialisierung

Oversampling ThreadVery High Priority

Main ThreadHigh Priority

IO_In_fast

Minimal Pre-/Post-

stop

go

IO_Out_fast

Oversampling

1/n ms

processing

Counter n:1

Datenpuffer

Main Cycle Timer Event

generate event onevery n-th cycle

Datenpuffer

CarMaker Programmer’s Guide Version 2.1.6

Page 20: IPG_CarMaker Programmers Guide

20The CarMaker Environment

CarMaker Flow Process Charts

Figure 1.10 depicts the timeline of the oversampling procedure. Imporant is that the over-sampling thread has higher priotrity than the main thread to ensure favored execution.

Figure 1.10: Timing Diagram

t

OversamplingThread

Main Thread

Main Cycle, 1ms

OversamplingCycle

Idle

Prioritycollected datato be handled

in Main Thread

CarMaker Programmer’s Guide Version 2.1.6

Page 21: IPG_CarMaker Programmers Guide

21The CarMaker Environment

The main cycle explained

1.4 The main cycle explained

We now take a look at HilMain.c, the module that controls execution of the CarMaker sim-ulation program and represents the main cycle of CarMaker. It is important to get an ideaof what’s going on in the main cycle in order to understand which tasks the vehicle modulehas to perform, how the interface to the vehicle module is organized and how it works.

Figure 1.12: Main Cycle – Detailed View

stop

go1ms

IO_In

User_In

DVA IO_In

Driving Managerincludes IPG-DRIVER

DVA IO_DM

Calculation ofall Models

One integration step.

User_Calc

xyz_Calc.

User_Out

IO_Out

DVA IO_Out

DStorePutVec

AposPoll, Apos...

Handle recievedMessages,Send Messages

DStoreWrite Values ofselected Variablesto Results File

IPG-MOVIE

IPG-CONTROL

Instruments

ring buffer(8 MB)

CarMaker Programmer’s Guide Version 2.1.6

Page 22: IPG_CarMaker Programmers Guide

22The CarMaker Environment

The main cycle explained

1.4.1 An pseudo code excerpt from HilMain.c

Note: The CASE statement is not considered to be “fall-through” like in C.

/* Things done only once. */Setup all modulesRegister quantities of all modules in the data dictionaryExport current configuration of the simulation program

SimCore.State = ’Idle’

FOREVER {/* Do next 1 ms simulation step */

Read hardware inputs

SWITCH SimCore.State {CASE ’SimStart’:

Prepare the simulationInitialize DrivMan and vehicle moduleCalculate static equilibrium position of the vehicleIF everything is prepared THEN

SimCore.State = ’Simulate’

CASE ’Simulate’:Perform DrivMan calculationsPerform vehicle calculationsIF end of testrun THEN

SimCore.State = ’SimStop’

CASE ’SimStop’:Run down the simulationIF everything is finished THEN

SimCore.State = ’Idle’

CASE ’Idle’:Do nothing special

}

Put calculated vehicle quantities into interface variable

Write hardware outputs

IF SimCore.State == ’Simulate’ THENStore simulation results of current simulation step

Perform Apo background communication tasksRead Apo messages from CarMaker interface toolsIF message ’Start simulation!’ received THEN

SimCore.State = ’SimStart’ELSE IF message ’Stop simulation!’ received THEN

SimCore.State = ’SimStop’Send Apo messages to CarMaker interface tools

}

The pseudo code listing above gives you a simplified high-level picture of the main actionsthat go on inside HilMain.c. A first look at the code reveals two important points about theprogram:

• The basic tasks of the main routine: Program setup, calculations, hardware i/o,

storage of results, Apo communication.

• The event driven nature of the main routine.

CarMaker Programmer’s Guide Version 2.1.6

Page 23: IPG_CarMaker Programmers Guide

23The CarMaker Environment

The main cycle explained

We will now inspect each of these points more closely since they are crucial to an under-standing of the vehicle module interface.

1.4.2 Basic tasks of the main routine

Program setup is done only once and before entering the event loop. This is the time forall modules to register any quantities in the data dictionary for later access by CarMakerinterface tools using Apo services and for the storage of simulation results. Also, informationabout the current configuration of the simulation program and of its modules (i.e. when itwas built, version numbers of libraries and modules, etc.) are gathered and exported to afile later read by the CarMaker GUI.

Calculations are split among the DrivMan module and the vehicle module. The term alsoinclude the tasks performed e.g. at the beginning and end of a testrun simulation.

Hardware input/output is done before and after all calculations have been done. First thehardware is read, providing input for the calculations to be done next. After the calculationshave been accomplished, the calculated values are output to the hardware. Of course thisis only relevant for CarMaker/HIL. In case of CarMaker/Offline the functions called are emp-ty.

Storage of results takes place after the calculations. A vector containing all values of inter-est of the current time step is put into a buffer, that gets written to a results file asynchro-nously by a separate background thread.

Apo communication is handled at the end of the event loop. It consists of three tasks. First,Apo must be given a chance to handle its internal communication tasks, e.g. answering aninterface tool that likes to connect to the CarMaker simulation program. Next, the programmust read and interpret all Apo messages that may have been sent by CarMaker interfacetools since the beginning of the current simulation cycle. Third, there might be some mes-sages the simulation program might want to send to connected interface tools itself.

Other tasks like reading input from file and direct variable access (DVA) are not shown inthe pseudo code. They do not directly interfere with the tasks of the vehicle module andhave been left out for the purpose of clarity.

1.4.3 The event loop of the main routine

The basic principle of the main routine is that it’s event driven. In case of the CarMaker sim-ulation program, this is just a short term for the following (abstract) behaviour:

• The program runs in an endless loop, the so called event loop.

• During each cycle the program is always in exactly one of several well-defined

states. Each state has a certain, well-defined meaning, and depending on the

current state some action is performed.

• During the cycle one or more events may occur, provoking some reaction of the

program. One possible reaction is a change of the current state. If no event occurs,

the current state doesn’t change.

In theory, the simulation program should only be in one of two states: Either it is simulatinga testrun, or it isn’t. In reality, finer control of the sequence of events requires more statesto be used. Nevertheless, all states fall into one of the two categories mentioned: simulatingor not simulating.

There are several kinds of events that can happen and that may cause a change of state inthe simulation program. One possible event is some kind of error condition, e.g. the vehicleleaves the road during simulation or a connected hardware controller unit reports a problemwith one of its sensors, so that the current testrun should be aborted. Other events are of a

CarMaker Programmer’s Guide Version 2.1.6

Page 24: IPG_CarMaker Programmers Guide

24The CarMaker Environment

The main cycle explained

more harmless nature, e.g. the preparation phase of a simulation is over and the programshould proceed with the actual simulation. A third kind of events are messages sent byCarMaker interface tools that are connected to the simulation program. Think of a userpressing the Start or Stop button of the CarMaker GUI. In this case the CarMaker GUIsends an Apo message to the simulation program, telling it to start or stop the simulation ofthe current testrun.

When the program is not simulating a testrun, it is in state Idle . We may call it the defaultstate of the program. Immediately after initialization and between testruns the program is instate Idle. This does not imply that the program is doing nothing. Maybe a good circumscrip-tion of the actions performed in this state is “simulation of a vehicle standing still”.

The three states pertaining to the simulation of a testrun are SimStart , Simulate and Sim-Stop .

If a simulation is started, the program first enters state SimStart . This state is mainly asso-ciated with preparations at the beginning of the simulation. E.g. the vehicle reads its currentparameters from file and tries to find its static equilibrium position. Maybe ignition is turnedon, the engine is started, and so on.

If all preparations are done (and everything is ok), the current state changes to Simulate .Now the program is really performing the simulation of the testrun. It normally remains inthis state until the testrun ends or is aborted because of some error condition or manualintervention of the user.

To end a simulation, the simulation program changes its state to SimStop . The idea of thisstate is to run down the simulation gracefully and bring the vehicle to a stop. When this hasbeen accomplished, the program automatically changes to state Idle.

CarMaker Programmer’s Guide Version 2.1.6

Page 25: IPG_CarMaker Programmers Guide

25The CarMaker Environment

A stripped down CM_Main.c

1.5 A stripped down CM_Main.c

Below you find C code fragments that correspond to the pseudo code listing in the previoussection. The correspondence is not 100%, but you will recognize all important points. Weadded most of the calls to functions defined in HilUser.c, so that the code is more complete.What we left out is the code to change the current state of the simulation program, i.e.changes made to SimCore.State; this would have added unnecessary complexity, since infact there are more well defined states than the four mentioned in the previous chapter. Nev-ertheless, the C code provides you with all the necessary detail needed for a deeper under-standing of HilMain.c.

DrivManClear();Vhcl_Clear();

IO_Init();HilUser_SystemInit(); /* via Hil_GetSystemParameters() */

DrivManDeclareQuantities();Vhcl_DeclareQuantities();HilUser_DeclareQuantities()

Vhcl_ExportConfig(); /* via Hil_ExportConfig() */

for (;;) {IO_In();HilUser_IO_In();

switch (SimCore.State) {case State_SimStartXXX:

Vhcl_NewInit(); /* via Hil_SimStart() */Vhcl_StaticCond(); /* via Hil_SimStart() */HilUser_SimStart(); /* via Hil_SimStart() */break;

case State_Simulate:Vhcl_GetVhclState();DrivManCalc();Vhcl_Calc();break;

case State_SimStopXXX:HilUser_IOGetIdle();HilUser_SimStop(); /* via Hil_SimStop() */break;

case State_Idle:Vhcl_GetVhclState();break;

}

Vhcl_Out();

HilUser_IO_Out();IO_Out();

DStorePutVec();

AposPoll();while (/*any Apo message received */) {

Hil_ApoMsgEval();HilUser_ApoMsgEval();

CarMaker Programmer’s Guide Version 2.1.6

Page 26: IPG_CarMaker Programmers Guide

26The CarMaker Environment

Main Loop

}Hil_ApoSend();HilUser_ApoSend();

}

1.6 Main Loop

CarMaker Programmer’s Guide Version 2.1.6

Page 27: IPG_CarMaker Programmers Guide

27The CarMaker Environment

SimStart

1.7 SimStart

State

Funktionen, Module In OutIdle

Init

Sim

Stop

✗ State_Idle SimStart()

State_SimStart1: wait until Hil_SimStart() is finished

State_SimStart2: start engine, if desiredin MainLoop: DrivManCalc()

State_SimStart3: PreSimulate()OffsetTStart = 0SimCore.State = State_Simulatein MainLoop: DrivManCalc()

✗ SimStart (Project, ... )(SimCore.State = State_Idle)

ProjectUserNameFNameOutFName

SimCore.State= State_SimStart

ApoMsg: SimStart

✗ Hil_SimStart()in MainLoop as seperate thread(SimCore.State = State_SimStart1)

SimCore.T = 0.0SimCore.State

= State_SimStart1

in Hil_SimStart():

SimCore.SimPhase = SimPhaseInitLogReset()Car.Distance, ... = 0Trailer.<xyz> = 0SimCore.SimStartNo++Eintrag in’s LogbuchHil_TestRunInit()HilUser_SimStart()CarModelStaticCond()

i = SimCore.SimPhaseSimCore.SimPhase = SimPhaseSimCarModelCalc(0.0)CarModel_Out()SimCore.SimPhase = i;

SimCore.Trailer.Active == 1TrailerCalcStaticCond()

CreateMovie()CreateCarMovieObject()CreateTrailerMovieObject()

SimCore.SimPhase = SimPhaseSimDStoreSaveBegin(0, -1)

CarMaker Programmer’s Guide Version 2.1.6

Page 28: IPG_CarMaker Programmers Guide

28The CarMaker Environment

SimStart

Hil_TestRunInit()* Hil_SaveSystemParameters() Parame-ter sichern* Info-Files einlesen für Versuch, Fahr-zeug, Reifen* Hil_GetSystemParameters()* PrepareStoring()* PSChs_fromFileInit()* AmbientInit()* DrivManNewInit()* BrakeInit()* PowerTrainInit()* CarModelNewInit()* TrailerInit()* VerifyMode? -> CarModelVerify()

HilUser_SimStart()Parametrierung anwendungsspezifischerTeile, Unterscheidung nach IO-Konfigura-tion

HilUser_GetSystemParameters()IO_GetConfig()

State

Funktionen, Module In OutIdle

Init

Sim

Stop

CarMaker Programmer’s Guide Version 2.1.6

Page 29: IPG_CarMaker Programmers Guide

29The CarMaker Environment

SimStop

1.8 SimStop

State

Funktionen, Module In OutIdle

Init

Sim

Stop

✗ SimStop () SimCore.State= State_SimStop

✗ State_SimStop SimCore.State= State_SimStop1

SimCore.SimPhase= SimPhaseEnd

SimCore.SimEndKl15Off-> Kl15

DStoreSaveEnd(0)

✗ State_SimStop1 run down IO quantities into idle conditionsWarten, bis SaveStatus gleich DStore_SaveInactiveSimCore.State = State_SimStop1a

State_SimStop1a set I/O quantities to idle conditionsSimCore.State = State_SimStop2

State_SimStop2 Hil_SimStop() in extra ThreadSimCore.State = State_SimStop3

State_SimStop3 warten, bis Hil_SimStop() beendet

State_SimStop4 SimCore.State = State_IdleSimCore.SimPhase = SimPhaseIdle

HilUser_SimStop()

Hil_SimStop()Freigeben einiger Strukturen:TrailerDelete()DrivManDelete()AmbientDelete()PSChs_fromFileDelete()

HilUser_IOGetIdle()Überprüfen, ob sich das Fahrzeug bereitsin Ruhe befindet.Überführen relevanter Signale in denRuhezustand.

CarMaker Programmer’s Guide Version 2.1.6

Page 30: IPG_CarMaker Programmers Guide

30Logging Module

General information

Chapter 2

Logging Module

Inside your CarMaker code, e.g. during a simulation, there might arise situations where itwould seem useful to leave a short informational note about the current situation or informthe user about the circumstances of an error, that just occured. You may consider usingprintf() for this purpose, but this is not recommended under real-time conditions. Also, whenthe CarMaker simulation program is running on the real-time CPU, there is not necessarilya terminal available where the output of printf() could go.

In general it seems useful to keep a history of important or unusual situations and eventsduring the simulation of a testrun, that does not disappear when the simulation is finishedor the user turns off his his computer. This is why CarMaker offers a logging facility thatkeeps a record of events for each simulation in a log file. The log file can then be inspectedat a later time or kept as a protocol e.g. of a driving maneuver that the connected hardwarecontroller unit is still unable to handle.

In this section we’d like to show you how to use basic functionality of the Log module in yourown code. Advanced features exists but are out of scope of this text.

2.1 General information

Each time a CarMaker simulation program is started it creates a new log file in the SimO-utput subdirectory of the CarMaker project directory. Log messages are recorded in the logfile with a time stamp relative to the start of the current simulation.

Log messages fall into one of the following three categories, that determine the importanceof a message:

• Errors

Issuing an error log message causes the current simulation to be aborted, so

messages of this category should be reservered for cases where the program code

is unable to cope with the current situation.

• Warnings

This category should be used for situations that are unnormal, but not critital. It

means that the program code is able to handle the situation gracefully. A typical

CarMaker Programmer’s Guide Version 2.1.6

Page 31: IPG_CarMaker Programmers Guide

31Logging Module

Recommended use

example would be a parameter read during initialization that is out of range and

has to be overridden with a more meaningful value.

• Purely informational messages

Use this category to inform about special events or conditions, like e.g. an ABS

controller that is deactivated. It is also intended for debugging purposes. E.g.

while customizing CarMaker for your real-time application, you may find it

useful to tell that a certain point in initialization has been reached, or log the

results of some critical computation.

Furthermode, warnings and errors are categorized by the time they are issued:

• The fault happended during inititialization

• The fault happened during simulation

• The fault happened neither during initialization nor during simulation, it is

considered to be a more general fault

2.2 Recommended use

As a rule of thumb, the number of log file entries should be kept to a minimum so as toincrease readability. Entries should be kept short and informational. It is not useful to clutterthe log file with lots of messages, especially under real-time conditions. It does not makesense to issue one or more log message in each simulation cycle, i.e. every millisecond;this unnecessarily wastes CPU power and network bandwidth.

2.2.1 List of functions

A look at the available functions should make clear, that they are quite straightforward touse. Use them as you use any function of the printf() family.

Please note the following peculiarity, though: Except for Log(), all functions automaticallyadd a line feed character (\n) to the string to be added to the log file.

#include “Log.h”

void LogErrStr (unsigned ECId, const char *msg);void LogErrF (unsigned ECId, const char *format, ...);

void LogWarnStr (unsigned ECId, const char *msg);void LogWarnF (unsigned ECId, const char *format, ...);

void Log (const char *format, ...); /* no line feed added automatically */

/* Constants to be used for the ECId parameter */enum {

EC_Init /* Initialization fault */EC_Sim /* Simulation fault */EC_General /* General fault */

};

CarMaker Programmer’s Guide Version 2.1.6

Page 32: IPG_CarMaker Programmers Guide

32Logging Module

Recommended use

Example

#include “Log.h”

LogErrF(EC_Init, “Tyre parameter file ’%s’ not found.“, fname);

LogWarnStr(EC_Sim, “Controller unit not responding.”);

Log(“Braking distance >= 50m\n“);

CarMaker Programmer’s Guide Version 2.1.6

Page 33: IPG_CarMaker Programmers Guide

33Infofile Module

Infofile format

Chapter 3

Infofile Module

In the CarMaker environment, configuration and parameter information is stored in ASCIIfiles that use a special format for easy access by program code. Such files are called info-files and the CarMaker library libcarmaker.a contains the Infofile module functionality usedfor opening, reading and writing to infofiles and accessing infofile data, all in a keyword ori-ented manner. For user code this offers a standardized and easy to use method to organizeand access data in a file. It also avoids the difficulties of defining appropriate data struc-tures, learning the syntax and checking for errors.

When the simulation of a testrun starts, almost all testrun configuration data is contained ininfofiles in the Data subdirectory of the current CarMaker project directory. This includesinformation about the configuration of the virtual driver, the vehicle, tires etc. At the begin-ning of a simulation the modules that need specific configuration and initialization data mustretrieve this data from the appropriate infofile.

This sction gives a basic overview and also gives a concise list of the infofile functions inboth the C and Tcl/Tk programming environments.

3.1 Infofile format

Normally, in the CarMaker environment the user can edit most data stored in infofiles com-fortably using specifically tailored programs like the CarMaker GUI. This does not mean,however, that the data stored is totally inaccessible outside the CarMaker environment.Infofiles are human-readable ASCII files, i.e. they can be viewed and edited with an ordinaryASCII text editor, making them much easier to handle than the binary data files often usedby other Software.

CarMaker Programmer’s Guide Version 2.1.6

Page 34: IPG_CarMaker Programmers Guide

34Infofile Module

Access functions

Data is stored as key-value pairs. The order in which key-value pairs appear in an infofile isnot important. Keys names can (and should) be hierarchically organized using the dot char-acter as a separator. A value is basically a number, a strings or a text (i.e. a sequence ofstrings). This is best illustrated by a short example:

As you surely have noticed, there’s a difference between keys with a numeric or string valueand keys with a text value. A text key is always delimited by a colon (‘:’) character and thefollowing lines containing its value (the text lines) must be indented with a single tab char-acter.

It is not our objective to discribe the exact syntactic conventions of infofiles in this section.Please refer to existing infofiles in the Data subdirectory of your CarMaker project directory.As you will quickly see, infofile syntax is not at all a terribly complicated matter.

3.2 Access functions

Functions for opening and reading an infofile exist. They return a so called infofile handle oftype “struct tInfos *”, that is a pointer to the data read from the infofile. This handle can beused to access individual keys and retrieve their value. Normally the CarMaker library auto-matically opens and reads all important infofiles of the current testrun and stores the infofilehandles in the global variable SimEnv. Also, when the CarMaker environment invokes aninitialization function like e.g. Vhcl_NewInit(), an infofile handle is automatically passed asa parameter. This means that in most cases you should not have to worry about how to readan infofile into memory. For more details see the example code below.

Access functions named iGetXXX() retrieve different types of values from keys: Strings,texts, double precision floating point values and signed or unsigned long integer values.Parameters to these functions are an infofile handle and a key name. Non-existence of akey accessed using these functions is considered to be an error.

For the purpose of retrieving values from keys that are only optionally contained in an info-file, a second set of functions named iGetXXXOpt() is available. They take an additionalparameter to be used as the key’s default value in case the key doesn’t exist. (The iGetTx-tOpt() function is an exception to this rule; check for a NULL pointer returned by this func-tion.) Non-existence of a key accessed with these functions is not considered to be an error.

Functions for the retrieval of other, higher level data types like tables and vectors also exist,Please refer to the functions description in this section for more information.

Composer = Sergej ProkofjefTitle = Peter and the Wolf, Op. 67Premiere.Year = 1936Premiere.Month = MayMovements:

IntroductionThe Story BeginsThe Bird

CarMaker Programmer’s Guide Version 2.1.6

Page 35: IPG_CarMaker Programmers Guide

35Infofile Module

Error handling

3.3 Error handling

In case of an error an appropriate log message is automatically issued by the functionsdescribed above. In addition, an internal infofile error counter is maintained by the Infofilemodule. In case an error occurs (i.e. a non-optional key doesn’t exist or a key’s value couldnot be retrieved), the error counter is automatically incremented. This counter provides anefficient way of error checking for your code (see next paragraph for an outline of how touse this feature). The current value of the infofile error counter can be read using the Get-InfoErrorCount() function.

Error handling is best implemented as follows: before reading any infofile keys store the cur-rent infofile error counter’s value in a variable. Then access all necessary infofile keys(optional or not) in a row. After that, compare the current error counter with the value storedat the beginning. If the two values differ, at least one key’s value could not be retrieved andyour code should report an error. The example below illustrates this technique.

CarMaker Programmer’s Guide Version 2.1.6

Page 36: IPG_CarMaker Programmers Guide

36Infofile Module

C Function List

Example

3.4 C Function List

3.4.1 General Functions

InfoNew ()

Prototype

extern tInfos *InfoNew (void);

Arguments

none

Description

Creates a new instance of type tInfos.

Return Value

Pointer (handle) to the newly created tInfos instance, or a NULL pointer on failure.

# Infofile read by the example code (taken from Data/Vehicle/DemoCar)

Body.Mass = 1301

PowerTrain.Kind = Front

#include “infoc.h”#include “InfoUtils.h”#include “Environment.h” /* for SimEnv global variable */

intVhcl_NewInit (const struct tInfos *Inf /*vehicle parameters*/){

int count = GetInfoErrorCount();double vel, pos, mass;char *ptkind;

mass = iGetDbl(Inf, "Body.mass");ptkind = iGetStr(Inf, “PowerTrain.Kind”);

/* testrun parameters */vel = iGetDblOpt(SimEnv.TestRun.Inf, "DrivMan.Velocityt0", 0.0);pos = iGetDblOpt(SimEnv.TestRun.Inf, "Road.CarStartPos", 1.0);

if (GetInfoErrorCount() != count)return -1; /* Error */

return 0;}

CarMaker Programmer’s Guide Version 2.1.6

Page 37: IPG_CarMaker Programmers Guide

37Infofile Module

C Function List

InfoDelete ()

Prototype

extern int InfoDelete (tInfos *inf);

Arguments

• inf - handle of the data type tInfos to be deleted

Description

Deletes the specified tInfos data type.

Return Value

(check with frank)

InfoRead ()

Prototype

extern int InfoRead (tErrorMsg **perrors, tInfos *inf, const char *filename);

Arguments

• perrors - pointer to an array that will contain any errors generated during the readingof the infofile

• inf - handle of type tInfos that will be used to store the information read

• filename - name of the infofile to be read

Description

Reads from the file specified in filename and writes to the tInfos buffer pointed to by inf .

Return Value

Returns the number of errors that were generated during the read and that are containedin the perrors list. If the value is (0) then no errors were generated, if the value is ( greaterthan 0 ) then there were syntax errors during the read, if the value is (less than 0) then therewere access, i.e., hard errors during the read which caused the read to fail.

InfReadMem ()

Prototype

extern int InfoReadMem (tErrorMsg **perrors, tInfos *inf, char *bufStart, int bufSize);

Arguments

• perrors - pointer to an array that will contain any errors generated during the readingof the buffer

• inf - handle of type tInfos that specifies the memory location where the informationread will be stored

• bufStart - pointer to the buffer to be read

• bufSize- length, in bytes, of the buffer to be read

Description

Reads from the specified buffer and writes to the tInfos buffer pointed to by inf .

CarMaker Programmer’s Guide Version 2.1.6

Page 38: IPG_CarMaker Programmers Guide

38Infofile Module

C Function List

Return Value

Returns the number of errors that were generated during the read and that are containedin the perrors list. If the value is (0) then no errors were generated, if the value is ( greaterthan 0 ) then there were syntax errors during the read, if the value is (less than 0) then therewere access, i.e., hard errors during the read which caused the read to fail.

InfoWrite ()

Prototype

extern int InfoWrite (tInfos *inf, const char *filename);

Arguments

• inf - tInfos handle to the infofile buffer

• filename - name of the file to be written to

Description

Writes the information contained in the tInfos buffer inf to the file specified by filename .

Return Value

Returns -1 on failure, and 0 otherwise.

InfoListKeys ()

Prototype

char **InfoListKeys (tInfos *inf, const char *prefix, tIterKind kind);typedef enum { Keys, Subkeys, Unread_Keys, All_Keys,} tIterKind;

Arguments

• inf - tInfos handle to the infofile buffer

• prefix - specified the key prefix to be matched when searching for keys

• kind - the kind of key that will be included in the list. Must be one of the following enumtypes: Keys, Subkeys, Unread_Keys, or All_Keys.

Description

Used to get a list of the keys that match the specified search criteria. Searching is doneusing the two arguments prefix and kind. Prefix specifies a character string to match.Kind specifies the key search type to be used. The following kinds are possible:

• Keys - Once the all keys are identified with the specified prefix, will list the key seg-ments that have a unique top level key segment. For example, if the prefix = AA, kind =Keys and the following list of key is used in a search:

AA.XX.11

AA.XX.22

AA.YY.11

AA.YY.22

CarMaker Programmer’s Guide Version 2.1.6

Page 39: IPG_CarMaker Programmers Guide

39Infofile Module

C Function List

... then, the keys that would match the search criteria would be AA.XX, AA.YY, AA.ZZ. Thethird part of the key will play no role in this case and would be truncated from the key namewhen shown in the list. The list returned would be:

AA.XX, AA.YY, AA.ZZ

• Subkeys - The same as Keys except the list will be generated without the prefix partlisted and only the matching subkey portion. The same search as described beforewould then return:

XX, YY, ZZ

• Unread_Keys - Only those keys with the matching prefix that have not been accessed(read or write) will be included in the list.

• All_Keys - All keys with the matching prefix will be returned. The whole key name willbe listed. for example, using the same table and prefix as was used before, thereturned list would be:

AA.XX.11, AA.XX.22, AA.YY.11, AA.YY.22, AA.ZZ.11, AA.ZZ.22

Return Value

Returns a NULL terminated list of keys, i.e. an array of char arrays.

InfoKeyKind ()

Prototype

tKeyKind InfoKeyKind (tInfos *inf, const char *key);typedef enum { No_Key, Empty_Key, String_Key, Text_Key, Prefix_Key} tKeyKind;

Arguments

• inf - tInfos handle to the infofile buffer

• key - name of the key

Description

Returns the type of value assigned to the specified key.

Return Value

The return value is an enum type that can be one of the following:

• No_Key - There is no key with the name specified

• Empty_Key - The key is not assigned a value

• String_Key - The key contains a string of data (i.e. the value is on a single line)

• Text_Key - The key contains text or a table of data (i.e. the value spans more than oneline)

• Prefix_Key - The specified key is a prefix and not a complete key.

AA.ZZ.11

AA.ZZ.22

CarMaker Programmer’s Guide Version 2.1.6

Page 40: IPG_CarMaker Programmers Guide

40Infofile Module

C Function List

InfoDelKey ()

Prototype

int InfoDelKey (tInfos *inf, const char *key);

Arguments

• inf - tInfos handle to the infofile buffer

• key - name of the key

Description

Deletes the keys from the infofile buffer specified with inf that have the exact name askey.

Return Value

Returns 0 on success, -1 on failure.

InfoDelTree

Prototype

int InfoDelTree (tInfos *inf, const char *key);

Arguments

• inf - tInfos handle to the infofile buffer

• key - name of the key

Description

Deletes the keys from the infofile buffer specified with inf that have the same root as (i.e.begin with) key.

Return Value

Returns 0 on success, -1 on failure.

3.4.2 Read Functions

InfoGetStr ()

Prototype

int InfoGetStr (char **pval ,tInfos *inf, const char *key);

Arguments

• pval - pointer to the string that is read from the infofile buffer. The memory associatedwith this variable should NOT be freed by the user.

• inf - tInfos handle to the infofile buffer

• key - name of the key to read

Description

Gets the string value of key located in the infofile buffer that is specfied with the handle inf .

CarMaker Programmer’s Guide Version 2.1.6

Page 41: IPG_CarMaker Programmers Guide

41Infofile Module

C Function List

Return Value

Returns 0 on success, -1 on failure.

InfoGetLong ()

Prototype

int InfoGetLong (long *pval, tInfos *inf, const char *key);

Arguments

• pval - pointer to the value of type long int that is read from the infofile buffer. The mem-ory associated with this variable should NOT be freed by the user.

• inf - tInfos handle to the infofile buffer

• key - name of the key to read

Description

Gets the long int value of key located in the infofile buffer that is specfied with the handleinf .

Return Value

Returns 0 on success, -1 on failure.

InfoGetDbl ()

Prototype

int InfoGetDbl (double *pval ,tInfos *inf, const char *key);

Arguments

• pval - pointer to the value of type double that is read from the infofile buffer. The mem-ory associated with this variable should NOT be freed by the user.

• inf - tInfos handle to the infofile buffer

• key - name of the key to read

Description

Gets the double value of key located in the infofile buffer that is specfied with the handleinf .

Return Value

Returns 0 on success, -1 on failure.

InfoGetTxt ()

Prototype

int InfoGetTxt (char ***pval ,tInfos *inf, const char *key);

CarMaker Programmer’s Guide Version 2.1.6

Page 42: IPG_CarMaker Programmers Guide

42Infofile Module

C Function List

Arguments

• pval - pointer to the text string value that is read from the infofile buffer. The memoryassociated with this variable should NOT be freed by the user.

• inf - tInfos handle to the infofile buffer

• key - name of the key to read

Description

Gets the text string value of key located in the infofile buffer that is specfied with the handleinf . Used to read key values that span multiple lines.

Return Value

Returns 0 on success, -1 on failure.

InfoGetStrDef ()

Prototype

int InfoGetStrDef (char **pval , tInfos *inf, const char *key, const char *def);

Arguments

• pval - pointer to the string value that is read from the infofile buffer. The memory asso-ciated with this variable should NOT be freed by the user.

• inf - tInfos handle to the infofile buffer

• key - name of the key to read

• def - default key value

Description

Gets the string value of key located in the infofile buffer that is specfied with the handle inf .If there is no value assigned to it then the default value will be used.

Return Value

Returns 0 on success, 1 if the key doesn’t exist and -1 on failure.

InfoGetLongDef ()

Prototype

int InfoGetLongDef(long *pval, tInfos *inf, const char *key, long def);

Arguments

• pval - pointer to the long int value that is read from the infofile buffer. The memoryassociated with this variable should NOT be freed by the user.

• inf - tInfos handle to the infofile buffer

• key - name of the key to read

• def - default key value

CarMaker Programmer’s Guide Version 2.1.6

Page 43: IPG_CarMaker Programmers Guide

43Infofile Module

C Function List

Description

Gets the long int value of key located in the infofile buffer that is specfied with the handleinf . If there is no value assigned to it then the default value will be used.

Return Value

Returns 0 on success, 1 if the key doesn’t exist and -1 on failure.

InfoGetDblDef ()

Prototype

int InfoGetDblDef (double *pval ,tInfos *inf, const char *key, double def);

Arguments

• pval - pointer to the double value that is read from the infofile buffer. The memoryassociated with this variable should NOT be freed by the user.

• inf - tInfos handle to the infofile buffer

• key - name of the key to read

• def - default key value

Description

Gets the double value of key located in the infofile buffer that is specfied with the handleinf . If there is no value assigned to it then the default value will be used.

Return Value

Returns 0 on success, 1 if the key doesn’t exist and -1 on failure.

InfoGetStrDef ()

Prototype

int InfoGetTxtDef (char ***pval, tInfos *inf, const char *key, char **def);

Arguments

• pval - pointer to the text string value that is read from the infofile buffer. The memoryassociated with this variable should NOT be freed by the user.

• inf - tInfos handle to the infofile buffer

• key - name of the key to read

• def - default key value

Description

Gets the text string value of key located in the infofile buffer that is specfied with the handleinf . Used to read key values that span multiple lines. If there is no value assigned to it thenthe default value will be used.

CarMaker Programmer’s Guide Version 2.1.6

Page 44: IPG_CarMaker Programmers Guide

44Infofile Module

C Function List

Return Value

Returns 0 on success, 1 if the key doesn’t exist and -1 on failure.

3.4.3 Write Functions

InfoSetStr ()

Prototype

int InfoSetStr(tInfos *inf, const char *key, const char *val);

Arguments

• inf - tInfos handle to the infofile buffer

• key - name of the key to be set

• val - new string value to be written to the key

Description

Sets the value of the key. If the specified key does not exist then one will be created.

Return Value

Returns 0 on success, and -1 on failure.

InfoSetLong ()

Prototype

int InfoSetLong(tInfos *inf, const char *key, long val);

Arguments

• inf - tInfos handle to the infofile buffer

• key - name of the key to be set

• val - new long int value to be written to the key

Description

Sets the value of the key. If the specified key does not exist then one will be created.

Return Value

Returns 0 on success, and -1 on failure.

InfoSetDbl ()

Prototype

int InfoSetDbl(tInfos *inf, const char *key, double val);

CarMaker Programmer’s Guide Version 2.1.6

Page 45: IPG_CarMaker Programmers Guide

45Infofile Module

C Function List

Arguments

• inf - tInfos handle to the infofile buffer

• key - name of the key to be set

• val - new double value to be written to the key

Description

Sets the value of the key. If the specified key does not exist then one will be created.

Return Value

Returns 0 on success, and -1 on failure.

InfoSetTxt ()

Prototype

int InfoSetTxt(tInfos *inf, const char *key, char **val);

Arguments

• inf - tInfos handle to the infofile buffer

• key - name of the key to be set

• val - new text string value to be written to the key

Description

Sets the value of the key. If the specified key does not exist then one will be created.

Return Value

Returns 0 on success, and -1 on failure.

3.4.4 Add/Move Functions

InfoMoveKeyBefore ()

Prototype

int InfoMoveKeyBefore (tInfos *inf, const char *destkey, const char *key);

Arguments

• inf - tInfos handle to the infofile buffer

• destkey - name of the destination key used as a reference for the move

• key - name of the key to be moved

Description

Moves the key specified by key directly before the key specified by destkey .

CarMaker Programmer’s Guide Version 2.1.6

Page 46: IPG_CarMaker Programmers Guide

46Infofile Module

C Function List

Return Value

Returns 0 on success, and -1 on failure.

InfoMoveKeyBehind ()

Prototype

int InfoMoveKeyBehind (tInfos *inf, const char *destkey, const char *key);

Arguments

• inf - tInfos handle to the infofile buffer

• destkey - name of the destination key used as a reference for the move

• key - name of the key to be moved

Description

Moves the key specified by key behind the key specified by destkey .

Return Value

Returns 0 on success, and -1 on failure.

InfoAddLineBefore ()

Prototype

int InfoAddLineBefore (tInfos *inf, const char *destkey, const char *val);

Arguments

• inf - tInfos handle to the infofile buffer

• destkey - name of the destination key used as a reference for the line insertion

• val - character string to be inserted

Description

Used to insert a comment or a blank line before the key specified by destkey .

Return Value

Returns 0 on success, and -1 on failure.

InfoAddLineBehind ()

Prototype

int InfoAddLineBehind (tInfos *inf, const char *destkey, const char *val);

Arguments

• inf - tInfos handle to the infofile buffer

CarMaker Programmer’s Guide Version 2.1.6

Page 47: IPG_CarMaker Programmers Guide

47Infofile Module

C Function List

• destkey - name of the destination key used as a reference for the line insertion

• val - character string to be inserted

Description

Used to insert a comment or a blank line behind the key specified by destkey .

Return Value

Returns 0 on success, and -1 on failure.

3.4.5 Help Functions

InfoMakeKey ()

Prototype

char *InfoMakeKey (char **subKeys);

Arguments

• subKeys - list of keys to be concatinated

Description

Concatinates a list of subkeys into a single key. The subkeys will be seperated with dot oper-ators (i.e. a period).

Return Value

Returns the newly formed key, or a NULL pointer on failure. The value is static and thereforeonly valid until the next call to this function.

InfoSplitKey ()

Prototype

char **InfoSplitKey (const char *key);

Arguments

• key - key to be split

Description

Splits a key into it subkeys, deliniated with the dot operator (i.e. with a period).

Return Value

Returns the list of subkeys, or a NULL pointer on failure. The value is static and thereforeonly valid until the next call to this function.

CarMaker Programmer’s Guide Version 2.1.6

Page 48: IPG_CarMaker Programmers Guide

48Infofile Module

Tcl/Tk Procedure List

3.4.6 Additional Functions

InfoStrError ()

Prototype

const char *InfoStrError (void);

Arguments

None

Description

Used to get the list of errors.

Return Value

Returns the list of errors

3.5 Tcl/Tk Procedure List

3.5.1 Library

Command

load <path_to_ifile.so>

This is a standard Tcl/Tk command. It should be called first to load the infofile library. Referto the Tcl/Tk documentation for a detailed description of the load command.

3.5.2 ifile

Procedure

ifile option <?arg1> <?arg2> ... <?arg n>

Description

ifile performs one of many operations depending on option. Also, the arguments that areneeded depend on option.

The following description will show the functionality of ifile for all possible options.

ifile new

ifile new <handle>

With the option new the ifile procedure is used to create a new infofile instance. It takesa single argument, called handle. handle is the name of a procedure that will be cre-ated when ifile new is invoked, and will be the procedure used to perform most of theoperations on the infofile instance (as described in the next section). It is called a han-dle because it is synonymous with a unique identifier, and used to specify the infofileinstance that will be created here and managed in subsequent calls (e.g. when readingand writing).

CarMaker Programmer’s Guide Version 2.1.6

Page 49: IPG_CarMaker Programmers Guide

49Infofile Module

Tcl/Tk Procedure List

This is synonymous with the C-function call to InfoNew().

ifile delete

ifile delete <handle>

With the option delete the infofile instance referred to by handle and created with thecall to ifile new is deleted. All data associated with the specified handle will be deleted.

This is synonymous with the C-function call to InfoDelete().

ifile makekey

ifile makekey <subkey list> <var>

With the option makekey the ifile procedure is used to concatanate a list of subkeysinto a single key. The subkeys will be delimited with the dot operator (i.e a period). Thefirst argument subkey list is the list of subkeys to be put together. The secondargument var is the variable that will contain the newly formed key.

This is synonymous with the C-function call to InfoMakeKeys().

ifile splitkey

ifile splitkey <key> <var>

With the option splitkey the ifile procedure is used to split the given key into the sub-keys, delimeted with the dot operator. The first argument key is the key to be split, andthe second argument, var, will contain the list of subkey that is created upon return.

This is synonymous with the C-function call to InfoSplitKeys().

ifile strerror

ifile strerror

With the option strerror the procedure ifile returns a text message that contains the lasterror that occured during an invocation to one of the infofile procedures.

ifile version

ifile version

With the option version the procedure ifile returns a string containg the version numberof the infofie library that is being used.

3.5.3 <handle>

The procedure <handle> is the one created with the call to ifile new <handle> as previ-ously described (see section on page 48). If, for example, the call was as follows:

ifile new myhandle

then <handle> would be myhandle (i.e. whatever name was given for the argument). Themyhandle function will then be use for a number of purposes based on the supplied optionand arguments. The synatax is:

<handle> option <?arg1> <?arg2> ... <?arg n>

The following description will show the functionality of <handle> for all possible options.

<handle> read

<handle> read <filename> <errorvar>

CarMaker Programmer’s Guide Version 2.1.6

Page 50: IPG_CarMaker Programmers Guide

50Infofile Module

Tcl/Tk Procedure List

With the option read the procedure <handle> adds the contents of a file into the datalocation that is associated with the given handle. The argument filename is the nameof the file to be read. The argument errorvar is a variable that will be used to storethe list of errors, or an empty string if there are no errors.

The procedure returns the number of errors that were generated during the read andthat are contained in the error list. If the value is (0) then no errors were generated, ifthe value is ( greater than 0 ) then there were syntax errors during the read, if the valueis (less than 0) then there were access, i.e., hard errors, during the read which causedthe read to fail.

This procedure is synonymous with the C-function InfoRead().

<handle> readmem

<handle> readmem <string> <errorvar>

With the option readmem the procedure <handle> adds the contents of a string intothe data location that is associated with the given handle. The argument string is thestring buffer to be read. The argument errorvar is a variable that will be used to storethe list of errors, or an empty string if there are no errors.

The procedure returns the number of errors that were generated during the read andthat are contained in the error list. If the value is (0) then no errors were generated, ifthe value is ( greater than 0 ) then there were syntax errors during the read, if the valueis (less than 0) then there were access, i.e., hard errors, during the read which causedthe read to fail.

This procedure is synonymous with the C-function InfoReadMem().

<handle> write

<handle> write <filename>

With the option write the procedure <handle> writes the infofile data to a file. Theargument filename is the name of the file to be written to.

<handle> getstr

<handle> getstr <key> <var> <?default-string>

With the option getstr the procedure <handle> reads the value of the given key andstore it in the specified variable. If the key contains data that spans more than one line(i.e. it is a text key) then the string that is returned will contain the lines of data seperat-ed by a newline character (\n).

The argument key is the name of the key to read, the argument var is the variable thatthe data will be stored, and the argument default-string is an optional argumentthat allows a default string to be specified if the key to be read is not assigned a value.

This procedure is synonymous with InfoGetStr().

<handle> setstr

<handle> setstr <key> <string>

With the option setstr the procedure <handle> assignes a string to the specified key.This procedure is used to set a single line of data. The argument key is the name ofthe key that will be set and the argument string contains the string data.

This procedure is synonymous with InfoSetStr().

<handle> gettxt

<handle> gettxt <key> <var> <?default-list>

CarMaker Programmer’s Guide Version 2.1.6

Page 51: IPG_CarMaker Programmers Guide

51Infofile Module

Tcl/Tk Procedure List

With the option gettxt the procedure <handle> reads the value of the given key andstore it in the specified variable. The argument key is the name of the key to read, theargument var is the variable that the data will be stored, and the argument default-string is an optional argument that allows a default list to be specified if the key to beread is not assigned a value.

This procedure is synonymous with InfoGetTxt().

<handle> settxt

<handle> settxt <key> <list>

With the option settxt the procedure <handle> assignes a string to the specified key.This procedure is used to set multiple lines of data. The argument key is the name ofthe key that will be set and the argument list contains the data list.

This procedure is synonymous with InfoSetTxt().

<handle> keykind

<handle> keykind <key>

With the option keykind the procedure <handle> returns the key type/kind of the spec-ified key. Possible key types are:

- no_key

- string_key

- text_key

This procedure is synonymous with InfoKeyKind().

<handle> delkey

<handle> delkey <key>

With the option delkey the procedure <handle> deletes the given key and its value.

This procedure is synonymous with InfoDelKey().

<handle> listkeys

<handle> listkeys <prefix> <kind> <var>

With the option listkeys the procedure <handle> returns the list of keys that start withprefix and are of the given kind. The argument prefix is the prefix subkey that issearched for, the argument kind is the kind of search to be done, and the argumentvar is the variable that will store the results upon return.

See the description of InfoListKeys() for more information.

In case of the Tcl function an additional value matching_keys for the kind argument canbe specified, which enables pattern matching using shell wildcard characters like ? [ ] *etc.

<handle> movekeybefore

<handle> movekeybefore <destkey> <key>

With the option movekeybefore the procedure <handle> moves the specified key tothe position directly before the destination key.

This procedure is synonymous with the C-function InfoMoveKeyBefore().

<handle> movekeybehind

<handle> movekeybehind <destkey> <key>

CarMaker Programmer’s Guide Version 2.1.6

Page 52: IPG_CarMaker Programmers Guide

52Infofile Module

Tcl/Tk Procedure List

With the option movekeybehind the procedure <handle> moves the specified key tothe position directly behind the destination key.

This procedure is synonymous with the C-function InfoMoveKeyBehind().

<handle> addlinebefore

<handle> addlinebefore <?destkey> <string>

With the option addlinebefore the procedure <handle> adds the specified key to theposition directly before the destination key. If the destination key is omitted then theline will be added before the very first line.

This procedure is synonymous with the C-function InfoAddLineBefore().

<handle> addlinebehind

<handle> addlinebehind <?destkey> <string>

With the option addlinebehind the procedure <handle> adds the specified key to theposition directly behind the destination key. If the destination key is omitted then theline will be added after the very first line.

This procedure is synonymous with the C-function InfoAddLineBehind().

CarMaker Programmer’s Guide Version 2.1.6

Page 53: IPG_CarMaker Programmers Guide

53Data Dictionary

Defining DataDict Variables

Chapter 4

Data Dictionary

4.1 Defining DataDict Variables

Inside the CarMaker simulation program the DataDict module stores important variables(quantities) of the program in a data dictionary. This dictionary is the basis for the followingfunctionality in the CarMaker environment:

• Storage of simulation resultsOnly quantities registered in the data dictionary can be selected for storage in a resultsfile.

• Availability of online data during a simulationCarMaker user interface tools can request the simulation program to send them the val-ues of selected quantities at regular intervals. Online 3D animation of the vehicle withIPG-MOVIE and data visualization with IPG-CONTROL during a running simulation arejust two examples of how programs make use of the simulation program’s data dictio-nary.

General information

Registering a variable in the dictionary means that you have to specify a name and a unitfor the variable, and its address in memory. Name and unit length should be kept to a max-imum of 32 characters. The name can be arbitrary, it does not have the be the C code nameof the variable. The unit should be the physical unit of the quantity in question. If your vari-able has no correspondence with a physical unit, specify an empty string. Typical examplesof units used in the CarMaker environment are rpm, rad/s^2, m/s, m/s^2, rad/s, m, bar.

For each basic C type (double, float, int, ...) of a variable there is a corresponding functionDDictDefXXX() to register this variable in the data dictionary. Variables whose values aremonotone increasing over time should be registered using a second set of functions DDict-DefXXXMon(). Tools like IPG-CONTROL rely heavily on the correct specification of thismonotonicity property.

For integer variables, additionally the number of states must be specified. If you know therange of values of a variable is from 0 to 5, specify 6 as the number of states. If your vari-able’s values do not start at 0 or do not have an upper limit or the number of states would

CarMaker Programmer’s Guide Version 2.1.6

Page 54: IPG_CarMaker Programmers Guide

54Data Dictionary

Defining DataDict Variables

be greater than approximately 16, specify 0 as the number of states. Again, this is importantfor tools like IPG-CONTROL that may use this information to optimize display of the valuesof this quantity.

Recommended use

Organize the names of your quantities in a systematic and consistent manner, group themby common prefixes, use a naming hierarchie with different hierarchy levels separated by adot character. This makes life easier for both CarMaker user interface tools that have to offera complete list of quantities in a GUI, and for users that have to select quantities from sucha list.

Do not clutter the dictionary with lots of variables of only minor interest. The number of vari-ables in the dictionary should be kept to a meaningful minimum. An oversized data dictio-nary may have an impact on real-time performance of the application.

Register dictionary variables only in functions explicitly intended for this purpose, e.g.Vhcl_DeclareQuantities(). It is crucial for proper operation of the data dictionary that dictio-nary variables are not registered at arbitrary times.

Do not register local variables of a function, use global variables instead. After registeringa variable, the variable is expected to be allocated and available until the program ends.Otherwise memory access errors may result.

CarMaker Programmer’s Guide Version 2.1.6

Page 55: IPG_CarMaker Programmers Guide

55Data Dictionary

Defining DataDict Variables

List of functions

#include “DataDict.h”

/* nst: number of states */

void DDictDefDouble (const char *name, const char *unit,double *var);

void DDictDefFloat (const char *name, const char *unit,float *var);

void DDictDefLong (const char *name, const char *unit, int nst,long *var);

void DDictDefULong (const char *name, const char *unit, int nst,unsigned long *var);

void DDictDefInt (const char *name, const char *unit, int nst,int *var);

void DDictDefUInt (const char *name, const char *unit, int nst,unsigned int *var);

void DDictDefShort (const char *name, const char *unit, int nst,short *var);

void DDictDefUShort (const char *name, const char *unit, int nst,unsigned short *var);

void DDictDefChar (const char *name, const char *unit, int nst,char *var);

void DDictDefUChar (const char *name, const char *unit, int nst,unsigned char *var);

/* Monotone increasing quantities */

void DDictDefDoubleMon (const char *name, const char *unit,double *var);

void DDictDefFloatMon (const char *name, const char *unit,float *var);

void DDictDefLongMon (const char *name, const char *unit, int nst,long *var);

void DDictDefULongMon (const char *name, const char *unit, int nst,unsigned long *var);

void DDictDefIntMon (const char *name, const char *unit, int nst,int *var);

void DDictDefUIntMon (const char *name, const char *unit, int nst,unsigned int *var);

void DDictDefShortMon (const char *name, const char *unit, int nst,short *var);

void DDictDefUShortMon (const char *name, const char *unit, int nst,unsigned short *var);

void DDictDefCharMon (const char *name, const char *unit, int nst,char *var);

void DDictDefUCharMon (const char *name, const char *unit, int nst,unsigned char *var);

CarMaker Programmer’s Guide Version 2.1.6

Page 56: IPG_CarMaker Programmers Guide

56Data Dictionary

Defining DataDict Variables

Example

Current limitations

Variables may be defined only once. Exception to the rule: The address of the variable isallowed to change, i.e. name, unit, number of states and its monotonicity must remain thesame as before. This is useful for variables that are dynamically (re-)allocated each time asimulation starts. Normally you do not have to worry about this.

#include “DataDict.h”

float Car_Veloc;double Car_Dist;char SomeSwitch; /* 0 = Off, 1 = On */unsigned int Counter;

void Vhcl_DeclareQuantities (void){

DDictDefFloat (“Car.Velocity”, “m/s”, &Car_Velocity);DDictDefDoubleMon (“Car.RoadCoord”, “m”, &Car_Dist);DDictDefChar (“SomeSwitch”, ““, 2, &SomeSwitch);DDictDefUInt (“Counter”, ““, 0, &Counter);

}

CarMaker Programmer’s Guide Version 2.1.6

Page 57: IPG_CarMaker Programmers Guide

57Integrating Simulink models

Starting Matlab

Chapter 5

Integrating Simulink models

To connect a Simulink model with CarMaker, a CarMaker interface blockset is available. Theblocks of the blockset give read and write access to all variables of the CarMaker dictionaryand also permit the definition of new dictionary variables.

In Real-Time Workshop, using a special CarMaker code generation target, C code can gen-erated from a Simulink model. The resulting C code is especially tailored to fit into theCarMaker architecture.

Compiling the generated C code and linking with the CarMaker libraries lead to an execut-able CarMaker simulation program. Inside the program, either stand-alone or under realti-me conditions, the Simulink model runs as an integral part of the CarMaker simulation.Multiple Simulink models may be integrated in the same CarMaker executable, each oneperforming a different computational task.

5.1 Starting Matlab

Matlab and CarMaker work together by extending Matlab’s search path, so that Matlabknows where to find the CarMaker blocksets and utility commands. The Matlab search pathis extended by execution of a small script named cmenv.m , which is contained in the mdlsubdirectory of a CarMaker project directory. Execution of this script may be done manually,but there’s also a way to invoke it automatically each time Matlab is started.

Starting Matlab under Unix

In your shell (probably running in an xterm or some other console window) change to themdl subdirectory of your CarMaker project directory, then simply start Matlab:

% cd </path/to/your/project_dir>/mdl% matlab

Depending on how you set up your working directory (see above), you may have to invokecmenv.m manually:

>> cmenv

CarMaker Programmer’s Guide Version 2.1.6

Page 58: IPG_CarMaker Programmers Guide

58Integrating Simulink models

Starting Matlab

The cmenv.m script should issue a message like the following in your Matlab console win-dow:

CarMaker directory: /opt/ipg/hil/linux-2.1addpath /opt/ipg/hil/linux-2.1/Matlabaddpath /opt/ipg/hil/linux-2.1/Matlab/v6.1-r12.1addpath /opt/ipg/hil/linux-2.1/CM4SLaddpath </path/to/your/project_dir>/srcInitialize CarMaker for Simulink.Done.

Starting Matlab under Windows

Starting Matlabusing Windows

Explorer

In Windows Explorer, simply double click on a Simulink model’s .mdl file in the mdl subdi-rectory of your CarMaker project directory. This will automatically start Matlab with mdl asits current working directory.

Starting Matlabusing a desktop

shortcut

An alternative way of starting Matlab is by creating a desktop shortcut to one of your Simu-link models’ .mdl file. In the shortcut’s properties dialog then, set the working directory tothe path the mdl subdirectory of your CarMaker project directory. Matlab may then be start-ed by double-clicking on the desktop shortcut’s icon and your model will be loaded automat-ically.

Depending on how you set up your working directory (see above), you may have to invokecmenv.m manually:

>> cmenv

The cmenv.m script should issue a message like the following in your Matlab console win-dow:

CarMaker directory: c:/ipg/hil/win32-2.1addpath c:/ipg/hil/win32-2.1/Matlabaddpath c:/ipg/hil/win32-2.1/Matlab/v6.1-r12.1addpath c:/ipg/hil/win32-2.1/CM4SLaddpath <x:/path/to/your/project_dir>/srcInitialize CarMaker for Simulink.Done.

Automating search path setup during Matlab startup

You may want to make use of Matlab’s startup file, i.e. a file called startup.m in Matlab’sworking directory will be executed automatically when Matlab is started. Just make surethat cmenv is invoked in your startup.m file and you’re done. The advantage of this methodis that the search path is setup for CarMaker without having to load a Simulink model first.See your Matlab documentation for further details about the Matlab startup options.

CarMaker Programmer’s Guide Version 2.1.6

Page 59: IPG_CarMaker Programmers Guide

59Integrating Simulink models

Step-by-step: Integrating a Simulink model

5.2 Step-by-step: Integrating a Simulink model

As an introduction to the CarMaker interface blockset and the CarMaker target for Real-Time Workshop, we’d like to demonstrate how easy it is to integrate a Simulink model intoCarMaker. We’ll start from scratch with a new Simulink model and lead you through the fewsteps until the model is running inside CarMaker and its output signals can be watched indiagram window of IPG-CONTROL.

We assume that you’re working in a fresh copy of the template project directory to be foundunder Examples/Car_Generic in the CarMaker installation directory. Prerequisite on yourside is also a basic familiarity with the CarMaker C level interface and you should know howto rebuild and run the CarMaker simulation program and start a simulation.

The example was created with the stand-alone version of CarMaker under Linux, using Mat-lab 6.5.1 (R13 SP 1). However, there should be no difficulty in running the example onanother platform with a different version of CarMaker or any other Matlab version supportedby CarMaker.

5.2.1 Creating the Simulink model

Start Matlab in the mdl subdirectory of the project directory.

Create a new Simulink model like the following one and save it under the nameSimuModel.mdl .

In the Simulink library the orange blocks of the CarMaker Interface blockset can be foundunder Blocksets & Toolboxes, the Integrator block is under Continuous, and the Trigonomet-ric Function comes from Math Operations.

In the Block Parameters dialog of the From CM Dict, To CM Dict and Def CM Dict blocks,leave all parameters at their default, just enter the name of the quantity. You’ll probably won-der about the notation we use for the quantity names: The $ sign stands for the modelname, i.e. SimuModel in our case. Using the model name as a prefix, we can keep all modelquantities together, which makes them easier to identify among all the other quantities inCarMaker’s data dictionary. Also, once we decide to give our model a different name, afterrebuilding the code all of the model’s quantity names will have changed automatically.

The model does not do something particularly useful. It uses the current simulation time asits input and provides its sine and cosine as outputs. We just want the model to be calledby CarMaker once each simulation cycle, so that we can observe its changing output sig-nals.

5.2.2 Setting simulation parameters

Before the C code can be generated with Real-Time Workshop, a few of your model’s sim-ulation parameters need to be changed.

Figure 5.1: The SimuModel.mdl example model

CarMaker Programmer’s Guide Version 2.1.6

Page 60: IPG_CarMaker Programmers Guide

60Integrating Simulink models

Step-by-step: Integrating a Simulink model

Open the dialog Simulation / Simulation Parameters in the menubar of the model window.

Solver settings

On the Solver tab, the following changes from the default settings should be made:

• Simulation timeStop time: inf, because CarMaker determines when the simulation stops

• Solver optionsType: Fixed-step, ode1 (Euler), because of the Integrator block in our modelFixed step size: 0.001, because CarMaker runs with a step size of 1 msMode: SingleTasking, always use SingleTasking with CarMaker

Your solver settings should now look like this:

Real-Time Workshop settings

On the Real-Time Workshop tab, we first need to set the correct target so that the C codeto be generated fits with CarMaker.

• Category: Target configuration

• ConfigurationSystem target file: CarMaker.tlc, use the Browse... button to set thisGenerate code only: on / activated, in this example compilation will be done manually

Figure 5.2: Solver settings

CarMaker Programmer’s Guide Version 2.1.6

Page 61: IPG_CarMaker Programmers Guide

61Integrating Simulink models

Step-by-step: Integrating a Simulink model

look

The screendump below shows what your target configuration settings shouldlike:

The code generation options for the selected CarMaker target can be found on the sametab of the dialog:

• Category: CarMaker code generation options

• Matlab include path: /fs/opt/matlab651-r13, change this accordingly

• CarMaker project directory: ../../src, the default value is fine

• CarMaker model wrapper type: Plain, the default value is fine

Except for probably the Matlab include path (the name is bit misleading; what is meant isthe directory where to find Matlab’s include directories, i.e. normally the Matlab root direc-tory), the default settings are ok, so everything will probably look like this:

Close the dialog and save your model with the current settings.

Your model is now ready for the C code generation.

Figure 5.3: Real-Time Workshop, target configuration

Figure 5.4: Real-Time Workshop, CarMaker code generation options

CarMaker Programmer’s Guide Version 2.1.6

Page 62: IPG_CarMaker Programmers Guide

62Integrating Simulink models

Step-by-step: Integrating a Simulink model

5.2.3 Generating and compiling the model C code

Generating the C code

In the menu bar of your model window invoke Tools / Real-Time Workshop / Build Model.

Rea l -T ime Wor kshop wi l l now automat i ca l l y make a new subd i rec to r ySimuModel_CarMaker_rtw and create the model C code files inside that directory. Aftercode generation is complete you will find the following files there:

SimuModel.cSimuModel.hSimuModel.mkSimuModel_private.hSimuModel_types.hSimuModel_wrap.cSimuModel_wrap.hmodelsources.txtrtmodel.hrtw_proj.tmw

(Number and names of the files actually generated may vary depending on the Matlab ver-sion you’re using for this example.)

Compiling and creating the model library

Open a te r mina l w indow (e.g . x te r m) , change in to the newly c rea tedSimuModel_CarMaker_rtw directory and compile the code with the following commands:

% cd <path to your project directory>/mdl/SimuModel_CarMaker_rtw% make -f SimuModel.mk

After the make command has finished, in the mdl directory above, you will find a new filenamed libSimuModel_linux.a , parallel to your SimuModel.mdl file. This file is calledthe model library and contains the compiled mode C code that we’re now going to integrateinto the CarMaker simulation program.

Here’s what your mdl directory might look like now:

.|-- SimuModel.mdl|-- SimuModel_CarMaker_rtw| |-- SimuModel.c| |-- SimuModel.h| |-- SimuModel.mk| |-- SimuModel_private.h| |-- SimuModel_types.h| |-- SimuModel_wrap.c| |-- SimuModel_wrap.h| |-- modelsources.txt| |-- rtmodel.h| ‘-- rtw_proj.tmw|-- cmenv.m‘-- libSimuModel_linux.a

5.2.4 Integrating the model into CarMaker

Integration of a Simulink model into CarMaker means logical and physical integration.

CarMaker Programmer’s Guide Version 2.1.6

李飞强
无效
Page 63: IPG_CarMaker Programmers Guide

63Integrating Simulink models

Step-by-step: Integrating a Simulink model

For logical integration, the model code must actually be called from within CarMaker inorder to initialize the model code, call it during each simulation cycle, and perform cleanupactions after the simulation.

Physical integration comprises of adding the model library code to the CarMaker simulationprogram, i.e. linking the simulation program against the model library when rebuildingCarMaker.

The following steps take place in the src subdirectory of your CarMaker project directory.In the previously started terminal window change to the src directory with the followingcommand:

% cd <path to your project directory>/src

Calling the model from User.c

Edit the file User.c with your favourite ASCII editor for programming and look for the follow-ing line quite at the beginning:

/* #define SIMULINK_EXAMPLE */

Remove the comments as follows, leaving no blanks at the beginning or at the end:

#define SIMULINK_EXAMPLE

That should activate the remaining SIMUMODEL integration code in User.c . Your modelwill now be called by CarMaker during the simulation. We included the integration code inUser.c to save you some typing when trying to run this example. To find out in detail aboutall calls to libSimuModel_linux.a , simply search the file for all occurrences of the stringSIMUMODEL. See also the description of the Plain wrapper template in this manual.

Adding the model library to the simulation program

The steps required to build a CarMaker simulation program, i.e. compiling and linking it, arecontrolled by the Makefile . Edit Makefile with your favourite ASCII editor for program-ming, locate the "Example of a Simulink model" section and change it as follows:

### Example of a Simulink model

DEF_CFLAGS += -DRT -DUSE_RTMODEL

MATSUPP_MATVER = v6.5.1-r13LD_LIBS += $(MATSUPP_LIB)OBJS += ../mdl/libSimuModel_$(ARCH).a

### END (Example of a Simulink model)

Building the simulation program

In the terminal window, still in the src directory, enter the following command to build thesimulation program:

% make

When make has finished you will find a new CarMaker.linux executable file in the srcdirectory, which can now be used to test your model running a simulation.

5.2.5 Running the model

Now that everything is ready, try the following steps:

• Start the CarMaker GUI.

• Tell it to use the CarMaker.linux executable file just created.

CarMaker Programmer’s Guide Version 2.1.6

Page 64: IPG_CarMaker Programmers Guide

64Integrating Simulink models

Step-by-step: Integrating a Simulink model

xi-

• Invoke Application / Start & Connect.

• Invoke File / Open... and load the Braking testrun.

• Invoke File / IPG-CONTROL.

• Display SimuModel.quant1 and SimuModel.quant2 in a diagram window.

• Start a simulation by pressing the big green Start button.

After the simulation, if everything went right, your diagram should look appromately like this one:

Congratulations, you’ve just integrated your first Simulink model into CarMaker.

Figure 5.5: SimuModel output in IPG-CONTROL

CarMaker Programmer’s Guide Version 2.1.6

Page 65: IPG_CarMaker Programmers Guide

65Integrating Simulink models

The CarMaker interface blockset

5.3 The CarMaker interface blockset

The CarMaker interface blockset contains blocks that serve the purpose of directly connect-ing a Simulink model with CarMaker. The blocks may be used as an alternative or in addi-tion to the Simulink’s standard Inport and Outport blocks at a model’s top level.

You may find the blockset in the Simulink library browser, under Blocksets and Toolboxes.Double click on Matlab Support for CarMaker, or simply type

>> CarMaker

in Matlab’s command window.

5.3.1 Accessing the CarMaker dictionary

The CarMaker interface blockset contains two blocks, From CM Dict and To CM Dict, forread and write access of CarMaker dictionary variables. The variable to be accessed is sim-ply specified by its name.

When a non existent dictionary variable is given as a parameter of a From CM Dict or ToCM Dict block, CarMaker will report the following error at the start of a simulation:

Model ‘abcde’: Missing quantity in data dict: ‘xyz’

Figure 5.6: Simulink library browser (Unix): CarMaker interface blockset

Figure 5.7: Simulink library browser (Unix): CarMaker interface blockset

CarMaker Programmer’s Guide Version 2.1.6

Page 66: IPG_CarMaker Programmers Guide

66Integrating Simulink models

The CarMaker interface blockset

From CM Dict

The From CM Dict block reads a variable in the CarMaker dictionary and provides its currentvalue on the block’s output port. The variable needs not to be defined with a Def CM Dictblock in the model; any existing dictionary variable may be read.

Enter the name of the variable in the block parameters dialog of the block. In the model, thename will be displayed inside the block’s symbol.

To CM Dict

The To CM Dict block writes the current value at the block’s input port to a variable in theCarMaker dictionary. The variable needs not to be defined with a Def CM Dict block in themodel; any existing dictionary variable may be written to.

Enter the name of the variable in the block parameters dialog of the block. In the model, thename will be displayed inside the block’s symbol.

5.3.2 Defining CarMaker dictionary variables

A Simulink model can define its own variables in the CarMaker dictionary, because theremay be signals that are to be monitored with IPG-CONTROL. Also, before a signal can besaved as part of the simulation results file, it must be put into the CarMaker dictionary.

When you define a dictionary variable in Simulink model, it is recommended to prefix itsname with the model’s name or with a convenient abbreviation. This makes it easier for youto identify the model’s variables in the dictionary with tools like the CarMaker GUI or IPG-CONTROL. Example: A dictionary variable xyz defined in a Simulink model called MyModelshould be given the name MyModel.xyz.

Figure 5.8: From CM Dict block parameters dialog

Figure 5.9: To CM Dict block parameters dialog

CarMaker Programmer’s Guide Version 2.1.6

Page 67: IPG_CarMaker Programmers Guide

67Integrating Simulink models

The CarMaker interface blockset

A convenient shortcut exists for this purpose: The character $ in a variable’s name will beautomatically expanded to the model’s name. In the example above, instead of MyMod-el.xyz you may also type the shorter form $.xyz.

The shortcut works for all blocks accessing the CarMaker dictionary. It saves you some key-strokes, reduces the probability of typing errors, and proves to be really valuable once themodel is saved under a different name.

When defining a dictionary (using the Def CM Dict block) that is already defined somewhereelse, CarMaker will report the following error at the start of a simulation:

Model ‘abcde’: Error defining quantity ‘xyz’

If you need to access the dictionary variable in other parts of CarMaker, you may want toconsider defining it in the wrapper module, defining a C variable for it and declaring it in thewrapper’s header file.

Def CM Dict

The Def CM Dict block defines a variable in the CarMaker dictionary.

Enter the name of the variable in the block parameters dialog of the block. In the model, thename will be displayed inside the block’s symbol.

The variable may also be given a unit, this is recommended but optional. See IPG-CON-TROL for units used with CarMaker. Specifying a unit serves as some kind of documenta-tion about the variable, but also allows IPG-CONTROL to display it on the same axis withother dictionary variables of the same unit.

If the variable’s values are strictly monotonic increasing over time, you should check theStricly monotone checkbox. Again, this is an information that tools like IPG-CONTROLneed for proper display of the variable’s values.

Choose the variable’s type according to your needs and the range of values of the variable.You may choose between two floating point types and six integer types. When in doubt useDouble.

Figure 5.10: Def CM Dict block parameters dialog

CarMaker Programmer’s Guide Version 2.1.6

Page 68: IPG_CarMaker Programmers Guide

68Integrating Simulink models

The CarMaker interface blockset

For discrete variables (any of the integer types), if the range of values starts at 0 and hasan reasonably small upper limit (e.g. an indicator light that is either on or off), it may makesense to specify the number of discrete states of the variable. For the indicator light therewould be 2 discrete values (0=off, 1=on). Again this is information is provided mainly forIPG-CONTROL which displays variables with a limited number of states in a special, spacesaving way. Specifying a value of 0 in this field means that no special state info is available.For the Double and Float type, the value of this field is ignored.

5.3.3 Accessing C variables

Use of a From CM Var or To CM Var block is intended for accessing a C variable that is notdefined in the dictionary. You have to make sure that the variable exists and is declaredproperly in all C code modules where the variable is used.

RTW’s custom code library blocks might be handy for adding a #include of the proper head-er file for the referenced variable at the top of your model source file. An alternative placefor this is the wrapper header file of your model, which gets #include’d automatically by thegenerated model source code.

If a non existent C variable is specified as a parameter of a From CM Var or To CM Var block,you will very likely get warnings from the compiler about not knowing the type of the vari-able, and an error like

unresolved external reference: ‘xyz’

reported by the linker.

From CM Var

The From CM Var block reads a C variable and provides its current value on the block’s out-put port. The variable’s name will be put without change into the model’s C code.

Enter the name of the variable in the block parameters dialog of the block. In the model, thename will be displayed inside the block’s symbol.

Figure 5.11: From CM Var block parameters dialog

CarMaker Programmer’s Guide Version 2.1.6

Page 69: IPG_CarMaker Programmers Guide

69Integrating Simulink models

The CarMaker interface blockset

To CM Var

The To CM Var block writes the current value at the block’s input port to a C variable. Thevariable’s name will be put without change into the model’s C code.

Enter the name of the variable in the block parameters dialog of the block. In the model, thename will be displayed inside the block’s symbol.

Figure 5.12: To CM Var block parameters dialog

CarMaker Programmer’s Guide Version 2.1.6

Page 70: IPG_CarMaker Programmers Guide

70Integrating Simulink models

The CarMaker target for Real-Time Workshop

5.4 The CarMaker target for Real-Time Workshop

...

The CarMaker target is based on the Generic Real-Time Target (grt_malloc) coming withReal-Time Workshop. A special version of the target for use with Visual C++ 6.0 under MSWindows is also available.

...

Components involved when integrating a Simulink model into CarMaker:

• The generated model C code.

• A wrapper module, providing the model interface to CarMaker

• The run-time library libMatSupp.a .

...

5.4.1 Code generation with the CarMaker target

...

The wrapper is the link between CarMaker and the C code generated by Real-Time Work-shop. The wrapper shields CarMaker from the details of the generated C code, providing aconsistent API rather independent of the Matlab version used. In order to integrate a Simu-link model, CarMaker will interface the model only by means of the model API provided bythe wrapper.

...

The wrapper files

XXX_CarMaker_rtw/XXX_wrap.cXXX_CarMaker_rtw/XXX_wrap.h

will only be created once, during the first time you ever generate C code of your model.Since the wrapper will normally require further customization, subsequent invocations ofReal-Time Workshop will refrain from overwriting existing wrapper files. You may force rec-reation of the wrapper files by removing them before the next code generation.

...

5.4.2 Choosing the right model wrapper

Using a module wrapper

In most cases a Simulink model is to implement a CarMaker module managed byCarMaker’s module manager. For this purpose a number of predefined module wrappertemplates are available in the CarMaker target for Real-Time Workshop:

• Aero

• Brake

• PTClutch

• PTDriveLine

• PTEngine

• PTGearBox

• PowerTrain

• Steering

CarMaker Programmer’s Guide Version 2.1.6

Page 71: IPG_CarMaker Programmers Guide

71Integrating Simulink models

The CarMaker target for Real-Time Workshop

• SuspExtFrcs

• Tire

Typically such a module is selected by an appropriate entry in the vehicle parameter file,e.g. Steering.Kind in case of a steering model. During a simulation the model will be invokedautomatically by CarMaker’s model manager.

The functional interface of a module wrapper consists of only a single function

XXX_Register()

which should be called once from the User_Register() function in file src/User.c . In thisfunction you can also change the name under which your model is registered in CarMakerand which must be specified in the vehicle parameter file accordingly. The default name isthe name of the Simulink model, but you may use any ordinary C string like e.g."WhizBrake-4.2" instead.

The BodyCtrl and UserSteer examples are both integrated into CarMaker using using amodule wrapper. See chapter Demonstration Examples and the source code in Examples/RTW in the CarMaker installation directory.

Using the Plain wrapper

In case a Simulink model does not implement one of the CarMaker modules, the generalpurpose Plain wrapper should be used. Since CarMaker’s model manager will not beinvolved, a model instance pointer must be managed and the functional interface of thewrapper is slightly more complex:

XXX_InstXXX_DeclQuants()XXX_New()XXX_Delete()XXX_Calc()

The typical invocation of these functions can be found in file src/User.c , in the SIMUMOD-EL integration code as used in the step-by-step example in a previous chapter. Simply lookfor occurences of the string SIMULINK_EXAMPLE in the source code of src/User.c .

The TractCtrl example was also integrated into CarMaker using using the Plain wrapper.See chapter Demonstration Examples and the source code in Examples/RTW in theCarMaker installation directory.

5.4.3 Customizing the wrapper

Setting the solver

Which Simulink solver is used by a model is determined in the wrapper C code itself and iscompletely independent of the solver setting in the model’s simulation parameters. The cor-responding code block can be found quite at the beginning of a XXX_wrap.c file:

#define rtode_CreateIntegrationData rt_ode1_CreateIntegrationData#define rtode_DestroyIntegrationData rt_ode1_DestroyIntegrationData#define rtode_UpdateContinuousStates rt_ode1_UpdateContinuousStates

The default is to use the ODE1 solver. In order to use any of the other fixed step solverssupported by Real-Time Workshop, change all three occurrences of ode1. Possible valuesare ode1, ode2, ode3, ode4 and ode5.

Be sure that the all three #define’s are set to the same solver; mixing solvers will very prob-ably cause the simulation program to crash.

CarMaker Programmer’s Guide Version 2.1.6

Page 72: IPG_CarMaker Programmers Guide

72Integrating Simulink models

The CarMaker target for Real-Time Workshop

Connecting Inports and Outports of a Simulink model

Inports and Outports of a Simulink model constitute the preferred way of connecting themodel to CarMaker. They are accessed in function XXX_Calc() of the wrapper.

...

This is best explained by the wrapper source code of the examples.

Defining additional quantities

The wrapper function XXX_DeclQuants() will either be called automatically by theCarMaker model manager, or manually in case of a Plain wrapper.

#include "InfoUtils.h"DDictDefXXX()

...

Reading additional parameters

The wrapper function XXX_SetParams() will be called automatically called during initializa-tion of the model, i.e. it will be called indirectly via XXX_New().

#include "InfoUtils.h"iRead2()iGetXXX()iGetXXXOpt()

...

See also the chapter about CarMaker’s tunable parameter interface.

5.4.4 Integrating the model library

Including the wrapper header file

Typically, for a Simulink model mdl/XXX.mdl , a line like

#include "../mdl/XXX_CarMaker_rtw/XXX_wrap.h"

must be added to file User.c , provided that you’re actually calling the model from User.c .

...

Compiling the model library

Typically, for a Simulink model mdl/XXX.mdl , the following command, issued in directorymdl/XXX_CarMaker_rtw , will compile the model library:

% make -f XXX.mk

...

Linking with the model library

The following statements must be present exactly once in the Makefile :

DEF_CFLAGS += -DRT -DUSE_RTMODELMATSUPP_MATVER = v6.5.1-r13LD_LIBS += $(MATSUPP_LIB)

The Matlab version should match the one you’re using; possible values are:

CarMaker Programmer’s Guide Version 2.1.6

Page 73: IPG_CarMaker Programmers Guide

73Integrating Simulink models

The CarMaker target for Real-Time Workshop

v6.1-r12.1v6.5-r13v6.5.1-r13v7.0-r14v7.0.1-r14v7.0.4-r14v7.1-r14

For each Simulink model to be integrated, add a line like the following:

OBJS += ../mdl/libXXX_$(ARCH).a

The Makefile of each CarMaker project directory template does already contain theselines, but they are commented out by default. You simply need to remove the comments andadapt the lines accordingly.

CarMaker Programmer’s Guide Version 2.1.6

Page 74: IPG_CarMaker Programmers Guide

74Integrating Simulink models

CarMaker’s tunable parameter interface

5.5 CarMaker’s tunable parameter interface

5.5.1 Introduction

Let’s take a look at the following, very primitive Simulink model.

The gain factor is not a constant value but a workspace variable named k.

>> disp(k)0.7827

We want to generate C code for this simple model and we want to be able to set a differentgain factor at the beginning of each simulation. In other words, we want the gain blocks’sparameter k to be a tunable parameter. Being able to change a block parameter’s valueafter C code generation, when the code is running, that’s what tunable parameters are allabout.

Usually, at the beginning of a simulation, CarMaker reads all information about testruns,vehicle configuration etc. from external parameter files. These files are named Infofiles afterthe way the data they contain is formatted. The CarMaker target’s tunable parameter inter-face is mostly about storing Matlab workspace variables in Infofiles, retrieving a tunableparameter’s value from an Infofile or setting it directly.

To make use of CarMaker’s tunable parameter interface with a Simulink model one normallyhas to perform the following steps:

• Enabling tunable parameters in the Simulink model.

• Adding statements to the model wrapper which modify the model’s tunable parameters.

• Creating infofile entries with the values of all parameters to be tuned (optional).

The remaining sections of this chapter will guide you through the details of parameter tun-ing, always keeping an eye on the simple example introduced at the beginning.

Figure 5.13: Simulink model with a single parameter

Figure 5.14: Simulink model with a single parameter

CarMaker Programmer’s Guide Version 2.1.6

Page 75: IPG_CarMaker Programmers Guide

75Integrating Simulink models

CarMaker’s tunable parameter interface

5.5.2 Enabling tunable parameters in a Simulink model

Let’s continue with our little Simulink model. The next thing we do is to tell Simulink that theworkspace variable k should be treated as a tunable parameter and tell Real-Time Work-shop to include special parameter tuning data in the generated C code.

Matlab 6.x For Matlab 6.x models enabling parameter tuning can be done as follows:

In the model window’s menu bar, in the Simulation menu, we choose Simulation Param-eters... In the dialog, on the Advanced tab, we select Inline parameters and click on theConfigure... button.

In the Model Parameter Configuration dialog, we add k to the list of Global (tunable)parameters, like in the screendump below.

Make sure that the storage class of the parameter is SimulinkGlobal. The CarMaker target’stunable parameter interface functions apply to parameters of this storage class only.

Figure 5.15: Selecting Inlne parameters

Figure 5.16: Marking parameter k as tunable

CarMaker Programmer’s Guide Version 2.1.6

Page 76: IPG_CarMaker Programmers Guide

76Integrating Simulink models

CarMaker’s tunable parameter interface

Next, on the Real-Time Workshop tab, we select the CarMaker target and enable codegeneration for tunable parameters by adding the -aParameterTuning=1 option in the Systemtarget file entry.

Matlab 7.x For Matlab 7.x models the steps are similar to those for Matlab 6.x described above:

In the model window’s menu bar, in the Simulation menu, choose Configuration Param-eters... which opens a dialog.

In the listbox on the left click on Optimization. On the tab select Inline parameters andclick on the Configure... button. This will bring up the same Model Parameter Configu-ration dialog as described above for our example model.

In the listbox on the left click, under Real-Time Workshop click on Interface. On the tab,in the Data exchange area, select C-API as Interface and make sure that Parametersin C API is enabled.

5.5.3 Modifying tunable parameters in the model wrapper

After you’ve generated C code for your model using the model settings explained in the pre-ceding paragraphs, in principle everything is ready for parameter tuning at runtime. Whatremains to be done is to write the program statements that assign the tunable parametersof a model their desired values, either coming from an Infofile or being the result of somecalculation.

The model wrapper (file XXX_wrap.c ) generated by Real-Time Workshop contains a func-tion called XXX_SetParams() which will be called automatically everytime the model is ini-tialized at the beginning of a simulation. In a newly created wrapper module the functiondoes almost nothing. Add your parameter tuning statements at the location indicated below:

voidXXX_SetParams (SimStruct *rts, struct tMatSuppTunables *tuns, struct tInfos *Inf){

/*Log("%s_SetParams()\n", Modelname);*/

/* * Parameter tuning - Part 1 * This is the place to modify parameters of a storage class * other than ‘SimulinkGlobal’. */

if (tuns == NULL)

Figure 5.17: Enabling code generation for tunable parameters

CarMaker Programmer’s Guide Version 2.1.6

Page 77: IPG_CarMaker Programmers Guide

77Integrating Simulink models

CarMaker’s tunable parameter interface

return; /* No tunable parameters in this model. */

/* * Parameter tuning - Part 2 * This is the place to modify parameters of storage class ‘SimulinkGlobal’, * e.g. using the CarMaker target’s tunable parameter interface. */

/*MatSupp_TunRead(tuns, ...);*//*MatSupp_TunReadDef(tuns, ...);*//*MatSupp_TunReadAll(tuns, ...);*/

}

As you can see, parameter tuning for parameters which were not assigned the Simulink-Global storage class is also possible and has its place in the wrapper. See the BodyCtrlexample in the Examples/RTW directory of your CarMaker installation, to see how tuning ofan ExportedGlobal parameter could be done.

To stay with our simple Simulink model, the parameter tuning code for out simple modelmay (after having removed most of the comments) look like this:

voidsimple_SetParams (SimStruct *rts, struct tMatSuppTunables *tuns, struct tInfos *Inf){

/*Log("%s_SetParams()\n", Modelname);*/

if (tuns == NULL)return; /* No tunable parameters in this model. */

MatSupp_TunReadAll(tuns, Inf, Modelname);}

Running the model in CarMaker would then proceed as follows: During initialization of asimulation, all tunable parameters will be reset to their original values (i.e. the values theyhad when the C code was generated). After that simple_SetParams() will be called auto-matically. Our function tries to find entries for all the tunable parameters of the model in thevehicle parameter file (Inf handle). If an infofile entry named simple.k is present, k will beset to the entry’s value. If no such entry is present, k will keep its original value (0.7827 inour case). The simulation will then proceed using the actual value of k.

A detailed description of the functions of CarMaker’s tunable parameter interface can befound in the next chapter. At the end of each function’s description you will find one or moresmall examples which may help you setting up your parameter tuning code inXXX_SetParams().

For accessing Infofile values you may also want to refer to functions of the Infofile library.See the specific chapter in this manual and also the include file of the library, to be found atinclude/infoc.h in your CarMaker installation.

5.5.4 Parameter values in Infofiles

The last question is how to make Infofile entries for the tunable parameters of a model. Nor-mally one wants to take a snapshot of the current values of the Matlab workspace variablesin question (probably at the time the model C code is generated) and create the correspond-ing entries in an Infofile.

CarMaker’s tunable parameter interface provides several utility commands available at theMatlab prompt, which help you in automatically creating infofile entries for the tunableparameters of a Simulink model. Please refer to the online help of the following commands,their use should be rather self explaining:

>> help cmtuncreate>> help cmtunappend

CarMaker Programmer’s Guide Version 2.1.6

Page 78: IPG_CarMaker Programmers Guide

78Integrating Simulink models

CarMaker’s tunable parameter interface

>> help cmtundump

These commands make use of the ifile suite of commands for infofile access, for which anonline help is available, too:

>> help ifile

Tunable parameters will be stored using the ifile_setmat command (uses InfoSetMat()) andCarMaker’s tunable parameter interface functions will try to read them using InfoGetMat()and InfoGetMatDef() of the infofile library.

The tInfoMat infofile entries created by InfoSetMat() are capable of storing most of Matlab’snumeric types, including complex and n-dimensional matrices in an infofile entry. For themost common and simple cases like scalars and vectors, however, a tInfoMat entry with itsstructure header may sometimes be “too much”. For this reason, compatibility with earlierinfofile entry formats like

SomeScalar = 3.1415SomeVector = 10 12 13 14 15 16 17

is provided when reading an entry with InfoGetMat() / InfoGetMatDef(). This means in manycases you may stay with the simpler entries like the ones mentioned, which also has theadvantage of being compatible with other CarMaker components with no such strong con-nection to Matlab.

5.5.5 Adding tunable parameters to the CarMaker dictionary

After initialization a tunable parameter’s value remains constant during the whole simula-tion, so normally there’s no point in making it a dictionary quantity so that e.g. it can be mon-itored in IPG-CONTROL. But think of what would be possible if the parameter could bechanged on the fly using Direct Variable Access (DVA).

For example, you may want to experiment with a parameter’s value during the simulation,observing the immediate change in your model’s behaviour.

Or suppose you want to be able to activate or deactivate parts of your Simulink model atwill. Simply add a Gain block to a signal which multiplies the signal by either 0 or 1, makethe block’s gain factor tunable and add it to the CarMaker dictionary.

Definition of such a parameter quantity means adding some code to the function DeclPa-rameterQuants(), to be found in a Simulink model’s wrapper module (XXX_wrap.c ). Let’sadd a single scalar parameter MyParam to the dictionary:

static voidDeclParameterQuants (struct tMatSuppTunables *tuns){

MatSupp_TunDDictDefScalar(tuns, “MyParam”, INFOMAT_DOUBLE, “kappa”, “kg/s”);}

The quantity will be called kappa and its unit will be kg/s. Giving the resulting dictionaryquantity a name different from that of the parameter allows for e.g addition of some kind ofname prefix like the model’s name etc.

Please note that the DeclParameterQuants() function will be called twice, first with tunsequal to NULL. The reasons for the two invocations lie in the internal sequence of events dur-ing CarMaker testrun initialization. When the function is entered for the first time, the mod-el’s XXX_New() function has not yet been called so absolutely no tunable parameterinformation is available. Still, this is the time when dictionary quantities must be defined, sothe necessary information about the tunable parameter’s type must be supplied explicitly toMatSupp_TunDDictDefScalar(), e.g. INFOMAT_DOUBLE in our case.

Only scalar tunable parameters may be defined as dictionary quantities. For complex tun-able parameters the quantity will reflect only the state of the real part.

CarMaker Programmer’s Guide Version 2.1.6

Page 79: IPG_CarMaker Programmers Guide

79Integrating Simulink models

CarMaker’s tunable parameter interface

5.5.6 Known limitations

Parameters in multiple model instances in Matlab 6.x

When working with multiple instances of a model, e.g. multipe instances of a tire model, allinstances share the same set of tunable parameters. As a consequence, when you modifya tunable parameter in one instance, the modification will apply to all other instances of themodel as well and all instances will do their calculations using the parameter’s new value.

Please note that this is a fundamental limitation of Real-Time Workshop’s Generic Real-Time Target in Matlab 6.x, on which the CarMaker target is based, and not a limitation ofCarMaker’s tunable parameter interface.

Multiple tunable parameter instances in Matlab 6.x

In Matlab 6.x the generated C code may contain multiple instances of a tunable parameterthat all need updating when the parameter’s value is changed (see the Real-Time Work-shop manual for details about parameter instances in the generated C code). The functionsof the CarMaker tunable parameter interface do handle this, but when such a tunableparameter is added to the CarMaker dictionary, the dictionary quantity will reflect only thestate of the first instance of the tunable parameter. This limitation also applies to changingsuch a parameter quantity’s value with DVA.

CarMaker Programmer’s Guide Version 2.1.6

Page 80: IPG_CarMaker Programmers Guide

80Integrating Simulink models

CarMaker’s tunable parameter interface

5.5.7 Tunable parameter interface functions

MatSupp_TunRead() – Read a parameter from an infofile

Syntax

int MatSuppTunRead (const tMatSuppTunables *tuns,const char *param,const struct tInfos *inf,const char *key)

Description

Reads the value of tunable parameter param from the entry named key in infofile inf.

The function is intended to be used from within XXX_SetParams() in the model wrapper. Inthis context a valid tuns handle as well as a vehicle data infofile handle Inf are available bydefault.

If successful, the function returns 0. In case of an error, -1 is returned and an error messagewill be issued to the CarMaker log.

Example

MatSupp_TunRead(tuns, “MyParam”, Inf, “Body.mass”);

MatSupp_TunReadDef() – Read a parameter from an infofile

Syntax

int MatSuppTunReadDef (const tMatSuppTunables *tuns,const char *param,const struct tInfos *inf,const char *key,const struct tInfoMat *def

)

Description

Reads the value of tunable parameter param from the entry named key in infofile inf. If forany reason he value cannot be set from the infofile entry, the provided default value is usedinstead. A default value of NULL means to use the parameter’s original value as the default.

The function is intended to be used from within XXX_SetParams() in the model wrapper. Inthis context a valid tuns handle as well as a vehicle data infofile handle Inf are available bydefault.

If successful, the function returns 0. In case of an error, -1 is returned and an error messagewill be issued to the CarMaker log.

Example

MatSupp_TunReadDef(tuns, “MyParam1”, Inf, “Steering.Rack2StWhl”, NULL);

CarMaker Programmer’s Guide Version 2.1.6

Page 81: IPG_CarMaker Programmers Guide

81Integrating Simulink models

CarMaker’s tunable parameter interface

tInfoMat *mat = InfoMatMakeScalar(INFOMAT_DOUBLE, 0, 3.14, 0);MatSupp_TunReadDef(tuns, “MyParam2”, Inf, “Body.mass”, mat);

MatSupp_TunReadAll() – Read all parameters from an infofile

Syntax

int MatSuppTunReadAll (const tMatSuppTunables *tuns,const struct tInfos *inf,const char *keyprefix

)

Description

This is a convenience function that reads the values of all tunable parameters of a Simulinkmodel from the infofile inf. Each parameter’s name is used as the key to look up the corre-sponding infofile entry.

Optionally a prefix can be prepended to all names – e.g. if a parameter’s name is “kappa”and keyprefix is “SuperABS” , the resulting infofile key will be “SuperABS.kappa” . A keyprefixvalue of NULL or an empty string ““ both mean that no prefix should be prepended.

Internally the function calls MatSupp_TunRead() , i.e. for each parameter a corresponding info-file entry is considered to be mandatory. If an entry for a parameter cannot be read an errormessage will be issued to the CarMaker log.

The function returns the number of parameters that could not be read.

The function is intended to be used from within XXX_SetParams() in the model wrapper. Inthis context a valid tuns handle as well as a vehicle data infofile handle Inf are available bydefault.

Example

MatSupp_TunReadAll(tuns, Inf, Modelname);MatSupp_TunReadAll(tuns, Inf, “SuperABS“);MatSupp_TunReadAll(tuns, Inf, ““);

MatSupp_TunReadAllOpt() – Read all parameters from an infofile

Syntax

void MatSuppTunReadAllOpt (const tMatSuppTunables *tuns,const struct tInfos *inf,const char *keyprefix

)

Description

This is a convenience function that reads the values of all tunable parameters of a Simulinkmodel from the infofile inf. Each parameter’s name is used as the key to look up the corre-sponding infofile entry.

CarMaker Programmer’s Guide Version 2.1.6

Page 82: IPG_CarMaker Programmers Guide

82Integrating Simulink models

CarMaker’s tunable parameter interface

Optionally a prefix can be prepended to all names – e.g. if a parameter’s name is “kappa”and keyprefix is “SuperABS” , the resulting infofile key will be “SuperABS.kappa” . A keyprefixvalue of NULL or an empty string ““ both mean that no prefix should be prepended.

Internally the function calls MatSupp_TunReadDef(..., NULL) , i.e. for each parameter a cor-responding infofile entry is considered to be optional. No error will be issued if a parametercannot be read.

The function is intended to be used from within XXX_SetParams() in the model wrapper. Inthis context a valid tuns handle as well as a vehicle data infofile handle Inf are available bydefault.

Example

MatSupp_TunReadAllOpt(tuns, Inf, Modelname);MatSupp_TunReadAllOpt(tuns, Inf, “SuperABS“);MatSupp_TunReadAllOpt(tuns, Inf, ““);

MatSupp_TunGetDbl() – Get a parameter’s value

Syntax

double MatSupp_TunGetDbl (const tMatSuppTunables *tuns,const char *param)

Description

Returns the value of tunable parameter param, automatically converting from the parame-ter’s internal type to type double.

Only non-complex scalar parameters may be accessed with this function. For other typesuse MatSupp_TunGetDblVec() or MatSupp_TunGetMat().

In case of an error the function returns 0.0 and an error message will be issued to theCarMaker log.

The function is intended to be used from within XXX_SetParams() in the model wrapper. Inthis context a valid tuns handle is available by default.

Example

kappa = MatSupp_TunGetDbl(tuns, “kappa”);

MatSupp_TunGetDblVec() – Get a parameter’s value

Syntax

double *MatSupp_TunGetDblVec (const tMatSuppTunables *tuns,const char *param,int *nvalues)

CarMaker Programmer’s Guide Version 2.1.6

Page 83: IPG_CarMaker Programmers Guide

83Integrating Simulink models

CarMaker’s tunable parameter interface

Description

Returns the value of tunable parameter param in an array of type double, automatically con-verting from the parameter’s internal type. The number of elements will be stored in nval-ues. After use the array should be free()’ed by the caller.

Both non-complex scalar and vector parameters may be accessed with this function. Forother types MatSupp_TunGetMat() should be used.

In case of an error the function returns NULL and an error message will be issued to theCarMaker log.

The function is intended to be used from within XXX_SetParams() in the model wrapper. Inthis context a valid tuns handle is available by default.

Example

double *values;int i, nvalues;

values = MatSupp_TunGetDblVec(tuns, “MyParam“, &nvalues);for (i=0; i<nvalues; i++)

Log(“MyParam[%d] = %g\n“, i, values[i]);free(values);

MatSupp_TunGetMat() – Get a parameter’s value

Syntax

tInfoMat *MatSupp_TunGetMat (const tMatSuppTunables *tuns,const char *param)

Description

Returns the value of tunable parameter param in a tInfoMat structure. After use InfoF-reeMat() should be called to release the tInfoMat structure.

Almost all parameter types, real or complex, may be accessed with this function.

In case of an error the function returns NULL and an error message will be issued to theCarMaker log.

The function is intended to be used from within XXX_SetParams() in the model wrapper. Inthis context a valid tuns handle is available by default.

Example

tInfoMat *mat;

mat = MatSupp_TunGetMat(tuns, “MyParam”);

/* ...modify mat’s value as you like... */

MatSupp_TunSetFromMat(tuns, “MyParam”, mat);InfoFreeMat(mat);

CarMaker Programmer’s Guide Version 2.1.6

Page 84: IPG_CarMaker Programmers Guide

84Integrating Simulink models

CarMaker’s tunable parameter interface

MatSupp_TunSetFromDbl() – Set a parameter’s value

Syntax

int MatSupp_TunSetFromDbl (const tMatSuppTunables *tuns,const char *param,double value)

Description

Sets tunable parameter param to the specified value, automatically converting to theparameter’s internal type.

Only non-complex scalar parameters may be accessed with this function. For other typesuse MatSupp_TunSetDblVec() or MatSupp_TunSetMat().

If successful, the function returns 0. In case of an error, -1 is returned and an error messagewill be issued to the CarMaker log.

The function is intended to be used from within XXX_SetParams() in the model wrapper. Inthis context a valid tuns handle is available by default.

Example

MatSupp_TunSetFromDbl(tuns, “MyParam”, 42.0);

MatSupp_TunSetFromDblVec() – Set a parameter’s value

Syntax

int MatSupp_TunSetFromDblVec (const tMatSuppTunables *tuns,const char *param,int nvalues,const double *values)

Description

Sets tunable parameter param to the data stored in the values array with nvalues manyentries, automatically converting the data to the parameter’s internal type.

Both non-complex scalar and vector parameters may be accessed with this function. Forother types MatSupp_TunSetMat() should be used.

If successful, the function returns 0. In case of an error, -1 is returned and an error messagewill be issued to the CarMaker log.

The function is intended to be used from within XXX_SetParams() in the model wrapper. Inthis context a valid tuns handle is available by default.

Example

double vec[3];

vec[0] = 3.14;vec[1] = 6.28;

CarMaker Programmer’s Guide Version 2.1.6

Page 85: IPG_CarMaker Programmers Guide

85Integrating Simulink models

CarMaker’s tunable parameter interface

vec[2] = 9.42;MatSupp_TunSetFromDblVec(tuns, “MyParam”, 3, vec);

MatSupp_TunSetFromMat

Syntax

int MatSupp_TunSetFromMat (const tMatSuppTunables *tuns,const char *param,const tInfoMat *value)

Description

Sets tunable parameter param to the specified value.

Almost all parameter types, real or complex, may be accessed with this function.

If successful, the function returns 0. In case of an error, -1 is returned and an error messagewill be issued to the CarMaker log.

The function is intended to be used from within XXX_SetParams() in the model wrapper. Inthis context a valid tuns handle is available by default.

Example

tInfoMat *mat;double vec[3];

vec[0] = 3.14;vec[1] = 6.28;vec[2] = 9.42;mat = InfoMatMakeRowVector(INFOMAT_DOUBLE, 3, vec, NULL);MatSupp_TunSetFromMat(tuns, “MyParam”, mat);InfoFreeMat(mat);

MatSupp_TunDDictDefScalar – Define a parameter quantity

Syntax

int MatSupp_TunDDictDefScalar (const tMatSuppTunables *tuns,const char *param,tInfoMatType type,const char *name, const char *value)

Description

Makes tunable scalar parameter param an analog, non-monotonic CarMaker dictionaryquantity. The quantity can be given a name different from that of the parameter.

The type argument serves as an aid when the function is called with tuns equal to NULL. Itmust match the tunable parameter’s internal type (e.g. INFOMAT_DOUBLE).

If successful, the function returns 0. In case of an error, -1 is returned and an error messagewill be issued to the CarMaker log.

CarMaker Programmer’s Guide Version 2.1.6

Page 86: IPG_CarMaker Programmers Guide

86Integrating Simulink models

CarMaker’s tunable parameter interface

The function is intended to be used from within DeclParameterQuants() in the model wrap-per. In the latter context an appropriate tuns handle is available by default.

Examples

MatSupp_TunDDictDefScalar(tuns, “MyParam”, INFOMAT_SINGLE, “kappa”, “kg/s”);

/* Use the automatically generated model name as a prefix. */MatSupp_TunDDictDefScalar(tuns, “MySwitch”, INFOMAT_UINT32, QUOTE(MODEL) “.enable”, “”);

/* Use a fixed model name as a prefix. */MatSupp_TunDDictDefScalar(tuns, “MySwitch”, INFOMAT_UINT32, “MyModel.enable”, “”);

CarMaker Programmer’s Guide Version 2.1.6

Page 87: IPG_CarMaker Programmers Guide

87Integrating Simulink models

Miscellaneous

5.6 Miscellaneous

5.6.1 Upgrading to a new CarMaker version

When upgrading to a new CarMaker version, always be sure to update your cmenv.m scriptas well:

• Either replace it with its successor, to be found in Examples/Car_Generic/mdl/cmenv.m in the installation directory of the new CarMaker version (recommended).

• Or change the setting of the cminstdir variable in the first few lines of your cmenv.mscript and make it point to the new version.

There might be other files, too, that may need to be updated. Check the wrapper sourcecode and regenerate you model C code. The Release Notes document coming withCarMaker will provide you with the necessary information.

5.6.2 Integration of more than one model

Integration of more than one Simulink model into CarMaker should be possible withoutproblems, if the following conditions are met:

• The C code for all Simulink models was generated using the same version of Matlab.

• The C code for all Simulink models was generated using the same version ofCarMaker’s Matlab Support Package.

Failure to meet these conditions may lead to errors while linking the CarMaker executableor to subtle problems during simulation.

5.6.3 Using blocks from the CarMaker for Simulink blockset

...

5.6.4 CarMaker and Matlab installed on different computers

If CarMaker and Matlab are not available on the same computer, two problems arise:

• C code generation with Real-Time Workshop is not possible because the CarMaker tar-get is not available on the Matlab host.

• Compiling the model library of a Simulink model is not possible because the necessaryMatlab *.h include files are not available on the CarMaker host.

A solution exists for both problems.

Making the CarMaker target available on the Matlab host

The text below describes the steps for a CarMaker host running Linux and a Matlab hostrunning MS Windows, but operating systems used don’t really play an important role here.The same technique also applies to scenarios with a different “operating system mix”; ofcourse OS specific file and directory names need to be adapted accordingly.

Copying theCarMaker target

directory

Copy the directory containing the CarMaker target

/opt/ipg/hil/<version>/Matlab

(i.e. the one in the installation directory of the CarMaker version you use) from the CarMakerhost to the Matlab host. Be sure that the copy is complete and includes all subdirectories.

CarMaker Programmer’s Guide Version 2.1.6

Page 88: IPG_CarMaker Programmers Guide

88Integrating Simulink models

Miscellaneous

All S-functions coming with the CarMaker target need to be recompiled for the Matlab ver-sion installed on the Matlab host. For this reason the source code of all S-functions is partof the package.

Start Matlab and change to the directory of the CarMaker target that matches your Matlabversion (here version 6.5.1 is assumed):

>> cd <location_of_the_copy_you_made>/Matlab/v6.5.1-r13

Invoke the m-file script that recompiles all S-functions:

>> mksfun

The compilation process should proceed without any warnings or errors.

After compilation is done, check that the following files exist in your current working direc-tory:

>> dir *.dllmhdefhil.dllmhfromhil.dllmhfromhilvar.dllmhtohil.dllmhtohilvar.dll

If all files exist, you’re done. The CarMaker target for Real-Time Workshop is ready for use.

Generating Ccode

In order to use the CarMaker target on the Matlab system, it’s directory must be added toMatlab’s search path. This was described in detail at the beginning of this manual. But sincethe Matlab system is without a proper CarMaker installation, the cmenv.m script will verylikely not work. That means before you can use the package you have to issue the the nec-essary command in Matlab manually (or put it into a small m-file script). In our case, thecommand looks like:

>> addpath <location_of_the_copy_you_made>/Matlab/v6.5.1-r13)

After that everything should work as described in the other chapters of this manual. C codegeneration with Real-Time Workshop and the CarMaker target should be possible withoutany problems.

Make sure that the Generate code only checkbox in the Real-Time Workshop tab of theSimulation parameters dialog is checked, since compilation can only be done on theCarMaker system. Thus, after code generation is complete, all generated files must betransfered to the CarMaker system.

Important note When transfering files between the CarMaker host and the Matlab host, make absolutelysure that you use 100% identical file names on both sides. Beware of subtle differences interms of upper/lower case of characters.

Differing filenames may lead to compilation errors on the CarMaker system. Both the gen-erated C code and the generated Makefile contain the original file names and identifiersderived from them and are very sensitive to changes in the naming of files.

“File not found”, “No such file or directory” oder “Don’t know how to make XXX” when com-piling a model are typical indications of unexpectedly renamed files.

Making the Matlab include files available on the CarMaker host

A supplemental CarMaker package (CarMaker-matinc-XX.tgz ) containing the Matlabinclude files is available on request. Simply add the package to your CarMaker installationusing the IPG installer.

CarMaker Programmer’s Guide Version 2.1.6

Page 89: IPG_CarMaker Programmers Guide

89Integrating Simulink models

Miscellaneous

In order to make use of the newly installed include files, Real-Time Workshop must beinformed that the include files can be found somewhere in the CarMaker installation direc-tory. Open the Simulation / Simulation Parameters... dialog of your model. On the Real-Time Workshop tab, the code generation options for the CarMaker target must be changedas follows:

• Category: CarMaker code generation options

• Matlab include path: $(MATSUPP_DIR)/matlab

Now regenerate the C code of your model.

If regeneration of the C code is not an option, an alternative would be to edit the generatedXXX.mk Makefile of your model C code and change the value of the CM_MATINCPATH vari-able to the above mentioned value:

CM_MATINCPATH = "$(MATSUPP_DIR)/matlab"

After the changes are made, you should be able to compile the model library without a Mat-lab installation available on the CarMaker host.

5.6.5 Troubleshooting

Real-Time Workshop automatically deletes files

Since Matlab version 6.0, Real-Time Workshop places the C code files generated from aSimulink model in a subdirectory <ModelName>_<TargetName>_rtw. Since Matlab version6.5, Real-Time Workshop, before generating new code, automatically does a cleanup in thissubdirectory and deletes files it considers to be “old” or “temporary”.

This behaviour may collide with the common practice of keeping additional user code need-ed to compile the model in this directory. C code files, as well as e.g. customized Makefilesare affected.

Closer observation shows that files containing the text “target specific file” in the very firstline will not be touched or deleted by Real-Time Workshop, so this might be a workaroundto the problem. Nevertheless it seems to be safer to keep user code files in a different placeand not in the subdirectory obviously under Real-Time Workshop’s control.

Integration of multiple models leads to link error

The C code generated by Real-Time Workshop contains a function rt_CallSys(). This func-tion has global scope, which makes the linker issue a “duplicate definition error” when link-ing two ore more Simulink models into CarMaker.

Since rt_CallSys() doesn’t seem to be used anywhere in the code or in the runtime library,a possible workaround is commenting out the function completely in the generated sourcecode. The drawback of this method is, that each time you generate code from one of theSimulink models, you’ll have to repeat this step.

CarMaker Programmer’s Guide Version 2.1.6

Page 90: IPG_CarMaker Programmers Guide

90Integrating Simulink models

Demonstration examples

5.7 Demonstration examples

The CarMaker target for Real-Time Workshop comes with several example models. Theycan be found under Examples/RTW in the CarMaker installation directory:

• BodyCtrl

• TractCtrl

• UserSteer

All examples are complete with source code and parameter files.

5.7.1 Contents of the examples directory

Each example XXX typically consists of the following parts:

• README-XXX.txtText file containing a detailed description of the example.

• mdl/XXX.mdlmdl/XXX_CarMaker_rtw/XXX_wrap.hmdl/XXX_CarMaker_rtw/XXX_wrap.cSimulink model of the example, together with the wrapper source files.

• src_XXXDirectory containing everything needed to build a CarMaker simulation program withthe example model integrated.

• Data/TestRun/Examples/Simulink/...Data/Vehicle/...Testrun and vehicle parameter files needed to run the example.

5.7.2 Preparing the examples

Before you can actually use the examples, some preparation is necessary.

Copying the examples into your project directory

The example directory contains nothing but the examples and is by no means a completeproject directory. Instead it is intended to be added to a fresh project directory derived fromthe standard Examples/Car_Generic .

Simply copy the complete contents of the Examples/RTW directory into a new project direc-tory. Everything should fall into place and after the few remaining steps described beloweverything should be ready for your first simulation.

Choosing the right mdl directory

Since the model C code generated by Real-Time Workshop may differ significantly depend-ing on the Matlab version actually used, three mdl directories are provided, one for eachmajor Matlab version:

• mdl61 – for Matlab version 6.1

• mdl65 – for Matlab versions 6.5 and 6.5.1

• mdl70 – for Matlab versions 7.0, 7.0.1 and 7.0.4

Pick the directory that fits your Matlab version and either rename it to mdl or copy its con-tents to an existing mdl directory. The files in src_XXX expect their remaining model partsto be found in the mdl directory.

CarMaker Programmer’s Guide Version 2.1.6

Page 91: IPG_CarMaker Programmers Guide

91Integrating Simulink models

Demonstration examples

You probably won’t need the other mdl directories so you may safely remove them from yourproject directory.

Setting the right Matlab version in the Makefiles

Just like choosing the right mdl directory, the Makefiles need to know which Matlab versionyou are using. Unfortunately this is hard to determine automatically.

In order to use example XXX, open src_XXX/Makefile using your favourite ASCII editorand change the line

MATSUPP_MATVER = v6.5.1-r13

using one of the following values:

v6.1-r12.1v6.5-r13v6.5.1-r13v7.0-r14v7.0.1-r14v7.0.4-r14

5.7.3 Rebuilding an example

A complete rebuild of example XXX just takes a few steps.

• In the mdl directory, generate the C code of model XXX.mdl .

• Compile the C code generated in directory mdl/XXX_CarMaker_rtw .

• Rebuild the CarMaker simulation program in the src_XXX directory.

These are the same steps as described in the chapter "Step-by-Step: Integrating a Simulinkmodel".

CarMaker Programmer’s Guide Version 2.1.6

Page 92: IPG_CarMaker Programmers Guide

92CarMaker for Simulink

Demonstration examples

Chapter 6

CarMaker for Simulink

CarMaker for Simulink is a complete integration of IPG’s vehicle dynamics simulation soft-ware, CarMaker, into The MathWorks’ modeling and simulation environment, Matlab/Simu-link. The highly optimized and robust features of CarMaker were added to the Simulinkenvironment using an S-Function implementation and the API functions that are providedby Matlab/Simulink. CarMaker for Simulink is not a loosely coupled co-simulation but aclosely linked combination of the two best-in-class applications, resulting in a simulationenvironment that has both good performance and stability.

Because of this integration, it is now possible to use the power and functionality ofCarMaker in the intuitive and full-featured environment of Simulink. And using CarMaker inSimulink is no different than using standard S-Function blocks or built in Simulink blocks.The CarMaker blocks are connected the same way other Simulink blocks are connected,and existing Simulink models can now easily be added to the CarMaker vehicle model withliterally a few clicks of the mouse.

Integration does not, however, mean a loss of functionality, as all the features that makeCarMaker the premier software in its domain have been included, and can now be used inconjuction with Simulink’s rich tool set. The CarMaker GUI can still be used for simulationcontrol and parameter adjustments, as well as defining maneuvers and road configurations.IPG-CONTROL can still be used for data analysis and graphing. IPG-MOVIE can still beused to bring the vehicle model to life, with realistic animation and rendering of the multi-body vehicle model in 3-Dimensional space.

Access to CarMaker simulation results is possible using the cmread utility that can be calledfrom within Matlab. This utility loads the data of any CarMaker simulation results file into theMatlab workspace. After that, the data can be manipulated and viewed, e.g. for postpro-cessing purposes, using any of the available Matlab tools.

In short, CarMaker for Simulink is not a stripped down version of the original, but a completesystem that can become a part of any Simulink simulation quickly and easily. This chapterof the Programmer’s Manual will show you just how easy it can be.

CarMaker Programmer’s Guide Version 2.1.6

Page 93: IPG_CarMaker Programmers Guide

93CarMaker for Simulink

CarMaker for Simulink basics

6.1 CarMaker for Simulink basics

6.1.1 Creating a new CarMaker project directoryWorking with CarMaker for Simulink is organized around a so called project directory. Eachproject directory has a fixed directory structure with subdirectories like Data, SimInput,SimOutput, src, mdl etc. The mdl subdirectory is intended as the default place whereto keep the CarMaker for Simulink models.

In order to start modeling you need to make a fresh copy of the Car_Generic_SL templateproject directory. This directory is part of the examples that come with CarMaker and canusually be found in

/opt/ipg/hil/linux-2.1/Examples/Car_Generic_SL

and on MS Windows systems in

c:\ipg\hil\win32-2.1\Examples\Car_Generic_SL

of the installed product.

Making a copy of Car_Generic_SL gives you a ready-to-run Simulink model with an initialset of CarMaker for Simulink blocks, some example Simulink models, a clean set ofCarMaker configuration files for a simple vehicle and several test runs.

Start with these files and modify or extend them step by step according to your needs.

6.1.2 Starting Matlab

Matlab and CarMaker for Simulink work together by extending Matlab’s search path, so thatMatlab knows where to find CarMaker for Simulink’s blockset and auxiliary commands. TheMatlab search path is extended by execution of a small script named cmenv.m , which iscontained in the mdl subdirectory of a CarMaker project directory. Execution of this scriptmay be done manually, but there’s also a way to invoke it automatically each time Matlab isstarted or a model is loaded.

The golden rule is: Always keep the cmenv.m script in the same directory as your Simulinkmodel. Whenever you load a Simulink model which contains the CarMaker subsystem blockfrom the CarMaker for Simulink blockset, cmenv.m will be executed automatically. Thisdefault behaviour should be sufficient for most uses of CarMaker for Simulink.

Alternatively, you may want to make use of Matlab’s startup file, i.e. a file called startup.min Matlab’s working directory will be executed automatically when Matlab is started. Justmake sure that cmenv is invoked in your startup.m file and you’re done. The advantage ofthis method is that the search path is setup for CarMaker without having to load a Simulinkmodel first. See your Matlab documentation for further details about the Matlab startupoptions.

Starting Matlab under Unix

In your shell (probably running in an xterm or some other console window) change to themdl subdirectory of your CarMaker project directory, then simply start Matlab:

% cd </path/to/your/project_dir>/mdl% matlab

Depending on how you set up your working directory (see above), you may have to load aCarMaker for Simulink model or invoke cmenv.m manually:

>> cmenv

CarMaker Programmer’s Guide Version 2.1.6

Page 94: IPG_CarMaker Programmers Guide

94CarMaker for Simulink

CarMaker for Simulink basics

The cmenv.m script should issue a message like the following in your Matlab console win-dow:

CarMaker directory: /opt/ipg/hil/linux-2.1addpath /opt/ipg/hil/linux-2.1/Matlabaddpath /opt/ipg/hil/linux-2.1/Matlab/v6.1-r12.1addpath /opt/ipg/hil/linux-2.1/CM4SLaddpath </path/to/your/project_dir>/srcInitialize CarMaker for Simulink.Done.

Starting Matlab under Windows

Starting Matlabusing Windows

Explorer

In Windows Explorer, simply double click on a Simulink model’s .mdl file in the mdl subdi-rectory of your CarMaker project directory. This will automatically start Matlab with mdl asits current working directory.

Starting Matlabusing a desktop

shortcut

An alternative way of starting Matlab is by creating a desktop shortcut to one of your Simu-link models’ .mdl file. In the shortcut’s properties dialog then, set the working directory tothe path the mdl subdirectory of your CarMaker project directory. Matlab may then be start-ed by double-clicking on the desktop shortcut’s icon and your model will be loaded automat-ically.

Depending on how you set up your working directory (see above), you may have to load aCarMaker for Simulink model or invoke cmenv.m manually:

>> cmenv

The cmenv.m script should issue a message like the following in your Matlab console win-dow:

CarMaker directory: c:/ipg/hil/win32-2.1addpath c:/ipg/hil/win32-2.1/Matlabaddpath c:/ipg/hil/win32-2.1/Matlab/v6.1-r12.1addpath c:/ipg/hil/win32-2.1/CM4SLaddpath <x:/path/to/your/project_dir>/srcInitialize CarMaker for Simulink.Done.

6.1.3 Creating a new model

You can start building your own model by extending the generic.mdl model that is part ofevery CarMaker project directory, but you may create a new CarMaker for Simulink modelfrom scratch as well.

Creating a new model is only a matter of drag’n’drop. Open the CarMaker for Simulinkblockset (in the Simulink library, under Blocksets & Toolboxes, double click on the CarMakerfor Simulink block). From the blockset window that opens drag’n’dop at least the followingtwo blocks into your empty model:

• the block labeled Open GUI

• the subsystem block labeled CarMaker

The CarMaker Model Configuration block is optional; you may add it any time later.

CarMaker Programmer’s Guide Version 2.1.6

Page 95: IPG_CarMaker Programmers Guide

95CarMaker for Simulink

CarMaker for Simulink basics

Your model should now look like this:

CarMaker for Simulink works with all standard Simulink solvers. No special solver settingsare required to run a CarMaker for Simulink model.

Normally, however, CarMaker for Simulink should be given control of the simulation, i.e. asimulation should stop according to the criteria configured in a test run. Examples for suchcriteria: A certain distance that has been driven, an error condition met and, of course, atotal time elapsed. This requires the simulation stop time in Simulink to be set to inf , i.e.from Simulink’s point of view it should run forever.

To set the simulation stop time, select Simulation / Simulation Parameters from the modelwindow’s menu bar. The entry field for the simulation stop time is on the Solver tab.

After that, your model is ready for simulation.

6.1.4 Starting the CarMaker GUI

The single tool central to all work with CarMaker for Simulink is the CarMaker GUI. It is usedfor configuration of test runs and other parts of the CarMaker environment. A runningCarMaker GUI is required to perform any simulation with CarMaker for Simulink.

The easiest way to start the CarMaker GUI is to double click on the CarMaker GUI block ofyour Simulink model. If no CarMaker GUI is running, a new one will be started. If aCarMaker GUI is already running, its window will pop up and come to the foreground.

The CarMaker GUI may as well be started from the Matlab console. This does not requireany model to be already loaded. Use the following command:

>> CM_Simulink

6.1.5 Running a simulation

You may start and stop a simulation the way you normally do with Simulink, i.e. by invokingStart or Stop from the Simulation menu of your model window.

In CarMaker for Simulink, there’s a (possibly easier accessible) alternative: The big greenand red Start and Stop buttons of the CarMaker GUI.

Both ways of controlling a simulation may be mixed freely, e.g. you may start a simulationfrom the CarMaker GUI, then stop it via the model window and vice versa.

Figure 6.1: A newly created model

CarMaker Programmer’s Guide Version 2.1.6

Page 96: IPG_CarMaker Programmers Guide

96CarMaker for Simulink

CarMaker for Simulink basics

6.1.6 Switching between several Simulink models

In case you have several models loaded in Simulink, the question is: When using the Startbutton of the CarMaker GUI, how does the CarMaker GUI know, which model to start?

In the rare case the CarMaker GUI can’t find out itself, it will ask you (see dialog shownbelow). Otherwise the CarMaker GUI will simulate the model that was simulated last.

To switch to a different model, either double-click on the model’s CarMaker GUI button orexplicitly invoke a simulation from that model’s window. Next time you press the green Startbutton in the CarMaker GUI, the new model will be simulated.

6.1.7 Switching between several CarMaker project directories

During your Matlab session with CarMaker for Simulink you may change Matlab’s currentworking directory to another CarMaker project directory. CarMaker for Simulink will noticethe change and ask you what to do. Normally changing to another project directory requiresthe GUI to be restarted.

6.1.8 Dealing with the start values of your model

...

In the CarMaker GUI use Simulation / Determine Start Values to take a snapshot of thevehicle state at an arbitrary time during a testrun. CarMaker will store the current vehiclestate into the SimOutput/<hostname>/Snapshot.info file. See the CarMaker ReferenceManual for details.

Use the cmstartcond command on the Matlab console to read the start values into theMatlab workspace. The workspace variables containing the start values can then be usedto parametrize blocks of the Simulink model. This may be done automatically each time asimulation starts using one of Simulink’s model callback functions. See the Simulink manualfor details.

...

Figure 6.2: CarMaker asking which model to use

CarMaker Programmer’s Guide Version 2.1.6

Page 97: IPG_CarMaker Programmers Guide

97CarMaker for Simulink

CarMaker for Simulink basics

6.1.9 Working in a non-default model directory

The default place for your Simulink models is in the mdl subdirectory of your Car Makerproject directory. You may, however, want to organize things differently and keep your mod-els, parameter files etc. in a different place.

When CarMaker for Simulink starts, it tries to find the directories containing configurationinformation about the vehicle, test runs etc. The directory names are SimInput,SimOutput, Movie, Data etc. In the Car_Generic_SL template you will find them paral-lel to the model directory, mdl .

The search strategy to locate the configuration directories is as follows: Starting in your cur-rent working directory (i.e. the directory where you started Matlab), CarMaker for Simulinkworks its way upward through the entire directory tree and checks for a complete set of theconfiguration directories. Once they are found, the search stops. Once the topmost direc-tory is reached and nothing is found, an error message will be issued.

That means you can place your model(s) in a directory parallel to the configurations direc-tories (like the standard mdl directory) or in a subdirectory somewhere below, allowing youto organize things in a flexible way. In the latter case, however, be sure to adapt your localcmenv.m file to the new directory organizsation, so that Matlab still has the src directory inits search path (important if you rebuilding the model library).

6.1.10 Upgrading to a new CarMaker version

When upgrading to a new CarMaker version, always be sure to update your cmenv.m scriptas well:

• Either replace it with its successor, to be found in Examples/Car_Generic_SL/mdl/cmenv.m in the installation directory of the new CarMaker for Simulink version (recom-mended).

• Or change the setting of the cminstdir variable in the first few lines of your cmenv.mscript and make it point to the new version.

There might be other files, too, that must be updated. The Release Notes of everyCarMaker version will provide you with the necessary information.

In case you’re working with a CarMaker model library that you’ve compiled and linked your-self (i.e. you’ve made some changes to the C code) it is also required that you rebuild themodel library. When you invoke libcarmaker4sl from the Matlab command line, the Appli-cation.Version line shows you (in parentheses) the CarMaker for Simulink version yourmodel library was built for.

6.1.11 Troubleshooting

When I want to run a simulation, I get the following error message:Minimum step size (...) is larger than the fastest discrete samplingperiod (0.001) time.

Simulink will not allow you to set a solver step size greater than 0.001 seconds in modelscontaining CarMaker for Simulink blocks. The reason for this is the internal configuration ofthe CarMaker for Simulink blocks, which use a fixed sample time of one millisecond.

CarMaker Programmer’s Guide Version 2.1.6

Page 98: IPG_CarMaker Programmers Guide

98CarMaker for Simulink

CarMaker for Simulink basics

After trying to add or remove blocks of the active CarMaker modelwhile the simulation is running, suddenly the Start/Stop buttons of theCarMaker GUI do not work anymore.

This behaviour has been observed with Matlab 6.5 and later versions under MS Windows.After closing the error message window telling you "Cannot change the model ... while thesimulation is running", there seems to be some disorder in Matlab’s event processing. Youmay stop the simulation using Simulation / Stop from the model’s window, however. Afterthe simulation has been stopped, the buttons of the CarMaker GUI will work again asexpected.

S-functions using ssGet/SetUserData(ssGetRootSS(SimStruct *S)) donot work or cause Matlab to crash.

During a simulation of a Simulink model CarMaker for Simulink relies on having completecontrol over the user data pointer associated with the model. Adding an S-function to aCarMaker for Simulink model, that makes use of the pointer itself, would seriously confuseCarMaker for Simulink, resulting in Matlab crashes and possible loss of data. This situationis not likely to change in the future.

When I start CarMaker for Simulink, I see the following message:

Warning: CarMaker command engine task could not be startedCarMaker will be fully functional, but can only starta simulation in Simulink. The CarMaker GUI’s start/stopbuttons, Model Check, Driver Adaption, ScriptControletc. won’t work

This message is most often seen when Java is not properly enabled in Matlab or when try-ing to use Matlab 6.1 on a SuSE Linux 9.x system.

When I try to simulate, I see the following message:

libcarmaker4sl.mexglx: missing symbol: CarMaker4SL_CMLib

You’re trying to use a model library compiled with CarMaker 2.0 or older. Please updateboth your Simulink model and model library C code and recompile your model library.

CarMaker Programmer’s Guide Version 2.1.6

Page 99: IPG_CarMaker Programmers Guide

99CarMaker for Simulink

Using the C language interface

6.2 Using the C language interface

The C language interface of CarMaker for Simulink is almost 100% compatible withCarMaker/HIL and its cousin for standalone simulations. The differences are located mostlyin the initialization and shutdown code of the model library.

6.2.1 Rebuilding the model library

The part of CarMaker for Simulink, that does the actual numerical calculations for each timestep, is called the model library. The model library is implemented as a separate modulethat can be extended and rebuilt by the user. A prebuilt version of the model library can befound in the CarMaker for Simulink installation directory. This is also the default library thatis normally used as long as no custom library was built. Matlab’s search path is used todetermine which version of the model library is “the right one”. See below for details.

Rebuilding on Unix platforms (and on Windows using MinGW)

Rebuilding the model library is a matter of invoking the make command in the src directory,like this:

% cd src% make

This will produce a libcarmaker4sl.mexglx (or .dll , depending on the Matlab platform).

Rebuilding under Windows using Microsoft Visual C

CarMaker for Simulink provides a makefile for Microsoft Visual C 6.0. The file is called src/Makefile.vc and is intended for use with Microsoft’s nmake command line utility.

Using nmake requires that your account’s environment is set up properly, i.e. the commandsearch path and several environment variables are set correctly for use with the Microsoftcompiler. If unsure, try executing the file called VCVARS32.BAT(to be found in the compil-er’s installation directory) in your command window once. After that, you should be able touse the Microsoft compiler and its utility programs from the command line.

To rebuild the CarMaker for Simulink model library in a command window, make sure thatyour current working directory is the src directory, then type

nmake /f Makefile.vc

Just like its Unix counterparts, the makefile will produce a libcarmaker4sl.dll .

6.2.2 Identifying which model library you are using

The CarMaker for Simulink model library can actually be invoked as a Matlab command.This can be used in two ways.

First, the model library is located using the Matlab search path. To find out about the loca-tion of the model library in use, at the Matlab prompt try Matlab’s which command:

>> which libcarmaker4sl/space/myproject/esp/src/libcarmaker4sl.mexglx

If you did not recompile the model library, the output will probably point to the library in theCarMaker for Simulink installation directory.

The search path itself is set in the mdl/cmenv.m script of your project directory. The scriptextends the search path to search your project’s src directory first and CarMaker for Simu-link’s installation directory next. That is, a model library in your src directory is always pre-

CarMaker Programmer’s Guide Version 2.1.6

Page 100: IPG_CarMaker Programmers Guide

100CarMaker for Simulink

Using the C language interface

ferred to the CarMaker for Simulink’s default model library. You may inspect the currentsearch path with Matlab’s path command. Depending on how you organize your projectsource code it might make sense to edit mdl/cmenv.m to have a different configuration ofthe Matlab search path.

Second, when called directly, the model library gives you information about itself, e.g. whenand how it was created. At the matlab prompt, type the following command and check theoutput:

>> libcarmaker4sl

Application.Version = Car_Generic ?.?Application.BuildVersion = 8Application.CompileTime = 2004-01-14 18:19:52Application.CompileBy = fhApplication.CompileSystem = dagobert.ipg.deApplication.CompileFlags: -O3 -DNDEBUG -DLINUX -D_REENTRANT -Wall -Wimplicit -Wmissing-prototypes -D_GNU_SOURCE -DCM_SINGLE_THREADS -DCM4SL -fPIC -pthreadApplication.Libs: libcar4sl.a libcarmaker4sl.a libipgroad.a libipgdriver.a

6.2.3 Integrating model C code built with Real-Time Workshop

CarMaker for Simulink is compatible with the CarMaker interface blockset . The CarMakertarget.can be used with a model to generate C code using Real-Time Workshop. The Ccode can then be integrated into CarMaker for Simulink on the C code level just like withCarMaker/HIL or CarMaker for standalone applications.

Please note, however, that generation of C code from a CarMaker for Simulink model is notsupported.

CarMaker Programmer’s Guide Version 2.1.6

Page 101: IPG_CarMaker Programmers Guide

101CarMaker for Simulink

The CarMaker for Simulink blockset

6.3 The CarMaker for Simulink blockset

You may find the CarMaker for Simulink blockset in the Simulink library browser, underBlocksets and Toolboxes. Double click on CarMaker for Simulink, or simply type

>> CarMaker4SL

in Matlab’s command window (assuming your Matlab search path was set up properly).

The CarMaker for Simulink blockset should not be confused with the Matlab Support forCarMaker blockset, which serves a different purpose. See the CarMaker Programmer’sManual for details.

6.3.1 General information

Block properties

The CarMaker for Simulink blocks of the CarMaker subsystem are direct feed through andrun with a fixed step size of 1 ms, independently of the rest of the model.

CarMaker for Simulink blocks do not have continuous states in the Simulink sense of theword. They do have internal state variables but these are integrated using CarMaker inter-nal solvers independently of Simulink.

Modeling principles

The CarMaker for Simulink simulation model is made up of a subsystem containing a chainof individual blocks. When Simulink executes CarMaker, all blocks of this CarMaker blockchain must be executed in order and exactly once. Algebraic loops involving individualblocks of the CarMaker block chain are not permitted.

Figure 6.3: Simulink library browser (Unix): Blocksets und Toolboxes

Figure 6.4: Simulink library browser (Unix): CarMaker for Simulink blockset

CarMaker Programmer’s Guide Version 2.1.6

Page 102: IPG_CarMaker Programmers Guide

102CarMaker for Simulink

The CarMaker for Simulink blockset

Replacing existing CarMaker functionality with Simulink blocks can be done by

• overriding signals and

• disabling unneeded internal CarMaker funcionality using special parameters

It can NOT be done by

• replacing, removing or reordering CarMaker blocks

For further details please see the demonstration examples and their description in this man-ual.

Purpose of the Sync_In and Sync_Out ports

The Sync_In and Sync_Out ports are an important concept in CarMaker for Simulink.

• They guarantee proper order of executation of the CarMaker blocks.

• They let you choose exactly when a CarMaker dictionary variable is accessed with aRead CM Dict or Write CM Dict block. You may want to read the most up to date valueof a variable (and not the value calculated in the previous cycle) or override the value ofa variable only after it’s been calculated internally by CarMaker.

6.3.2 Utility blocks

Open GUI

The Open GUI block is used to connect the Simulink model to a running CarMaker GUI pro-cess. If no running GUI can be detected the user will be prompted to open a new CarMakerGUI, to manually reconnect from the undetected CarMaker GUI, or to cancel the attempt toconnect to the CarMaker GUI.

Double clicking the Open GUI block may also be used to switch between models, i.e. to“activate” a certain model in case several models are loaded in Matlab. The “active” modelis the one that will be simulated when you click the Start button in the CarMaker GUI.

CarMaker Model Configuration

This block has been provided as a place to keep some settings specific to a CarMaker forSimulink model. The block is not required in order to run a model.

Figure 6.5: CarMaker Model Configuration dialog

CarMaker Programmer’s Guide Version 2.1.6

Page 103: IPG_CarMaker Programmers Guide

103CarMaker for Simulink

The CarMaker for Simulink blockset

Server application name

The server application name is the name under which you can identify your currentCarMaker for Simulink session in e.g. IPG-CONTROL. Try File / Connect To Applica-tion... in the IPG-CONTROL main window to see the list of all APO applications currentlyrunning on hosts of your network. Each line displayed in this list is the server applicationname of a running APO application.

If your model does not contain a CarMaker Model Configuration block or the Server appli-cation name entry of the block is left empty, something like CarMaker 2.1 - Car_Generic ischosen as the server application name of your current CarMaker for Simulink session.

Almost all examples models in the mdl_examples subdirectory of Car_Generic_SL usetheir own model specific server application name.

Command line arguments

This entry makes it possible to pass special options to CarMaker when running yourCarMaker for Simulink model. Examples are the -disableXXX flags to tell CarMaker tobypass one of its internal modules and use the values computed by your Simulink modelinstead.

Besides the options described in this manual, being able to specify CarMaker commandline arguments is mainly intended for internal development and debugging purposes. Enter-help and start a simulation to get a generic list of available CarMaker command lineoptions. Please note that not all options displayed have been verified to make much sensein CarMaker for Simulink or even yield meaningful results. Use this feature with care.

6.3.3 CarMaker dictionary blocks

Read CM Dict

The Read CM Dict block reads a variable in the CarMaker dictionary and provides its cur-rent value on the block’s output port. The variable needs not to be defined with a Define CMDict block in the model; any existing dictionary variable may be read.

Enter the name of the variable in the block parameters dialog of the block. In the model, thename will be displayed inside the block’s symbol.

When a non existent dictionary variable is given as a parameter of a Read CM Dict block,Simulink will report the following error at the start of a simulation:

Variable ’abcde’ not in dictionary

Figure 6.6: Read CM Dict block parameter dialog

CarMaker Programmer’s Guide Version 2.1.6

Page 104: IPG_CarMaker Programmers Guide

104CarMaker for Simulink

The CarMaker for Simulink blockset

Write CM Dict

The Write CM Dict block writes the current value at the block’s input port to a variable in theCarMaker dictionary. The variable needs not to be defined with a Define CM Dict block inthe model; any existing dictionary variable may be written to.

Enter the name of the variable in the block parameters dialog of the block. In the model, thename will be displayed inside the block’s symbol.

When a non existent dictionary variable is given as a parameter of a Write CM Dict block,Simulink will report the following error at the start of a simulation:

Variable ’abcde’ not in dictionary

Define CM Dict

A Simulink model can define its own variables in the CarMaker dictionary, because theremay be signals that are to be monitored with IPG-CONTROL or accessed using Direct Vari-able Access. Also, only signals defined in the CarMaker dictionary can be saved as part ofa CarMaker simulation results file.

The Def CM Dict block defines a variable in the CarMaker dictionary.

When you define a dictionary variable in Simulink model, it is recommended to prefix itsname with the model’s name or with a convenient abbreviation. This makes it easier for youto identify the model’s variables in the dictionary with tools like the CarMaker GUI or IPG-CONTROL. Example: A dictionary variable xyz defined in a Simulink model called MyModelshould be given the name MyModel.xyz or MM.xyz .

Figure 6.7: Write CM Dict block parameter dialog

CarMaker Programmer’s Guide Version 2.1.6

Page 105: IPG_CarMaker Programmers Guide

105CarMaker for Simulink

The CarMaker for Simulink blockset

Be careful not to define a dictionary variable with the Define CM Dict block that is alreadydefined somewhere else. Currently no error message will be issued in this case.

Enter the name of the variable in the block parameters dialog of the block. In the model, thename will be displayed inside the block’s symbol.

The variable may also be given a unit, this is recommended but optional. See IPG-CON-TROL for units used with CarMaker. Specifying a unit serves as some kind of documenta-tion about the variable, but also allows IPG-CONTROL to display it on the same axis withother dictionary variables of the same unit.

If the variable’s values are strictly monotonic increasing over time, you should check theStricly monotone checkbox. Again, this is an information that tools like IPG-CONTROLneed for proper display of the variable’s values.

Choose the variable’s type according to your needs and the range of values of the variable.You may choose between two floating point types and six integer types. When in doubt useDouble.

For discrete variables (any of the integer types), if the range of values starts at 0 and hasan reasonably small upper limit (e.g. an indicator light that is either on or off), it may makesense to specify the number of discrete states of the variable. For the indicator light therewould be 2 discrete values (0=off, 1=on). Again this is information is provided mainly forIPG-CONTROL which displays variables with a limited number of states in a special, spacesaving way. Specifying a value of 0 in this field means that no special state info is available.For the Double and Float type, the value of this field is ignored.

Dictionary initialization

When CarMaker for Simulink has been started, but before the first simulation is run, theCarMaker dictionary does not yet know about any additional dictionary variables that will bedefined in your model. To make these variable known to CarMaker for Simulink at startup,you may create a file called startup.dict in your model directory, that describes theirproperties.

The file is in plain ASCII and may contain empty lines, comment lines starting with “#”, andlines defining dictionary variables. Each line containing a variable definition consists of 5columns, separated by tabs and spaces:

• Column 1: The name of the variable.

• Column 2: The unit of the variable. A “-” (minus, hyphen) character means “no unit”.The unit is used only for display purposes, in tools like IPG-CONTROL. CarMaker forSimulink internally uses SI units, no automatic unit conversion whatsoever takes place.

Figure 6.8: Define CM Dict block parameter dialog

CarMaker Programmer’s Guide Version 2.1.6

Page 106: IPG_CarMaker Programmers Guide

106CarMaker for Simulink

The CarMaker for Simulink blockset

• Column 3: The type of the variable. Here’s a list of allowed types and their correspond-ing C type:

• Column 4: The number of states.

• Column 5: Special properties. Again, this is used only for display purposes. If the vari-able is monotonic and increasing, specify “M”. Otherwise specify “-”.

Examples:

PT.GearBox.GearNo-long 0 -PT.Engine.rotvrad/sfloat 0 -Car.Distancem float 0 M

See also the documentation of the Define CM Dict block.

6.3.4 General purpose blocks

Vehicle Sensor

The Vehicle Sensor block is the CarMaker for Simulink equivalent of CarMaker’s vehiclebody sensor facility as defined in include/Car/MBSUtils.h.With a Vehicle Sensor block youcan define a body sensor on the vehicle and receive the following information as outputs ofthe block.

Dictionary Variable Type C Data Type

double double

float float

ulong unsigned long

long signed long

ushort unsigned short

short signed short

uchar unsigned char

char signed char

Figure 6.9: Vehicle Sensor block parameter dialog

CarMaker Programmer’s Guide Version 2.1.6

Page 107: IPG_CarMaker Programmers Guide

107CarMaker for Simulink

The CarMaker for Simulink blockset

A Vehicle Sensor block has always a sync port. Connect it to the Sync_Out signal of anappropriate CarMaker for Simulink block so that its value will be calculated as late as pos-sible.

Trailer Sensor

The Trailer Sensor block is the CarMaker for Simulink equivalent of CarMaker’s trailer bodysensor facility as defined in include/Car/MBSUtils.h.Behaviour and configuration is almostidentical to the Vehicle Sensor block except that the sensor is mounted on the trailer. Fordetails see chapter , "Vehicle Sensor".

6.3.5 CarMaker subsystem

The tables in this chapter show the relationship between a signal name of the CarMakersubsystem, the corresponding C variable, and (if it exists) its name in the CarMaker dictio-nary. For most signals this information is suffient to find the place of its exact definiton in theCarMaker reference manual.

CarMaker for Simulink signals are all in SI units.

Output No. Name Description

0 – 2 Pos_1 Position (body frame)

3 – 5 Pos_0 Position (global frame)

6 – 8 Vel_1 Velocity (body frame)

9 – 11 Vel_0 Velocity (global frame)

12 – 14 Acc_1 Acceleration (body frame)

15 – 17 Acc_0 Acceleration (global frame)

18 – 20 Omega_1 Angle velocity (body frame)

21 – 23 Omega_0 Angle velocity (global frame)

24 – 26 Alpha_1 Angle acceleration (body frame)

27 – 29 Alpha_0 Angle acceleration (global frame)

30 – 32 O1O_1 Position (same as block parameters)

33 – 35 O1O_0 Position (global frame), same as Pos_1

Figure 6.10: Trailer Sensor block parameter dialog

CarMaker Programmer’s Guide Version 2.1.6

Page 108: IPG_CarMaker Programmers Guide

108CarMaker for Simulink

The CarMaker for Simulink blockset

Ambient

Ambient.Misc

DrivMan

DrivMan.Steering

DrivMan.Brake

DrivMan.PT

Ambient.Misc C Variable Dictionary Variable

Ambient Temperature Ambient.Temperature Ambient.Temperature

Ambient AirDensity Ambient.AirDensity Ambient.AirDensity

Ambient AirPressure Ambient.AirPressure Ambient.AirPressure

Ambient AirHumidity Ambient.AirHumidity Ambient.AirHumidity

DrivMan.Steering C Variable Dictionary Variable

DrivMan Steering Ang DrivMan.Steering.Ang DM.Steer.Ang

DrivMan Steering AngVel DrivMan.Steering.AngVel DM.Steer.AngVel

DrivMan Steering AngAcc DrivMan.Steering.AngAcc DM.Steer.AngAcc

DrivMan Steering Trq DrivMan.Steering.Trq DM.Steer.Trq

DrivMan Steering ByTrq DrivMan.ActualMan.SteerBy DM.SteerBy

DrivMan.Brake C Variable Dictionary Variable

DrivMan BrakeFrcMax DrivMan.BrakeFrcMax

DrivMan Brake DrivMan.Brake DM.Brake

DrivMan BrakePark DrivMan.BrakePark DM.BrakePark

DrivMan.PT C Variable Dictionary Variable

DrivMan StarterCtrl DrivMan.StarterCtrl DM.StarterCtrl

DrivMan SelectorCtrl DrivMan.SelectorCtrl DM.SelectorCtrl

DrivMan GearNo DrivMan.GearNo DM.GearNo

DrivMan Ignition DrivMan.Ignition Kl15SW

DrivMan Clutch DrivMan.Clutch DM.Clutch

DrivMan Gas DrivMan.Gas DM.Gas

CarMaker Programmer’s Guide Version 2.1.6

Page 109: IPG_CarMaker Programmers Guide

109CarMaker for Simulink

The CarMaker for Simulink blockset

Brake

Brake.IF.In

Brake.IF.Out

Brake.IF.In C Variable Dictionary Variable

Brake IF Use_pMCInput Brake.IF.Use_pMCInput

Brake IF pMC_in Brake.IF.pMC_in Brake.pMC_in

Brake IF PumpIsOn Brake.IF.PumpIsOn Brake.PumpIsOn

Brake IF BooSignal Brake.IF.BooSignal Brake.BooSignal

Brake IF T_env Brake.IF.T_env Brake.T_env

Brake Valve_In_FL Brake.IF.V[0] Brake.Valve_In_FL

Brake Valve_In_FR Brake.IF.V[1] Brake.Valve_In_FR

Brake Valve_In_RL Brake.IF.V[2] Brake.Valve_In_RL

Brake Valve_In_RR Brake.IF.V[3] Brake.Valve_In_RR

Brake Valve_Out_FL Brake.IF.V[4] Brake.Valve_Out_FL

Brake Valve_Out_FR Brake.IF.V[5] Brake.Valve_Out_FR

Brake Valve_Out_RL Brake.IF.V[6] Brake.Valve_Out_RL

Brake Valve_Out_RR Brake.IF.V[7] Brake.Valve_Out_RR

Brake Valve_PV_FRRL Brake.IF.V[8] Brake.Valve_PV_FRRL

Brake Valve_PV_FLRR Brake.IF.V[9] Brake.Valve_PV_FLRR

Brake Valve_SV_FRRL Brake.IF.V[10] Brake.Valve_SV_FRRL

Brake Valve_SV_FLRR Brake.IF.V[11] Brake.Valve_SV_FLRR

Brake IF V[12] Brake.IF.V[12]

Brake IF V[13] Brake.IF.V[13]

Brake IF V[14] Brake.IF.V[14]

Brake IF V[15] Brake.IF.V[15]

Brake.IF.Out C Variable Dictionary Variable

Brake IF pMC Brake.IF.pMC Brake.pMC

Brake IF pWB FL Brake.IF.pWB[0] Brake.pWB_FL

Brake IF pWB FR Brake.IF.pWB[1] Brake.pWB_FR

Brake IF pWB RL Brake.IF.pWB[2] Brake.pWB_RL

Brake IF pWB RR Brake.IF.pWB[3] Brake.pWB_RR

Brake IF Trq_tot FL Brake.IF.Trq_tot[0] Brake.Trq_FL _tot

Brake IF Trq_tot FR Brake.IF.Trq_tot[1] Brake.Trq_FR_tot

Brake IF Trq_tot RL Brake.IF.Trq_tot[2] Brake.Trq_RL_tot

Brake IF Trq_tot RR Brake.IF.Trq_tot[3] Brake.Trq_RR_tot

Brake IF Rel_SW Brake.IF.Rel_SW Brake.Rel_SW

Brake IF PuRetVolt Brake.IF.PuRetVolt Brake.PuRetVolt

Brake IF PistTravel Brake.IF.PostTravel Brake.PistTravel

Brake IF PedTravel Brake.IF.PedTravel Brake.PedTravel

CarMaker Programmer’s Guide Version 2.1.6

Page 110: IPG_CarMaker Programmers Guide

110CarMaker for Simulink

The CarMaker for Simulink blockset

Powertrain

The PT Engine Trq signal was implemented using the EngineControl hook and will alwaysbe one cycle late.

Using the EngineControl hook in the C level interface will collide with CarMaker for Simu-link’s PT Engine Trq signal. Results will not be as expected.

PowerTrain.Misc

Steering

Steer.IF

Brake IF DiaphTravel Brake.IF.DiaphTravel Brake.DiaphTravel

Brake.IF.Out C Variable Dictionary Variable

PowerTrain.Misc C Variable Dictionary Variable

PT WFL rot PowerTrain.WFL.rot PT.WFL.rot

PT WFR rot PowerTrain.WFR.rot PT.WFR.rot

PT WRL rot PowerTrain.WRL.rot PT.WRL.rot

PT WRR rot PowerTrain.WRR.rot PT.WRR.rot

PT WFL rotv PowerTrain.WFL.rotv PT.WFL.rotv

PT WFR rotv PowerTrain.WFR.rotv PT.WFR.rotv

PT WRL rotv PowerTrain.WRL.rotv PT.WRL.rotv

PT WRR rotv PowerTrain.WRR.rotv PT.WRR.rotv

PT Trq_Supp2Bdy1_1 PowerTrain.Trq_Supp2Bdy1[1]

PT.Trq_Supp2Bdy1.y

PT Engine on PowerTrain.Engine.on PT.Engine.on

PT Engine rotv PowerTrain.Engine.rotv PT.Engine.rotv

PT GearBox rotv_in PowerTrain.GearBox.rotv_in PT.GearBox.rotv_in

PT Engine Trq(EngineControl)

(PowerTrain.Engine.Trq) (PT.Engine.Trq)

Steer.IF C Variable Dictionary Variable

Steering IF Ang Steering.IF.Ang Steer.WhlAng

Steering IF AngVel Steering.IF.AngVel Steer.WhlVel

Steering IF AngAcc Steering.IF.AngAcc Steer.WhlAcc

Steering IF Trq Steering.IF.Trq Steer.WhlTrq

Steering IF TrqStatic Steering.IF.TrqStatic Steer.WhlTrqStatic

Steering IF L q Steering.IF.L.q Steer.L.q

Steering IF L qp Steering.IF.L.qp Steer.L.qp

Steering IF L qpp Steering.IF.L.qpp Steer.L.qpp

CarMaker Programmer’s Guide Version 2.1.6

Page 111: IPG_CarMaker Programmers Guide

111CarMaker for Simulink

The CarMaker for Simulink blockset

External Suspension Forces

Using the Suspension Forces hook in the C level interface will collide with the correspond-ing CarMaker for Simulink signals. Results will not be as expected.

lSpring

vDamp

lStabi

Steering IF L iSteer2q Steering.IF.iSteer2q Steer.L.iSteer2q

Steering IF R q Steering.IF.R.q Steer.R.q

Steering IF R qp Steering.IF.R.qp Steer.R.qp

Steering IF R qpp Steering.IF.R.qpp Steer.R.qpp

Steering IF R iSteer2q Steering.IF.R.iSteer2q Steer.R.iSteer2q

Steering IF L Frc Steering.IF.L.Frc Steer.L.Frc

Steering IF L Inert Steering.IF.L.Inert Steer.L.Inert

Steering IF R Frc Steering.IF.R.Frc Steer.R.Frc

Steering IF R Inert Steering.IF.R.Inert Steer.R.Inert

Steer.IF C Variable Dictionary Variable

lSpring C Variable Dictionary Variable

lSpring FL lSpring[0] inCar_SuspForcesHook_Calc()

Car.SpringFL.l

lSpring FR lSpring[1] inCar_SuspForcesHook_Calc()

Car.SpringFR.l

lSpring RL lSpring[2] inCar_SuspForcesHook_Calc()

Car.SpringRL.l

lSpring RR lSpring[3] inCar_SuspForcesHook_Calc()

Car.SpringRR.l

vDamp C Variable Dictionary Variable

vDamp FL vDamp[0] inCar_SuspForcesHook_Calc()

Car.DampFL.v

vDamp FR vDamp[1] inCar_SuspForcesHook_Calc()

Car.DampFR.v

vDamp RL vDamp[2] inCar_SuspForcesHook_Calc()

Car.DampRL.v

vDamp RR vDamp[3] inCar_SuspForcesHook_Calc()

Car.DampRR.v

lStabi C Variable Dictionary Variable

lStabi FL lStabi[0] inCar_SuspForcesHook_Calc()

Car.StabiFL.l

CarMaker Programmer’s Guide Version 2.1.6

Page 112: IPG_CarMaker Programmers Guide

112CarMaker for Simulink

The CarMaker for Simulink blockset

FSpring

FDamp

FStabi

lStabi FR lStabi[1] inCar_SuspForcesHook_Calc()

Car.StabiFR.l

lStabi RL lStabi[2] inCar_SuspForcesHook_Calc()

Car.StabiRL.l

lStabi RR lStabi[3] inCar_SuspForcesHook_Calc()

Car.StabiRR.l

lStabi C Variable Dictionary Variable

FSpring C Variable Dictionary Variable

FSpring FL FSpring[0] inCar_SuspForcesHook_Calc()

Car.SpringFL.Frc_ext

FSpring FR FSpring[1] inCar_SuspForcesHook_Calc()

Car.SpringFR.Frc_ext

FSpring RL FSpring[2] inCar_SuspForcesHook_Calc()

Car.SpringRL.Frc_ext

FSpring RR FSpring[3] inCar_SuspForcesHook_Calc()

Car.SpringRR.Frc_ext

FDamp C Variable Dictionary Variable

FDamp FL FDamp[0] inCar_SuspForcesHook_Calc()

Car.DampFL.Frc_ext

FDamp FR FDamp[1] inCar_SuspForcesHook_Calc()

Car.DampFR.Frc_ext

FDamp RL FDamp[2] inCar_SuspForcesHook_Calc()

Car.DampRL.Frc_ext

FDamp RR FDamp[3] inCar_SuspForcesHook_Calc()

Car.DampRR.Frc_ext

FStabi C Variable Dictionary Variable

FStabi FL FStabi[0] inCar_SuspForcesHook_Calc()

Car.StabiFL.Frc_ext

FStabi FR FStabi[1] inCar_SuspForcesHook_Calc()

Car.StabiFR.Frc_ext

FStabi RL FStabi[2] inCar_SuspForcesHook_Calc()

Car.StabiRL.Frc_ext

FStabi RR FStabi[3] inCar_SuspForcesHook_Calc()

Car.StabiRR.Frc_ext

CarMaker Programmer’s Guide Version 2.1.6

Page 113: IPG_CarMaker Programmers Guide

113CarMaker for Simulink

The CarMaker for Simulink blockset

Car

Car.Virtual

Car.Aero

Car.Load

Car.Virtual C Variable Dictionary Variable

Car Virtual Frc_1 x Car.Virtual.Frc_1[0] Car.Virtual.Frc_1.x

Car Virtual Frc_1 y Car.Virtual.Frc_1[1] Car.Virtual.Frc_1.y

Car Virtual Frc_1 z Car.Virtual.Frc_1[2] Car.Virtual.Frc_1.z

Car Virtual Frc_0 x Car.Virtual.Frc_0[0] Car.Virtual.Frc_0.x

Car Virtual Frc_0 y Car.Virtual.Frc_0[1] Car.Virtual.Frc_0.y

Car Virtual Frc_0 z Car.Virtual.Frc_0[2] Car.Virtual.Frc_0.z

Car Virtual Trq_1 x Car.Virtual.Trq_1[0] Car.Virtual.Trq_1.x

Car Virtual Trq_1 y Car.Virtual.Trq_1[1] Car.Virtual.Trq_1.y

Car Virtual Trq_1 z Car.Virtual.Trq_1[2] Car.Virtual.Trq_1.z

Car Virtual Trq_0 x Car.Virtual.Trq_0[0] Car.Virtual.Trq_0.x

Car Virtual Trq_0 y Car.Virtual.Trq_0[1] Car.Virtual.Trq_0.y

Car Virtual Trq_0 z Car.Virtual.Trq_0[2] Car.Virtual.Trq_0.z

Car.Aero C Variable Dictionary Variable

Vehicle sRoadAero Vehicle.sRoadAero Vehicle.sRoadAero

Vehicle Wind_vel_0 x Vehicle.Wind_vel_0[0] Vhcl.Wind.vx

Vehicle Wind_vel_0 y Vehicle.Wind_vel_0[1] Vhcl.Wind.vy

Vehicle Wind_vel_0 z Vehicle.Wind_vel_0[2] Vhcl.Wind.vz

car Aero vRes_1 x (car.Aero.IF.ApproachVel_1[0])

Car.Aero.vres_1.x

car Aero vRes_1 y (car.Aero.IF.ApproachVel_1[1])

Car.Aero.vres_1.y

car Aero vRes_1 z (car.Aero.IF.ApproachVel_1[2])

Car.Aero.vres_1.z

car Aero Frc_1 x (car.Aero.IF.Frc_1[0]) Car.Aero.Frc_1.x

car Aero Frc_1 y (car.Aero.IF.Frc_1[1]) Car.Aero.Frc_1.y

car Aero Frc_1 z (car.Aero.IF.Frc_1[2]) Car.Aero.Frc_1.z

car Aero Trq_1 x (car.Aero.IF.Trq_1[0]) Car.Aero.Trq_1.x

car Aero Trq_1 z (car.Aero.IF.Trq_1[1]) Car.Aero.Trq_1.y

car Aero Trq_1 y (car.Aero.IF.Trq_1[2]) Car.Aero.Trq_1.z

Car.Load C Variable Dictionary Variable

Car Load_0 mass Car.Load[0].mass Car.Load.0.mass

Car Load_0 tx Car.Load[0].pos[0] Car.Load.0.tx

Car Load_0 ty Car.Load[0].pos[1] Car.Load.0.ty

CarMaker Programmer’s Guide Version 2.1.6

Page 114: IPG_CarMaker Programmers Guide

114CarMaker for Simulink

The CarMaker for Simulink blockset

Car.Trq_T2W

Car.Fr1

WheelCarier.Misc

Car Load_0 tz Car.Load[0].pos[2] Car.Load.0.tz

Car Load_1 mass Car.Load[1].mass Car.Load.1.mass

Car Load_1 tx Car.Load[1].pos[0] Car.Load.1.tx

Car Load_1 ty Car.Load[1].pos[1] Car.Load.1.ty

Car Load_1 tz Car.Load[1].pos[2] Car.Load.1.tz

Car Load_2 mass Car.Load[2].mass Car.Load.2.mass

Car Load_2 tx Car.Load[2].pos[0] Car.Load.2.tx

Car Load_2 ty Car.Load[2].pos[1] Car.Load.2.ty

Car Load_2 tz Car.Load[2].pos[2] Car.Load.2.tz

Car.Load C Variable Dictionary Variable

Car.Trq_T2W C Variable Dictionary Variable

Car Trq_T2WFL Car.Tire[0].Trq_T2W Car.Trq_T2WFL

Car Trq_T2WFR Car.Tire[1].Trq_T2W Car.Trq_T2WFR

Car Trq_T2WRL Car.Tire[2].Trq_T2W Car.Trq_T2WRL

Car Trq_T2WRR Car.Tire[3].Trq_T2W Car.Trq_T2WRR

Car.Fr1 C Variable Dictionary Variable

Car Fr1 rx Car.Fr1.r_zyx[0] Car.Fr1.rx

Car Fr1 ry Car.Fr1.r_zyx[1] Car.Fr1.ry

Car Fr1 rz Car.Fr1.r_zyx[2] Car.Fr1.rz

Car Fr1 rvx Car.Fr1.rv_zyx[0]

Car Fr1 rvy Car.Fr1.rv_zyx[1]

Car Fr1 rvz Car.Fr1.rv_zyx[2]

WheelCarrier.Misc C Variable Dictionary Variable

car Susp FL GenInert1 (car.SuspF.L.GenInert[1]) Car.CFL.GenInert1

car Susp FR GenInert1 (car.SuspF.R.GenInert[1]) Car.CFR.GenInert1

car Susp FL GenFrc1 (car.SuspF.L.GenFrc[1]) Car.CFL.GenFrc1

car Susp FR GenFrc1 (car.SuspF.R.GenFrc[1]) Car.CFR.GenFrc1

CarMaker Programmer’s Guide Version 2.1.6

Page 115: IPG_CarMaker Programmers Guide

115CarMaker for Simulink

The CarMaker for Simulink blockset

Tire

TireXX_In The Tire_In signals are always valid, independent of the tire model specified in the currentlyselected tire parameter file. .

TireXX_Out The Tire_Out signals will only be used if FileIdent is CarMaker-Tire-CM4SL in the currentlyselected tire parameter file.

For XX substitute one of FL, FR, RL, RR, according to the tire in question

TireXX_In C Variable Dictionary Variable

Tire_In Load IF->Frc_H[2]in tFcnCalc_Tire(MP, IF, dt)

Car.FzXX

Tire_In vxtrans IF->P_v0_H[0]in tFcnCalc_Tire(MP, IF, dt)

Car.vxXX

Tire_In vytrans IF->P_v0_H[1]in tFcnCalc_Tire(MP, IF, dt)

Car.vyXX

Tire_In vrot IF->vBeltin tFcnCalc_Tire(MP, IF, dt)

Car.vXX

Tire_In Camber IF->InclinAnglein tFcnCalc_Tire(MP, IF, dt)

Car.InclinAngleXX

Tire_In mu IF->muRoadin tFcnCalc_Tire(MP, IF, dt)

Car.muRoadXX

TireXX_Out C Variable Dictionary Variable

Tire_Out Slp IF->Slpin tFcnCalc_Tire(MP, IF, dt)

Car.LongSlipXX

Tire_Out Alpha IF->Alphain tFcnCalc_Tire(MP, IF, dt)

Car.SlipAngleXX

Tire_Out LongFrc IF->Frc_H[0]in tFcnCalc_Tire(MP, IF, dt)

Car.FxXX

Tire_Out SideFrc IF->Frc_H[1]in tFcnCalc_Tire(MP, IF, dt)

Car.FyXX

Tire_Out LoadFrc IF->Frc_H[2]in tFcnCalc_Tire(MP, IF, dt)

Car.FzXX

Tire_Out OverturnTrq IF->Trq_H[0]in tFcnCalc_Tire(MP, IF, dt)

Car.TrqOvertXX

Tire_Out RollResist IF->Trq_H[1]in tFcnCalc_Tire(MP, IF, dt)

Car.TrqRollXX

Tire_Out AlignTrq IF->Trq_H[2]in tFcnCalc_Tire(MP, IF, dt)

Car.TrqAlignXX

CarMaker Programmer’s Guide Version 2.1.6

Page 116: IPG_CarMaker Programmers Guide

116CarMaker for Simulink

The CarMaker for Simulink blockset

Trailer

Car.Hitch

Car.Hitch.FrcTrq

Trailer.Load

Car.Hitch C Variable Dictionary Variable

Car Hitch tx Car.Hitch.t_0[0] Car.Hitch.tx

Car Hitch ty Car.Hitch.t_0[1] Car.Hitch.ty

Car Hitch tz Car.Hitch.t_0[2] Car.Hitch.tz

Car Hitch vx Car.Hitch.v_0[0] Car.Hitch.vx

Car Hitch vy Car.Hitch.v_0[1] Car.Hitch.vy

Car Hitch vz Car.Hitch.v_0[2] Car.Hitch.vz

Car.Hitch.FrcTrq C Variable Dictionary Variable

Car Hitch Frc2Car x Car.Hitch.Frc2Car[0] Car.Hitch.Frc2Car.x

Car Hitch Frc2Car y Car.Hitch.Frc2Car[1] Car.Hitch.Frc2Car.y

Car Hitch Frc2Car z Car.Hitch.Frc2Car[2] Car.Hitch.Frc2Car.z

Car Hitch Trq2Car x Car.Hitch.Trq2Car[0] Car.Hitch.Trq2Car.x

Car Hitch Trq2Car y Car.Hitch.Trq2Car[1] Car.Hitch.Trq2Car.y

Car Hitch Trq2Car z Car.Hitch.Trq2Car[2] Car.Hitch.Trq2Car.z

Trailer.Load C Variable Dictionary Variable

Trailer Load_0 mass Trailer.Load[0].mass Tr.Load.0.mass

Trailer Load_0 tx Trailer.Load[0].tx Tr.Load.0.tx

Trailer Load_0 ty Trailer.Load[0].ty Tr.Load.0.ty

Trailer Load_0 tz Trailer.Load[0].tz Tr.Load.0.tz

Trailer Load_1 mass Trailer.Load[1].mass Tr.Load.1.mass

Trailer Load_1 tx Trailer.Load[1].tx Tr.Load.1.tx

Trailer Load_1 ty Trailer.Load[1].ty Tr.Load.1.ty

Trailer Load_1 tz Trailer.Load[1].tz Tr.Load.1.tz

Trailer Load_2 mass Trailer.Load[2].mass Tr.Load.2.mass

Trailer Load_2 tx Trailer.Load[2].tx Tr.Load.2.tx

Trailer Load_2 ty Trailer.Load[2].ty Tr.Load.2.ty

Trailer Load_2 tz Trailer.Load[2].tz Tr.Load.2.tz

CarMaker Programmer’s Guide Version 2.1.6

Page 117: IPG_CarMaker Programmers Guide

117CarMaker for Simulink

Demonstration examples

6.4 Demonstration examples

CarMaker for Simulink comes with a number of example models demonstrating variousapplications, features and modeling techniques. The examples are complete with

• the Simulink model

• Matlab parameter files and scripts, if needed

• configuration files, i.e. testruns, vehicle data, tire data, etc.

All examples can be used with Matlab 6.1 and later versions.

Please note : The examples presented in this chapter were intended to show how to makeuse of a particular interface of CarMaker for Simulink, but not to provide an elaborated appli-cation or a fully fledged, 100% physically sound replacement of a particular CarMaker sub-system.

Making a local copy of the examples

All Simulink models described in this chapter can be found in the mdl_examples subdirec-tory of the standard Examples/Car_Generic_SL template project directory.

In order to get known to the examples or to use them as a starting point for your ownprojects, you should make a local copy of the standard template project directory and workwith that copy.

CarMaker Programmer’s Guide Version 2.1.6

Page 118: IPG_CarMaker Programmers Guide

118CarMaker for Simulink

Demonstration examples

6.4.1 ABSdemo

The ABSdemo model is a modified version of the Anti-Lock Brake System demo that comeswith Simulink (type absbrake in the Matlab command windows or use the Simulink librarybrowser to see the original model).

Files belonging to this example

• mdl_examples/ABSdemo.mdlmdl_examples/ABSdata.mThe Simulink model and its parameter file.

• mdl_examples/ABSplot.mScript to plot some diagrams after the simulation.

• Data/TestRun/Examples/Simulink/ABSdemoThe testrun to be used with this example.

Details about the example

• The model is very limited and only useful in conjunction with the ABSdemo testrun.Don’t try to use it with other testruns.

Figure 6.11: ABSdemo example model

CarMaker Programmer’s Guide Version 2.1.6

Page 119: IPG_CarMaker Programmers Guide

119CarMaker for Simulink

Demonstration examples

6.4.2 BodyCtrl

In this example the Simulink model implements some kind of active body control, that triesto keep the vehicle upright by applying extra suspension forces to the chassis.

Files belonging to this example

• mdl_examples/BodyCtrl.mdlThe Simulink model.

• Data/TestRun/Examples/Simulink/BodyCtrlA testrun to demonstrate the working of the model.

Details about the example

• The model is connected to CarMaker using the vehicle’s external suspension interface.

• The BodyCtrl testrun demonstrates how the chassis is kept upright while the vehicle isdriving in a long curve. The model is not limited to this particular testrun, though.

• In CarMaker for Simulink the FSpring/FDamp/FStabi outputs of the External Suspen-sion Forces subsystem will be active if the SuspExtFrcs.Kind entry in the vehicleparameter file is either not present or is empty or has the value CM4SL.

• This model is also available as an example of the CarMaker target for Real-Time Work-shop to show how Simulink models can be integrated into CarMaker using Real-TimeWorkshop generated C code.

Figure 6.12: BodyCtrl example model

CarMaker Programmer’s Guide Version 2.1.6

Page 120: IPG_CarMaker Programmers Guide

120CarMaker for Simulink

Demonstration examples

6.4.3 ESPTemplate

This model is not so much a ready-to-run example, but should serve as a starting point foran ESP implementation instead.

Files belonging to this example

• mdl_examples/ESPTemplate.mdlThe Simulink model.

Details about the example

• The purpose of the Collect ESP Signals and Engine ECU subsystems is to collect andtransform typical ESP signals connected to CarMaker.

• The ESP ECU subsystem is the place where the Simulink blocks of ESP controller unitshould go.

Figure 6.13: ESPTemplate example model

CarMaker Programmer’s Guide Version 2.1.6

Page 121: IPG_CarMaker Programmers Guide

121CarMaker for Simulink

Demonstration examples

6.4.4 SoftABS

The SoftABS model contains a simple implementation of an Anti-Lock Brake System.

Files belonging to this example

• mdl_examples/SoftABS.mdlmdl_examples/SoftABS_params.mThe Simulink model and its parameter file.

Details about the example

• For each wheel, the brake torque is adjusted in order to keep slip to an upper limit.

• Try the example with the Braking_mu_split testrun and compare the results to a sim-ulation with the generic.mdl model.

Figure 6.14: SoftABS example model

CarMaker Programmer’s Guide Version 2.1.6

Page 122: IPG_CarMaker Programmers Guide

122CarMaker for Simulink

Demonstration examples

6.4.5 TractCtrl

The TractCtrl example implements some kind of traction control, controlling the brakingtorques of the front wheels and reducing engine torque if necessary.

Files belonging to this example

• mdl_examples/TractCtrl.mdlThe Simulink model.

• Data/TestRun/Examples/Simulink/TractCtrlA testrun to demonstrate the working of the model.

Details about the example

• None; the model is quite simple.

• This model is also available as an example of the CarMaker target for Real-Time Work-shop to show how Simulink models can be integrated into CarMaker using Real-TimeWorkshop generated C code.

Figure 6.15: TractCtrl example model

CarMaker Programmer’s Guide Version 2.1.6

Page 123: IPG_CarMaker Programmers Guide

123CarMaker for Simulink

Demonstration examples

6.4.6 UserBrake

This example shows how to replace CarMaker’s internal braking module on the Simulinklevel.

Files belonging to this example

• mdl_examples/UserBrake.mdlThe Simulink model.

Details about the example

• CarMaker’s internal braking module is completely disabled, because the -disablebrakecommand line argument is set in the CarMaker Model Configuration block (see figurebelow).

Figure 6.16: UserBrake example model

Figure 6.17: UserBrake model configuration

CarMaker Programmer’s Guide Version 2.1.6

Page 124: IPG_CarMaker Programmers Guide

124CarMaker for Simulink

Demonstration examples

6.4.7 UserPowerTrain

This example shows how to replace CarMaker’s internal powertrain module on the Simulinklevel. It does not contain a complete implementation of a powertrain, but just tries to showthe functioning of the powertrain interface.

Files belonging to this example

• mdl_examples/UserPowerTrain.mdlThe Simulink model.

• Data/Vehicle/DemoCar_UserPTA vehicle with a powertrain configuration as described below.

• Data/TestRun/Examples/Simulink/UserPowerTrainA testrun to demonstrate the working of the model.

Details about the example

• The model is very limited and only useful in conjunction with the UserPowerTrain tes-trun. Don’t try to use it with other testruns.

• CarMaker’s internal powertrain module is completely disabled, because the -disable-powertrain command line argument is set in the CarMaker Model Configuration block(see figure below).

• When simulating with a powertrain implemented in Simulink, you have to make sureyour vehicle configuration file (Data/Vehicle/DemoCar_UserPT for this example)contains the following entries:

- PowerTrain.Kind = ““

- PowerTrain.ET.on

- PowerTrain.ET.nIdle

- PowerTrain.ET.rotv

- PowerTrain.GearBox.iForwardGears

- PowerTrain.GearBox.iBackwardGears

- PowerTrain.DL.Diff.i

Figure 6.18: UserPowerTrain example model

CarMaker Programmer’s Guide Version 2.1.6

Page 125: IPG_CarMaker Programmers Guide

125CarMaker for Simulink

Demonstration examples

Figure 6.19: UserPowerTrain model configuration

CarMaker Programmer’s Guide Version 2.1.6

Page 126: IPG_CarMaker Programmers Guide

126CarMaker for Simulink

Demonstration examples

6.4.8 UserSteer

This example shows how to replace CarMaker’s internal steering module on the Simulinklevel.

Files belonging to this example

• mdl_examples/UserSteer.mdlThe Simulink model.

Details about the example

• CarMaker’s internal steering module is completely disabled, because the -disablesteercommand line argument is set in the CarMaker Model Configuration block (see figurebelow).

• This model is also available as an example of the CarMaker target for Real-Time Work-shop to show how Simulink models can be integrated into CarMaker using Real-TimeWorkshop generated C code.

Figure 6.20: UserSteer example model

Figure 6.21: UserSteer model configuration

CarMaker Programmer’s Guide Version 2.1.6

Page 127: IPG_CarMaker Programmers Guide

127CarMaker for Simulink

Demonstration examples

6.4.9 UserSteerTorque

This is another example of how to replace CarMaker’s internal steering module on theSimulink level. In contrast to the UserSteer example, this model implements steering bytorque. It was modeled after the standard CarMaker example C code in Examples/Car_Components/MySteering.c . See the source code for details.

Files belonging to this example

• mdl_examples/UserSteerTorque.mdlThe Simulink model.

• Data/TestRun/Examples/Simulink/Hockenheim_UserSteerTorqueA testrun to demonstrate the working of the model.

Details about the example

• CarMaker’s internal steering module is completely disabled, because the -disablesteerparameter is set in the CarMaker Model Configuration block (see figure below).

• To simulate with this model, make sure to switch on Steer by Torque in the LateralDynamics part of the CarMaker GUI’s maneuver dialog. TheHockenheim_UserSteerTorque testrun is just a copy of the Road/Hockenheim testrunwith Steer by Torque enabled.

• Driver Adaption will not work with this model because the corresponding IPG-DRIVERfunctionality is not yet suited to steering by torque.

Figure 6.22: UserSteerTorque example model

CarMaker Programmer’s Guide Version 2.1.6

Page 128: IPG_CarMaker Programmers Guide

128CarMaker for Simulink

Demonstration examples

• Driver Adaption currently does not work with this model. Use steering by angle instead.

Figure 6.23: UserSteerTorque model configuration

CarMaker Programmer’s Guide Version 2.1.6

Page 129: IPG_CarMaker Programmers Guide

129CarMaker for Simulink

Demonstration examples

6.4.10 UserTire

This example shows how to replace CarMaker’s internal tire module on the Simulink level.

Files belonging to this example

• mdl_examples/UserTire.mdlThe Simulink model.

• Data/TestRun/Examples/Simulink/Hockenheim_UserTireA testrun to demonstrate the working of the model. It is a copy of the Road/Hockenheimtestrun with the appropriate tire model selected and a non-zero initial speed.

• Data/Tire/DT_CM4SL_UserTireA tire data file used in the example testrun.

Details about the example

• The TireXX_Out signals will only be used if in the tire parameter file the FileIdent entryhas the value CarMaker-Tire-CM4SL , i.e. in the CarMaker GUI, for the testrun, select atire data file with this property.

• When simulating with a tire data file not containing this specific FileIdent entry, an inter-nal CarMaker tire model will be used instead.

• Apart from the correct FileIdent entry, the tire parameter file must contain correctparameters for the tire. CarMaker needs these values for proper initialization.

• The example is not very well suited for stand still conditions.

Figure 6.24: UserTire example model

CarMaker Programmer’s Guide Version 2.1.6

Page 130: IPG_CarMaker Programmers Guide

130CarMaker utilities for Matlab

Importing simulation results with cmread

Chapter 7

CarMaker utilities for Matlab

7.1 Importing simulation results with cmread

With the cmread utility, that comes with the Matlab support package for CarMaker, it’s pos-sible to load CarMaker simulation results files (“erg files”, named after their file extension.erg ) into the Matlab workspace. Once available in the workspace, the simulation data canbe used and manipulated in every conceivable way, e.g. for postprocessing and plotting.

Invoking cmread

Basically cmread works as follows:

• cmread let’s you specify a path, either to a directory or to a file. In case a directory isspecified, you may select a file with the mouse in a file browser window. By default thecurrent directory (in CarMaker for Simulink the current SimOutput directory) is implied.

• The return value of cmread must be assigned to a workspace variable. The result is aMatlab struct with one member for each results file variable loaded. This way, severalresults files may be loaded into the workspace (e.g. for comparison), the data of eachfile stored in a different workspace variable.

• By specifying one or more patterns it’s possible to select only a subset of all variablescontained in a results file. By default all variables are loaded into the workspace.

The next section contains some examples that should make clear how cmread works. Forfurther details see the cmread ’s online help page in Matlab, by typing

>> help cmread

at the Matlab prompt.

cmread example use

Loading a resultsfile

“Open a file browser window, let me select the results file with the mouse, and assign thedata to the workspace variable a”:

>> a = cmread;

CarMaker Programmer’s Guide Version 2.1.6

Page 131: IPG_CarMaker Programmers Guide

131CarMaker utilities for Matlab

Importing simulation results with cmread

“Open a file browser window with the contents of my CarMaker for Simulink simulationresults directory, let me select the results file with the mouse, and assign the data to theworkspace variable a”:

>> a = cmread(‘../SimOutput/myhost‘);

You may have to replace the name ‘myhost’ with the hostname of the computer you’re using.

“Load two different simulation results file into the workspace”:

>> a = cmread(‘SpecialManoeuver1.erg’);>> b = cmread(‘SpecialManoeuver2.erg’);

Working with theloaded data

“Display the contents of variable a, which contains the loaded data”:

>> disp(a)Car_CFL_rx:[1x1 struct]Car_CFL_ry:[1x1 struct]Car_CFL_rz:[1x1 struct]...Time [1x1 struct]

Please note the difference between the names of the variables in the results file and thenames of the struct members. cmread automatically renames variables that do not matchthe syntax of Matlab’s data types. This includes changing ‘.’ to ‘_’ and truncating long namesif necessary.

“Display the contents of the Car.vx variable”:

>> disp(a.Car_vx)unit: ‘m/s’nstates: 0data: [1x10144 double]

“Show a speed-over-time diagram, plot the course of the car”:

>> plot(a.Time.data, a.Car_vx.data)>> plot(a.Car_Fr1_tx.data, a.Car_Fr1_ty.data)

Loading only asubset of the

variables from aresults file

“Open a file browser window showing the current directory, let me select the results file withthe mouse, and assign the data of Time, all DrivMan and all PT variables to the workspacevariable a”:

>> a = cmread(‘.’, ‘Time’, ‘DM*’, ‘PT*’);

Function arguments following the specified directory ‘.’ may be variable names as well aspatterns of names. cmread may be invoked with any number of name/pattern arguments.Patterns follow the syntax that normally can be used for filenames. Listed below are thespecial characters most often used for patterns.

• * matches any string including the empty string

• ? matches any single character

• [...] matches any of the characters enclosed between the brackets

CarMaker Programmer’s Guide Version 2.1.6

Page 132: IPG_CarMaker Programmers Guide

132CarMaker utilities for Matlab

Accessing CarMaker Infofiles

7.2 Accessing CarMaker Infofiles

Infofile access, i.e. access to CarMaker parameter files, can be acomplished usingCarMaker’s ifile command for Matlab.

For a quick start see the ifile online help page, by typing

>> help ifile

at the Matlab prompt.

CarMaker Programmer’s Guide Version 2.1.6

Page 133: IPG_CarMaker Programmers Guide

133MIO – M-Module Input/Output

Supported M-Modules

Chapter 8

MIO – M-Module Input/Output

8.1 Supported M-Modules

8.1.1 M3 / M27 / M43: Binary / Relay Outputs (8/16 channels)

Connector assignment M3/M27

Pin Signal Pin Signal

1 Out_2 14 Out_1

2 Out_0 15 Out_3

3 Out_6 16 Out_5

4 Out_4 17 Out_7

5 Out_10 18 Out_9

6 Out_8 19 Out_11

7 Out_14 20 Out_13

8 Out_12 21 Out_15

9 I+24V 22 I+24V

10 I+24V 23 GND

11 GND 24 GND

12 GND 25 GND

13 GND

1 14

2513

CarMaker Programmer’s Guide Version 2.1.6

Page 134: IPG_CarMaker Programmers Guide

134MIO – M-Module Input/Output

Supported M-Modules

Connector assignment M43

Initialization, Configuration

• MIO_M3_Config() / MIO_M27_Config() / MIO_M43_Config()

Set Output Signals

• MIO_M3_Set() / MIO_M27_Set() / MIO_M43_Set()

8.1.2 M4: Analog Outputs (4 channels)

Connector assignment M4

Initialization, Configuration

• MIO_M4_Config()

Pin Signal Pin Signal

1 A0 (A = working contact) 14 M0

2 R0 (R = rest contact) 15 A1

3 M1 16 R1

4 A2 17 M2

5 R2 18 A3

6 M3 19 R3

7 A4 20 M4

8 R4 21 A5

9 M5 22 R5

10 A6 23 M6

11 R6 24 A7

12 M7 25 R7

13 GND

1 14

2513

MxRx

Ax

Pin Signal Pin Signal

1 GND 14 OutU_0

2 GND 15 OutI_0

3 GND 16 OutU_1

4 GND 17 OutI_1

5 GND 18 OutU_2

6 GND 19 OutI_2

7 GND 20 OutU_3

8 GND 21 OutI_3

9 GND 22 GND

10 GND 23 +15V

11 GND 24 -15V

12 GND 25 +5V

13 GND

1 14

2513

CarMaker Programmer’s Guide Version 2.1.6

Page 135: IPG_CarMaker Programmers Guide

135MIO – M-Module Input/Output

Supported M-Modules

• MIO_M4_Reset()

• MIO_M4_SetMode()

• MIO_M4_SetModeByte()

Set Output Signals

• MIO_M4_Set()

• MIO_M4_SetV()

8.1.3 M15: Frequency Generator (2 channels)

Connector assignment

Initialization, Configuration

• MIO_M15_Config()

• MIO_M15_Reset()

Set Output Signals

• MIO_M15_SetAnalogOut()

• MIO_M15_SetLowHigh()

• MIO_M15_SetMode()

• MIO_M15_SetPulseWidth()

• MIO_M15_SetPeriod()

• MIO_M15_Trigger()

Pin Signal Description

1-4 GND_0 Ground Channel 0

5-8 GND_1 Ground Channel 1

14 UL_0 “Low” Voltage Outputs from AD converters

15 UH_0 “High” Voltage Outputs from AD converters

16 PB_0 TTL Outputs of Frequency Generators

17 UPB_0 Actual Output Frequency Signal

18 UL_1 “Low” Voltage Outputs from AD converters

19 UH_1 “High” Voltage Outputs from AD converters

20 PB_1 TTL Outputs of Frequency Generators

21 UPB_1 Actual Output Frequency Signal

1 14

2513

CarMaker Programmer’s Guide Version 2.1.6

Page 136: IPG_CarMaker Programmers Guide

136MIO – M-Module Input/Output

Supported M-Modules

8.1.4 M31 / M32: Binary Inputs (16 channels)

Connector assignment M31/M32

Initialization, Configuration

• MIO_M31_Config() / MIO_M32_Config()

Get Input Signals

• MIO_M31_Read() / MIO_M32_Read()

Pin Signal Pin Signal

1 In_0 14 In_1

2 In_2 15 In_3

3 In_4 16 In_5

4 In_6 17 In_7

5 In_8 18 In_9

6 In_10 19 In_11

7 In_12 20 In_13

8 In_14 21 In_15

9 I-GND 22 I-GND

10 I-GND 23 I-GND

11 I-GND 24 I-GND

12 I-GND 25 I-GND

13 I-GND

1 14

2513

CarMaker Programmer’s Guide Version 2.1.6

Page 137: IPG_CarMaker Programmers Guide

137MIO – M-Module Input/Output

Supported M-Modules

8.1.5 M5 / M34 / M35 / M35N: Analog Inputs (16/8 channels)

Connector assignment M5/M34/M35/M35N

Initialization, Configuration

• MIO_M5_Config() / MIO_M34_Config() / MIO_M35_Config()

• MIO_M5_Reset() / MIO_M34_Reset() / MIO_M35_Reset()

Get Input Signals

• MIO_M5_Read() / MIO_M34_Read() / MIO_M35_Read()

• MIO_M5_Read_bp() / MIO_M34_Read_bp() / MIO_M35_Read_bp()

• MIO_M5_ReadV() / MIO_M34_ReadV() / MIO_M35_ReadV()

M35N Compatibility Issues

Some versions of the M35N module do not operate according to the specification, due todifferent firmware bugs:

• M35N modules of revision of 5.1 or lower do not start a conversion when writing ataddress 0x02. As a consequence, data acquisition with the function MIO_M35_ReadV()does not work properly: the data which is read from the module is invalid.

• M35N modules of revision of 5.2, start a conversion when writing at address 0x02. But,when reading data from address 0x00 right after starting a conversion (by writing toaddress 0x02), the result is not from the conversion which was started right before.Instead, the data fetched derives from the conversion before last. When reading datawith the function MIO_M35_ReadV() , this leads to a permutation of the channels: e.g. ifdata should be obtained from channels 0, 1, 2 and 4 (ChMask = 0x17 ) and stored in thearray Values[4] , then the data of channel 0 will be stored in Values[1] , channel 1 inValues[2] , channel 2 in Values[3] and channel 4 in Values[0] .

• M35N modules do not work properly on A201 carrier boards of the first generation.When reading inputs, the values toggle between 0 and the real value. Upgrade to thenewer A201S carrier board is recommended.

If you are using a M35N module of revision 5.2 or earlier, please contact IPG for a firmwareupdate or workaround.

Pin Signal Pin Signal

1 In_0 14 In_8 (In_0-)

2 In_1 15 In_9 (In_1-)

3 In_2 16 In_10 (In_2-)

4 In_3 17 In_11 (In_3-)

5 In_4 18 In_12 (In_4-)

6 In_5 19 In_13 (In_5-)

7 In_6 20 In_14 (In_6-)

8 In_7 21 In_15 (In_7-)

9 BI 22 Trigger

10 GND 23 +15V

11 GND 24 -15V

12 GND 25 +5V

13 GND

1 14

2513

CarMaker Programmer’s Guide Version 2.1.6

Page 138: IPG_CarMaker Programmers Guide

138MIO – M-Module Input/Output

Supported M-Modules

8.1.6 M51: Quadruple CAN Interface

Connector assignment M51

Initialization, Configuration

• MIO_M51_Config()

• MIO_M51_Reset()

• MIO_M51_Delete()

• MIO_M51_SetBufSize()

• MIO_M51_SetCommParam()

• MIO_M51_SetTxTimeout()

• MIO_M51_EnableIds()

• MIO_M51_DisableIds()

Polling Mode Operation

• MIO_M51_Poll()

Sequential Send/Receive Mode

• MIO_M51_Send()

• MIO_M51_SendExt()

• MIO_M51_SendV()

• MIO_M51_SendBufClear()

• MIO_M51_SendStat()

• MIO_M51_Recv()

• MIO_M51_RecvExt()

• MIO_M51_RecvBufClear()

• MIO_M51_RecvStat()

• MIO_M51_TxAbort()

Pin Signal Pin Signal

1 CAN0_low 14 CAN0_high

2 CAN0_GND 15 CAN0_VCC

3 16

4 CAN1_low 17 CAN1_high

5 CAN1_GND 18 CAN1_VCC

6 19

7 CAN2_low 20 CAN2_high

8 CAN2_GND 21 CAN2_VCC

9 22

10 CAN3_low 23 CAN3_high

11 CAN3_GND 24 CAN3_VCC

12 25

13

1 14

2513

CarMaker Programmer’s Guide Version 2.1.6

Page 139: IPG_CarMaker Programmers Guide

139MIO – M-Module Input/Output

Supported M-Modules

Mailboxes

• MIO_M51_MBoxEnable()

• MIO_M51_MBoxDisable()

• MIO_M51_MBoxCreate()

• MIO_M51_MBoxDelete()

• MIO_M51_MBoxRead()

• MIO_M51_MBoxReadExt()

Additional Functions

• MIO_M51_SetTimestampFct()

• MIO_M51_SetTransMode()

• MIO_M51_UnlockTxBuf()

CAN Trace

• MIO_M51_TraceInit()

• MIO_M51_TraceStop()

Diagnostics

• MIO_M51_Status()

• MIO_M51_GetRxErrCnt()

• MIO_M51_GetTxErrCnt()

• MIO_M51_CANInfo()

Debugging

• MIO_M51_GetRegister()

• MIO_M51_ListAddr()

• MIO_M51_DumpPSCC()

CarMaker Programmer’s Guide Version 2.1.6

Page 140: IPG_CarMaker Programmers Guide

140MIO – M-Module Input/Output

Supported M-Modules

8.1.7 M62: Analog Outputs (4 channels)

Connector assignment M62

Initialization, Configuration

• MIO_M62_Config()

• MIO_M62_Reset()

Set Output Signals

• MIO_M62_Set()

• MIO_M62_SetV()

Pin Signal Pin Signal

1 Out_8 14 Out_0

2 Out_9 15 Out_1

3 Out_10 16 Out_2

4 Out_11 17 Out_3

5 Out_12 18 Out_4

6 Out_13 19 Out_5

7 Out_14 20 Out_6

8 Out_15 21 Out_7

9 GND 22 GND

10 GND 23 +15V

11 GND 24 -15V

12 GND 25

13 GND

1 14

2513

CarMaker Programmer’s Guide Version 2.1.6

Page 141: IPG_CarMaker Programmers Guide

141MIO – M-Module Input/Output

Supported M-Modules

8.1.8 M72: Motion Counter

Connector assignment M72

Initialization, Configuration

• MIO_M72_Config()

• MIO_M72_Reset()

• MIO_M72_Download()

• MIO_M72_SetMode()

Counter Get / Set

• MIO_M72_GetCounter()

• MIO_M72_SetCounter()

Set Output Signals

• MIO_M72_SetOutPort()

Pin Signal Pin Signal Pin Signal

1 16 31

2 AIN0+ 17 AIN1+ 32 AIN2+

3 AIN0- 18 AIN1- 33 AIN2-

4 19 34

5 BIN0+ 20 BIN1+ 35 BIN2+

6 BIN0- 21 BIN1- 36 BIN2-

7 22 37

8 CIN0+ 23 CIN1+ 38 CIN2+

9 CIN0- 24 CIN1- 39 CIN2-

10 25 40

11 DIN0+ 26 DIN1+ 41 DIN2+

12 DIN0- 27 DIN1- 42 DIN2-

13 28 43

14 Out0 29 Out1 44 Out2

15 IGND 30 Out3

1

16

31

44

3015

CarMaker Programmer’s Guide Version 2.1.6

Page 142: IPG_CarMaker Programmers Guide

142MIO – M-Module Input/Output

Supported M-Modules

8.1.9 M77: Quadruple RS232/423 - RS422/485 UART

Connector assignment M77

Initialization, Configuration

• MIO_M77_Config()

• MIO_M77_Reset()

• MIO_M77_Config()

• MIO_M77_Reset()

• MIO_M77_UART_Reset()

• MIO_M77_UART_Flush()

• MIO_M77_SetBaud()

• MIO_M77_SetMode()

Data Transfer

• MIO_M77_Write()

• MIO_M77_Read()

Diagnostics

• MIO_M77_RxFillLvl()

• MIO_M77_TxFillLvl()

Pin Signal Pin Signal

1 TXD/RXD[0]+ 14 TXD/RXD[0]-

2 TXD[0]+ 15 TXD[0]-

3 TERM[0] 16 I-GND[0]

4 TXD/RXD[1]+ 17 TXD/RXD[1]-

5 TXD[1]+ 18 TXD[1]-

6 TERM[1] 19 I-GND[1]

7 TXD/RXD[2]+ 20 TXD/RXD[2]-

8 TXD[2]+ 21 TXD[2]-

9 TERM[2] 22 I-GND[2]

10 TXD/RXD[3]+ 23 TXD/RXD[3]-

11 TXD[3]+ 24 TXD[3]-

12 TERM[3] 25 I-GND[3]

13

1 14

2513

CarMaker Programmer’s Guide Version 2.1.6

Page 143: IPG_CarMaker Programmers Guide

143MIO – M-Module Input/Output

Supported M-Modules

8.1.10 M392 / M393: Analog Inputs (16/8 channels)

Connector assignment M392

Initialization, Configuration

• MIO_M392_Config() / MIO_M393_Config()

• MIO_M392_Reset() / MIO_M393_Reset()

• MIO_M392_Delete() / MIO_M393_Delete()

• MIO_M392_Setup() / MIO_M393_Setup()

• MIO_M392_SetupV() / MIO_M393_SetupV()

• MIO_M392_SetAcqTime() / MIO_M393_SetAcqTime()

• MIO_M392_SetMAF() / MIO_M393_SetMAF()

Get Input Signals

MIO_M392_Read() / MIO_M393_Read()

MIO_M392_ReadV() / MIO_M393_ReadV()

Additional Functions

• MIO_M392_GetRes() / MIO_M393_GetRes()

• MIO_M392_Version() / MIO_M393_Version()

• MIO_M392_Sync() / MIO_M393_Sync()

Pin Signal Pin Signal

1 In_0 14 In_8 (In_0-)

2 In_1 15 In_9 (In_1-)

3 In_2 16 In_10 (In_2-)

4 In_3 17 In_11 (In_3-)

5 In_4 18 In_12 (In_4-)

6 In_5 19 In_13 (In_5-)

7 In_6 20 In_14 (In_6-)

8 In_7 21 In_15 (In_7-)

9 BI 22 Trigger

10 GND 23 +15V

11 GND 24 -15V

12 GND 25 +5V

13 GND

1 14

2513

CarMaker Programmer’s Guide Version 2.1.6

Page 144: IPG_CarMaker Programmers Guide

144MIO – M-Module Input/Output

Supported M-Modules

8.1.11 M461/3: Pulse Width and Angle Measurement (4 channels)

Connector assignment M461/3

Initialization, Configuration

• MIO_M461_3_Config()

• MIO_M461_3_Reset()

• MIO_M461_3_SetPolarity()

Get Signals

• MIO_M461_3_GetWidth()

• MIO_M461_3_GetWidthV()

• MIO_M461_3_GetAngle()

• MIO_M461_3_GetAngleV()

Pin X2 Signal

1, 14 1, 2 IO_GND (ground for voltage separated I/O)

6, 19 11, 12 IO_VCC (5V f. voltage separated I/O)

11 21 IMB6: /SYNC, signal for frequency synchronization

13 VME_GND

15 4 Input_0, pulse width/frequency

16 6 Input_1, pulse width/frequency

17 8 Input_2, pulse width/frequency

18 10 Input_3, pulse width/frequency

24 22 IMB7: OSC, clock for frequency

25 24 IMB9: /Reset (mostly not necessary)

1 14

2513

CarMaker Programmer’s Guide Version 2.1.6

Page 145: IPG_CarMaker Programmers Guide

145MIO – M-Module Input/Output

Programming M-Module I/O

8.2 Programming M-Module I/O

The initialization process for the MIO software module depends on your hardware configu-ration. First, you have to initialize the MIO software module in general. Then, according tothe installed M-Module hardware, you initialize the installed M-Module carrier boards, fol-lowed by successive configuration of the mounted M-Modules. A flow chart of the wholeprocess is shown in Figure 8.1.

Of course, a wrong initialization may affect the operability of the whole test stand. So, youhave to react on any error during the hardware initialization. To simplify this process, theMIO software module collects errors internally in a list and allows you to check for errors atsome particular points of time. By this way, it is not necessary to check every single call toMIO_xx() functions.

8.2.1 MIO Initialization

The first step to initialize the MIO hardware is the initialization of the MIO software modulein general, by calling the function MIO_Init() . The function checks, if the driver of the device/dev/MIO fits to the version of the MIO software module.

Figure 8.1: Initialization of the MIO software module

No

Yes

No

Yes

MIO_Init()

MIO_ErrorGet()

Errors?

MIO Initialization

Log Error

MIO_ErrorGet() moreErrors?

Error Handling

Exit

MIO_MasterConfig()

Carrier Board Initialization

No

YesmoreBoards?

MIO_Mxx_Config()

M-Module Configuration

No

YesmoreModules?

MIO_ResetModules()

Errors?MIO_ErrorGet()

No

Yes

MIO Initialization OK

CarMaker Programmer’s Guide Version 2.1.6

Page 146: IPG_CarMaker Programmers Guide

146MIO – M-Module Input/Output

Programming M-Module I/O

As the only argument, MIO_Init() requires the base address of the VME bus addressspace, where the MIO hardware is mapped to. In the CarMaker environment, there are twoVME bus address spaces available by default: A16/D16 and A24/D16 . The two global pointervariables A16D16 and A24D16 point to these VME bus address spaces and can be passeddirectly to MIO_Init() .

If you want to use the MIO hardware in a different VME bus address space, you might haveto map the address space on your own. With LynxOS, running on the Motorola Single BoardComputers MVME2400, MVME2600 and MVME5100, there are the following VME busaddress spaces available:

With LynxOS, running on the Motorola MVME5500, the Kernel addresses differ:

To map a VME bus address space into a user process, you have to open the memory device/dev/mem . Once opened, you can map any Kernel Physical address as an offset to the filedescriptor of the memory device, into the address space of a user process. This is donewith the help of the system call mmap() . The following Listing 8.1 shows how to map the A32/D32 address space:

Table 8.1: VME bus address spaces (MVME2x00, MVME5100)

VME bus address space Kernel Physical Address

A32/D32 0xd0000000 .. 0xdfffffff

A24/D16 0xe0000000 .. 0xe0ffffff

A32/D16 0xe1000000 .. 0xef7fffff

A16/D32 (A16/D16) 0xefff0000 .. 0xefffffff

Table 8.2: VME bus address spaces (MVME5500)

VME bus address space Kernel Physical Address

A32/D32 0xd0000000 .. 0xdfffffff

A24/D16 0xe0000000 .. 0xe0ffffff

A32/D16 0xe1000000 .. 0xe17fffff

A16/D32 (A16/D16) 0xe1800000 .. 0xe180ffff

Listing 8.1: Example for the mapping of a VME bus address space

1: /* mapping VMEbus A32/D32 address space */2: int MemDev;3: void A32D32;4: unsigned pflags = (PROT_READ | PROT_WRITE | PROT_EXEC | PROT_UNCACHE);5: unsigned mflags = (MAP_SHARED);6:7: /* open memory device */8: if ((MemDev=open("/dev/mem", O_RDWR)) < 0) {9: perror("open ’/dev/mem’");

10: exit(1);11: }12:13: A32D32 = mmap(NULL, 0x10000000, pflags, mflags, MemDev, 0xd0000000);14: if (A32D32 == MAP_FAILED) {15: perror("mmap VMEbus A32/D32 address space");16: exit(1);17: }

CarMaker Programmer’s Guide Version 2.1.6

Page 147: IPG_CarMaker Programmers Guide

147MIO – M-Module Input/Output

Programming M-Module I/O

After calling MIO_Init() , it is strongly recommended to check, if the initialization was suc-cessful, or if an error occurred. If there was an error and you do not handle it before con-tinuing with the configuration of the MIO hardware, the application might cause bus errorsor segmentation violations. For an example of the error handling after calling MIO_Init() ,refer to Listing 8.2.

The rest of the MIO hardware initialization can be done in one step, without special errorhandling in between the different function calls.

8.2.2 M-Module Carrier Board Configuration

Depending on your hardware configuration, you have one ore more M-Module CarrierBoards in your realtime system installed. Each of it claims an address range of 2048 (MENA201, 4 M-Module slots), 512 (MEN B201, 1 M-Module slot) or 1024 (MEN B202, 2 M-Mod-ule slots) bytes in size, somewhere in the selected VME bus address space. Thus, each M-Module slot claims an address window of 512 (0x200) bytes.

The base address of a carrier board is selected by two DIL switches, located on top of theboard. The DIL switches allow you set bits 11 to 23 of the base address. For each addressbit, if the switch is “on”, the according address bit is compared with 0; if the switch is “off”,the according address bit is compared with 1. The following Figure 8.2 shows how to con-figure the DIL switches of the carrier boards A201S, B201 and B202 for A16/D16 access ataddress 0x0. If you have an older version of the A201 (A201 or A201N), refer to the hard-ware documentation from MEN.

The switch SRT selects the VME bus address space. If set to 1 (“off”), which is the factorydefault, the carrier board is configured for the A24/D16 address space. Setting SRTto 0 (“on”),configures the carrier board for the A16/D16 address space. In this case you should also setthe upper address lines A16 to A23 to 1 (“off”).

Of course, the carrier boards need not to be configured to claim a contiguous part of theVME bus address space, as well as the calls to MIO_MasterConfig() to configure the boards,need not to be performed in ascending order. But, it is advisable to configure the first carrierboard for the base address 0x0, the second for 0x800 (A201), and so forth. This helps toavoid confusions. In the same way, you should configure the carrier board with the lowestaddress first, then the remaining boards in ascending order. Refer to Listing 8.2 for anexample.

Figure 8.2: Setting the base address on M-Module Carrier Boards A201S, B201 and B202

SRTunusedunusedA11A12A13A14A15

onoff

01

A16A17A18A19A20A21A22A23

1

234

56

78

1

234

56

78

CarMaker Programmer’s Guide Version 2.1.6

Page 148: IPG_CarMaker Programmers Guide

148MIO – M-Module Input/Output

Programming M-Module I/O

The function MIO_MasterConfig() communicates with the MIO driver in order to scan the giv-en address range for MIO hardware. Normally, probing an unused VME address causes abus error, which crashes the application. By scanning the base address through the MIOdriver, VME bus errors are caught transparently to the user process. If no MIO hardware isfound at the given address, an error is stored in the MIO error list and can be checked after-wards. The application will not crash because of nonexistent hardware.

8.2.3 M-Module Configuration

After the configuration of the M-Module Carrier Boards, you have to configure the installedM modules, each with the appropriate MIO_Mxx_Config() function. Each MIO_Mxx_Config()function requires at least one argument, the slot number of the M module.

When registering a module, the MIO software module checks, if there is a M moduleinstalled at the given slot, and if the type of the installed module matches the selectedMIO_Mxx_Config() function. If a mismatch is detected, an error is stored in the MIO error listto be checked afterwards. However, in some circumstances a module mismatch cannot beruled out completely: some older M modules do not have an Id EEPROM, so the MIO soft-ware module cannot determine the type of installed module and has to rely on your inputs.

If you do not want the MIO_Mxx_Config() to detect a module type mismatch, call the functionMIO_CheckModuleType() first. This function checks, if there is a M module located at the givenslot, and if the module matches the given module type.

The slot numbers of the installed M modules depend on the hardware configuration and onthe order in which the M-Module Carrier Boards are initialized. Normally, the carrier boardwith the lowest address gets assigned slots 0 to 3 (A201), followed by the remaining boardsin ascending order at slots 4 to 7 for the second, slots 8 to 11 for the third, and so forth. Oneach carrier board, the rightmost M module is the one with the lowest slot number.

A typical hardware configuration is shown in Figure 8.3.

After all M modules have been registered, and prior to any access to the modules, you haveto check again if there was an error during the MIO hardware initialization. If there was anerror and you do not handle it before accessing the MIO hardware, the application mightcause bus errors or segmentation violations. For an example of the error handling after theregistration of M modules, refer to Listing 8.2.

The last step of the MIO hardware initialization is to reset all M modules to their initial stateby calling MIO_ResetModules() .

Figure 8.3: Typical MIO configuration

me

n

A20

1S

Slot 4: M15Slot 5: M15Slot 6: M43Slot 7

A20

1S

me

n

Slot 0: M34Slot 1: M62Slot 2: M51Slot 3: M31

me

n

A20

1SM

VM

E24

xx

MO

TOR

OLA

DEBUG ETHERNET

AB

T

RS

T

PCI MEZZANINE CARD PCI MEZZANINE CARD

Slot 8Slot 9Slot 10Slot 110x1000

0x0800

0x0000

CarMaker Programmer’s Guide Version 2.1.6

Page 149: IPG_CarMaker Programmers Guide

149MIO – M-Module Input/Output

Programming M-Module I/O

8.2.4 Error Handling

Initializing the MIO hardware is a critical part. If the hardware configuration does not matchthe requirements of the application, the MIO hardware cannot be accessed safely. Access-ing wrong or nonexistent MIO hardware, causes VME bus errors, which crashes the appli-cation. During the initialization, the MIO software module detects hardware mismatchesand catches VME bus errors. Any error that occurs during the initialization is stored in anerror list, together with a detailed description.

As the MIO software module stores a couple of errors, it is not necessary to check for errorsafter every MIO function call. This helps to keep the source code of your application man-ageable and readable. However, there are to points of time, at which its is strongly recom-mended to check for errors: after calling MIO_Init() and after the registration of the MIO

CarMaker Programmer’s Guide Version 2.1.6

Page 150: IPG_CarMaker Programmers Guide

150MIO – M-Module Input/Output

Programming M-Module I/O

hardware, before accessing M modules (especially before calling MIO_ResetModules() ). Thefollowing Listing 8.1 shows the MIO initialization of a typical CarMaker/HIL MIO hardwareconfiguration. You can use it as template four your own application.

Checking for errors should always be done in a loop, until there are no more errors avail-able. Use the function MIO_ErrorGet() to obtain error codes and error descriptions from theMIO software module. Calling this function returns the oldest error and deletes it from theerror list. If there are errors – including the one which is returned – MIO_ErrorGet() returnsa value greater than 0. If there are no more errors left, the return value is 0.

Listing 8.2: Initialization of the MIO hardware

1: int2: IO_Init(void)3: {4: tMIO_ErrCode ErrCode;5: const char *ErrMsg;6:7: Log("IO Configuration: %d\n", ConnectedIO);8:9: /*** MIO software module(s): check version numbers */

10: MIO_CheckVersion();11:12: /*** hardware configuration */13: if (ConnectedIO == IO_DemoApp) {14: int nErrors = Log_nError;15:16: /*** MIO initialization */17: if (MIO_Init(A16D16) < 0) {18: while (MIO_ErrorGet(&ErrCode, &ErrMsg) > 0)19: LogErrF(EC_General, ErrMsg);20: LogErrF(EC_General, "MIO initialization failed. IO disabled (1)");21: SetConnectedIO("none");22: return -1;23: }24:25: /*** MEN carrier board initialization */26: MIO_MasterConfig(0, 4, 0); /* A201S, 4 slots */27: MIO_MasterConfig(4, 4, 0x800); /* A201S, 4 slots */28:29: Slot.AD = 0; Slot.DA = 1; Slot.CAN = 2; Slot.Din = 3;30: Slot.FG1 = 4; Slot.FG2 = 5; Slot.Rel = 6;31:32: /*** module set up */33: MIO_M34_Config(Slot.AD); /* 12bit Analog In, (16 Channels) */34: MIO_M62_Config(Slot.DA); /* 12bit Analog Out, (16 Channels) */35: MIO_M51_Config(Slot.CAN, -1); /* CAN interface, ( 4 Channels) */36: MIO_M31_Config(Slot.Din); /* 16bit Digital In */37: MIO_M15_Config(Slot.FG1); /* digital FG */38: MIO_M15_Config(Slot.FG2); /* digital FG */39: MIO_M43_Config(Slot.Rel); /* 8bit Relais Output */40:41: /*** check for errors */42: while (MIO_ErrorGet(&ErrCode, &ErrMsg) > 0)43: LogErrF(EC_General, ErrMsg);44: if (nErrors != Log_nError) {45: LogErrF(EC_General, "MIO initialization failed. IO disabled (2)");46: SetConnectedIO("none");47: return -1;48: }49:50: MIO_ResetModules();51: }52:53: return 0;54: }

CarMaker Programmer’s Guide Version 2.1.6

Page 151: IPG_CarMaker Programmers Guide

151MIO – M-Module Input/Output

Programming M-Module I/O

If there was an error during the initialization of the MIO hardware, it is not safe to access theM modules. It is strongly recommended to disable I/O and prompt the user to solve the prob-lems first.

CarMaker Programmer’s Guide Version 2.1.6

Page 152: IPG_CarMaker Programmers Guide

152MIO – M-Module Input/Output

Administrative Functions

8.3 Administrative Functions

8.3.1 Initialization and M-Module Configuration

MIO_Init()

Function prototype

int MIO_Init(void *IO_Space)

Description

This function initializes the MIO module. It has to be called once at program start and priorto any other MIO function. The registration table of M modules will be cleared, the configu-ration of all modules will get lost.

In order to assure proper access to the M modules, MIO_Init() opens the device /dev/MIOand checks the version of the MIO device driver. The initialization fails, if the MIO modulewas compiled with a newer version of the MIO driver, or if the compatibility version of theMIO driver is newer than the MIO module.

The argument IO_Space gives the base address of the VME bus address space, where allM modules are located.

If the initialization was successful, MIO_Init() returns a file handle to the MIO driver (>= 0),otherwise it returns an error code (< 0).

Example if (MIO_Init(A16D16) < 0) { while (MIO_ErrorGet(&ErrCode, &ErrMsg) > 0) LogErrF(EC_General, ErrMsg); LogErrF(EC_General, "MIO initialization failed. IO disabled"); return -1;}

MIO_MasterConfig()

Function prototype

int MIO_MasterConfig(int StartSlotNo, int Slots, long BaseAddr)

Description

Call this function to register M module carrier boards. The type of carrier board is recog-nized by the argument Slots :

• MEN A201 (4 Slots)

• MEN B201 (1 Slot)

• MEN B202 (2 Slots)

The argument StartSlotNo gives the slot number for the first M module on the carrier board.BaseAddr gives the base address of the carrier board as an offset to the address of the VMEbus address space.

CarMaker Programmer’s Guide Version 2.1.6

Page 153: IPG_CarMaker Programmers Guide

153MIO – M-Module Input/Output

Administrative Functions

In this way you can register different types of M module carrier boards in an arbitrary order.You can choose nearly freely the assignment of slot numbers to the M modules. Of course,it is recommended to configure the carrier boards contiguous in increasing order to avoidconfusions.

If BaseAddr has an invalid value, or if any of the slots StartSlotNo .. StartSlotNo+Slots-1are already in use, or if no M module carrier board is detected at BaseAddr , thenMIO_MasterConfig() returns an error code. Otherwise, the return value is 0.

Example MIO_MasterConfig(0, 4, 0);MIO_MasterConfig(4, 4, 2048);

This registers two M module carrier boards, each with 4 slots (type MEN A201). The firstboard is configured to occupy slots 0 .. 3, beginning at offset 0, the second carrier boardhas an offset of 2048 and continues with slots 4 .. 7.

MIO_CheckModuleType()

Function prototype

int MIO_CheckModuleType(int Slot, int Type)

Description

This function checks, if there is a M module located at a given slot and if it is of a specifictype.

Slot gives the M module slot where the module is mounted, Type specifies the module type(M module number) to be expected.

If there is no M module located at Slot , or if the M module is not of type Type , then a value<0 is returned. If there is a M module located at slot Slot , but the module type could not bedetermined due to a lack of an Id EEPROM, then a value >0 is returned. If the M module atslot Slot is of type Type, then MIO_CheckModuleType() returns 0.

Example if (MIO_CheckModuleType(4, MIO_MT_M35) == 0) MIO_M35_Config(4);else if (MIO_CheckModuleType(4, MIO_MT_M34) == 0) MIO_M34_Config(4);else return -1;

This example checks, if there is either a M35 module or a M34 module located at slot 4 andautomatically calls the appropriate MIO_Mxx_Config() function. It is a common way to initial-ize one of the hard- and software compatible A/D conversion modules M34, M35 or M35N,without being aware of the exact hardware configuration.

MIO_RegisterModule()

Function prototype

int MIO_RegisterModule(int Slot, int Type)

Description

Before a M module can be used, i t has to be registered with the funct ionMIO_RegisterModule() .

CarMaker Programmer’s Guide Version 2.1.6

Page 154: IPG_CarMaker Programmers Guide

154MIO – M-Module Input/Output

Administrative Functions

The registration of M modules is done automatically by the MIO_Mxx_Config() function. Youdo not have to call this function explicitly. However, in some cases – e.g. if you implementsupport for an unsupported M module on your own – this function might be useful.

Slot gives the M module slot where the module is mounted, Type specifies the module type(M module number).

The function MIO_RegisterModule() scans the given M module slot and checks by readingthe contents of the Id EEPROM, if the module type matches Type . If Slot is out of range, ifthere is a different or even no M module mounted at Slot , then an error code is returned. IfType matches the type of the mounted M module at Slot – or if the module has no IdEEPROM – then MIO_RegisterModule() returns 0.

MIO_ResetModules()

Function prototype

void MIO_ResetModules(void)

Description

This function scans all configured M modules and calls the specific MIO_Mxx_Reset() func-tions, in order to (re-)initialize all configured M modules.

This function should be called at the beginning of your application, after all M modules havebeen configured successfully.

MIO_DeleteAll()

Function prototype

void MIO_DeleteAll(void)

Description

At the end of your application, before exiting and after the last access to any M module, thisfunction should be called. MIO_DeleteAll() marks all configured M modules as unused andfrees all occupied resources. Before using any M module again, the associatedMIO_Mxx_Config() function has to be called again.

8.3.2 MIO and M-Module Information

MIO_GetVersion()

Function prototype

const char *MIO_GetVersion(void)

Description

This function returns a string with some information of the MIO software module. The stringlooks like

CarMaker Programmer’s Guide Version 2.1.6

Page 155: IPG_CarMaker Programmers Guide

155MIO – M-Module Input/Output

Administrative Functions

mio.o lynx4 1.0.3 2005-07-07

and contains the name of the MIO software module (mio.o ), the target architecture (lynx4),the version of the module and the compilation date. This identification is used to check, ifthe header file which you use when compiling your application, matches the used MIO soft-ware module.

MIO_ModuleInfo()

Function prototype

char *MIO_ModuleInfo(int Slot, MIO_Type ModuleType)

Description

Returns a description for a M module. If Slot has a valid value – which means that there isa module found at Slot – then MIO_ModuleInfo() returns a description of this module. If Slothas an invalid value (e.g. -1), then a description for a M module of type ModuleType isreturned.

MIO_ModuleShow()

Function prototype

void MIO_ModuleShow(void)

Description

This function prints configuration information for all registered M modules to stdout .Please use this function for debugging purpose, only.

8.3.3 VME Bus Interrupt Handling

MIO_SetIntrHandler()

Function prototype

void MIO_SetIntrHandler(int Slot, int IntrLevel, int IntrVecNo, int ExternalDTACK)

Description

This function configures the MC68C153 compatible interrupt controller on the MEN M mod-ule carrier boards A201, B201 and B202.

The location of the M module is specified by Slot . To activate interrupts for the given M mod-ule, the interrupt controller at Slot is programmed with the interrupt level IntrLevel (0 .. 7)and the interrupt vector IntrVecNo (valid range is 48 .. 255 for VME bus I/O interrupts underLynxOS). The flag ExternalDTACK specifies, if the M module at Slot generates the interruptvector and the /DTACK signal on its own (ExternalDTACK = 1), or if this has to be done bythe interrupt controller (ExternalDTACK = 0),.

CarMaker Programmer’s Guide Version 2.1.6

Page 156: IPG_CarMaker Programmers Guide

156MIO – M-Module Input/Output

Administrative Functions

MIO_VMEIntrDisable()

Function prototype

void MIO_VMEIntrDisable(void)

Description

This function disables interrupts for all mounted M modules by configuring the MC68C153compatible interrupt controller on the MEN M module carrier boards A201, B201 and B202.

MIO_VMEIntrEnable()

Function prototype

void MIO_VMEIntrEnable(void)

Description

This function (re-)enables interrupts for all mounted M modules by configuring theMC68C153 compatible interrupt controller on the MEN M module carrier boards A201,B201 and B202.

8.3.4 Shared Memory Management

MIO_GetShMem()

Function prototype

char *MIO_GetShMem(tMIO_SharedMem *shmem)

Description

With LynxOS, the only way to allocate physical contiguous memory in user processes areShared Memory Objects. Physical contiguous memory is required, if both, user processand kernel, need to access a portion of memory simultaneously, especially if the memoryhas to be accessed within an interrupt routine.

A Shared Memory Object is identified by an unique name, which has to be constructedaccording the standard path name rules. Once created, a Shared Memory Object can beaccessed by other processes, too. It continues to exist even after the creating process ter-minates.

The function MIO_GetShMem() creates a Shared Memory Object and maps physical contigu-ous memory to it. The name and the desired size for the Shared Memory Object is passedthrough the pointer *shmem to a data structure of type tMIO_SharedMem :

Listing 8.3: The tMIO_SharedMem struct

1: typedef struct {2: char *Addr;3: int fid;4: int Len;5: char *Name;6: } tMIO_SharedMem;

CarMaker Programmer’s Guide Version 2.1.6

Page 157: IPG_CarMaker Programmers Guide

157MIO – M-Module Input/Output

Administrative Functions

MIO_GetShMem() takes the name, pointed to by the data field *Name, to open a new SharedMemory Object with the system call shm_open() . If a Shared Memory Object with the samename already exists, it will be deleted first. The file descriptor of the newly created SharedMemory Object will be stored in the data field fid .

The desired size of the Shared Memory Object is specified by the data field Len . If Len is nota multiple of the page size (4 kB), Len will be rounded up to the next multiple of the pagesize. The size of the Shared Memory Object is set with the system call ftruncate() .

The next step is to map physical contiguous memory to the Shared Memory Object of Lenbytes. This is done with the system call mmap() . The address to the mapped memory regionis stored in the data field *Addr .

If the creation of the Shared Memory Object was successful, MIO_GetShMem() returns apointer to the mapped memory region. Otherwise, MIO_GetShMem() returns the NULL pointer.

MIO_RemShMem()

Function prototype

void MIO_RemShMem(tMIO_SharedMem *shmem)

Description

Shared Memory Objects, that were created by the function MIO_GetShMem() , can be deletedwith a call to function MIO_RemShMem().

Again, MIO_RemShMem()takes a pointer to the data structure tMIO_SharedMem (see Listing 8.3),which contains the address to the mapped memory region (*Addr ), the file descriptor to theShared Memory Object (fid ), the length of the mapped memory region (Len ) and the nameof the Shared Memory Object (*Name).

MIO_RemShMem() first unmaps the mapped memory region at *Addr with the system callmunmap() and closes the Shared Memory Object by calling the system call close() . Afterthat, the Shared Memory Object is deleted with the system call shm_unlink() .

With shm_unlink() , the Shared Memory Object is deleted immediately only, if there are noother references to it. If there are still references – e.g. by another process – then theShared Memory Object will only be marked for deletion. Only if all file descriptors to it havebeen closed, the Shared Memory Object will be finally deleted. This might cause problems,if you recreate a formerly deleted Shared Memory Object again, while another processaccesses the Shared Memory Object, too.

8.3.5 Error Handling Functions

MIO_ErrorGet()

Function prototype

int MIO_ErrorGet(tMIO_ErrCode *ErrCode, const char **ErrMsg)

CarMaker Programmer’s Guide Version 2.1.6

Page 158: IPG_CarMaker Programmers Guide

158MIO – M-Module Input/Output

Administrative Functions

Description

If errors occur during a call to MIO_xx() functions, an error message and a description isgenerated and stored in an internal error list. This list holds up to 10 errors, which can beobtained with the function MIO_ErrorGet() .

MIO_ErrorGet() takes the oldest error in the list and writes the error code to the variablepointed to by *ErrCode . A pointer to the error message is stored in the variable pointed toby **ErrMsg . The error message contains a brief description of the error, which is very usefulto find the reason of the error.

A return value < 0 indicates, that there was an error while returning the error – usually, thishappens only, if either *ErrCode or **ErrMsg are NULL. A return value >= 0 indicates that thereare remaining errors, including the one which is returned at the same time. If there are nomore errors available, then 0 is returned.

If MIO_ErrorGet() returns an error, then the error is also deleted from the list.

MIO_ErrorClear()

Function prototype

void MIO_ErrorClear(void)

Description

This function clears the list of errors, even if no errors were requested with the functionMIO_ErrorGet() .

CarMaker Programmer’s Guide Version 2.1.6

Page 159: IPG_CarMaker Programmers Guide

159MIO – M-Module Input/Output

M-Module Function Description

8.4 M-Module Function Description

8.4.1 M3: Binary Outputs (16 channels)

MIO_M3_Config()

Function prototype

int MIO_M3_Config(int Slot)

Description

By calling the function MIO_M3_Config() the configuration of the I/O hardware, i.e. the allo-cation of a M-Module card location with a module of type M3 is specified. This function mustonly be called one time, before any attempted access to the module.

The argument Slot is the slot number (position) of the M-Module.

Initial state of all output channels is undefined, and determined by the given module hard-ware. If the module cannot be configured/initialized the function returns an error code, oth-erwise 0 is returned.

MIO_M3_Set()

Function prototype

void MIO_M3_Set(int Slot, int Value)

Description

Sets the value of all binary outputs (e.g. sets the relay positions). The bit position indicatesthe channel number. For example, channel 0 would be set with the lowest bit, channel 1 thesecond lowest bit, etc.

The argument Slot is the slot number (position) of the M-Module.

8.4.2 M4: Analog Outputs (4 channels)

MIO_M4_Config()

int MIO_M4_Config(int Slot)

Description

By calling the function MIO_M4_Config() the configuration of the I/O hardware, i.e. the allo-cation of a M-Module card location with a module of type M4 is specified. This function mustonly be called one time, before any attempted access to the module.

The argument Slot is the slot number (position) of the M-Module.

Initial state of all output channels:

• Range of values 0V .. 10V

CarMaker Programmer’s Guide Version 2.1.6

Page 160: IPG_CarMaker Programmers Guide

160MIO – M-Module Input/Output

M-Module Function Description

• Output levels: 0V

If the module cannot be configured/initialized the function returns an error code, otherwise0 is returned.

MIO_M4_Reset()

void MIO_M4_Reset(int Slot)

Description

The function sets all output channels for the module back to the initial state.

MIO_M4_SetMode()

void MIO_M4_SetMode(int Slot, int Ch, int Gain, int Bipolar)

Description

With the help of this function the amplification factor can be selected and switched betweenunipolar/bipolar mode for a channel.

Slot and Ch indicate the card location and the channel number.

The arguments Gain and Bipolar specify the voltage range of the outputs:

MIO_M4_SetModeByte()

void MIO_M4_SetModeByte(int Slot, unsigned char Mode)

Description

Sets the mode register (affects all channels) of the AD transducer. See hardware Descrip-tion from MEN.

Slot indicates the card location of the module.

MIO_M4_Set()

void MIO_M4_Set(int Slot, int Ch, int Value)

Description

Sets the value of an output channel.

Gain Bipolar Voltage Range [V]

0 0 0 V .. 10 V

0 1 -5 V .. 5 V

1 0 0 V .. 20 Va

a. Range is limited to approx. 15V1 1 -10 V .. 10 V

CarMaker Programmer’s Guide Version 2.1.6

Page 161: IPG_CarMaker Programmers Guide

161MIO – M-Module Input/Output

M-Module Function Description

Slot and Ch indicate the card location and the channel number.

Value : contains the desired value left justified in a 16bit short integer (not signed). i.e. inde-pendent of the width of the transducer (12 bits, 14 bits or 16 bits) the value 0 is the minimumvoltage level, 65535 the maximum voltage level. However, when set to bipolar mode ( seeMIO_M4_SetMode() ), 32768 stands for 0 V.

MIO_M4_SetV()

void MIO_M4_SetV(int Slot, int ChMask, int *Values)

Description

This function is similar to MIO_M4_Set() , but allows to set several channels simultaneously.This function makes setting several channels very efficient. The new values are transferredto the D/A converters, and the new levels appear at the outputs at the same time.

The argument Slot is the slot number (position) of the M-Module.

The channels are selected with the bit mask ChMask (bit 0 .. 3 used): Bit n is to be set to 1,if the channel n is to be set. ChMask = 0xf (1+2+4+8=0xf) would therefore mean that all fourchannels are to be set.

Values is a pointer to an array (vector), which contains the desired values listed consecu-tively, i.e. without gaps for the channels that are not selected.

8.4.3 M5: Analog Inputs (16/8 channels)

The older M5 module cannot be switched between unipolar/bipolar modes through soft-ware, but can only be modified through hardware. In each case, however, the appropriatehardware configuration function must be called!

MIO_M5_Config()

int MIO_M5_Config(int Slot)

Description

(see function description for MIO_M34_Config)

MIO_M5_Reset()

void MIO_M5_Reset(int Slot)

Description

(see function description for MIO_M34_Reset)

MIO_M5_Read()

void MIO_M5_Read(int Slot, int Ch, int Gain)

CarMaker Programmer’s Guide Version 2.1.6

Page 162: IPG_CarMaker Programmers Guide

162MIO – M-Module Input/Output

M-Module Function Description

Description

(see function description for MIO_M34_Read)

MIO_M5_Read_bp()

void MIO_M5_Read_bp(int Slot, int Ch, int Gain)

Description

(see function description for MIO_M34_Read_bp)

MIO_M5_ReadV()

void MIO_M5_ReadV(int Slot, unsigned ChMask, int GainMode, int *Values)

Description

(see function description for MIO_M34_ReadV)

8.4.4 M15: Frequency Generator (2 channels)

MIO_M15_Config()

int MIO_M15_Config(int Slot)

Description

By calling the function MIO_M15_Config() the configuration of the I/O hardware, i.e. the allo-cation of a M-Module card location with a module of type M15 is specified. This functionmust only be called one time, before any attempted access to the module.

After power-up, the states of the output lines are undefined. The output signals PB_x will beset to UL_x or UH_x, according to the Jumper settings J1 (controls PB_0) and J2 (controlsPB_1). However, the voltage levels of UL_x and UH_x may differ from -10V and +10V, respec-tively.

MIO_M15_Reset()

void MIO_M15_Reset(int Slot)

Description

Sets the frequency generator module back to the initial state:

• All voltage levels low/high are set to 0V

• Activates clock signal for D/A converters (12 bits resolution)

• Pulse rate = 1 Clock Unit

CarMaker Programmer’s Guide Version 2.1.6

Page 163: IPG_CarMaker Programmers Guide

163MIO – M-Module Input/Output

M-Module Function Description

MIO_M15_SetAnalogOut()

void MIO_M15_SetAnalogOut(int Slot, int Ch, unsigned Value)

Description

The function makes it possible to use the four D/A converters on the card, which normallydefine the low/high level of the frequency generator outputs as universal (slow) 12bit D/Aconverters.

Slot and Ch indicate the card location and the channel number:

Channel 0 = UH_0, channel 1 = UL_0, channel 2 = UH_1, channel 3 = UL_1.

The most significant 12 bits for the output voltage are to be indicated left justified in 16 a bitword, i.e. to 0x0 = -10V, 0xffff = +10V.

MIO_M15_SetLowHigh()

void MIO_M15_SetLowHigh(int Slot, int Ch, unsigned Low, unsigned High)

Description

Gives the voltage levels for the Low and High phase of the output signal.

Slot and Ch indicate the card location and the channel number.

Low and High contain the output voltage as a 16bit word (only the 12 most significant bitsare used). 0x0 = -10V, 0xffff = +10V.

Additional pins are available on the module that have the opposite voltage of the UL_x andUH_x signals (i.e. if UL_0 is +5V then there is a pin on the M15 module that will provide -5V).See the description of the M15 module for more information.

MIO_M15_SetMode()

void MIO_M15_SetMode(int Slot, int Ch, int Mode)

Description

This function allows you to control one of the four timer chips (of type 82C54), located onthe M-Module, directly. For further information, about how to address and program the threetimers on the 82C54, please refer to the appropriate data sheet.

Slot and Ch indicate the card location and the channel number (of one of the two functiongenerator channels).

MIO_M15_SetPulseWidth()

void MIO_M15_SetPulseWidth(int Slot, int Ch, unsigned Width)

CarMaker Programmer’s Guide Version 2.1.6

Page 164: IPG_CarMaker Programmers Guide

164MIO – M-Module Input/Output

M-Module Function Description

Description

Sets the pulse width of the output signal.

Slot and Ch indicate the card location and the channel number.

Width is the length of the low phase in “base clock” units, i.e. the number of periods of thesignal after the first divisor.

Example MIO_M15_SetPeriod(s, c, 8, 1000);MIO_M15_SetPulseWidth(s, c, 400);

Results in a 1000 Hz signal with 40% low.

MIO_M15_SetPeriod()

void MIO_M15_SetPeriod(int Slot, int Ch, unsigned Period0, unsigned Period1)

Description

Sets the period of the frequency generator.

Slot and Ch indicate the card location and the channel number.

Period0 and Period1 are the values for the two successively switched 16 bit timers. Theclock frequency is 8MHz, the unit for Period0 is therefore 0.125 micro seconds. The mini-mum adjustable period is 0.5 us.

MIO_M15_Trigger()

void MIO_M15_Trigger(int Slot, int Ch)

Description

(planned function, not yet implemented)

Triggers the beginning of the next period. Is, among other things, useful with the change ofa long time period on a much shorter time period. Normally the short time period is affectedonly after the current, long period.

Slot and Ch indicate the card location and the channel number.

8.4.5 M27: Binary Output (16 channels)

MIO_M27_Config()

int MIO_M27_Config(int Slot)

Description

(see function description for MIO_M3_Config() )

CarMaker Programmer’s Guide Version 2.1.6

Page 165: IPG_CarMaker Programmers Guide

165MIO – M-Module Input/Output

M-Module Function Description

MIO_M27_Set()

void MIO_M27_Set(int Slot, int Value)

Description

(see function description for MIO_M3_Set() )

8.4.6 M31: Binary Inputs (16 channels)

MIO_M31_Config()

int MIO_M31_Config(int Slot)

Description

By calling the function MIO_M31_Config() the configuration of the I/O hardware, i.e. the allo-cation of a M-Module card location with a module of type M31, is specified. This functionmust only be called one time, before any attempted access to the module.

The module M31 is software-compatible to the module M32.

Slot is the number of the M-Module card location.

MIO_M31_Read()

int MIO_M31_Read(int Slot)

Description

Reads the values of the 16 input ports as a 16 bit value. Bit n corresponds to input n.

Slot is the number of the M-Module card location.

8.4.7 M32: Binary Inputs (16 channels)

MIO_M32_Config()

int MIO_M32_Config(int Slot)

Description

(see function description for MIO_M31_Config() )

MIO_M32_Read()

int MIO_M32_Read(int Slot)

Description

(see function description for MIO_M31_Read() )

CarMaker Programmer’s Guide Version 2.1.6

Page 166: IPG_CarMaker Programmers Guide

166MIO – M-Module Input/Output

M-Module Function Description

8.4.8 M34: Analog Inputs (16/8 channels)

MIO_M34_Config()

int MIO_M34_Config(int Slot)

Description

By calling the function MIO_M34_Config() the configuration of the I/O hardware, i.e. the allo-cation of a M-Module card location with a module of type M34 is specified. This functionmust only be called one time, before any attempted access to the module.

The modules M34, M35 and M35N are software-compatible.

Slot is the number of the M-Module card location.

Initial state of input channels:

Application factor for an input signal = 1

If the module cannot be configured/initialized the function returns an error code, otherwise0 is returned.

MIO_M34_Reset()

void MIO_M34_Reset(int Slot)

Description

The function resets the input ports of the module to the initial state (see MIO_M34_Config() ).

MIO_M34_Read()

int MIO_M34_Read(int Slot, int Ch, int Gain)

Description

The function reads the measured value of an input port in unipolar mode (measuring range,0 V .. 10 V when gain = 1).

Time requirement on successive calls, without change on channel or gain:

If channel or gain are changed by the preceding call then the double conversion time isneeded. With the help of the function MIO_M34_ReadV() several channels can be queriedmore efficiently (approximately simple transformation time per channel).

Slot and Ch indicate the card location and the channel number.

M-Module Conversion time

M5 10 us

M34 10 us

M35 14 us

M35N 7.8 us

CarMaker Programmer’s Guide Version 2.1.6

Page 167: IPG_CarMaker Programmers Guide

167MIO – M-Module Input/Output

M-Module Function Description

The parameter Gain determines the amplification factor:

• Gain = 0x00 for an amplication factor 1

• Gain = 0x01 for an amplication factor 2

• Gain = 0x10 for an amplication factor 4

• Gain = 0x11 for an amplication factor 8

Return Value: The 12 bits measured value (with M35/M35N: 14 bits), left justified in a 16 bitinteger value.

MIO_M34_Read_bp()

int MIO_M34_Read_bp(int Slot, int Ch, int Gain)

Description

Same function as MIO_M34_Read() , except that the read is done in bipolar mode.

Return Value: The 12 bits measured value (with M35/M35N: 14 bits), left justified in a 16 bitinteger value.

MIO_M34_ReadV()

void MIO_M34_ReadV(int Slot, unsigned ChMask, int GainMode, int *Values)

Description

Similar to MIO_M34_Read() , except several channels can be read simultaneously. The func-tion is very efficient when many channels are being read.

Slot is the number of the M-Module card location.

ChMask is a bit field (bit 0..3 used), which specifies the channels which can be queried. If bitn has the value 1, the channel n is queried.

Example ChMask = 0x1f8;MIO_M34_ReadV(s, c, ChMask, 0, v);

Causes the inquiry of channel 3 .. 8.

Values is an array pointer to a memory location where the values (beginning with the lowestchannel number) will be stored.

8.4.9 M35/M35N: Analog Inputs (16/8 channels)

MIO_M35_Config()

int MIO_M35_Config(int Slot)

Description

(see function description for MIO_M34_Config() )

CarMaker Programmer’s Guide Version 2.1.6

Page 168: IPG_CarMaker Programmers Guide

168MIO – M-Module Input/Output

M-Module Function Description

MIO_M35_Reset()

void MIO_M35_Reset(int Slot)

Description

(see function description for MIO_M34_Reset() )

MIO_M35_Read()

int MIO_M35_Read(int Slot, int Ch, int Gain)

Description

(see function description for MIO_M34_Read() )

MIO_M35_Read_bp()

int MIO_M35_Read_bp(int Slot, int Ch, int Gain)

Description

(see function description for MIO_M34_Read_bp() )

MIO_M35_ReadV()

void MIO_M35_ReadV(int Slot, unsigned ChMask, int GainMode, int *Values)

Description

(see function description for MIO_M34_ReadV() )

8.4.10 M43: Relay Outputs (8 channels)

MIO_M43_Config()

int MIO_M43_Config(int Slot)

Description

(see function description for MIO_M3_Config() )

MIO_M43_Set()

void MIO_M43_Set(int Slot, int Value)

Description

(see function description for MIO_M3_Set() )

CarMaker Programmer’s Guide Version 2.1.6

Page 169: IPG_CarMaker Programmers Guide

169MIO – M-Module Input/Output

M-Module Function Description

8.4.11 M51: Quadruple CAN Interface

MIO_M51_Config()

int MIO_M51_Config(int Slot, int IRQlevel)

Description

By calling the function MIO_M51_Config() the configuration of the I/O hardware, i.e. the allo-cation of a M-Module card location with a module of type M51 is specified. This functionmust only be called one time, before any attempted access to the module.

Slot is the number of the M-Module card location.

IRQlevel specifies the priority that the interupts will be handled. The possible values are list-ed below:

• negative value (usually -1) - IRQlevel will be automatically chosen

• zero - if 0 is specified then the module will be configured in polling mode with interruptsdisabled

• one through seven - a value in the range 1 .. 7 sets the interrupt priority level, with onebeing the highest priority and seven being the lowest priority

All CAN controllers are set to the default state, listed below:

• Baud rate of 200 kBit/s, single sample point (see MIO_M51_SetCommParam() )

• Send and receive buffer size is 64 messages (see MIO_M51_SetBufSize() )

• No mailboxes are defined (see MIO_M51_MBoxCreate() )

• No message IDs are enabled (see MIO_M51_EnableIds() )

• Transparency mode is turned off (see MIO_M51_SetTransMode() )

• There is no timeout when sending a message (see MIO_M51_SetTxTimeout() )

If the module cannot be configured/initialized the function returns an error code, otherwise0 is returned.

MIO_M51_Reset()

void MIO_M51_Reset(int Slot)

Description

The function resets all CAN interfaces back to the initial state (see MIO_M51_Config() ). Arunning transmission, if necessary, is stopped and the messages in the send and receivebuffers are lost. The transmission parameters and mailboxes must be reconfigured thereaf-ter.

MIO_M51_Delete()

void MIO_M51_Delete(int Slot)

CarMaker Programmer’s Guide Version 2.1.6

Page 170: IPG_CarMaker Programmers Guide

170MIO – M-Module Input/Output

M-Module Function Description

Description

Deactivates the module located in Slot and frees memory and resources allocated to themodule. All mailboxes for the module will be deleted and the resources deallocated.

After the call to MIO_M51_Delete() the function MIO_M51_Config() must be called before themodule can be used again.

MIO_M51_SetBufSize()

void MIO_M51_SetBufSize(int Slot, int Ch, int RxSize, int TxSize)

Description

The size of the send and receive buffers can be changed by calling MIO_M51_SetBufSize() .

Slot and Ch give the location and channel number of the CAN interface.

RxSize and TxSize indicate the number of messages which the receive and/or send bufferscan hold. The following applies to both parameters: minimum buffer size is 2, the maximumsize is not limited, and the default value is 64.

Realtime conditions will not be met when resizing the buffer to a larger size. Changing thebuffer size to something smaller, however, will meet realtime conditions.

MIO_M51_SetCommParam()

int MIO_M51_SetCommParam(int Slot, int Ch, int Baudrate, int SamplePoint, int SynchJumpWidth, int Sample3)

Description

With the function MIO_M51_SetCommParam() the CAN communication parameters are speci-fied. The values needed for the programming of the CAN interface module SJA1000 are rel-atively complex, are subject to a number of restrictions and are not particularly meaningfulas numerical values. For this reason more general and understandable parameters areused.

Slot and Ch give the location and channel number of the CAN interface.

Baudrate is the data transmission rate, e.g. 250000. Only values that can be derived by inte-gral division from 8 MHz (the oscillator frequency is 16 MHz, divisor >= 3) can be used.

SamplePoint indicates the sample point (i.e. the point in time within the bounds of the bitperiod that the bit will be evaluated as (1) high or (0) low) for the value of a bit. The indicationtakes place in per cent, relative to the bit period. Valid values: 0..100, typically: 65.

SynchJumpWidth specifies over how many internal clock units the time slot pattern per databit can be adapted. This makes a resynchronisation possible on the bit stream of the trans-mitter with a slightly deviating clock rate. Range of values: 1-4, typically: 2.

Sample3 is a flag that specifies whether the individual bits that are transmitted, are sampledonce (Sample3==0) or three times (Sample3==1). Usually with high data transmission ratesonly one sample is necessary, but with slower transmission rates the three sample methodis recomended.

If the requested baud rate is invalid, or impossible, the function returns an error code, oth-erwise 0 is returned.

CarMaker Programmer’s Guide Version 2.1.6

Page 171: IPG_CarMaker Programmers Guide

171MIO – M-Module Input/Output

M-Module Function Description

If the value of the selected bit period (dependent on the data transmission rate) is notknown, MIO_M51_SetCommParam() determines and uses the configuration with the smallestdeviation.

More details are available with the documentation of the SJA1000 controller from Phillips.

MIO_M51_SetTxTimeout()

void MIO_M51_SetTxTimeout(int Slot, int Ch, int Timeout)

Description

Currently has no effect.

MIO_M51_EnableIds()

void MIO_M51_EnableIds(int Slot, int Ch, int StartId, int n)

Description

MIO_M51_EnableIds() enables the receipt of the specified IDs, beginning with StartId andending with StartId + (n-1).

Slot und Ch give the location and channel number of the CAN interface.

The acceptance mask of the interface module is configured accordingly. SeeMIO_M51_SetTransMode() .

MIO_M51_DisableIds()

void MIO_M51_DisableIds(int Slot, int Ch, int StartId, int n)

Description

MIO_M51_DisableIds() removes n IDs from the list of accepeted IDs, beginning with StartIdand ending with StartId + n . This does not influence messages that are already containedin the receive buffer.

Slot und Ch give the location and channel number of the CAN interface.

The acceptance mask of the interface module is adapted automatically in order to keep theCPU load to a minimum.

MIO_M51_Poll()

int MIO_M51_Poll(void)

Description

This function is needed, if CAN interfaces are configured for Polling mode (seeMIO_M51_Config() ). It has to be called every milli second.

CarMaker Programmer’s Guide Version 2.1.6

Page 172: IPG_CarMaker Programmers Guide

172MIO – M-Module Input/Output

M-Module Function Description

MIO_M51_Poll() checks all registered M51 modules whether Polling mode is enabled or not.The CAN interfaces of the module are then checked for received CAN messages. All avail-abe messages will be copied out of the CAN controllers into the Rx buffer, ready to be readout by the functions MIO_M51_Recv() and MIO_M51_RecvExt() . MIO_M51_Poll() will also try tosend as many messages as possible available in the Tx buffer, where they are stored by thefunctions MIO_M51_Send() , MIO_M51_SendExt() and MIO_M51_SendV() .

Currently, there is a limitation when CAN controllers are used in Polling mode: The SJA1000CAN controllers on the M51 module only have a Rx FIFO on-chip, but no Tx FIFO. As aconsequence, in most cases only one CAN message can be sent with each call ofMIO_M51_Poll() . Even if you would call MIO_M51_Poll() several times per cycle, you couldnot be sure, that there will be no CAN messages left unsent in the Tx buffer. The Tx buffermay overflow, even if there is not much CAN traffic.

MIO_M51_Send()

int MIO_M51_Send(int Slot, int Ch, CAN_Msg *Msg)

Description

The indicated message is sent, i.e. written into the send buffer working as FIFO. The func-tion works non-blocking, i.e. it returns in each case immediately. If the send buffer is full, themessage is ignored and the error code -1 is returned.

Slot und Ch give the location and channel number of the CAN interface.

Msg is the address of a data structure CAN_Msg(see Listing 8.6), which contains the messageto be sent.

The function returns 0 on success, and -1 otherwise.

Since CarMaker 2.0, this function is deprecated. Use MIO_M51_SendExt() instead.

MIO_M51_SendExt()

int MIO_M51_SendExt(int Slot, int Ch, CAN_MsgExt *MsgExt)

Description

The indicated message is sent, i.e. written into the send buffer working as a FIFO. The func-tion works non-blocking, i.e. it returns in each case immediately. If the send buffer is full, themessage is ignored and the error code -1 is returned.

Slot and Ch give the location and channel number of the CAN interface.

MsgExt is the address of a data structure CAN_MsgExt (see Listing 8.7) which contains themessage to be sent.

CarMaker Programmer’s Guide Version 2.1.6

Page 173: IPG_CarMaker Programmers Guide

173MIO – M-Module Input/Output

M-Module Function Description

The function returns 0 on success, and -1 otherwise.

Example

You should always prefer to use this function instead of MIO_M51_Send() . Since CarMaker2.0, the SJA1000 CAN controllers are operated in the PeliCAN mode, which allows to dealwith extended CAN messages. The function MIO_M51_Send() is provided for compatibilityreason, only. In fact, MIO_M51_Send() is just a wrapper function, which copies the contentsof the old CAN_Msgstruct into the new struct CAN_MsgExt and finally calls MIO_M51_SendExt() .This results in a slight loss of performance.

MIO_M51_SendV()

int MIO_M51_SendV(int Slot, int Ch, int MsgId, void *Data, int DataLen)

Description

MIO_M51_SendV() is a variant of the function MIO_M51_SendExt() (MIO_M51_Send() ) with samefunctionality, however in this case the components of the CAN Message are specified asseparate parameters:

• the message Id is specified in MsgId ,

• the pointer to the data block is specified in Data

• the number of data bytes is specified in DataLen (0 .. 8)

See the description of MIO_M51_SendExt() .

Example

MIO_M51_SendBufClear()

void MIO_M51_SendBufClear(int Slot, int Ch)

Listing 8.4: Example for MIO_M51_SendExt()

1: {2: CAN_MsgExt m;3:4: m.MsgId = 123;5: m.FrameFmt = 0;6: m.RTR = 0;7: m.FrameLen = 2;8: m.Data[0] = 0x18;9: m.Data[1] = 0xFF;

10: MIO_M51_SendExt(2, 0, &m);11: }

Listing 8.5: Example for MIO_M51_SendV()

1: {2: static char Data1[] = {0x07, 0x00, 0x00, 0x00};3: static char Data2[] = {0x07, 0x00, 0xff, 0xff};4:5: MIO_M51_SendV(2, 0, 0x400, Data1, 4);6: MIO_M51_SendV(2, 0, 0x401, Data2, 4)7: }

CarMaker Programmer’s Guide Version 2.1.6

Page 174: IPG_CarMaker Programmers Guide

174MIO – M-Module Input/Output

M-Module Function Description

Description

The function empties the send buffer. A running transmission procedure (i.e. a messagewhich is being evaluated by the interface module) will not be affected.

Slot and Ch give the location and channel number of the CAN interface.

MIO_M51_SendStat()

int MIO_M51_SendStat(int Slot, int Ch)

Description

The function returns the number of messages that have not yet been sent from the sendbuffer. The function can be used to recognize a possible overflow of the send buffer or tomeasure the time requirement needed to empty the send buffer.

Slot and Ch give the location and channel number of the CAN interface.

MIO_M51_Recv()

int MIO_M51_Recv(int Slot, int Ch, CAN_Msg *Msg)

Description

Reads the next Message from the receive buffer. The function works non-blocking, i.e., itreturns immediately in each case. If the receive buffer is empty, the function returns theerror code (-1). On success, the return value is 0.

Slot and Ch give the location and channel number of the CAN interface.

The received message is returned in *Msg . The data structure CAN_Msghas the followingstructure:

In order to receive messages with certain ids, the id must be enabled by calling the functionMIO_M51_EnableIds() .

Since CarMaker 2.0, this function is deprecated. Use MIO_M51_RecvExt() instead.

MIO_M51_RecvExt()

int MIO_M51_RecvExt(int Slot, int Ch, CAN_MsgExt *MsgExt)

Listing 8.6: The CAN_Msg struct

1: typedef struct {2: unsigned short MsgId :11;3: unsigned short RTR :1;4: unsigned short FrameLen:4; /* 0..8 */5: unsigned char Data[8];6: } CAN_Msg;

CarMaker Programmer’s Guide Version 2.1.6

Page 175: IPG_CarMaker Programmers Guide

175MIO – M-Module Input/Output

M-Module Function Description

Description

Reads the next Message from the receive buffer. The function works non-blocking, i.e., itreturns immediately in each case. If the receive buffer is empty, the function returns theerror code (-1). On success, the return value is 0.

Slot and Ch give the location and channel number of the CAN interface.

The received message is returned in *MsgExt . The data structure CAN_MsgExt has the follow-ing structure:

In order to receive messages with certain ids the id must be enabled by calling the functionMIO_M51_EnableIds() .

You should always prefer to use this function instead of MIO_M51_Recv() . Since CarMaker2.0, the SJA1000 CAN controllers are operated in the PeliCAN mode, which allows to dealwith extended CAN messages. The function MIO_M51_Recv() is provided for compatibilityreason, only. In fact, MIO_M51_Recv() is just a wrapper function, which callsMIO_M51_RecvExt() and copies the contents of the new CAN_MsgExt struct into the old structCAN_Msg. This results in a slight loss of performance.

MIO_M51_RecvBufClear()

void MIO_M51_RecvBufClear(int Slot, int Ch)

Description

The function empties the receive buffer. The contents of the mailboxes are not affected.

Slot and Ch give the location and channel number of the CAN interface.

MIO_M51_RecvStat()

int MIO_M51_RecvStat(int Slot, int Ch)

Description

This status function returns the number of messages in the receive buffer.

Slot and Ch give the location and channel number of the CAN interface.

MIO_M51_TxAbort()

int MIO_M51_TxAbort(int Slot, int Ch)

Listing 8.7: The CAN_MsgExt struct

1: typedef struct {2: unsigned MsgId;3: unsigned char FrameFmt :1;4: unsigned char RTR :1;5: unsigned char FrameLen :4;6: unsigned char Data[8];7: } CAN_MsgExt;

CarMaker Programmer’s Guide Version 2.1.6

Page 176: IPG_CarMaker Programmers Guide

176MIO – M-Module Input/Output

M-Module Function Description

Description

This status function returns the number of messages in the receive buffer.

Slot and Ch give the location and channel number of the CAN interface.

MIO_M51_MBoxEnable()

int MIO_M51_MBoxEnable(int Slot, int Ch)

Description

Enables the mailboxes on the specified slot and channel. Must be called beforeMIO_M51_MBoxCreate() .

This function does not meet realtime conditions.

MIO_M51_MBoxDisable()

void MIO_M51_MBoxDisable(int Slot, int Ch)

Description

Disables the mailboxes on the specified slot and channel.

This function does not meet realtime conditions.

MIO_M51_MBoxCreate()

int MIO_M51_MBoxCreate(int Slot, int Ch, int Id)

Description

The function MIO_M51_MBoxCreate() adds a mailbox to the message ID specified by the argu-ment Id ,assuming one does not already exist. The receipt of the messages that have thespeci f ied ID is act ivated with this cal l and a separate cal l to the funct ionMIO_M51_EnableIds() is not necessary.

Each message received will increment a counter and set a time stamp. Normally a defaulttime stamp is set to the system time by using the function SysGetUTime() .

Slot and Ch give the location and channel number of the CAN interface.

The parameter Id gives the message ID for the mailbox.

The use of mailboxes can be an alternative to the functions MIO_M51_Recv() andMIO_M51_RecvExt() . Instead of reading the messages from the receive ring buffer they areread from the mailbox with the corresponding identifier.

Using the software implemented mailboxes it is possible then to simulate a full CAN imple-mentation, which is usually done with on-chip hardware. Full CAN has an acceptance filterthat is used to filter out all messages that are not desired. The M51 module CAN controllershave filters but they would not fulfill full CAN criteria since the filters are not perfect and allowsome of the undesired messages to pass through. By using mailboxes it is possible to filterall undesired messages and therefore have what could be considered full CAN functionality,although it would not be as fast as a hardware implementation and would require CPU time.

CarMaker Programmer’s Guide Version 2.1.6

Page 177: IPG_CarMaker Programmers Guide

177MIO – M-Module Input/Output

M-Module Function Description

CAN messages that are sent to a mailbox are not sent to the receive buffer and can there-fore not be read using the functions MIO_M51_Recv() and MIO_M51_RecvExt() . Also, the mail-box holds only one single message, with a counter number and a time stamp that can beused to determine if new messages have been received and/or if there are messages thathave been overwritten before being read.

MIO_M51_MBoxDelete()

int MIO_M51_MBoxDelete(int Slot, int Ch, int Id)

Description

The mailbox with the specified id is deleted. The messages with the id Id will then be sentto the receive buffer.

Slot and Ch give the location and channel number of the CAN interface.

MIO_M51_MBoxRead()

long MIO_M51_MBoxRead(int Slot, int Ch, int Id, CAN_Msg *Msg, unsigned *pTimestamp)

Description

MIO_M51_MBoxRead() reads the contents of the mailbox identified by Id .

Slot and Ch give the location and channel number of the CAN interface.

Id is the message identifier whose mailbox is to be read.

pTimestamp will contain a pointer to the timestamp of the last message upon return.

Msg contains the CAN message.

The function returns the number of messages that were put into the mailbox since its cre-ation. If the mailbox does not exist, -1 is returned.

Since CarMaker 2.0, this function is deprecated. Use MIO_M51_MBoxReadExt() instead.

MIO_M51_MBoxReadExt()

long MIO_M51_MBoxReadExt(int Slot, int Ch, int Id, CAN_MsgExt *MsgExt, unsigned *pTimestamp)

Description

MIO_M51_MBoxReadExt() reads the contents of the mailbox identified by Id .

The function does the same as MIO_M51_MBoxRead() , but instead of returning the receivedmessage in a CAN_Msgstruct, the message is stored in a CAN_MsgExt struct. The structCAN_MsgExt accepts both, basic and extended CAN messages.

You should always prefer to use this function instead of MIO_M51_MBoxRead() . SinceCarMaker 2.0, the SJA1000 CAN controllers are operated in the PeliCAN mode, whichallows to deal with extended CAN messages. The function MIO_M51_MBoxRead() is provided

CarMaker Programmer’s Guide Version 2.1.6

Page 178: IPG_CarMaker Programmers Guide

178MIO – M-Module Input/Output

M-Module Function Description

for compatibility reason, only. In fact, MIO_M51_MBoxRead() is just a wrapper function, whichcalls MIO_M51_MBoxReadExt() and copies the contents of the new CAN_MsgExt struct into theold struct CAN_Msg. This results in a slight loss of performance.

MIO_M51_SetTimestampFct()

MIO_TimestampFct MIO_M51_SetTimestampFct(int Slot, int Ch, unsigned (*Func)(void))

Description

With the help of this function a user defined function can be specified for the determinationof the time stamps in place of the normally used system function SysGetUTime() . A typicalapplication is the installation of a timer with a higher resolution.

Func is a pointer to a function, which returns the time stamp (type unsigned int ). It is nec-essary that the function has a small time requirement – less than 2 micro seconds – and iscallable from the interrupt level.

Slot and Ch give the location and channel number of the CAN interface.

A pointer to the old time stamp function is returned.

MIO_M51_SetTransMode()

void MIO_M51_SetTransMode(int Slot, int Ch, int OnOff)

Description

With MIO_M51_EnableIds() the user can freely determine the messages which can bereceived. Normally with the help of the acceptance mask of the interface module the mes-sages are pre-selected (hardware function, no CPU load). Since this selection is indistinct(some messages which were not selected are still received), additional selection by soft-ware is used.

In the transparency mode the preselection in hardware is deactivated, however the softwareselection remains active. The transparency mode makes it possible, for example, to log allCAN traffic in the background. Applications that read the messages with MIO_M51_Recv() orMIO_M51_RecvExt() from the receive buffer will still only see the selected Messages.

The CPU load is substantially higher with transparency mode switched on due to the miss-ing hardware preselection. In particular, this is to be considered during high data transmis-sion rates and high bus utilization.

Slot and Ch give the location and channel number of the CAN interface.

OnOff = 1 activates, OnOff = 0 deactivates transparent mode.

MIO_M51_UnlockTxBuf()

int MIO_M51_UnlockTxBuf(int Slot, int Ch)

Description

This function prevents the transmit buffer from overflowing, if some inconsistency of databetween user process and MIO driver lead to a frozen CAN transmitter.

CarMaker Programmer’s Guide Version 2.1.6

Page 179: IPG_CarMaker Programmers Guide

179MIO – M-Module Input/Output

M-Module Function Description

MIO_M51_UnlockTxBuf() checks if the transmit buffer is at least half full and whether the CANcontroller is still transmitting CAN messages or not. In case the CAN transmitter is lockedup in some undesired state the transmission of CAN messages will be reinitiated.

Use this function carefully. Normally, the CAN transmitter never freezes. If you use this func-tion, some essential CAN messages may get lost.

MIO_M51_TraceInit()

int MIO_M51_TraceInit(int Slot, int BufSize, char ChMask)

Description

Enables a data trace for CAN messages received and transmitted by the M51 module atslot Slot on all channels specified by ChMask.

A buffer of BufSize bytes will be allocated to hold all CAN messages received and transmit-ted on the specified CAN channels. Note, that currently the CAN messages will be loggedby the user process. So, there will always be a significant period of time between logging amessage and being handled by the MIO driver (and therefore being really received or reallytransmitted).

MIO_M51_TraceStop()

int MIO_M51_TraceStop(int Slot, const int Abort, const char *FName)

Description

MIO_M51_TraceStop() stops logging of CAN messages and writes the contents of the previ-ously allocated buffer (obtained by using MIO_M51_UnlockTxBuf() ) to the file FName. IfMode != 0 , then no bytes will be written. The CAN trace will be aborted.

This function does not meet real time conditions, as there is file I/O.

MIO_M51_Status()

int MIO_M51_Status(int Slot, int Ch, CAN_Info *Info)

CarMaker Programmer’s Guide Version 2.1.6

Page 180: IPG_CarMaker Programmers Guide

180MIO – M-Module Input/Output

M-Module Function Description

Description

Returns some status information of the CAN controller located on the M51 module at slotSlot and channel Ch. The information will be written to a CAN_Info struct, which is definedas listed below:

The data field TxClearCnt contains additional information about how often the transmit buff-er was cleared, e.g. automatically by the MIO driver when there was an Bus Error interrupt.

MIO_M51_GetRxErrCnt()

int MIO_M51_GetRxErrCnt(int Slot, int Ch)

Description

Returns the value of the receive error counter register of the CAN controller at Slot and Ch.

MIO_M51_GetTxErrCnt()

int MIO_M51_GetTxErrCnt(int Slot, int Ch)

Description

Returns the value of the transmit error counter register of the CAN controller at Slot and Ch.

MIO_M51_CANInfo()

char *MIO_M51_CANInfo(int Slot, int Ch, char *Buf, char *LinePrefix)

Description

Writes some useful and descriptive information about the CAN controller at Slot and Ch intobuffer Buf , or directly to standard out.

If Buf is not NULL, then the information will be written into Buf , otherwise it is written directlyto stdout . LinePrefix will be prepended each written line. This is useful, if you want to logBuf with the Log functions of CarMaker.

Listing 8.8: The CAN_Info struct

1: typedef struct CAN_Info {2: unsigned char Mode; /* Mode register */3: unsigned char Status; /* Status register */4: unsigned char IntrEnable; /* Interrupt Enable register */5: unsigned char BusTiming[2]; /* Bus Timing registers */6: unsigned char ArbLostCapt; /* Arbitration Lost Capture register */7: unsigned char ErrCodeCapt; /* Error Code Capture register */8: unsigned char ErrWarnLmt; /* Error Warning Limit */9: unsigned char RxErrCnt; /* Receive Error Counter */

10: unsigned char TxErrCnt; /* Transmit Error Counter */11: unsigned char RxMsgCnt; /* No of Messages available in RxFIFO */12: unsigned char ClockDivider; /* Clock Divider register */13: unsigned char AcceptCode[4]; /* Acceptance Code registers */14: unsigned char AcceptMask[4]; /* Acceptance Mask registers */15: unsigned TxClearCnt[5]; /* No of Auto Clears for TxErrCnt */16: } CAN_Info;

CarMaker Programmer’s Guide Version 2.1.6

Page 181: IPG_CarMaker Programmers Guide

181MIO – M-Module Input/Output

M-Module Function Description

The printed information looks like:

Bus Status: Bus-OnTransmitter Status: idle, last Tx completed, TxBuf releasedReceiver Status: idle, RxFIFO emptyChip State: Active / TxErrCnt = 51, RxErrCnt = 50

Buf should have a size of at least 300 bytes.

MIO_M51_GetRegister()

int MIO_M51_GetRegister(int Slot, int Ch, unsigned addr, int reset)

Description

Returns the value of register at addr on CAN controller at Slot and Ch. If reset = 1, then theCAN controller will be requested to enter reset mode first before reading the register value.

MIO_M51_ListAddr()

void MIO_M51_ListAddr(int Slot, int Ch)

Description

Prints a table with all registers and addresses of the CAN controller at Slot and Ch to stan-dard out.

MIO_M51_DumpPSCC()

void MIO_M51_DumpPSCC(int Slot, int Ch)

Description

Dumps all register values of the CAN controller at Slot and Ch to standard out.

8.4.12 M62: Analog Outputs (4 channels)

MIO_M62_Config()

int MIO_M62_Config(int Slot)

Description

By calling the function MIO_M62_Config() the configuration of the I/O hardware, i.e. the allo-cation of a M-Module card location with a module of type M62, is specified. This functionmust only be called one time, before any attempted access to the module.

The argument Slot is the slot number (position) of the M-Module.

Initial state of all output channels:

Output level: 0V

Jumper J1/J2 is used to specify bipolar or unipolar mode.

CarMaker Programmer’s Guide Version 2.1.6

Page 182: IPG_CarMaker Programmers Guide

182MIO – M-Module Input/Output

M-Module Function Description

If the module cannot be configured/initialized the function returns an error code, otherwise0 is returned

MIO_M62_Reset()

void MIO_M62_Reset(int Slot)

Description

The function resets all output channels to the initial state (see MIO_M62_Config() ).

MIO_M62_Set()

void MIO_M62_Set(int Slot, int Ch, int Value)

Description

Sets the value of an output channel.

Slot and Ch indicate the card location and the channel number.

Value contains the output value left justified in a 16bit short integer (not signed). Indepen-dent of the width of the transducer (12 bits, 14 bits or 16 bits) the value 0 is the minimumvoltage level and 65535 is the maximum voltage level. In bipolar mode (see Jumper J1, J2of the hardware description), 32768 stands for 0 V.

MIO_M62_SetV()

void MIO_M62_SetV(int Slot, int ChMask, int *Values)

Description

Similar to MIO_M62_Set() , however several output channels can be set at the same time.This function is particularly efficient for setting several channels. Due to the hardware struc-ture of the module the values appear temporally transferred at the exits.

Slot indicates the card location of the module.

The channels concerned are represented by the bit list ChMask (bit 0 .. 3 used): Bit n is setto 1 if channel n is to be set. Therefore, if ChMask==0xf (1+2+4+8=0xf) then all four chan-nels are to be set.

Values is a pointer to an array (vector), which contains the desired values in concise form,i.e. without gaps for unselected channels.

8.4.13 M72: Motion Counter

MIO_M72_Config()

int MIO_M72_Config(int Slot)

CarMaker Programmer’s Guide Version 2.1.6

Page 183: IPG_CarMaker Programmers Guide

183MIO – M-Module Input/Output

M-Module Function Description

Description

By calling the function MIO_M72_Config() the configuration of the I/O hardware, i.e. the allo-cation of a M-Module card location with a module of type M72, is specified. This functionmust only be called one time, before any attempted access to the module.

The argument Slot is the slot number (position) of the M-Module.

The function MIO_M72_Config() also downloads new firmware to the module. After the down-load, the module is in its initial state, with no timer active.

If the module cannot be configured/initialized the function returns an error code, otherwise0 is returned.

MIO_M72_Reset()

void MIO_M72_Reset(int Slot)

Description

This function configures the four counters of the M72 module to Single Counter mode andpreloads the counters with zero.

MIO_M72_Download()

int MIO_M72_Download(int Slot, const unsigned char *Data, int DataLen)

Description

The function MIO_M72_Download() takes a new firmware Data and downloads DataLen bytesto the M72 module. The firmware will be automatically downloaded when callingMIO_M72_Config() . So, there is no need to call this function separately.

MIO_M72_SetMode()

void MIO_M72_SetMode(int Slot, int Ch, MIO_M72_Mode Mode)

Description

Sets the operating mode of counter Ch to Mode. The following operating modes are support-ed:

Mode Operating mode

0 inactive

1 single count

2 1x quadrature

3 2x quadrature

4 4x quadrature

5 frequency measurement

6 pulse width “high”

7 pulse width “low”

CarMaker Programmer’s Guide Version 2.1.6

Page 184: IPG_CarMaker Programmers Guide

184MIO – M-Module Input/Output

M-Module Function Description

Description of operating modes

• Single Count mode:

This is the operation mode for classic up- and down-counting.

A rising edge at xIN0 increments the counter, a rising edge at xIN1 decrements thecounter. A rising edge at xIN2 can clear or load the counter, depending on the program-ming of the Counter Control Register.

Alternatively, a connection to the comparator unit for clearing or loading is possible.The Counter Control Register also determines the event on which the counter value ispassed to the Counter Output Latch Register, as is the case for all counter modes. Thelatched counter value can be read out from the Counter Output Latch Register.

• 1x Quadrature mode:

Similar to Single Count mode, 1x Quadrature mode is a classic up- and down-countingmode.

However, a rising edge at xIN0 generates a count pulse in any case. xIN1 defines thedirection: “high” means counting up, “low” means counting down. (When using RS422signals, it is possible to invert polarities by reversing the input lines.)

In 1x Quadrature mode you can already evaluate the signals of a rotary encoder. The“A” signal is connected to xIN0 , the “B” signal is connected to xIN1 . Depending on thedirection of rotation, the counter value is incremented or decremented by 1 with eachpulse at xIN0 . The signal often called “Z” can be connected to xIN2 and can be used toset, clear or latch the counter value as in Single Count mode.

• 2x Quadrature mode:

8 period measurement

9 timer

Mode Operating mode

Figure 8.4: Single Count mode

xIn0

xIn1

xIn2

2

3

1

123

preload/clear counter

count-up pulse

count-down pulse

Figure 8.5: 1x Quadrature mode

xIn0

xIn1

xIn2

3

1

12 3

preload/clear counter

count pulse - counting down

2 4 5

4 5 count pulse - counting up

Count -10 -2 -1 0

counting

counting up

down

up

down down down

up up

CarMaker Programmer’s Guide Version 2.1.6

Page 185: IPG_CarMaker Programmers Guide

185MIO – M-Module Input/Output

M-Module Function Description

In 2x Quadrature mode the xIN0 and xIN1 signals are evaluated differently than in Sin-gle Count and 1x Quadrature mode.

Each a rising and falling edge at xIN0 generate a count pulse. xIN1 defines the direc-tion, depending on xIN0 : “high” with a falling edge and “low” with a rising edge at xIN0count down, “high” with a rising edge and “low” with a falling edge at xIN0 count up.

This behavior make this mode suitable only for rotary or similar sensors. The “A” signalis now evaluated on both edges.

• 4x Quadrature mode:

The counter will be cleared or preloaded by signal xIN2 or by software. A rising and fall-ing edge at xIN0 and xIN1 create a count pulse. The counter increments when xIN0 isbefore xIN1 , the counter decrements when xIN0 is after xIN1 .

• Frequency Measurement mode:

The frequency will be measured at input xIN0 after activating the internal time base(10ms) (bit TimeBase in the Counter Control Register). The time base clears the counterand starts the measurement, the counter increments at each rising edge at xIN0 . Themeasurement stops after the time-out of the time base. The time base generates aReady interrupt and the counter value is latched.

Figure 8.6: 2x Quadrature mode

xIn0

xIn1

xIn2

4

1

12 5

preload/clear counter

count pulse - counting down

2 6 8

6 9 count pulse - counting up

Count -10 -3 -3 -1

counting

counting up

down

up

down down down

up up3 5 7 9

--

-2 -4 -2 0

Figure 8.7: 4x Quadrature mode

xIn0

xIn1

xIn2

6

1

12 9

preload/clear counter

count pulse xIN0 before xIN1 - counting

2 1 1

1 1 count pulse xIN0 after xIN1 - count

Count 10 3 3 1

4 8 1 1

--

2 4 2 0

735 9

111 1

Figure 8.8: Frequency Measurement mode

measuring frequency (10ms)

xIn032 54

12 5

counter cleared, measurement started

counting up at each rising edge

6 measurement stopped, interrupt generated-

1 6

CarMaker Programmer’s Guide Version 2.1.6

Page 186: IPG_CarMaker Programmers Guide

186MIO – M-Module Input/Output

M-Module Function Description

• Pulse Width “high” mode:

The signal, connected to input xIN0 , will be measured. The counter can be cleared orpreloaded, either using xIN2 , or by software. The measurement starts after the risingedge at xIN0 . It stops with the falling edge at xIN0 , activates the Ready interrupt andlatches the counter value. The counter clock (2.5 MHz) controls the counter.

• Pulse Width “low” mode:

The signal, connected to input xIN0 , will be measured. The counter can be cleared orpreloaded, either using xIN2 , or by software. The measurement starts after the fallingedge at xIN0 . It stops with the rising edge at xIN0 , activates the Ready interrupt andlatches the counter value. The counter clock (2.5 MHz) controls the counter.

• Period Measurement mode:

Figure 8.9: Pulse Width “high” mode

xIn0

12

preload/clear counter

rising edge starts measurement

6 rising edge starts measurement

Clock2.5MHz

3 4 7

xIn21

25

6

3 4 counting up at each rising edge

5 stop measurement, generate interrupt

7 counting up at rising edge

Figure 8.10: Pulse Width “low” mode

xIn0

12

preload/clear counter

falling edge starts measurement

Clock2.5MHz

3 4

xIn21

25

3 4 counting up at each rising edge

5 stop measurement, generate interrupt

CarMaker Programmer’s Guide Version 2.1.6

Page 187: IPG_CarMaker Programmers Guide

187MIO – M-Module Input/Output

M-Module Function Description

The signal, connected to input xIN0 , will be measured. The counter can be cleared orpreloaded, either using xIN2 , or by software. The measurement starts after the risingedge at xIN0 . It stops with the next rising edge at xIN0 , activates the Ready interruptand latches the counter value. The counter clock (2.5 MHz) controls the counter.

• Timer mode:

To initialize the timer, the counter must be cleared or preloaded using xIN2 or by soft-ware, then the Comparator_X register must be loaded with the timer value. The timerstarts either on xIN2 or by software (see bit TimerStart in the Counter Control Regis-ter). Comparator_X generates the Comparator interrupt after the time-out and stops thecounter. The M72 can be programmed to start further timer sequences through theCounter Control Register after the Comparator interrupt:. Depending on the Preloadand Clear bits, the Comparator interrupt clears or preloads and then starts the counteragain. Signal xIN1 controls the count direction. The counter increments when xIN1 is“high” and decrements when xIN1 is “low”. The counter runs with the internal counterclock (2.5MHz).

MIO_M72_GetCounter()

long MIO_M72_GetCounter(int Slot, int Ch)

Figure 8.11: Period Measurement mode

xIn0

12

preload/clear counter

rising edge starts measurement

Clock2.5MHz

5 6

xIn21

2 7

counting up at each rising edge

7 stop measurement, generate interrupt

3 4

3 6-

Figure 8.12: Timer mode

xIn1

1 preload/clear/start counter

(Comparator_X = 4)

Clock2.5MHz

4 5

xIn21

counter counts at each rising edge of clocksignal

6 Comparator_X = counter? => stopcounter and generate interrupt

2 3

2 5-

6

Count 10 2 3 4

count direction: up

CarMaker Programmer’s Guide Version 2.1.6

Page 188: IPG_CarMaker Programmers Guide

188MIO – M-Module Input/Output

M-Module Function Description

Description

Returns the current value of the 32 bit counter on slot Slot and channel Ch.

MIO_M72_SetCounter()

void MIO_M72_SetCounter(int Slot, int Ch, long Value)

Description

Preloads the counter at slot Slot and channel Ch with Value.

MIO_M72_SetOutPort()

void MIO_M72_SetOutPort(int Slot, unsigned Value)

Description

The function MIO_M72_SetOutPort() sets the values of the four output signals Out1 , Out2 ,Out3 and Out4 .

Slot gives the M-Module card location.

Value defines the states for the output signals, whereas only the 4 least signifgicant bits areused. If bit n is 1, then output signal n+1 will be set “high”, otherwise output signal n+1 willbe set “low”.

8.4.14 M77: Quadruple RS232/423 - RS422/485 UART

MIO_M77_Config()

int MIO_M77_Config(int Slot)

Description

By calling the function MIO_M77_Config() the configuration of the I/O hardware, i.e. the allo-cation of a M-Module card location with a module of type M77 is specified. This functionmust only be called one time, before any attempted access to the module.

Slot is the number of the M-Module card location.

The transmit trigger levels of all UARTs will be set to maximum (127), the receive triggerlevels to minimum (1). No other configuration is done on the UARTs, in particular the baudrate is not modified. The initialization is completed with the function MIO_M77_Reset() .

The input clock, which is important for the baud rate generation, is assumed to be 32 MHz.This does not meet the default configuration of a virgin M77 module. For CarMaker/HILapplications, the default oscillator with 18.432 MHz is replaced by an oscillator with 32 MHz.If your M77 module uses an oscillator with a frequency different from 32 MHz, you shouldchange the input clock with MIO_M77_SetInputClock() .

CarMaker Programmer’s Guide Version 2.1.6

Page 189: IPG_CarMaker Programmers Guide

189MIO – M-Module Input/Output

M-Module Function Description

If the module cannot be configured/initialized the function returns an error code, otherwise0 is returned.

MIO_M77_Reset()

void MIO_M77_Reset(int Slot)

Description

The function resets all UARTs to Power-Up state and sets the baud rate to maximum. Theresulting baud rate depends on the oscillator frequency:

Both FIFOs (Rx-FIFO and Tx-FIFO) are flushed. Any remaining data is lost.

The UARTs are configured as followed:

• 950 mode trigger levels enabled

• all interrupts disabled

• transmitter FIFO and receiver FIFO enabled

MIO_M77_GetInputClock()

int MIO_M77_GetInputClock(int Slot)

Description

Returns the input clock in Hz, which is needed to program the baud rate generator.

MIO_M77_SetInputClock()

void MIO_M77_SetInputClock(int Slot)

Description

Sets the input clock in Hz, which is needed to program the baud rate generator.

Table 8.3: Maximum possible baud rates

Oscillator frequency Maximum baud rate

1.8432MHz 115.200 kbaud

7.3728MHz 460.800 kbaud

14.7456MHz 921.600 kbaud

18.432 MHz 1.152 Mbaud

32.000 MHz 2.000 Mbaud

33.000 MHz 2.0625 Mbaud

40.000 MHz 2.500 Mbaud

50.000 MHz 3.125 Mbaud

60.000 MHz 3.750 Mbaud

CarMaker Programmer’s Guide Version 2.1.6

Page 190: IPG_CarMaker Programmers Guide

190MIO – M-Module Input/Output

M-Module Function Description

The input clock should always match the frequency of the oscillator, which is mounted onthe M77 module. If not, it is not possible to set accurate baud rates.

MIO_M77_UART_Reset()

void MIO_M77_UART_Reset(int Slot, int Ch)

Description

This function resets the UART at slot Slot and channel Ch to Power-Up state. The UARTresults in the same state as after a hardware reset. For a proper use, the UART has to bereinitialized.

MIO_M77_UART_Flush()

void MIO_M77_UART_Flush(int Slot, int Ch)

Description

Flushes the transmitter FIFO and receiver FIFO of the UART located at Slot and Ch. Anyremaining data bytes in the FIFOs get lost.

MIO_M77_SetBaud()

void MIO_M77_SetBaud(int Slot, int Ch, int Baud)

Description

Sets the desired baud rate by programming the divisor latch registers of the baud rate gen-erator. If the input clock is not divisible by the baud rate, the resulting baud rate may be dif-ferent from the requested. The divisor is determined through integer divisions with thefollowing formula:

divisor = (InputClock/RequBaudrate + 8) / 16 (EQ 1)

Thus, the resulting baud rate need not to be exactly the same value as the requested baudrate.

If the requested baud rate is near to the maximum and the input clock is not an integer mul-tiple of it, then the resulting baud rate may differ significantly. For example: if you want to seta baud rate of 1.5 Mbaud (32 MHz input clock!), the divisor will be 1, which results in themaximum baud rate of 2 Mbaud.

MIO_M77_SetMode()

void MIO_M77_SetMode(int Slot, int Ch, int Mode)

Description

This function allows to set the operating mode of the UART, located at Slot and Ch.

CarMaker Programmer’s Guide Version 2.1.6

Page 191: IPG_CarMaker Programmers Guide

191MIO – M-Module Input/Output

M-Module Function Description

The M77 module supports the following operating modes:

If you are using RS422 half-duplex mode or RS485 half-duplex mode, setting RX_EN(bit 3)enables echoing effect, clearing this bit disables the echoing effect. In the modes RS232,RS423, RS422 full-duplex and RS485 full-duplex, setting RX_EN has no effect.

MIO_M77_Write()

int MIO_M77_Write(int Slot, int Ch, char *Data, int Len)

Description

Writes up to Len bytes of the character array Data to the Transmitter FIFO of the UART locat-ed at Slot and Ch.

Returns the number of written bytes. Depending on the fill level of the Transmitter FIFO andthe baud rate, the number of written bytes can be about up to 128 bytes.

MIO_M77_Read()

int MIO_M77_Read(int Slot, int Ch, char *Data, int MaxLen)

Description

Reads all available or MaxLen bytes from the Receiver FIFO of the UART located at Slot andCh and copies them to the character array Data .

Returns the number of copied bytes. Depending on the fill level of the Receiver FIFO andthe baud rate, about up to 128 bytes can be copied from the UART to Data .

MIO_M77_RxFillLvl()

int MIO_M77_RxFillLvl(int Slot, int Ch)

Description

Returns the number of available bytes in the Receiver FIFO of the UART located at Slotand Ch.

Table 8.4: Operating modes of M77 module

Operating mode Mode (bits 0..2) Constants defined in mio.h

RS423 000 MIO_M77_MODE_RS423

RS422 half-duplex 001 MIO_M77_MODE_RS422half

RS422 full-duplex 010 MIO_M77_MODE_RS422full

RS485 half-duplex 011 MIO_M77_MODE_RS485half

RS485 full-duplex 100 MIO_M77_MODE_RS485full

RS232 111 MIO_M77_MODE_RS232

CarMaker Programmer’s Guide Version 2.1.6

Page 192: IPG_CarMaker Programmers Guide

192MIO – M-Module Input/Output

M-Module Function Description

MIO_M77_TxFillLvl()

int MIO_M77_TxFillLvl(int Slot, int Ch)

Description

Returns the number of bytes in the Transmitter FIFO of the UART located at Slot and Ch,that have not been transferred.

8.4.15 M392: Analog Inputs (16 channels)

MIO_M392_Config()

int MIO_M392_Config(int Slot)

Description

By calling the function MIO_M392_Config() the configuration of the I/O hardware, i.e. the allo-cation of a M-Module card location with a module of type M392 is specified. This functionmust only be called one time, before any attempted access to the module.

The argument Slot is the slot number (position) of the M-Module.

Initial state of the input ports:

• Measuring Range: -10V .. +10V

• Cycle time per channel: 20us

• All channels active

• Moving average filter deactivated

If the module cannot be configured/initialized the function returns an error code, otherwise0 is returned.

MIO_M392_Reset()

void MIO_M392_Reset(int Slot)

Description

Sets all input ports back to the initial state (see MIO_M392_Config() ).

MIO_M392_Delete()

void MIO_M392_Delete(int Slot)

Description

Deactivates the M-Module of type M392 located at the specified slot number. To reactivethe module the function MIO_M392_Config() must be called again.

CarMaker Programmer’s Guide Version 2.1.6

Page 193: IPG_CarMaker Programmers Guide

193MIO – M-Module Input/Output

M-Module Function Description

MIO_M392_Setup()

int MIO_M392_Setup(int Slot, int Ch, unsigned short Range)

Description

Sets the measuring range of a channel.

Slot and Ch indicate the card location and the channel number.

Range indicates the desired measuring range of the selected channel:

If Range contains an invalid value or if the measuring range can not be changed then thefunction will return an error code. A 0 is returned upon success.

MIO_M392_SetupV()

int MIO_M392_SetupV(int Slot, unsigned ChMask, unsigned short *Ranges)

Description

Similar to MIO_M392_Setup() , except the measuring range can be set for several channels.

Slot indicates the card location.

ChMask is a bit mask which indicates the channels which should be configured. If bit n hasthe value 1 the measuring range of channel n will be configured.

Ranges is a pinter to an array where the measuring ranges of the channels (concise, begin-ning with channel 0) are specified. The size of the field must correspond to at least the num-ber of existing channels on the M-Module (16 channels with module M392, 8 channels withmodule M393). An invalid value in the Ranges array will set the range to the default value(-10V .. +10V with the M392 and M393/V-Module, 0mA .. 20mA with the M393/C-Module).

If the setup fails then the function returns an error code. A 0 is returned upon success.

MIO_M392_SetAcqTime()

int MIO_M392_SetAcqTime(int Slot, int acqTime)

Description

Sets the acquisition time of the module’s channels. acqTime reflects the acquisition time fora single channel, so if n channels are active then the total acquisition time for once cyclewill be n*<actual acqTime>.

Range Measuring Range

0 -10V .. +10V bipolara

a. 0 .. 20 mA with M393/C-Module

1 0V .. 10V unipolar

2 -5V .. +5V bipolar

3 0V .. 5V unipolar

4 deactivated

CarMaker Programmer’s Guide Version 2.1.6

Page 194: IPG_CarMaker Programmers Guide

194MIO – M-Module Input/Output

M-Module Function Description

Slot gives the card location of the M-Module.

acqTime must be set to one of four values (0...3), which represent the acquisition timesshown in the table below:

After successful change of the cycle time, the function returns the total time, which is need-ed for the transformation of all activated channels, in micro seconds. If the cycle time cannotbe changed, or does not correspond the value of acqTime one o.g. values, it returns -1.

If the function is successful, the new cycle time, which is needed for the transformation ofall activated channels together, will be returned in microseconds (us). If an invalid value isused for acqTime or the function is not successful, then an error code is returned.

MIO_M392_SetMAF()

int MIO_M392_SetMAF(int Slot, int maf)

Description

Sets the value of the MA filter (Moving average filter) which is used for noise compensationand better DC accuracy. The DSP handles the filtering, so there is effectively no overheadassociated with this function.

Slot gives the card location.

Possible values for maf are shown in the table below:

Upon success the function returns the number of samples being averaged. Otherwise, anerror code is returned.

MIO_M392_Read()

int MIO_M392_Read(int Slot, int Ch)

Description

The function reads the measured value of an input port.

acqTime Acquisition time (per channel)

0 20 us

1 100 us

2 500 us

3 1 ms

maf Moving Average Over...

0 deactivated

1 8 Samples

2 16 Samples

3 32 Samples

4 64 Samples

5 128 Samples

CarMaker Programmer’s Guide Version 2.1.6

Page 195: IPG_CarMaker Programmers Guide

195MIO – M-Module Input/Output

M-Module Function Description

The average time needed for the operation depends on the number of activated channelsand specified acquisition time (see the description of MIO_M392_SetAcqTime() ).

Slot and Ch indicate the card location and the channel number.

The function returns the measured value, left justified in a 16 bit integer. The value 0 corre-sponds to the lowest and 65535 to the highest value in the measuring range of the respec-tive channel. If a bipolar measuring range is selected for the channel Ch, a value of 32768corresponds to 0V. Thus an offset must be subtracted from 32768 == 0x8000 to obtain asigned value. For example: if the measuring range is -5V .. +5V, the return value of 16384results in 16384-32768 = -16834, thus -2.5V.

MIO_M392_ReadV()

void MIO_M392_ReadV(int Slot, unsigned ChMask, int *Values)

Description

Similar to MIO_M392_Read() except several channels are read at once.

Slot indicates the card location of the M-Module.

ChMask is a bitmask which specifies the channels to be queried. If bit n has the value 1, thechannel n is queried.

Example ChMask = 0x1f8;MIO_M392_ReadV(s, ChMask, v);

This causes the inquiry of channel 3 .. 8.

Values is a pointer to an array where the values (concise, beginning with channel 0) will bewritten. With bipolar measuring, an offset of 32768 == 0x8000 must be subtracted from themeasured values, in order to get signed values (see function MIO_M392_Read() ).

MIO_M392_GetRes()

double MIO_M392_GetRes(int Slot, int Ch)

Description

Returns the resolution of the input port in V/digit (mA/digit with M393/C-Module)

Slot and Ch indicate the card location and the channel number.

Return value: If the selected input port is activated, the resolution for the adjusted measur-ing range is determined and returned. If the selected channel is deactivated, 0 is returned.

MIO_M392_Version()

int MIO_M392_Version(int Slot, tMIO_M392_vInfo *vInfo)

Description

Supplies information about the M-Module:

• Name of the M-Module (392 for module M392, or 393 for module M393)

CarMaker Programmer’s Guide Version 2.1.6

Page 196: IPG_CarMaker Programmers Guide

196MIO – M-Module Input/Output

M-Module Function Description

• Firmware version

• Kind of module (current/tension measurement)

• Accuracy of the resolution range (12 or 16 bits)

Slot indicates the card location of the M-Module.

The information about the M-Module is returned in *vInfo . The data structuretMIO_M392_vInfo is defined as followed:

The version of the firmware is decimally coded in the variable vFirmware . It can be computedaccording to the following formula:

Version = vFirmware/10 + (vFirmware%10)/10 (EQ 2)

Return value: 0 on success, error code otherwise.

MIO_M392_Sync()

int MIO_M392_Sync(int Slot)

Description

Determines if the M-Module is functioning properly.

Return value: 0 if the module is error free, error code otherwise.

8.4.16 M393: Analog Inputs (8 channels)

MIO_M393_Config()

void MIO_M393_Config(int Slot)

Description

(see function description for MIO_M392_Config() )

MIO_M393_Reset()

void MIO_M393_Reset(int Slot)

Description

(see function description for MIO_M392_Reset() )

Listing 8.9: The tMIO_M392_vInfo struct

1: typedef struct {2: unsigned short ModNo; /* Module number */3: unsigned short vFirmware; /* Firmware-Version */4: unsigned short CInputType; /* V/C (M393-Module only) */5: unsigned short resolution; /* Resolution (12/16 Bit) */6: } tMIO_M392_vInfo;

CarMaker Programmer’s Guide Version 2.1.6

Page 197: IPG_CarMaker Programmers Guide

197MIO – M-Module Input/Output

M-Module Function Description

MIO_M393_Delete()

void MIO_M393_Delete(int Slot)

Description

(see function description for MIO_M392_Delete() )

MIO_M393_Setup()

int MIO_M393_Setup(int Slot, int Ch, unsigned short Range)

Description

(see function description for MIO_M392_Setup() )

MIO_M393_SetupV()

int MIO_M393_SetupV(int Slot, unsigned ChMask, unsigned short *Ranges)

Description

(see function description for MIO_M392_SetupV() )

MIO_M393_SetAcqTime()

int MIO_M393_SetAcqTime(int Slot, int acqTime)

Description

(see function description for MIO_M392_SetAcqTime() )

MIO_M393_SetMAF()

int MIO_M393_SetMAF(int Slot, int maf)

Description

(see function description for MIO_M392_SetMAF() )

MIO_M393_Read()

int MIO_M393_Read(int Slot, int Ch)

Description

(see function description for MIO_M392_Read() )

CarMaker Programmer’s Guide Version 2.1.6

Page 198: IPG_CarMaker Programmers Guide

198MIO – M-Module Input/Output

M-Module Function Description

MIO_M393_ReadV()

void MIO_M393_ReadV(int Slot, unsigned ChMask, int *Values)

Description

(see function description for MIO_M392_ReadV() )

MIO_M393_GetRes()

double MIO_M393_GetRes(int Slot, int Ch)

Description

(see function description for MIO_M392_GetRes() )

MIO_M393_Version()

int MIO_M393_Version(int Slot, tMIO_M392_vInfo *vInfo)

Description

(see function description for MIO_M392_Version() )

MIO_M393_Sync()

int MIO_M393_Sync(int Slot)

Description

(see function description for MIO_M392_Sync() )

8.4.17 M461/3: Pulse Width and Angle Measurement (4 channels)

MIO_M461_3_Config()

int MIO_M461_3_Config(int Slot)

Description

By calling the function MIO_M461_3_Config() the configuration of the I/O hardware, i.e. theallocation of a M-Module-card location with a module of the type M461/3 are specified. Thisfunction must only be called one time, before any attempted access to the module.

Slot is the number of the M-Module card location.

Initial state of the input ports:

• Pulse width measurement: The High phase of the signal is measured.

• Angular measurement: One triggers with the rising edge.

CarMaker Programmer’s Guide Version 2.1.6

Page 199: IPG_CarMaker Programmers Guide

199MIO – M-Module Input/Output

M-Module Function Description

If the module cannot be configured/initialized the function returns an error code, otherwise0 is returned.

MIO_M461_3_Reset()

void MIO_M461_3_Reset(int Slot)

Description

The function puts all input por ts of the module back into the initial state (seeMIO_M461_3_Config() ).

MIO_M461_3_SetPolarity()

void MIO_M461_3_SetPolarity(int Slot,int Ch, int PeriodLvl, int AngleEdge)

Description

Specifies the level and/or the edge for the measurement of the pulse width and the angle.

Slot and Ch indicate the card location and the channel number.

PeriodLvl = 0 (default value) causes that the pulse width of the Low phase is measured.Time measurement begins with the falling edge of the signal and ends with the rising edge.With PeriodLvl = 1 the pulse width of the High phase is measured.

AngleEdge = 0 (default value) means that the angle (number of CLK pulses) between /SYNCand the falling edge of the input signal is determined.AngleEdge = 1 causes a counting of the CLK pulses up to the rising edge of the input signal.

Independently of the value for AngleEdge the measurement always begins with the risingedge of the /SYNC signal.

Figure 8.13: Timing Diagram

t

Pulse width measurement alwaysbegins with rising edge of /SYNC signal

CLK

/SYNC

Angle1 (AngleEdge=1 )

Width1 (PeriodLvl=0 )

Ch0

Ch1

Angle0 (AngleEdge=0 )

CarMaker Programmer’s Guide Version 2.1.6

Page 200: IPG_CarMaker Programmers Guide

200MIO – M-Module Input/Output

M-Module Function Description

Short, negative impulses for /SYNC are used, since for the duration of the Low level no CLKimpulses are counted. The /SYNC impulse may be shorter than Low/High phase of the CLKpulses.

Example

MIO_M461_3_GetWidth()

int MIO_M461_3_GetWidth(int Slot, int Ch)

Listing 8.10: Example for MIO_M461_3_SetPolarity()

1: void2: Config(void)3: {4: MIO_Init(A16D16);5:6: /* 1 Carrier Board */7: MIO_MasterConfig(0, 4, 0);8:9: /* Module configuration */

10: MIO_M4_Config(0);11: MIO_M461_3_Config(1);12: MIO_M51_Config(2, -1);13:14: MIO_ResetModules();15: }16:17:18: void19: TestDA(void)20: {21: int i;22: int OutVec[4];23:24: for (i=0; i<4096; i++) {25: OutVec[0] = i<<4;26: OutVec[1] = 0;27: OutVec[2] = i*9 << 4;28: OutVec[3] = i;29: MIO_M4_SetV(0, 0xf, OutVec);30: usleep(10000);31: }32: }33:34:35: void36: TestCAN(void)37: {38: static char LCD_Bell[] = {0x07, 0x01};39: static char LCD_CurBlink[] = {0x02, 0x10, 0x20};40:41: MIO_M51_SetCommParam(2, 0, 500000, 65, 2, 0);42: MIO_M51_EnableIds(2, 0, 0x101, 1);43:44: MIO_M51_SendV(2, 0, 0x100, LCD_CurBlink, 2);45: while (MIO_M51_RecvStat(2, 0) == 0) {46: MIO_M51_SendV(2, 0, 0x100, LCD_Bell, 2);47: sleep(3);48: }49: }

CarMaker Programmer’s Guide Version 2.1.6

Page 201: IPG_CarMaker Programmers Guide

201MIO – M-Module Input/Output

M-Module Function Description

Description

The function supplies the pulse width of the High and/or Low phase (dependent on the cur-rent configuration of the channel, see MIO_M461_3_SetPolarity() ) of the input signal. Thevalue measured last is returned in each case, i.e. it does not play a role since on the lastcall to the function a new measurement took place.

Slot and Ch indicate the card location and the channel number.

Return value: Pulse width of the input signal in micro seconds, range of values: 0 .. 224-1;on overflow the maximum value is returned.

MIO_M461_3_GetWidthV()

void MIO_M461_3_GetWidthV(int Slot, unsigned ChMask, int *Values)

Description

Similar to MIO_M461_3_GetWidth() , only several channels can be queried at the same time.

Slot is the number of the M-Module card location.

ChMask is a bit field (bit 0..3 used), which specifies the channels to be queried. If bit n hasthe value 1, the channel n is queried. ChMask = 0xf (1+2+4+8=0xf ) means thus all four chan-nels.

Values is a pointer to a field which contains the values (concise, beginning with the lowestchannel number).

MIO_M461_3_GetAngle()

int MIO_M461_3_GetAngle(int Slot, int Ch)

Description

The function supplies the number of angular clock ticks (input signal OSC, angle dependentclock) between the rising edge of the signal /SYNC and the selected edge of the input signal(see MIO_M461_3_SetPolarity() ). The value measured last is returned in each case, i.e. itdoes not play a role whether since the last call of the function a new measurement tookplace.

Slot and Ch indicate the card location and the channel number.

Return value: Angle (number of clocks of the signal OSC), range of values: 0 .. 216-1; on over-flow the maximum value is returned.

MIO_M461_3_GetAngleV()

void MIO_M461_3_GetAngleV(int Slot, unsigned ChMask, int *Values)

Description

Similar to MIO_M461_3_GetAngle() , only several channels can be queried at the same time.

Slot is the number of the M-Module card location.

CarMaker Programmer’s Guide Version 2.1.6

Page 202: IPG_CarMaker Programmers Guide

202MIO – M-Module Input/Output

M-Module Function Description

ChMask is a bit field (bit 0..3 used), which specifies the channels to be queried. If bit n hasthe value 1, the channel n is queried. ChMask = 0xf (1+2+4+8=0xf ) means thus all four chan-nels.

Values is a pointer to a field which contains the values (concise, beginning with the lowestchannel number).

CarMaker Programmer’s Guide Version 2.1.6

Page 203: IPG_CarMaker Programmers Guide

203MIO – M-Module Input/Output

mioutil - MIO configuration utility

8.5 mioutil - MIO configuration utility

Prior to the programming of M-Module I/O, there is normally done the hardware installationof the M modules. The M modules are mounted on M-Module Carrier Boards, which areconfigured for different base addresses and finally installed in the chassis of the realtimesystem. But, once u have finished this step, you cannot identify the different M modules fromoutside, anymore. The utility mioutil helps you in this situation. It is able to display yourMIO hardware configuration by scanning the VME bus for M-Module Carrier Boards andinstalled M modules.

When called without arguments, mioutil scans the beginning of the A16/D16 addressspace for MIO hardware and displays the result:

> mioutilmioutil: I/O configuration utilityVersion: 1.3 -- (c) 2005 IPG GmbH, Karlsruhe, e-mail [email protected]

Scanning VME bus ... done

M-Module configuration:=======================

MEN A201 at offset 0x0:-----------------------slot Mxxx Revision IRQ/vec description #0 M034 2.2 0 0 analog input (16/8 channels) #1 M062 0.1 0 0 analog output (16 channels) #2 M051 1.5 0 0 Quadruple CAN Interface #3 M031 0.2 0 0 binary input (16 channels)

MEN A201 at offset 0x800:-------------------------slot Mxxx Revision IRQ/vec description #4 M??? <unknown> #5 M??? <unknown> #6 M043 2.0 0 0 relay output (8 channels) #7 - <empty>

This works fine in most cases. The default configuration of the MIO hardware is the A16/D16address space, whereas the base addresses of the M-Module Carrier Boards are arrangedcontiguously, starting at offset 0. However, there are a couple of command line argumentsto account for different MIO configurations:

• -h / -help :

Prints a usage and exits:

> mioutil -hmioutil: I/O configuration utilityVersion: 1.3 -- (c) 2005 IPG GmbH, Karlsruhe, e-mail [email protected]

usage: mioutil [options] commandoptions: -h | -help print this help and exit -a16 VME address space A16D16 (default) -a24 VME address space A24D16 -n <num> number of M-Module carrier boards -o <offset1,offset2,...> address offsets of carrier boards (0x0) -t <type1,type2,...> types of carrier boards (A201) possible values: A201, B201, B202 -i <slot1,slot2,...> ignore M-Modules at slots -f search entire VME address space for M-Modules -r reset modules (only with ’config’ command)

CarMaker Programmer’s Guide Version 2.1.6

Page 204: IPG_CarMaker Programmers Guide

204MIO – M-Module Input/Output

mioutil - MIO configuration utility

commands: print print out detected M-Modules and exit (default) config <Mxxx=slot,...> config detected M-Modules: assume Mxxx at slot

• -a16:

Selects the A16/D16 VME bus address space. This is the default.

• -a24:

Selects the A24/D16 VME bus address space.

• -n <num> :

Allows you to specify the number of installed M-Module Carrier Boards.

• -o <offset1,offset2,...> :

Allows you to specify the base addresses of the installed M-Module Carrier Boards.The base addresses are given as a comma separated list of numbers in hexadecimalor decimal notation. Whitespaces are not allowed. A base address is always interpret-ed as an offset to the selected VME bus address space.

• -t <type1,type2,...> :

Allows you to specify the types of installed M-Module Carrier Boards. The types aregiven as a comma separated list. Possible values are “A201”, “B201” or “B202”.Whitespaces are not allowed. The type of a carrier board is used by mioutil to decide,how many M module slots are on the board.

• -i <slot1,slot2,...> :

Allows you to specify which M module slots should be ignored, when mioutil tries todetect the installed M modules. The slots are given as a comma separated list withoutwhitespaces. The M module detection routine excludes these slots from detection.

• -f :

Tells mioutil to scan the entire VME bus address space for MIO hardware.

• -r :

When used with the config command, mioutil also calls the functionMIO_ResetModules() after successful MIO initialization.

As the last command line argument, mioutil accepts a command word. Possible com-mands are:

• print :

Prints out the detected configuration of the MIO hardware and exits. This is the default,when mioutil is called without a command word.

• config <Mxxx=slot,...> :

For each detected M module, mioutil calls the appropriate MIO_Mxx_Config() function.In order to register M modules of unknown type, too – this happens, if the M moduledoes not have an Id EEPROM – mioutil allows you to add a comma separated list ofMxxx=slot pairs. mioutil then calls the appropriate MIO_Mxx_Config() functions at thegiven slots, too.

If used together with the option -r , then mioutil also calls the functionMIO_ResetModules() , after successful registration of M modules.

8.5.1 Version History

Version Changes

1.0 Initial version

CarMaker Programmer’s Guide Version 2.1.6

Page 205: IPG_CarMaker Programmers Guide

205MIO – M-Module Input/Output

mioutil - MIO configuration utility

1.1 Id-EEPROM access added. Needed, because removedfrom mio.c module to MIO driver

1.2 Improvements:• always scanning +3 carrier board locations when search-

ing for M modules• option -f for full VME bus scan

Bugs fixed:• bad version output• garbage output (error handling) removed• using offsets when dumping VME bus addresses

1.3 Improvements:• Support for MEN M35N Module added

1.5 Improvements:• Support for MEN M77 Module added

1.6 Improvements:• New command iddat to print full Id-EEPROM data

Version Changes

CarMaker Programmer’s Guide Version 2.1.6

Page 206: IPG_CarMaker Programmers Guide

206MIO – M-Module Input/Output

mioutil - MIO configuration utility

CarMaker Programmer’s Guide Version 2.1.6

Page 207: IPG_CarMaker Programmers Guide

207CANiogen – CANdb import tool

Chapter 9

CANiogen – CANdb import tool

Connecting an ECU to CarMaker/HIL normally requires the application engineer to code allCAN messages that have to be transferred between the ECU and the simulation program.This part is realized in the module IO.c through the functions IO_In() and IO_Out() . InIO_In() , CAN signals are extracted from received CAN messages and its values areassigned to associated input quantities. In IO_Out() , respectively, values of output quanti-ties are coded into CAN messages, which are transmitted to the ECU.

However, coding the handling of CAN messages by hand takes a lot of time and is error-prone. If you have a vector CAN data base, where the ECU is modeled within its surround-ing CAN network, you can automate this step with CANiogen.

CarMaker Programmer’s Guide Version 2.1.6

Page 208: IPG_CarMaker Programmers Guide

208CANiogen – CANdb import tool

Overview

9.1 Overview

9.1.1 Basic information

CANiogen is a command line tool, which is intended to be called automatically during thecompilation process of CarMaker/HIL. This guarantees, that changes to the CANdb and/orthe simulation program will affect the behavior of CarMaker/HIL.

As input, CANiogen gets a vector CANdb file. This file models a CAN network with all itsnetwork nodes (ECU) and defines CAN messages and CAN signals, which are transferredbetween the ECUs. Depending on the test stand, there are ECUs which are included ashardware components. Others might be realized in software, which means that their behav-ior is simulated by CarMaker/HIL.

The user now has the choice, to either call CANiogen with a list of ECUs which should beserved by CarMaker/HIL. CANiogen will then assume, that these ECUs build the real partof the CAN network, and will import all information from the CAN data base which is nec-essary to simulate the rest of the CAN network. Or, the user gives a list of simulated ECUs,that tells CANiogen, which ECUs build the simulated part of the CAN network. CANiogenwill then assume all other ECUs to be realized in hardware. In substitution for all ECUs,located in the simulated part of the CAN network, CarMaker/HIL will handle all CAN mes-sages (both, reception and transmission), which these ECUs exchange with real networknodes. The user can also decide to receive or send additional single messages, as well ashe can choose to receive additional single signals, which are not automatically included byCANiogen. All these information are entirely extracted from the given CAN data base.

The output generated by CANiogen, is an isolated C-module, which can be easily integrat-ed in CarMaker/HIL. The user only has to add about 5 lines of source code in the moduleIO.c , to activate the generated code. Additional lines are required for the assignmentbetween the generated I/O quantities and their associated model variables. Compared tothe conventional method – coding everything by hand – the amount of code the user isresponsible for, stays much more manageable.

The C-module generated by CANiogen (typically called IO_CAN), will be representedthrough the files IO_CAN.c , IO_CAN.h and IO_CAN_VarList.txt . The header fileIO_CAN.h defines a set of macros to encode/decode signals of CAN messages anddeclares several functions, that have to be called in IO.c . Each imported CAN signal, willbe presented by a generated I/O variable. These variables will be added to the Data Dictio-nary, too. To simplify the use of generated I/O variables in CarMaker/HIL, the fileIO_CAN_VarList.txt lists all handled CAN signals, together with the data type and fullvariable name. Finally, the file IO_CAN.c contains the generated functions.

CarMaker Programmer’s Guide Version 2.1.6

Page 209: IPG_CarMaker Programmers Guide

209CANiogen – CANdb import tool

Overview

shows, how the imported CAN data base will fit into the CarMaker/HIL environment.

9.1.2 Features

CANiogen was developed with the help of CANdb++ version 2.5 from Vector InformatikGmbH. Compatibility to CAN data bases that were created with other versions of CANdb++,cannot be guaranteed. However, it is not likely to meet a compatibility problem that makesthe import of a CAN data base impossible.

A vector CAN data base defines ECUs (network nodes) and CAN messages, which aretransferred inside a CAN network. Each CAN message has an unique message identifierand may contain up to 8 data bytes. The sender of a message codes CAN signals into thedata bytes, to supply information to other ECUs. The CAN signals may vary in size, i.e. thedata width need not to be a multiple of full bytes. Even worse, a CAN signal may be placedat any bit position within the data bytes, and can be stored in Motorola or Intel byte order.As a result, it is difficult to decode and encode the CAN signals by hand when programmingthe CAN traffic for a CarMaker/HIL application, and bugs are usual. CANiogen helps you,by automating the following steps:

• manages receiving and sending of CAN messages for a given ECUs, as specified inCAN data base

• generates CAN I/O variables for any signal of all imported CAN messages and ECUs

• generates Data Dictionary entries for all generated I/O variable (Data Dictionary entriescan be omitted explicitly for single I/O variables)

• imports additional CAN messages and signals of special interest

• retrieves information about how and how often to send a CAN message (cyclic, sponta-neous, ...) from the CAN data base

Figure 9.1: CANdb Import

CAN quantitiesCAN traf

fic

CANiogen

command line argumentsCAN data base

DataDictionary

CANHardware

CAN bus

Virtual Vehicle Environment CarMaker Interface Toolbox

CAN I/O I/O

PartialVehicleModels

APO Networ APO

CarMakerGUI Instruments

IPG-CONTROL

IPG-MOVIE

CarMaker Programmer’s Guide Version 2.1.6

Page 210: IPG_CarMaker Programmers Guide

210CANiogen – CANdb import tool

Overview

Additionally, CANiogen fully supports extended CAN messages with 29-bit-identifiers andis able to deal with multiplexed CAN signals.

CarMaker Programmer’s Guide Version 2.1.6

Page 211: IPG_CarMaker Programmers Guide

211CANiogen – CANdb import tool

Using CANiogen

9.2 Using CANiogen

9.2.1 The CANiogen Command Line

When called without arguments or with the option -h , CANiogen prints a usage and exits.The usage lists the current version of CANiogen and gives an overview of accepted com-mand line arguments. The following options are supported:

• -srvECU ECU1,ECU2,... :

Gives a comma separated list of ECUs which are part of the test stand and should beserved by the CarMaker/HIL application (see Serving ECUs (-srvECU option) in sec-tion 9.2.2 ’Importing Electronic Control Units (ECU)’)

• -simECU ECU1,ECU2,... :

Gives a comma separated list of ECUs which are part of the rest bus simulation andwhose CAN traffic should be simulated by the CarMaker/HIL application (see Simulat-ing ECUs (-simECU option) in section 9.2.2 ’Importing Electronic Control Units (ECU)’)

• -excECU ECU1,ECU2,... :

Gives a comma separated list of ECUs which should be ignored by CANiogen (seeExcluding ECUs (-excECU option) in section 9.2.2 ’Importing Electronic Control Units(ECU)’)

• -rcvMsg Msg1,Msg2,... :

Gives a list of CAN messages which should be additionally received (see section 9.2.3’Receiving CAN messages and signals of special interest’)

• -rcvSig Sig1,Sig2,... :

Gives a list of CAN signals which should be additionally received (see section 9.2.3’Receiving CAN messages and signals of special interest’)

• -sndMsg Msg1,Msg2,... :

Gives a list of CAN messages which should be additionally sent (see section 9.2.4’Sending arbitrary CAN messages’)

• -suppress Sig1,Sig2,... :

Gives a list of CAN signals which should not be listed in the Data Dictionary (see sec-tion 9.2.5 ’Suppressing of I/O variables in the Data Dictionary’)

• -ignore Inf1,Inf2,... :

Specifies which kind of information in the CAN data base should be ignored by CANio-gen (see section 9.2.6 ’Optimizing the output of CANiogen’)

• -genAll :

Tells CANiogen to generate as much C-code as possible (see section 9.2.6 ’Optimizingthe output of CANiogen’)

• -noRngChk :

Disables automatic range checking for signals when reading/writing the value from/tothe data bytes of a CAN message (see section 9.2.7 ’Disabling range checking of Sig-nal values’)

• -ioModule module_name :

Prefix for generated C-files, C-functions and I/O-variables. Default value is “IO_CAN”(see section 9.2.8 ’Naming of generated files, I/O variables and functions’)

• -ioPrefix prefix :

Prefix for generated I/O-variables, if required to be different from the prefix used for theC-files and C-functions (see section 9.2.8 ’Naming of generated files, I/O variables andfunctions’)

CarMaker Programmer’s Guide Version 2.1.6

Page 212: IPG_CarMaker Programmers Guide

212CANiogen – CANdb import tool

Using CANiogen

Extended features

Additionally to the options above, CANiogen accepts the following options:

• -user login :

Gives the login of the user who calls CANiogen. This might be necessary, if CANiogenfails to determine the login name automatically

• -host hostname :

Gives the host name of the computer, CANiogen is running on. This might be neces-sary, if CANiogen fails to determine the host name automatically

• -debug level :

Activates debugging output. Be careful with the use of this option. The higher the level,the more output is produced on the console. Be careful, it might be a multiple of theamount of generated source code

• -msgCTA att :

Name of CAN message attribute, which holds the cycle time for sending a CAN mes-sage. The default attribute is GenMsgCycleTime (see section 9.2.9 ’Extended fea-tures’)

• -msgDTA att :

Name of CAN message attribute, which holds the delay time when sending a CANmessage. This attribute is to be used to distribute the sending of the CAN message inbetween its cycle time. The default attribute is GenMsgDelayTime (see section 9.2.9’Extended features’)

• -msgSTA att :

Name of CAN message attribute, which holds the send type of a CAN message. Thedefault attribute is GenMsgSendType (see section 9.2.9 ’Extended features’)

• -msgSCAv value :

Value for CAN message attribute holding the send type of a CAN message, whichmarks a CAN message to be transmitted cyclically. The default value is cyclic (see sec-tion 9.2.9 ’Extended features’)

• -sigIVA att :

Name of CAN signal attribute, which holds the default value of a CAN signal. Thedefault attribute is GenSigInactiveValue (see section 9.2.9 ’Extended features’ on page217)

How to use CANiogen

To import a vector CAN data base, CANiogen requires the file name of a CANdb file (nor-mally provided with the extension .dbc ) and at least one of the options -simECU , -srvECU , -rcvMsg , -sndMsg or -rcvSig . If none of these options are given, CANiogen cannot import anydata due to lack of information and exits with an error message:

> CANiogen CANdb.dbcERROR: please specify at least: - one ECU to handle receipt and transmission of CAN messages and/or - one message to receive from CAN bus and/or - one signal to receive from CAN bus and/or - one message to send on CAN bus

The options -simECU and -srvECU cannot be used simultaneously.

A common CarMaker/HIL test stand realizes a complete virtual environment, whereasselective components of a virtual vehicle are realized in real hardware, such as a electroniccontrol unit (ECU). The ECU itself – let’s assume it’s name is ESP – is a part of a CAN net-work, described in the CAN data base (see Figure 9.2 for an example). It’s the job of

CarMaker Programmer’s Guide Version 2.1.6

Page 213: IPG_CarMaker Programmers Guide

213CANiogen – CANdb import tool

Using CANiogen

CarMaker/HIL, to simulate the behavior of a subset of this CAN network in such a manner,that the ECU believes to be located in a real vehicle. This subset will be defined through theoptions -srvECU , -simECU , -rcvMsg , -sndMsg and -rcvSig .

In the CAN network of Figure 9.2, the behavior of the ECUs Engine and StWhlSensorshould be simulated by CarMaker/HIL, in order to supply the ECU ESP with the CAN mes-sages Engine_1, Engine_2 and StWhlAng. On the other hand, CarMaker/HIL shouldreceive and evaluate the CAN message ESP, which is produced by the ECU ESP.

9.2.2 Importing Electronic Control Units (ECU)

CANiogen offers two ways to import ECUs as a whole from a CAN data base: with theoption -simECU and with the option -srvECU . These two options have oppositional effects, sothey cannot be used simultaneously.

Simulating ECUs (-simECU option)

With the option -simECU you give a list of all ECUs in the CAN data base, which send CANmessages to the real ECUs of the test stand, or receive CAN messages from them. CAN-iogen accepts a comma separated list of ECUs, as named in the CAN data base. UnknownECU names will result in an error message.

For this set of ECUs, CANiogen generates data structures and C code to manage all theCAN messages and signals, which are transferred to and from other ECUs in the sameCAN network. Typically, the import list of ECUs includes all these ECUs of the CAN database, which are simulated by CarMaker/HIL, except the ones which are part of the teststand hardware.

With a CAN data base, describing the CAN network of Figure 9.2, the command line mightlook something like:

> CANiogen -simECU Engine,StWhlSensor CANdb.dbc

In this case, the virtual CAN network spans the whole network, except the ECU ESP, asESP receives CAN messages from all the other ECUs. However, in other cases the virtualCAN network can be much smaller.

Figure 9.2: CAN network example

StWhlSensorEngineESP

ESPEngine_1Engine_2StWhlAng

Engine_1Engine_2

ESP StWhlAng

Virtual CANNetwork

CarMaker Programmer’s Guide Version 2.1.6

Page 214: IPG_CarMaker Programmers Guide

214CANiogen – CANdb import tool

Using CANiogen

Serving ECUs (-srvECU option)

This option causes right the opposite to the option -simECU . Instead of specifying a list ofECUs to be simulated by CarMaker/HIL, you give a list of ECUs which are part of the realCAN network. The remaining part of the CAN network is to be considered as virtual.

CANiogen then generates C code to supply these ECUs with CAN messages and CAN sig-nals from the virtual part of the CAN network. On the other hand, the information which thereal ECUs provide to the rest of the CAN network will be read back, too. Typically, the importlist of ECUs names all the ECUs, which are part of the test stand. The rest of the CAN net-work will be taken to be simulated by CarMaker/HIL.

With a CAN data base, describing the CAN network of Figure 9.2, the command line mightlook something like:

> CANiogen -srvECU ESP CANdb.dbc

In this case, the virtual CAN network spans the whole network, except the ECU ESP, asESP receives CAN messages from all the other ECUs. If the CAN network tends to be quitebig, and if there are only a few ECUs part of the test stand, you should prefer this option.

Excluding ECUs (-excECU option)

Of course, a CAN data base might include even much more information than needed for theCAN network simulation of a specific test stand. There are often ECUs defined which canbe ignored completely.

Its the option -excECU , that allows you to give a list of ECUs which should be ignored com-pletely when generating the data structures and C code for CarMaker/HIL.

9.2.3 Receiving CAN messages and signals of special interest

In some cases you may be interested in additional information from ECUs, that areenclosed in the real part of the CAN network, but do not interact with parts of the virtualCAN network. Normally, these ECUs would be ignored by CANiogen. The additional infor-mation, which you want to receive from the real part of the CAN network, can be specifiedthrough the options -rcvMsg and -rcvSig . When using these options, CANiogen alsoexpects comma separated lists of CAN message names (or ids - in decimal or hexadecimalnotation), or of CAN signal names, respectively.

Let’s assume the steering wheel sensor StWhlSensor in Figure 9.2 to be the only simulatedpart of the CAN network. The other ECUs (ESP and Engine) will supply each other with allneeded information. Only the CAN message StWhlAng has to be generated and transmit-ted by CarMaker/HIL. With the resulting command,

> CANiogen -simECU StWhlSensor CANdb.dbc

only the data structures and C code to handle the transmission of CAN message StWhlAng,will be generated by CANiogen. No further CAN messages or signals will be handled bydefault. Nevertheless, you may be interested in receiving information like the wheel speedsand yaw rate from the ECU ESP, as well as the engine speed from the ECU Engine. Let’sassume, that these information are provided by the CAN messages ESP, and the CAN sig-nal E2_Data1 in message Engine_2. The command line would now look like:

> CANiogen -srvECU ESP -msgCTA MsgCycleTimeAtt CANdb.dbc

9.2.4 Sending arbitrary CAN messages

Suppose, you have an ECU (ECU1) connected to your test stand, running a preliminaryfirmware version with limited operability. Another ECU (ECU2), which is also connected tothe test stand, expects to receive a special CAN message (0x180) from ECU1. But, ECU1

CarMaker Programmer’s Guide Version 2.1.6

Page 215: IPG_CarMaker Programmers Guide

215CANiogen – CANdb import tool

Using CANiogen

which should send this message, does not implement this function in its early version. So,we might have to simulate this CAN message by software, in order to complete the virtualenvironment. This is done with the option -sndMsg :

> CANiogen -srvECU ECU1,ECU2 -sndMsg 0x180 CANdb.dbc

The option -sndMsg tells CANiogen to generate all necessary I/O variables, timing datastructures and C-code to send CAN messages, even if they are part of the real CAN net-work.

9.2.5 Suppressing of I/O variables in the Data Dictionary

Depending on the size of the CAN network and the number of simulated ECUs, there maybe generated a huge amount of I/O variables. By default, all these I/O variables will be listedin the Data Dictionary, which may blow it up unnecessarily. As many of them will hardly inter-est the user, you are able to suppress the listing of any generated I/O variable in the DataDictionary with the option -suppress .

With the option -suppress , CANiogen accepts a comma separated list of patterns. A patterncan be just the name of a CAN signal, the name of a CAN message, or a combination ofsignal name and message name. Even the wildcard * is allowed. CANiogen accepts the fol-lowing patterns:

• -suppress S_Data1 :

The listing of all CAN signals, named S_Data1 in any CAN message will be suppressed.

• -suppress S_Data* :

The listing of all CAN signals that match the pattern S_Data* in any CAN message willbe suppressed.

• -suppress S_Data1@StWhlAng :

The listing of the CAN signal named S_Data1 in the CAN message StWhlAng will be sup-pressed.

• -suppress S_Data*@StWhlAng :

The listing of all CAN signals that match the pattern S_Data* in the CAN messageStWhlAng will be suppressed.

• -suppress S_Data*@StWhl* :

The listing of all CAN signals that match the pattern S_Data* in all CAN messageswhich match the pattern StWhl* will be suppressed.

If we look again at Figure 9.2, supposing that we want to suppress the listing of the signalsE_Data1 in the message ESPand all signals that begin with E1_Data , then the command linewill look like:

If you call CANiogen inside of a Unix-like command shell, you will have to quote the wild-cards like * , for instance by prepending a backslash \ . Otherwise, the command shell mayperform a command line substitution (as performed on a command like “copy *.dbc /tmp ”).

9.2.6 Optimizing the output of CANiogen

CANiogen will always try to minimize the amount of generated C-code. However, in somecases you might be interested in additional macros, I/O variables or CAN messages, or youwant to ignore obsolete information of the CAN data base. The following options allow youto control this:

• -ignore unknown :

CarMaker Programmer’s Guide Version 2.1.6

Page 216: IPG_CarMaker Programmers Guide

216CANiogen – CANdb import tool

Using CANiogen

This option tells CANiogen to ignore CAN messages and CAN signals to and from theECU Vextor__XXX. This is the default for messages and signals, that do not have asender or receiver

• -ignore nCyclic :

Use this option to exclude non cyclic CAN messages from the IO_CAN_Send() function.CANiogen generates the data structures for all Tx messages of an ECU, cyclic and noncyclic CAN messages. The -ignore nCyclic option tells CANiogen, that only thesemessages, which are recognized as cyclic, shall be included in the IO_CAN_Send() func-tion. Otherwise, even non cyclic Tx messages will be listed, but you can still control thetransmission with the timing parameters.

• -genAll :

To decode and encode signals in a CAN message, CANiogen generates *_SetV() and*_GetV() macros for each signal. Of course, many of these macros are unnecessary,because not every signal is received, as well as transmitted. CANiogen optimizes theoutput by generating only those macros, that are really necessary. If you use the option-genAll , all of the *_SetV() and *_GetV() macros are generated, whether needed ornot. This may increase drastically the amount of generated code.

9.2.7 Disabling range checking of Signal values

According to the attributes of a signal, which are defined in the CAN data base file, CANio-gen generates the *_SetV() and *_GetV() macros to limit the value of the signal to fit intothe range of its minimum and maximum. This limiting is performed always when encodingthe value of a signal into a CAN message, as well as when decoding it out of a CAN mes-sage. As a consequence, the value of a signal can never be out of range.

However, if you are testing the functionality and reliability of an ECU, you might be interest-ed in disabling this range checking. This is done with the option -noRngChk .

CANiogen will then not include calls to the macros IO_CAN_FixMin() and IO_CAN_FixMax() inthe *_SetV() and *_GetV() macros. However, the macros IO_CAN_Range() , IO_CAN_FixMin()and IO_CAN_FixMax() are generated anyway and can be used by hand.

9.2.8 Naming of generated files, I/O variables and functions

Normally CANiogen names the generated files IO_CAN* and uses IO_CAN as prefix for allgenerated variables or functions. The output directory is always the present working direc-tory, from which CANiogen is called. CANiogen is intended to be called in the source direc-tory of your CarMaker/HIL project.

If you want to use more than one CAN data base simultaneously, you can initiate CANiogento use different prefixes in order to avoid conflicts during the compilation and linking pro-cess. This allows you to use different CAN data bases for different I/O configurations.

The prefix can be changed with the option -ioModule :

This prompts CANiogen to name the output files IO_ESP.* and to use the prefix IO_ESP forall generated I/O variables and functions.

Alternatively (or additionally), you can use the option -ioPrefix . CANiogen will then useanother prefix for generated I/O variables, which may differ from the file name. This prefixwill affect only the name of I/O variables, but not the name of data types and functions. Forinstance, if you call CANiogen with -ioPrefix IO_ESP , but do not use the option -ioModule ,the output files will still be named IO_CAN*, as well as the data types and functions will stillhave the prefix IO_CAN (e.g. tIO_CANVec , IO_CAN_Send() ), but all generated variables will havethe prefix IO_ESP (e.g. tIO_CANVec IO_ESP ).

CarMaker Programmer’s Guide Version 2.1.6

Page 217: IPG_CarMaker Programmers Guide

217CANiogen – CANdb import tool

Using CANiogen

Be careful when using more than one CAN data base. Generated files will be overwrittenwithout a prompt. It is recommended to use the option -ioModule with different modulenames for each imported CAN data base. The option -ioPrefix then is obsolete.

9.2.9 Extended features

Some informations, which CANiogen needs for the transmission of CAN messages and toinitialize variables, are encapsulated in attributes of messages and signals. As default,CANiogen evaluates the following attributes:

• GenMsgCycleTime (message attribute):

This attribute is checked to determine the cycle time for the transmission of a CANmessage. The value is expected to be an integer, which gives the cycle time in milliseconds. If this attribute is not found in the CAN data base, the send period of a CANmessages will be set to -1. You will then have to set the timing parameters of the CANmessages by hand in order to activate the transmission of CAN messages (see section9.3.4 ’The C module IO_CAN.c’ and section 9.4 ’Integration into CarMaker/HIL’).

If the cycle time is given by another attribute, you can tell CANiogen to use this attributeinstead, with the option -msgCTA:

> CANiogen -srvECU ESP -msgCTA MsgCycleTimeAtt CANdb.dbc

• GenMsgDelayTime (message attribute):

This attribute is used to distribute the transmission of different CAN messages withintheir cycle time. This helps to reduce the load of the CPU and the CAN bus. The trans-mission of a CAN message is triggered by the following condition:

if (GenMsgCycleTime > 0 && CycleNo%GenMsgCycleTime == GenMsgDelayTime)then send CAN messageelse do nothing

This means, a CAN message will only be sent, if GenMsgDelayTime is in the valid rangeof 0 <= GenMsgDelayTime < GenMsgCycleTime. You might have to adjust the timingparameter of a message by hand, if GenMsgDelayTime does not have a valid value (seesection 9.3.4 ’The C module IO_CAN.c’ and section 9.4 ’Integration into CarMaker/HIL’).

If the distribution is to be described better by another attribute, you can tell CANiogento use this attribute instead, with the option -msgDTA:

> CANiogen -srvECU ESP -msgDTA MsgDelayTimeAtt CANdb.dbc

• GenMsgSendType (message attribute):

This attribute is used to recognize, if a CAN message is to be transmitted periodicallyor not. As default, CANiogen compares the attribute AttMsgSndType with the string“cyclic”. The comparison is done case insensitive, which means that if the attributeAttMsgSndType does not include the string “cyclic” or any possible spelling of it with cap-ital letters, the CAN message will not be recognized as a cyclic message. But, as longas the option -ignore nCyclic is not used, the CAN message will be imported anyway.Only the timing parameters will be initialized with invalid values (-1), to prevent theautomatic transmission. You can still control the transmission of these messages byadjusting the timing parameters (see section 9.3.4 ’The C module IO_CAN.c’ and sec-tion 9.4 ’Integration into CarMaker/HIL’).

If the send type is to be described better by another attribute, or if cyclic messages areindicated by another value than “cyclic”, you can adjust this with the options -msgSTAand -msgSCAv:

> CANiogen -srvECU ESP -msgSTA MsgSendTypeAtt -msgSCAv AttValCyclic CANdb.dbc

• GenSigInactiveValue (signal attribute):

CarMaker Programmer’s Guide Version 2.1.6

Page 218: IPG_CarMaker Programmers Guide

218CANiogen – CANdb import tool

Using CANiogen

This attribute is used to initialize CAN signals with suitable values, especially those sig-nals, which are not provided with simulation results. If this attribute is not defined for asignal, its initial value will be set to 0, which might be invalid. To set the initial value byhand, please refer to section 9.3.4 ’The C module IO_CAN.c’ and section 9.4 ’Integra-tion into CarMaker/HIL’.

If the initial value of CAN signals is to be described better by another attribute, you canadjust this with the option -sigIVA :

> CANiogen -srvECU ESP -sigIVA SigStartValAtt CANdb.dbc

CarMaker Programmer’s Guide Version 2.1.6

Page 219: IPG_CarMaker Programmers Guide

219CANiogen – CANdb import tool

CANiogen’s output

9.3 CANiogen’s output

9.3.1 Output files

CANiogen generates a C module IO_CAN.c , the appropriate header file IO_CAN.h and acomplete list with all generated I/O variables in the file IO_CAN_VarList.txt (how tochange the naming of the files is described in section 9.2.8 ’Naming of generated files, I/Ovariables and functions’). All the files are generated in the current working directory, fromwhich CANiogen is executed. Existing files will be overwritten without a prompt. The outputfiles of CANiogen are not meant to be modified manually.

9.3.2 The header file IO_CAN.h

In the header file IO_CAN.h , CANiogen lists the data structures of the generated I/O vari-ables and defines several macros and functions for data access.

CarMaker Programmer’s Guide Version 2.1.6

Page 220: IPG_CarMaker Programmers Guide

220CANiogen – CANdb import tool

CANiogen’s output

I/O variables

The I/O variables are arranged hierarchically within data structures, which reflect the rela-tionship in the CAN data base. Within the data structure IO_CAN at top level, an ECU is pre-sented as a C data structure, which itself contains CAN messages, transmitted by the ECU.A CAN message is also defined as a C data structure, which lists its CAN signals accordingto their data type:

Listing 9.1: I/O variables generated by CANiogen

1: /* Input Vector for CAN communication */2: typedef struct {3: /* ECU ESP */4: struct {5: /* CAN Msg 0x101 (ESP) */6: struct {7: float E_Data3;8: int E_Data2;9: unsigned short E_Data1;

10: } ESP;11: } ESP;12:13: /* ECU Engine */14: struct {15: /* CAN Msg 0x201 (Engine_1) */16: struct {17: unsigned short E1_Data1;18: unsigned char E1_Info;19: unsigned char E1_MPlex;20: } Engine_1;21:22: /* CAN Msg 0x202 (Engine_2) */23: struct {24: unsigned int E2_Data1;25: unsigned char E2_Data2;26: } Engine_2;27: } Engine;28:29: /* ECU StWhlSensor */30: struct {31: /* CAN Msg 0x001 (StWhlAng) */32: struct {33: unsigned char S_Counter;34: float S_Data1;35: unsigned char S_Data1Inv;36: short S_Data2;37: } StWhlAng;38: } StWhlSensor;39: } tIO_CANVec;

CarMaker Programmer’s Guide Version 2.1.6

Page 221: IPG_CarMaker Programmers Guide

221CANiogen – CANdb import tool

CANiogen’s output

Timing parameters

For the CAN messages, which will be transmitted by CarMaker/HIL, a data structure withtiming information will be generated:

The timing information is fetched out of the CAN data base through the message attributesGenMsgCycleTime and GenMsgDelayTime . If everything works fine, then these attributes aredefined in the data base. So, the value of the attribute GenMsgCycleTime will be assigned tothe timing variable SendPeriod . This attribute defines a cycle time in milli seconds for cycli-cally transmitted CAN messages. The parameter SendDistrib is used to distribute all (Tx-)CAN messages with the same cycle time within their time slice. It’s the attributeGenMsgDelayTime , which is used to get the initial value for this parameter.

Listing 9.2: CAN message timings

1: /* Timing parameters for Tx CAN messages */2: typedef struct {3: int SendPeriod;4: int SendDistrib;5: } tIO_CANMsgTiming;6:7: typedef struct {8: /* ECU StWhlSensor */9: struct {

10: tIO_CANMsgTiming StWhlAng;11: } StWhlSensor;12:13: /* ECU Engine */14: struct {15: tIO_CANMsgTiming Engine_1;16: tIO_CANMsgTiming Engine_2;17: } Engine;18: } tIO_CANTimings;

CarMaker Programmer’s Guide Version 2.1.6

Page 222: IPG_CarMaker Programmers Guide

222CANiogen – CANdb import tool

CANiogen’s output

Function prototypes and macro definitions

For integration into CarMaker/HIL and for access to the generated I/O variables, CANiogengenerates a set of function prototypes and macros:

With these functions, all necessary steps to handle the imported CAN messages and sig-nals, are covered. The user only has to assign the value of model variables to the appropri-ate I/O variables and vice versa, while calibration is done automatically with the help of themacros IO_CAN_Msg_Signal_GetV() and IO_CAN_Msg_Signal_SetV() . To decode and encodethe I/O variables from/into CAN messages, the macros are used internally. They are listedin the header file for the sake of completeness, only.

Listing 9.3: Function prototypes and macros

1: /* Function definitions */2: int IO_CAN_Init_First(void);3: int IO_CAN_Init (void);4: int IO_CAN_Recv (CAN_Msg *Msg, unsigned CycleNo);5: int IO_CAN_RecvExt (CAN_MsgExt *MsgExt, unsigned CycleNo);6: void IO_CAN_RecvLoop (int Slot, int Channel, unsigned CycleNo);7: int IO_CAN_Send (int Slot, int Channel, unsigned CycleNo);8:9:

10: /* Makros to encode/decode values of signals */11: /* converting to signed value */12: #define IO_CAN_Cvt2Signed(v, dw, tmp) ( \13: ((tmp=v)&(((dw>32) ? 1ll : 1)<<(dw-1))) ? \14: (tmp|(((dw>32) ? -1ll : -1)<<(dw-1))) : tmp \15: )16:17: /* fixing range of value */18: #define IO_CAN_Range(v, min, max) ( \19: (v<min) ? min : (v>max) ? max : v \20: )21: #define IO_CAN_FixMin(v, min) ( \22: (v<min) ? min : v \23: )24: #define IO_CAN_FixMax(v, max) ( \25: (v>max) ? max : v \26: )27:28:29:30: #define IO_CAN_ESP_ID 257u /* MsgId=0x101 */31: #define IO_CAN_ESP_NAME "ESP"32: #define IO_CAN_ESP_DLC 833:34: #define IO_CAN_ESP_E_Data3_GetV(data) ( \35: IO_CAN_FixMin((IO_CAN_FixMax((0.035 * ( \36: IO_CAN_Cvt2Signed( \37: ((data[6]>>4) & 15) \38: | data[7]<<4, 12, DummyCvtI))), 143.36)), 0) \39: )40: #define IO_CAN_ESP_E_Data2_GetV(data) ( \41: IO_CAN_FixMin((IO_CAN_FixMax(( \42: IO_CAN_Cvt2Signed( \43: data[2] \44: | data[3]<<8 \45: | data[4]<<16 \46: | data[5]<<24, 32, DummyCvtI)), 0)), 0) \47: )48: ...

CarMaker Programmer’s Guide Version 2.1.6

Page 223: IPG_CarMaker Programmers Guide

223CANiogen – CANdb import tool

CANiogen’s output

9.3.3 The list of generated I/O variables in IO_VarList.txt

The intention of this file is to give the user a short and clear overview of all generated I/Ovariables. This is useful, because the user still has to complete the assignment between I/O variables and simulation variables in the I/O module file IO.c manually. In order to assistthe user in this step as much as possible, the file IO_VarList.txt lists all CAN signals byname, together with their C data type and their full variable name. Again, this list is arrangedhierarchically by ECUs and CAN messages:

9.3.4 The C module IO_CAN.c

Initialization

At the beginning, there is always needed an accurate initialization. This is done by the func-tions IO_CAN_Init_First() and IO_CAN_Init() . For each generated I/O variable there will becreated a Data Dictionary entry. The naming of these entries is geared to the hierarchicaldefinition in IO_CAN.h and follows the scheme IO_CAN.MsgName.SignalName .

Beside the Data Dictionary entries, the function IO_CAN_Init() also initializes the I/O vari-ables of all CAN signals and the timing parameters for transmitted CAN messages. But, theattributes, which define the initial values for CAN signals and the timing parameters for CANmessages, need not to be present in the CAN data base, or may be named different. As a

Listing 9.4: List of generated I/O variables

1: ECU ESP:2: ########3:4: CAN Msg 0x101 (ESP):5: signal data type full variable name6: ------------------------------------------------------------------------------7: E_Data3 float IO_CAN.ESP.ESP.E_Data38: E_Data2 int IO_CAN.ESP.ESP.E_Data29: E_Data1 unsigned short IO_CAN.ESP.ESP.E_Data1

10:11:12: ECU Engine:13: ###########14:15: CAN Msg 0x201 (Engine_1):16: signal data type full variable name17: ------------------------------------------------------------------------------18: E1_Data1 unsigned short IO_CAN.Engine.Engine_1.E1_Data119: E1_Info unsigned char IO_CAN.Engine.Engine_1.E1_Info20: E1_MPlex unsigned char IO_CAN.Engine.Engine_1.E1_MPlex21:22: CAN Msg 0x202 (Engine_2):23: signal data type full variable name24: ------------------------------------------------------------------------------25: E2_Data1 unsigned int IO_CAN.Engine.Engine_2.E2_Data126: E2_Data2 unsigned char IO_CAN.Engine.Engine_2.E2_Data227:28:29: ECU StWhlSensor:30: ################31:32: CAN Msg 0x001 (StWhlAng):33: signal data type full variable name34: ------------------------------------------------------------------------------35: S_Counter unsigned char IO_CAN.StWhlSensor.StWhlAng.S_Counter36: S_Data1 float IO_CAN.StWhlSensor.StWhlAng.S_Data137: S_Data1Inv unsigned char IO_CAN.StWhlSensor.StWhlAng.S_Data1Inv38: S_Data2 short IO_CAN.StWhlSensor.StWhlAng.S_Data2

CarMaker Programmer’s Guide Version 2.1.6

Page 224: IPG_CarMaker Programmers Guide

224CANiogen – CANdb import tool

CANiogen’s output

result, the initialization of CAN signals and timing parameters may have to be changedexplicitly after the initialization. It’s recommended, that the user double-checks these valuesand adjusts them manually, after calling the function IO_CAN_Init() , if necessary.

Reception of CAN messages

Received CAN messages will be handled by the functions IO_CAN_Recv() , IO_CAN_RecvExt()and IO_CAN_RecvLoop() .

The functions IO_CAN_Recv() and IO_CAN_RecvExt() expect a single CAN message as argu-ment and try to decode it by checking the message identifier. While IO_CAN_Recv() acceptsonly standard CAN messages with 12-bit-identifiers, IO_CAN_RecvExt() also deals withextended CAN messages and 29-bit-identifiers. If possible, you should prefer the versionfor extended CAN messages, as the standard version is in fact only a wrapper function,which slightly increases CPU load.

Alternatively to the functions IO_CAN_Recv() and IO_CAN_RecvExt() , CAN messages canalso be processed through the function IO_CAN_RecvLoop() . In this case, all available CANmessages will be fetched from the CAN controller and processed immediately. This functionis useful, if there is no further CAN traffic than those of the imported CAN data base. Callsto the function IO_CAN_RecvLoop() should not be mixed with the conventional method.

Transmission of CAN messages

The transmission of CAN messages is handled by the function IO_CAN_Send() . This functionrequires the cycle number CycleNo of the main simulation as argument. With the help of thecycle number and the timing parameters, it is decided for each CAN message, whether atransmission of the message is required or not. A CAN message is transmitted, wheneverthe following condition is fulfilled:

(CycleNo%IO_CAN_Timings.ECU.MsgName.SigName.SendPeriod > 0 && CycleNo%IO_CAN_Timings.ECU.MsgName.SigName.SendPeriod == IO_CAN_Timings.ECU.MsgName.SigName.SendDistrib)

Knowing this, you are able to control the transmission of any CAN message. Even noncyclic CAN messages can be sent with the help of a few lines of code. You just have to mod-ify the timing parameters of a message before calling the function IO_CAN_Send() . Of course,you should not forget to restore the timing parameters after returning from the functionIO_CAN_Send() :

Listing 9.5: Sending CAN messages manually

1: # if defined (WITH_IO_CAN)2: /* force transmission of message StWhlAng */3: if (ForceSend_StWhlAng == 1) {4: /* backup timing parameters */5: OldSendPeriod = IO_CAN_Timings.StWhlSensor.StWhlAng.SendPeriod;6: OldSendDistrib = IO_CAN_Timings.StWhlSensor.StWhlAng.SendDistrib;7: /* force transmission */8: IO_CAN_Timings.StWhlSensor.StWhlAng.SendPeriod = 1;9: IO_CAN_Timings.StWhlSensor.StWhlAng.SendDistrib = 0;

10: }11: IO_CAN_Send (Slot.CAN, 0, CycleNo);12: if (ForceSend_StWhlAng == 1) {13: /* restore timing parameters */14: IO_CAN_Timings.StWhlSensor.StWhlAng.SendPeriod = OldSendPeriod;15: IO_CAN_Timings.StWhlSensor.StWhlAng.SendDistrib = OldSendDistrib;16: }17: # endif

CarMaker Programmer’s Guide Version 2.1.6

Page 225: IPG_CarMaker Programmers Guide

225CANiogen – CANdb import tool

CANiogen’s output

And last, but not least, you are also able to trigger some events on the successful transmis-sion of a CAN message. Suppose you want to increment a counter in a CAN message, eachtime the message is transmitted, you just have to check the condition for this messageagain, after returning from the function IO_CAN_Send() :

Listing 9.6: Realizing a counter in a CAN message

1: # if defined (WITH_IO_CAN)2: IO_CAN_Send (Slot.CAN, 0, CycleNo);3: /* check, if message StWhlAng was sent, then increment S_Counter */4: if (IO_CAN_Timings.StWhlSensor.StWhlAng.SendPeriod > 05: && (CycleNo%IO_CAN_Timings.StWhlSensor.StWhlAng.SendPeriod6: == IO_CAN_Timings.StWhlSensor.StWhlAng.SendDistrib)) {7: IO_CAN.StWhlSensor.StWhlAng.S_Counter++;8: }9: # endif

CarMaker Programmer’s Guide Version 2.1.6

Page 226: IPG_CarMaker Programmers Guide

226CANiogen – CANdb import tool

Integration into CarMaker/HIL

9.4 Integration into CarMaker/HIL

The output of CANiogen is the largely independent C module IO_CAN, which is representedthrough the files IO_CAN.c and IO_CAN.h . The integration into a CarMaker/HIL project, isdone in three steps. First, you will have to slightly modify the existing C module file IO.c , toenable the CAN I/O part. Then you will have to build up the connection between parametersof the simulation models and the generated I/O variables. This requires a modification ofthe C module file User.c . In order to optimize the automatic build process, you may thenwant to add some new rules to the Makefile .

9.4.1 Modifications to IO.c

First, you have to include the header file IO_CAN.h in IO.c , in order to make known thedata structures, functions and macros, which are defined in IO_CAN.h :

Initialization

The initialization of the module IO_CAN is done in the two functions IO_Init_First() andIO_Init() . First, a call to the function IO_CAN_Init_First() has to be added to the functionIO_Init_First() . This guarantees, that all data structures, which are generated by CANio-gen, are properly initialized before the first use:

Listing 9.7: Including IO_CAN.h in IO.c

1: ...2: #include <CarMaker.h>3:4: #if defined (LYNXOS)5: # include <mio.h>6: # include <FailSafeTester.h>7: #endif8:9: #include "IO.h"

10: #if defined (WITH_IO_CAN)11: # include "IO_CAN.h"12: #endif13: ...

Listing 9.8: Low level initialization of module IO_CAN

1: int2: IO_Init_First (void)3: {4: memset (&IO, 0, sizeof(IO));5: memset (&Cal, 0, sizeof(Cal));6: memset (&Slot, 0, sizeof(Slot));7:8: #if defined (WITH_IO_CAN)9: /* Init I/O data structures */

10: IO_CAN_Init_First ();11: #endif12:13: return 0;14: }

CarMaker Programmer’s Guide Version 2.1.6

Page 227: IPG_CarMaker Programmers Guide

227CANiogen – CANdb import tool

Integration into CarMaker/HIL

Then, a call to the function IO_CAN_Init() has to be added to the function IO_Init() , inbetween the part of the appropriate I/O configuration. After calling the functionIO_CAN_Init() , you have the chance to adjust an arbitrary number of I/O or timing variables:

Reception of CAN messages

Received CAN messages will be handled in the function IO_In() . There are two possibilitieshow to realize that. If there are no other CAN messages to handle, than those, which arehandled by the module IO_CAN, you can use the function IO_CAN_RecvLoop() :

Listing 9.9: Initialization of module IO_CAN

1: int2: IO_Init(void)3: {4: ...5:6: /* hardware configuration */7: if (ConnectedIO == IO_None)8: return 0;9:

10: if (ConnectedIO == IO_DemoApp) {11: ...12: #if defined (WITH_IO_CAN)13: /* Init CAN I/O */14: IO_CAN_Init();15:16: IO_CAN.StWhlSensor.StWhlAng.S_Data1 = 15.0;17:18: IO_CAN_Timings.StWhlSensor.StWhlAng.SendPeriod = 10;19: IO_CAN_Timings.StWhlSensor.StWhlAng.SendDistrib = 4;20: ...21: #endif22: }23: ...24: return 0;25: }

Listing 9.10: Reception of CAN messages: IO_CAN_RecvLoop()

1: void2: IO_In(3: unsigned CycleNo)4: {5: ...6:7: if (ConnectedIO == IO_None)8: return;9:

10: if (ConnectedIO == IO_DemoApp) {11: ...12: #if defined (WITH_IO_CAN)13: IO_CAN_RecvLoop(Slot.CAN, 0, CycleNo);14: #endif15: ...16: }17: }

CarMaker Programmer’s Guide Version 2.1.6

Page 228: IPG_CarMaker Programmers Guide

228CANiogen – CANdb import tool

Integration into CarMaker/HIL

Otherwise, you have to use the conventional method, by receiving all available CAN mes-sages in a loop and passing them to the function IO_CAN_RecvExt() :

Transmission of CAN messages

CAN messages are usually transmitted in the function IO_Out() . That’s the place, where acall to the function IO_CAN_Send() is needed:

9.4.2 Modifications to User.c

Having performed the steps above, CarMaker/HIL would now handle a lot of CAN traffic.But, this is quite useless, until you do not make sure, that received CAN signals affect thesimulation models, as well as simulation results should be reflected in signals of transmittedCAN messages.

Listing 9.11: Reception of CAN messages: IO_CAN_RecvExt()

1: void2: IO_In(3: unsigned CycleNo)4: {5: CAN_MsgExt MsgExt;6:7: ...8:9: if (ConnectedIO == IO_None)

10: return;11:12: if (ConnectedIO == IO_DemoApp) {13: ...14: while (MIO_M51_RecvExt(Slot.CAN, 0, &MsgExt) == 0) {15: #if defined (WITH_IO_CAN)16: if (IO_CAN_RecvExt(&MsgExt, CycleNo) == 0)17: continue;18: #endif19:20: switch (MsgExt.MsgId) {21: ...22: }23: }24: }25: }

Listing 9.12: Transmission of CAN messages

1: void2: IO_Out(3: unsigned CycleNo)4: {5: if (ConnectedIO == IO_None)6: return;7:8: if (ConnectedIO == IO_DemoApp) {9: ...

10: #if defined (WITH_IO_CAN)11: IO_CAN_Send(Slot.CAN, 0, CycleNo);12: #endif13: }14: }

CarMaker Programmer’s Guide Version 2.1.6

Page 229: IPG_CarMaker Programmers Guide

229CANiogen – CANdb import tool

Integration into CarMaker/HIL

As previously performed with IO.c , you should first include the header file IO_CAN.h inUser.c :

Input processing

Imminently after having gained new values for I/O variables through received CAN messag-es, an assignment to the appropriate simulation quantities is required. This step is usuallyperformed in the function User_In() , which is called immediately after IO_In() :

Listing 9.13: Including IO_CAN.h in User.c

1: ...2: #include <CarMaker.h>3:4: #if defined (VHCL_IS_CAR)5: # include <Car/Vehicle_Car.h>6: #elif defined (VHCL_IS_MCYCLE)7: # include <MCycle/Vehicle_MCycle.h>8: #else9: # error ERROR Vehicle type not set!

10: #endif11:12: #include "IO.h"13: #include "User.h"14:15: #if defined (WITH_IO_CAN)16: # include "mio.h"17: # include "IO_CAN.h"18: #endif19: ...

Listing 9.14: Input processing

1: void2: User_In(3: const unsigned CycleNo)4: {5: ...6:7: #if defined (LYNXOS)8: if (ConnectedIO == IO_DemoApp) {9: # if defined (WITH_IO_CAN)

10: IO.ESP_Data = IO_CAN.ESP.ESP.E_Data3;11: ...12: # endif13: ...14: }15: ...16: #endif17: ...18: }

CarMaker Programmer’s Guide Version 2.1.6

Page 230: IPG_CarMaker Programmers Guide

230CANiogen – CANdb import tool

Integration into CarMaker/HIL

Output processing

Before being sent to the hardware, the output variables have to be updated with simulationresults. This is usually done in the function User_Out() , just before IO_Out() :

9.4.3 Modifications to the Makefile

As the command line for CANiogen may get very long – especially when you make use ofthe option -suppress – it is recommended to let the generation of IO_CAN.c and IO_CAN.hget managed by make. This requires the following steps:

• add object IO_CAN.o to the Makefile variable OBJS_CANIOGEN

• define preprocessor macro WITH_IO_CAN by adding -DWITH_IO_CAN to the Makefile vari-able DEF_CFLAGS

• create the variable IO_CAN_DB and assign the path to the CAN data base

• create the variable IO_CAN_FLAGS to hold the command line options for CANiogen

Listing 9.15: Output processing

1: void2: User_Out(3: const unsigned CycleNo)4: {5: ...6:7: #if defined (LYNXOS)8: if (ConnectedIO == IO_DemoApp) {9: # if defined (WITH_IO_CAN)

10: IO_CAN.StWhlSensor.StWhlAng.S_Data1 = DrivMan.Steering.Ang;11: ...12: # endif13: ...14: }15: ...16: #endif17: ...18: }

CarMaker Programmer’s Guide Version 2.1.6

Page 231: IPG_CarMaker Programmers Guide

231CANiogen – CANdb import tool

Integration into CarMaker/HIL

The Makefile should look something like:

If you want to use more than one CAN database simultaneously, you simply have to dupli-cate the Makefile variables IO_CAN_* , while appending the new object file to the variableOBJS_CANIOGENand appending a suitable preprocessor define to the variable DEF_CFLAGS. Inorder to avoid conflicts, there must also be adapted the names of the Makefile variablesand output files to different prefixes:

Listing 9.16: Defining Makefile variables for IO_CAN modules

1: ### I/O generator for CANdb files2:3: OBJS_CANIOGEN := IO_CAN.o4: DEF_CFLAGS += -DWITH_IO_CAN5:6: # to include CANdb files:7: # =======================8: # - chose new ioModule name (IO_XX)9: # - append IO_XX.o to OBJS_CANIOGEN

10: # - add -DWITH_IO_XX to DEF_CFLAGS11: # - set IO_XX_DB variable to CANdb file12: # - set IO_XX_FLAGS variable with desired command line parameters for CANiogen13: # - modifications to IO.c:14: # ˚ include IO_XX.h in IO.c15: # ˚ call IO_XX_Init() in IO_Init()16: # ˚ call IO_XX_Recv(), IO_XX_RecvExt() or IO_XX_RecvLoop() in IO_In()17: # ˚ call IO_XX_Send() in IO_Out()18: # - use preprocessor define WITH_IO_XX to encapsulate IO_XX specific code in19: # all source and header files20:21: # I/O Module IO_CAN.o22: IO_CAN_DB = ../CANdb/CANiogenGeneric.dbc23: IO_CAN_FLAGS = -srvECU ESP24:25: ### END (I/O generator for CANdb files)

Listing 9.17: Generating multiple IO_CAN modules

1: ### I/O generator for CANdb files2:3: OBJS_CANIOGEN := IO_CAN_ESP.o IO_CAN_Engine.o4: DEF_CFLAGS += -DWITH_IO_CAN_ESP -DWITH_IO_CAN_Engine5:6: # to include CANdb files:7: # =======================8: # - chose new ioModule name (IO_XX)9: # - append IO_XX.o to OBJS_CANIOGEN

10: # - add -DWITH_IO_XX to DEF_CFLAGS11: # - set IO_XX_DB variable to CANdb file12: # - set IO_XX_FLAGS variable with desired command line parameters for CANiogen13: # - modifications to IO.c:14: # ˚ include IO_XX.h in IO.c15: # ˚ call IO_XX_Init() in IO_Init()16: # ˚ call IO_XX_Recv(), IO_XX_RecvExt() or IO_XX_RecvLoop() in IO_In()17: # ˚ call IO_XX_Send() in IO_Out()18: # - use preprocessor define WITH_IO_XX to encapsulate IO_XX specific code in19: # all source and header files20:21: # I/O Module IO_CAN_ESP.o22: IO_CAN_ESP_DB = ../CANdb/CANiogenGeneric.dbc23: IO_CAN_ESP_FLAGS = -srvECU ESP24:25: # I/O Module IO_CAN_Engine.o26: IO_CAN_Engine_DB = ../CANdb/CANiogenGeneric.dbc27: IO_CAN_Engine_FLAGS = -srvECU Engine28:29: ### END (I/O generator for CANdb files)

CarMaker Programmer’s Guide Version 2.1.6

Page 232: IPG_CarMaker Programmers Guide

232CANiogen – CANdb import tool

Integration into CarMaker/HIL

It is not necessary to define any additional rule. The rules for the generation of the filesIO_CAN.c , IO_CAN.h and IO_CAN.o are generated automatically. This is controlled byappending the new object file to OBJS_CANIOGEN. The part of the Makefile , which createsthe rules, looks as followed:

If you want to use static rules – e.g. when using another compiler – you will have to definethe following rules for each IO_CAN module:

Listing 9.18: Automatic generation of rules for CANiogen

1: ### CANiogen specific rules2:3: $(OBJS_CANIOGEN): %.o: %.c %.h4: $(CC) $(CFLAGS) $(CANIOGEN_CFLAGS) -o $@ -c $<5: IO.o: IO.c IO.h $(OBJS_CANIOGEN:.o=.h)6:7: ifeq ($(CANIOGEN_CMD)x,x)8:9: $(OBJS_CANIOGEN:.o=.h): %.h: %.h.d

10: $(OBJS_CANIOGEN:.o=.c): %.c: %.c.d11: $(OBJS_CANIOGEN:.o=.h.d) $(OBJS_CANIOGEN:.o=.c.d):12: @$(MAKE) CANIOGEN_CMD=$(basename $(basename $@)) $(basename $@)13:14: else15:16: $(CANIOGEN_CMD).h $(CANIOGEN_CMD).c: $($(CANIOGEN_CMD)_DB)17: $(CANIOGEN) -ioModule $(CANIOGEN_CMD) $($(CANIOGEN_CMD)_FLAGS) $<18:19: endif20:21: ### END (CANiogen specific rules)

Listing 9.19: Using static rules

1: ### CANiogen specific rules2:3: IO_CAN_ESP.o: IO_CAN_ESP.c IO_CAN_ESP.h4: $(CC) $(CFLAGS) $(CANIOGEN_CFLAGS) -o $@ -c $<5: IO_CAN_Engine.o: IO_CAN_Engine.c IO_CAN_Engine.h6: $(CC) $(CFLAGS) $(CANIOGEN_CFLAGS) -o $@ -c $<7: IO.o: IO.c IO.h IO_CAN_ESP.h IO_CAN_Engine8:9: IO_CAN_ESP.h IO_CAN_ESP.c: $(IO_CAN_ESP_DB)

10: $(CANIOGEN) -ioModule IO_CAN_ESP $(IO_CAN_ESP_FLAGS) $<11: IO_CAN_Engine.h IO_CAN_Engine.c: $(IO_CAN_Engine_DB)12: $(CANIOGEN) -ioModule IO_CAN_Engine $(IO_CAN_Engine_FLAGS) $<13:14: ### END (CANiogen specific rules)

CarMaker Programmer’s Guide Version 2.1.6

Page 233: IPG_CarMaker Programmers Guide

233CANiogen – CANdb import tool

Version History

9.5 Version History

Version Changes

1.0 Initial version

1.0.2 Added Support for CAN data bases, without information about cycletime of Tx messages

1.0.3 Support for suppressed Data Dictionary entries added

1.0.4 Bugs fixed:• undefined variable bitfield , if signal is not of type INT

1.0.5 Bugs fixed:• signals with same name in different CAN messages not imported

correctly• extended CAN messages not handled correctly

1.1.0 Improvements:• creation of IO_CAN_VarList.txt which lists all I/O variables

Bugs fixed:• problems with extended CAN messages• problems with signed/unsigned integers

1.1.1pre1 Improvements:• option -suppress matches also CAN messages• unneeded information will be omitted in generated C code• consistency check and workarounds for CAN data bases• added support for default values of CAN signals• additional output file generated with list of I/O variables• unknown ECUs, signals and messages will be reported• added comment with message id in hex to header file

Bugs fixed:• CAN messages, that are transferred between virtual ECUs were

generated and handled, which led to unneeded code-> omitting all messages and signals, that are not received or trans-mitted by real ECUs

• duplicate CAN message names led to Tcl error-> added consistency check to generate unique message names

CarMaker Programmer’s Guide Version 2.1.6

Page 234: IPG_CarMaker Programmers Guide

234CANiogen – CANdb import tool

Version History

1.1.1pre2 Improvements:• option -srvECU, that allows to give a list of real ECUs which should

be served by CarMaker/HIL (this option cannot be used together withthe -simECU option)

• option -excECU to exclude ECUs from I/O generated code• option -sndMsg to explicitly send CAN messages

Bugs fixed:• Tcl error occurred when using -rcvSig option• received CAN signals were not correctly handled, when signal was

multiplexed and multiplexer missing in receive list-> add multiplexer to ioSigList , if needed

• in some cases, wrong data type was chosen for I/O variable. Mini-mum value and maximum value were not computed correctly-> compute minimum an maximum value with inclusion of factor andoffset to get data type for I/O variable

1.1.1pre3 Improvements:• -ignore nCyclic option to suppress sending of messages that are not

marked as cyclic• -msgSCAv option to give the attribute value, that marks a message

as cyclic

1.1.1pre4 Fixed problem with Signals in Intel Byte Order:• signals, which start at a bit position != %8 and ending in the same

date byte, were not correctly handled• max value of signal was not computed correctly• added Test for length of signal

1.1.1 Bugs fixed:• signal with data length < 8 bit was not encoded/decoded correctly

1.1.2 Bugs fixed:• in function IO_CAN_Recv() : Msg and MsgExt were mixed, data was cop-

ied in wrong direction

1.1.3 Bugs fixed:• When reading signal from CAN message or writing signal to CAN

message, the offset was not added if scaling factor was 1• Wrong range checking for signals with data type int

1.1.4 Improvements:• New option -noRngChk to disable automatic range checking for sig-

nals• Consistency check: warning if min value of signal is <0, but signal

has unsigned data type

1.1.5 Bugs fixed:• Offset for *_GetV() macro of signal printed to header file even if

*_GetV() macro not needed -> Syntax Error during compilation

1.1.6 Bugs fixed:• offset for *_GetV() macro of signal printed to header file even if

*_GetV() macro not needed

1.1.7 Bugs fixed:• missing brakes in *_GetV() macros -> Warnings during compilation

Version Changes

CarMaker Programmer’s Guide Version 2.1.6

Page 235: IPG_CarMaker Programmers Guide

235CANiogen – CANdb import tool

Version History

1.1.8 Bugs fixed:• wrong data type for declared I/O variables due to error in min/max

value computation

Version Changes

CarMaker Programmer’s Guide Version 2.1.6

Page 236: IPG_CarMaker Programmers Guide

236

CarMaker Programmer’s Guide Version 2.1.6

APO Messages

Chapter 10

APO Messages

Page 237: IPG_CarMaker Programmers Guide

237ScriptControl

Introduction

Chapter 11

ScriptControl

11.1 Introduction

ScriptControl is a tool used to create, manage and run scripts that automate the testing pro-cess of the CarMaker simulation environment. For example, scripts can be created to loada predefined testrun, start the testrun with a change to some input parameters, evaluate theresults and write a report summary to a log file.

All of the functionality of the CarMaker Interface Toolbox (CIT)1 can be automated withScriptControl. In addition, ScriptControl can interface directly to the Virtual Vehicle Environ-ment (VVE) 2 of CarMaker allowing user defined scripts to add functionality that is not con-tained in the CIT. This facilitates the creation of very useful and powerful scripts that cancompletely automate the testing process by, e.g., executing an unlimited number of pre-defined testruns (ISO lane-change maneuver, braking maneuver, etc.) filtering and loggingthe results, performing the same tests with changes to some of the input parameters, com-paring the results, and so on.

The ScriptControl scripting language is based on Tcl/Tk, an open-source, freely available,and well documented programming language. The Tcl/Tk language is robust and powerful,allowing for all of the standard programming constructs (loops, conditions, functions, etc.)and also includes a number of standard function libraries that are used to interface to thesystem (e.g. perform file I/O, spawn a process, etc.). More information about programmingin Tcl/Tk can be found at the end of this chapter.

The ScriptControl scripting language also contains a number of CarMaker specific com-mands. For example, commands are included that load and start a testrun, perform DVAaccess, control the FailSafeTester, log data, and a number of other useful tasks.

The remainder of this document will introduce you to test automation in ScriptControl andprovides a complete reference of all ScriptControl commands available.

1. The CIT is the set of tools used to interface to the virtual vehicle environment (VVE) of CarMaker, primarilyconsisting of the graphical user interfaces such as the CarMaker GUI, IPG-CONTROL, etc. Please refer to theCarMaker User’s Guide for more information on the CIT.

2. The VVE is the simulated vehicle environment that contains the vehicle model, driver model, etc. Please referto the CarMaker User’s Guide for more information on the VVE.

CarMaker Programmer’s Guide Version 2.1.6

Page 238: IPG_CarMaker Programmers Guide

238ScriptControl

Using the ScriptControl Window

11.2 Using the ScriptControl Window

The ScriptControl window is opened in the CarMaker GUI by going to the menu Simulation/ ScriptControl. The figure below shows the parts of the ScriptControl window. In the fol-lowing paragraphs we will describe each section:

A. Loaded Script Preview Area

In the upper part of the dialog you see the currently loaded script (read only). The buttonson the right side allow you to create a new script, load an existing one or open a script forediting.

B. Console, Interactive Commands

The console is used to interact directly with the CarMaker ScriptControl environment (aswell as the operating system). ScriptControl commands (and Tcl commands in general) canbe entered at the command prompt “>>” and will be executed immediately. When a com-mand has a return value, it will be shown. The cursor keys can be used to access formercommands and to edit the command line.

The console can also be used to view output from the scripts via the Log command. It isalso very helpful for debuggung scripts. While the script is running, you can enter com-mands to examine script variables, ...

C. Start/Stop Buttons

These buttons are used to start and stop the execution of the currently loaded script.

Figure 11.1: The ScriptControl dialog

A

C

B

C

CarMaker Programmer’s Guide Version 2.1.6

Page 239: IPG_CarMaker Programmers Guide

239ScriptControl

ScriptControl By Example

11.3 ScriptControl By Example

Please note: At the time of this writing redesign of the ScriptControland the ScriptControl window was still a work in progress. Because ofthis the necessary update of this chapter has been procrastinateduntil a more stable version is available.

The easiest way to learn is by doing, so in this section we will write a few small scripts thatdemonstrate the basic functionality of ScriptControl.

11.3.1 Example 1 – “Hello World!”

As is the custom when learning a programming language we will start with the “HelloWorld!” example that prints a text string to the screen. In this case the screen is theScriptControl command window. The following description gives step-by-step instructionsfor writing a simple script that prints the line “Hello World!” to the ScriptControl commandwindow.

Step 1 Open the ScriptControl dialog – CarMaker GUI menu Simulation / ScriptControl.

Step 2 Create a new script file – Press New. Use HelloWorld.tcl as name for the new script.

Step 3 Type the following in the text editor:

Log “Hello World!”

Step 4 To test the script, simply load it and press the Start button. The script will be displayed inthe Preview Area and the Start and Stop buttons will become active. Press the Start buttonto run the script. The test string “Hello World!” should be printed to the ScriptControl Con-sole. If not, check that there were no spelling errors or that there are no upper-case letterswhere there should be lowercase letters, and vice-versa (i.e. the commands are case sen-sitive). Correct any syntax errors and try again.

Analysis The command Log messagestr is used to print text to the console. The Log command canalso be used to print to a log file, or to both the command window and a log file. See thefunction description for more detailed information.

11.3.2 Example 2 – Starting a Testrun

In this example we will demonstrate how ScriptControl can be used to start and stopCarMaker testruns.

Step 1 Open a new script for editing.

Step 2 Type the following text:

LoadTestRun “Examples/Hockenheim”StartSimWaitForTime 30StopSim

Step 3 Save the newly created script as StartStopTest.tcl .

Step 4 Load the script and press the Start button. The example testrun named Hockenheim isloaded, started, runs for 30 seconds and stops.

CarMaker Programmer’s Guide Version 2.1.6

Page 240: IPG_CarMaker Programmers Guide

240ScriptControl

ScriptControl By Example

Analysis This example uses four commands. The first, LoadTestRun, will load the testrun specifiedin its arguments. The second command, StartSim, starts the testrun that was loaded withLoadTestRun. The third, WaitForTime, is a function that waits for the specified amount oftime before allowing the script to continue. The argument is in seconds.The last commandused in this example, StopSim, will stop the simulation.

The two commands StartSim and StopSim perform the same function as the big red andgreen Start and Stop buttons in CarMaker‘s main dialog (NOTE: they are not the same asthe red and green Start/Stop buttons in the ScriptControl GUI).

11.3.3 Example 3 – Subscribing to Quantities

During a simulation there are a number of variables that are updated and that can be viewedduring a running simulation (e.g with tools such as IPG-CONTROL). Simulation variableslike the vehicle’s velocity, acceleration, yaw rate, etc. can be viewed and plotted in both real-time and offline by using the appropriate evaluation utility (e.g. IPG-CONTROL or Matlab).The simulation variables are called Quantities in the CarMaker vernacular.

To have access to the quantities, first you have to subscribe the quantities you are interest-ed in. Subscribing meens the values of selected quantities will get transfered regularly inthe background (update rate approximately 50..100 Hz) from the simulation program toScriptControl. The values are placed in a shadow variable, the global array Qu.

The following example shows how to subscribe to one of the quantites in the CarMaker datadictionary. The quantity is then used in a conditional statement to branch the executionaccording to its value.

Step 1 Open a new script for editing.

Step 2 First, you have to subscribe all quantities you want to deal with. This is done with the com-mand QuantSubscribe followed by the list of quantities to be subscribed.

QuantSubscribe {Time Car.v}

Step 3 The following commands will load a testrun, start the simulation and wait for the simulationto start.

LoadTestRun "Examples/Hockenheim"StartSimWaitForStatus running

Step 4 Wait for the simulation time to reach 50 seconds.

WaitForCondition {$Qu(Time) > 50}

Step 5 Check the velocity when the simulation time is > 50. If the speed is less than 20 m/s thenstop the simulation. Otherwise, continue until the simulation time is > 100.

if {$Qu(Car.v) < 20} {StopSim

} else {WaitForCondition {$Qu(Time) > 100}StopSim

}

Step 7 Log the time and velocity before exiting the script.

Log "Speed = $Qu(Car.v) Time = $Qu(Time)"

Step 8 Save the script as QuantSubTest.tcl . Load it into ScriptControl and run it.

Analysis The whole script looks like the following:

CarMaker Programmer’s Guide Version 2.1.6

Page 241: IPG_CarMaker Programmers Guide

241ScriptControl

ScriptControl By Example

QuantSubscribe {Time Car.v}

LoadTestRun "Examples/Hockenheim"StartSim

WaitForStatus runningWaitForCondition {$Qu(Time) > 50}

if {$Qu(Car.v) < 20} {StopSim

} else {WaitForCondition {$Qu(Time) > 100}StopSim

}Log "Speed = $Qu(Car.v), Time = $Qu(Time)"

Being able to subscribe to quantities and use them inside of scripts is one of the most impor-tant features of ScriptControl. When combined with the standard Tcl commands and theScriptControl command extensions, the complexity of the script is only limited by the imag-ination of its creator.

11.3.4 Example 4 – Postprocessing and Report Generation

ScriptControl makes it easy to automate the generation of formatted reports. This sectiondiscusses the basics of creating HTML reports from test data.

During a simulation the ScriptControl script can be designed to monitor events and save thedata when certain condition arise, and to generate . For example, saving data whenever thevelocity is greater than a certain value.

The following script does two things. First it selects which quantities to save in the resultsfile. This is done with the function OutQuantsAdd. the second thing it does is save theresults to a file each time the velocity is greater than 30 m/s.

QuantSubscribe { Car.v }

# delete all quantities, add new quantitiesOutQuantsDelAllOutQuantsAdd {Car.v DM.Clutch DM.Gas Time}

# load the test runLoadTestRun "Examples/Road/Hockenheim"

# set storage mode to save allSaveMode hist_10s

# start of the simulationStartSim

# wait until the simulation startsWaitForStatus running

# Check the speed every second until the simulation is no longer# running. If the speed is greater than 30 m/s save the data.# Otherwise, stop saving the data until the speed reaches 30 m/s.

set flag "SaveNotStarted"while {[SimStatus]==0 && $flag=="SaveNotStarted"} {

if {$Qu(Car.v) > 20} {if {$Qu(Time) > 30} {

set flag "SaveStarted"}

CarMaker Programmer’s Guide Version 2.1.6

Page 242: IPG_CarMaker Programmers Guide

242ScriptControl

ScriptControl By Example

SaveStartLog "Data being saved..."sleep 1000

} else {Log "Speed is: $Qu(Car.v) m/s"

}sleep 1000

}

StopSim

# restore the default quantitiesOutQuantsRestoreDefs

After this script executes there will be a number of result files saved in the SimOutput direc-tory. This data can now be imported into ScriptControl with the commands:

set file "SimOutput/Offline/20040121/Examples_Hockenheim_132054.erg"ImportResFile $file {DM.Gas Car.vFL} VarLog [lindex $Var(Car.vFL) 5]

The erg file shown here is just an example and the path needs to be modified to point to theappropriate file.

However, now that we have the data we can perform operations on it, such as comparisonagainst expected results, pass/fail, etc.

After doing some analysis it makes sense to plot results that can be used in a report. thecommand Matlab2DPlot can be used (if Matlab is installed) to create a plot. The followingexample shows the commands used to create a plot:

set x “1 2 3 4 5 4 5 7 10"set y "1 2 3 4 5 6 7 8 9"set FName "c:/Test3.png"set args "’--rs’"Matlab2DPlot $x $y $FName "$args"

Here we have plotted two arbitary lists of numbers, but ideally this would be meaningful datagenerated after postprocessing the results of a simulation.

Now that we have the results and some nice plots, we can generate an html report that can,e.g. be posted on the Internet of local Intranet. To do this the html library functions arecalled. The Tcl/Tk version supplied with CarMaker, ActiveTcl from Active State, contains abuilt in library of HTML generation commands. To access the library you must fist load thehtml library. With Windows the comands are:

load "c:/Tcl/lib/tkhtml2.0/libTkHtml.dll"package require html

And for Linux:

source "/opt/tcl/lib/tcllib1.7/html/html.tcl"package require Tkhtml

Or something similar.

Now a report can be generated using the imported data, the generated plots, and the htmlfunctions. For details on the html functions refer to the ActiveTcl html library documentationat

http://ASPN.ActiveState.com/ASPN/docs/ActiveTcl/tcllib/html/html.html

CarMaker Programmer’s Guide Version 2.1.6

Page 243: IPG_CarMaker Programmers Guide

243ScriptControl

ScriptControl By Example

11.3.5 More Examples

Included in the distribution is an examples directory Data/Script/Examples that containsbasic scripts created to demonstrate some of the functionality of ScriptControl. The exam-ples include:

• Boolean.tclExample of some of the simple boolean expressions that can be formed in Tcl

• Clock.tclExample showing how to use the clock timer commands

• DVA.tclExample of the Direct Variable Access commands

• FST.tclExample of FailSafeTester commands (CarMaker/HIL only)

• ImportResFile.tclExample of the ImportResFile command

• IndicatorLights.tclShows how conditions can be used to show pass/fail status (CarMaker/HIL only)

• InfoFileModify.tclExample showing how to make changes directly to the InfoFile parameter database ofCarMaker

• Math.tclSimple Tcl math function example

• MiniManJump.tclShows how to jump to a specific minimaneuver

• OutputQuants.tclExample showing how to make changes to the output quantities list and how to savethe results

• Print.tclPrinting example

• QuantSubscribe.tclExample showing how to subscribe to a quantity

• SessionLog.tclExample that prints to the CarMaker session log

• SimStatus.tclShows a command that will return the simulation status

• RunScripts.tclExample showing how multiple scripts can be run from a single script

• StartStop.tclExample showing how to start and stop a testrun

• WaitForCondition.tclExample showing the WaitForCondition command and how it can be used to pausescript execution until the specified condition is met.

11.3.6 Tcl/Tk Documentation Links

Documentation available locally on Linux hosts

Under Linux, a special Tcl/Tk installation is provided by IPG. The complete documentationcan be viewed with the web browser of your choice under the following URL:

file:/opt/tcl/html/contents.htm

CarMaker Programmer’s Guide Version 2.1.6

Page 244: IPG_CarMaker Programmers Guide

244ScriptControl

ScriptControl By Example

Documentation available locally on Windows hosts

On Windows systems, the ActiveStateTcl package recommended for the CarMaker versionto be used must be installed (available at IPG or on the Internet). The complete documen-tation can be found following the corresponding entry in the Start menu, in Programs /ActiveStateTcl...

Documentation available on the internet

The Tcl Developer Xchange is the home of Tcl/Tk development:

http://www.tcl.tk

The Tcler’s Wiki is a collaborative web site with many useful pages of tips and tricks:

http://wiki.tcl.tk

Tcl/Tk literature

Tcl/Tk books can be purchased at all major bookstores. Lists of available books are acces-sible on the web sites mentioned before.

CarMaker Programmer’s Guide Version 2.1.6

Page 245: IPG_CarMaker Programmers Guide

245ScriptControl

ScriptControl Command Reference

11.4 ScriptControl Command Reference

11.4.1 Running a Simulation

LoadTestRun

Syntax

LoadTestRun file

Description

Loads the predefined CarMaker testrun stored in file. Specification of a relative filenamecauses the testrun to be loaded relative to the Data/TestRun directory of your CarMakerproject directory.

Example

LoadTestRun “Examples/Braking”

StartSim

Syntax

StartSim

Description

Starts the simulation of the currently loaded testrun.

This function corresponds to the CarMaker GUI’s big red Start button.

StopSim

Syntax

StopSim

Description

Stops the current simulation.

This function corresponds to the CarMaker GUI’s big green Stop button.

SimStatus

Syntax

SimStatus

CarMaker Programmer’s Guide Version 2.1.6

Page 246: IPG_CarMaker Programmers Guide

246ScriptControl

ScriptControl Command Reference

Description

Returns the current simulation status as an integer value.

The values are described in header file SimCore.h .

Example

set status [SimStatus]

WaitForStatus

Syntax

WaitForStatus status ?timeout_ms?

Description

Causes the script to wait until the specified simulation status is reached. Legal values forstatus are:

idle – The simulation has stopped, no simulation is running

running – The simulation is running

When the requested simulation status has been reached, the function returns 0.

An optional timeout value specified in milliseconds can be supplied. If the simulation doesnot enter the requested simulation status within timeout_ms milliseconds, the functionsstops waiting and returns -1.

Examples

WaitForStatus running 5000WaitForStatus idle

WaitForTime

Syntax

WaitForTime seconds

Description

Causes the script to wait until the simulation time reaches the specified time.

Example

WaitForTime 20

WaitForCondition

Syntax

WaitForCondition condition ?timeout_ms?

CarMaker Programmer’s Guide Version 2.1.6

Page 247: IPG_CarMaker Programmers Guide

247ScriptControl

ScriptControl Command Reference

Description

Causes the script to wait until the specified condition is satisfied. condition will be evaluatedin the context of the caller using Tcl’s expr command.

When the requested condition has been met, the function returns 0.

An optional timeout value specified in milliseconds can be supplied. If the simulation doesnot reach the condition within timeout_ms milliseconds, the functions stops waiting andreturns -1.

Example

WaitforCondition {Car.v > 50}

JmpToMiniMan – Jump to Mini-Maneuver

Syntax

JmpToMiniMan manid

Description

Causes the CarMaker simulation program to jump to the specified mini-maneuver. manidmust be a valid a mini-maneuver identifier of the testrun currently running.

Example

JmpToMiniMan 3

SetMiniManCmd – Set Mini-Maneuver Command

Syntax

SetMiniManCmd manid cmdstr ?activatenow?

Description

Causes the commands of the mini-maneuver manid to be replaced by the specified com-mand string. manid must be a valid a mini-maneuver identifier of the testrun currently run-ning. cmdstr is a string of mini-maneuver commands, separated by a newline character (\n),to set for this mini-maneuver.

A boolean value (0 or 1) for the parameter activatenow indicates whether CarMaker shouldjump to this mini-maneuver immediately after setting its command string. Specifying thisparameter is optional, default is 1 (i.e. activate the mini-maneuver).

Examples

SetMiniManCmd 2 {LogWrnS “Some warning!”}

set cmds {}lappend cmds {LogWrnS “Some warning!”}lappend cmds {LogWrnS “Some other warning!”}SetMiniManCmd 2 [join $cmds \n]

CarMaker Programmer’s Guide Version 2.1.6

Page 248: IPG_CarMaker Programmers Guide

248ScriptControl

ScriptControl Command Reference

11.4.2 Subscribing to Quantities

QuantSubscribe

Syntax

QuantSubscribe quantity_listQuantSubscribe -show

Description

Subscribes all quantities in the list quantity_list, before returning, it will wait for the firstquantity vector to arrive.

Subscribing to a quantity allows the value of the quantity to be read by the script. Any of thequantities that are defined in the CarMaker data dictionary can be accessed, allowing thevalue to be used in the user’s test automation script.

To have access to the quantities, first you have to subscribe the quantities you are interest-ed in. The subscribed quantities will be transfered from the simulation program to theScriptControl interpreter at regular intervals in the background (update rate approximately100 Hz). The values are placed in a shadow variable, the global array Qu.

Subscribing variable generates some amount of background activity, simulation programruns on a different host (as in CarMaker/HIL), it also generates network traffic. Thereforeonly a small subset of the available quantites is subscribed. Just to give an idea of the need-ed bandwidth: subscribing 20 float quantities results in a traffic of 10 KByte/sec, this is about1% of the bandwidth of fast ethernet (100 MBit).

Some special cases:

• Calling QuantSubscribe with an empty list {} will stop the subscription.

• QuantSubscribe -show returns the list of currently subscribed quantities.Note: You may find some additional quantities in this list, they are needed internaly.

Changes compared to CarMaker 2.0

• Please note that in ScriptControl of CarMaker 2.0 the values were also available as aformatted string in the Quantities array. For performance reasons this is no longerdone. If you need a formattet string, for example for right justified output or to have afixed number of digits right of the decimal point, please use the Log command with aformat string as first parameter (shown in the example below).Alternatively you can use the Tcl format command (see Tcl documentation).

• Previously a different technique was used to subscribe quantities. First a global arrayQuantities had to be filled with the requested quantity names and their default value.After that the command QuantSubscribe was called without parameters.

# OLD STYLE !array set Quantities {

Car.v 0Time 0

}QuantS ubscribe

The old style still supported, but should be avoided.

Example

# subscribe two quantities: Time, Car.v

CarMaker Programmer’s Guide Version 2.1.6

Page 249: IPG_CarMaker Programmers Guide

249ScriptControl

ScriptControl Command Reference

QuantSubscribe {Time Car.v}

# values output with full precisionLog “speed=$Qu(Car.v) at time=$Qu(Time)”

# output with limited precision (here 1 digit right of the decimal point)Log “speed=%.1f at time=%.1f” $Qu(Car.v) $Qu(Time)

# cancel subscriptionQuantSubscribe {}

CarMaker Programmer’s Guide Version 2.1.6

Page 250: IPG_CarMaker Programmers Guide

250ScriptControl

ScriptControl Command Reference

11.4.3 Clock Timers

Clock timers (or simply timers) are used to measure the amount of time that a condition istrue. For example, the time that the vehicle speed is greater than 50 kph can be measuredby using a timer.

The clock commands work using the simulation time Global.Time and are only relevantwhen a simulation is running. When no simulation is running the clock functions will not givepredictable results.

ClockCreate

Syntax

ClockCreate clockname condition

Description

Creates a clock timer by giving it a user specified clockname and associating a conditionwith it. Once the clock timer is started with ClockStart, condition will be evaluated regularlyat global scope using Tcl’s expr command and is expected to yield a boolean value.

Example

ClockCreate MyClock {$Qu(DM.Steer.Ang) > 0}

ClockDelete

Syntax

ClockDelete clockname

Description

Deletes a clock timer previously created with ClockCreate and frees the resources allocatedfor it. Whenever a clock timer will no longer be used it should be deleted wih this command.

Example

ClockDelete MyClock

ClockStart

Syntax

ClockStart clockname

Description

Starts a clock timer previously created with ClockCreate.

Example

ClockStart MyClock

CarMaker Programmer’s Guide Version 2.1.6

Page 251: IPG_CarMaker Programmers Guide

251ScriptControl

ScriptControl Command Reference

ClockStop

Syntax

ClockStop clockname

Description

Stops a clock timer previously created with ClockCreate and started with ClockStart.

Example

ClockStop MyClock

ClockGetTime

Syntax

ClockGetTime clockname

Description

Returns the elapsed clock time of a clock timer. The time can be read any time after Clock-Start is called.

Example

set TotalTime [ClockGetTime MyClock]

ClockReset

Syntax

ClockReset clockname

Description

Resets the clock time to 0 without stopping it.

Example

ClockReset MyClock

CarMaker Programmer’s Guide Version 2.1.6

Page 252: IPG_CarMaker Programmers Guide

252ScriptControl

ScriptControl Command Reference

11.4.4 Logging

In ScriptControl, two different concepts of logging exist.

The session log is a log file maintained by the CarMaker simulation program. This is theplace where messages pertaining to each simulation are logged. The CarMaker can displaythe session log in a separate window.

In your ScriptControl scripts, occasionally you may also want to issue messages describingthe progress of the automation script or inform about some important condition. Often exe-cution of your script spans multiple simulations and it is sufficient for a log message toappear only in the ScriptControl console window. This is why a second logging mechanismindependant of CarMaker’s session log was introduced.

The ScriptControl log is a log that uses the ScriptControl console window for output. Option-ally a separate log file can opened and messages will be put into that file, too.

It is recommended that ScriptControl scripts stick to the ScriptControl log for logging andkeep messages to the CarMaker log to a minimum.

OpenSLog – Open the ScriptControl log file

Syntax

OpenSLog path ?directory?

Please note: Specification of the directory parameter is unnecessary and supported forcompatibility reasons only. Its use is strongly deprecated.

Description

Opens the file with the specified path as the ScriptControl log file. If the file already exists,log messages will be appended to the end of the file. Using the optional directory argumentis equivalent to invoking the function as OpenSLog directory/path, i.e. it will simply beprepended to the path argument.

If path consists only of a single filename, the file will be opened in the SimOutput/ScriptLog subdirectory. In order to open a log file in the current working directory, specifyit as ./filename .

Examples

OpenSLog MyScript.logOpenSLog ./LogFileInCurrentDir.logOpenSLog SubDir/LogFileInOtherDir.log

CloseSLog – Close the ScriptControl log file

Syntax

CloseSLog

Description

Closes the ScriptControl log file that was opened in the previous call to OpenSLog.

CarMaker Programmer’s Guide Version 2.1.6

Page 253: IPG_CarMaker Programmers Guide

253ScriptControl

ScriptControl Command Reference

Log – Write to the ScriptControl log

Syntax

Log ?where? messagestrLog ?where? formatstr arg ?arg ...?

Description

Write a ScriptControl log message. The command supports two ways of specifying themessage to be logged.

The simple form consists of a single message string messagestr, that will be directly writtento the log. The more complex form consists of a format string controlling how the remainingarg argument(s) should be formatted. Internally Tcl’s format command is used for this pur-pose; details about the content of formatstr can be looked up in the corresponding Tcl man-ual page. For a first impression see the examples below.

Depending on the where parameter, the log message will be output on either theScriptControl console window, the ScriptControl log file, or both. Possible values for whereare:

screen – The message is output only to the ScriptControl console window.

file – The message is output only to the ScriptControl log file. The log file must beopened with OpenSLog before, otherwise an error is issued.

screen+ or file+ – The message is output to both the ScriptControl console windowand the ScriptControl log file. The log file must be opened with OpenSLog before, oth-erwise an error is issued.

If the where parameter is not specified, the beviour is as follows: The message is output tothe ScriptControl console window. If and only if a ScriptControl log file was opened withOpenSLog before, the message is also output to the log file.

For most uses, there’s no need to bother with the where parameter. Invoking the functionwith the message you want to log will just do the right thing.

Examples

Log “Message sent to the ScriptControl window and possibly to the ScriptControl log file.”Log screen “Message sent only to the ScriptControl window”Log file “Message sent only to the ScriptControl log file”Log screen+ “Message sent to both the ScriptControl window and log file.”Log file+ “Message sent to both the ScriptControl window and log file.”

Log “v = %6.2f m/s” $Qu(Car.v)Log “Gas = %2f %%, Brake = %2f %%“ [expr $Qu(DM.Gas) * 100.0] [expr $Qu(DM.Brake) * 100.0]

LogExec – Log Tcl command and execute it

Syntax

LogExec ?where? cmd

Description

Logs and executes a Tcl command script. First cmd is written to the ScriptControl log. After-wards cmd is executed in the context of the caller using Tcl’s eval command.

CarMaker Programmer’s Guide Version 2.1.6

Page 254: IPG_CarMaker Programmers Guide

254ScriptControl

ScriptControl Command Reference

For a description and recommended use of the where parameter see the Log command.

Examples

LogExec { set remark “The LogExec command is considered ridiculous” }LogExec screen { set x [expr sin($alpha)]}

SessionLogMsgSessionLogWarnSessionLogError – Issue a message to the CarMaker log

Syntax

SessionLogMsg messagestrSessionLogMsg formatstr arg ?arg ...?

SessionLogWarn messagestrSessionLogWarn formatstr arg ?arg ...?

SessionLogError messagestrSessionLogError formatstr arg ?arg ...?

Description

Write a message to the CarMaker session log, i.e. the log that is maintained by theCarMaker simulation program. Depending on the function that is invoked, the message willbe logged as either a normal messsage, a warning or an error. The commands support twoways of specifying the message to be logged.

The simple form consists of a single message string messagestr, that will be directly writtento the log. The more complex form consists of a format string controlling how the remainingarg argument(s) should be formatted. Internally Tcl’s format command is used for this pur-pose; details about the content of formatstr can be looked up in the corresponding Tcl man-ual page. For a first impression see the examples below.

It is recommended to keep session log messages to a minimum. Verbose logging can havenegative effects on readability of the log file and increases network and CPU usage.

Examples

SessionLogError “Error: There was an error detected! Take the appropriate action.”SessionLogWarn “Vehicle is too fast: v = %6.2f m/s” $Qu(Car.v)

CarMaker Programmer’s Guide Version 2.1.6

Page 255: IPG_CarMaker Programmers Guide

255ScriptControl

ScriptControl Command Reference

11.4.5 Accessing CarMaker Parameters in Infofiles

An infofile is an ASCII file that contains key-value pairs which represent simulation inputparameters. The key-value pairs are used to parameterize the simulation models and allowthe user the flexibility to customize the VVE so it behaves as desired (usually making itbehave like a real world vehicle, driver, etc. would). ScriptControl allows direct access to theInfoFile database information and can therefore be used to read or make parameter chang-es “on the fly”.

A minimal understanding about how information is stored in infofiles is required in order tounderstand the commands described below. Two kinds of keys can be present in an infofile:

A string key is, roughly spoken, “a key with an equal sign”, e.g.

CarLoad.0.mass = 50PowerTrain.Clutch.Kind = Manual

An text key is, roughly spoken, “a key with a colon” and spans multiple lines, e.g.

SuspR.Spring:-0.01000 -250.000.00000 0.001.00000 25000.00

Keys should always be accessed using commands that match their key kind, e.g. for textkeys always use IFileReadTxt and IFileModifyTxt.

And that’s it. For a full description of infofiles and the complete set of ifile commands seethe corresponding separate chapter in this manual.

IFileReadIFileReadTxT – Get a parameter’s value

Syntax

IFileRead filetoken keyIFileReadTxt filetoken key

Description

IFileRead returns the value of the specified string key.

IFileReadTxt returns the value of the specified text key as a list of strings.

The filetoken parameter is a shortcut for the infofile in question, legal values are:

SimParameters – The Data/Config/SimParameters file

ECUParameters – The Data/Config/ECUParameters file

TestRun – The testrun file currently loaded

Vehicle – The vehicle parameter file as specified in the current testrun

Trailer – The trailer parameter file as specified in the current testrun

Brake – The brake parameter file as specified in the current vehicle parameters

Tire0 , Tire1 , Tire2 , Tire3 – The tire parameter file as specified in the current testrun

Examples

set Load_0 [IFileRead TestRun CarLoad.0.mass]set AeroData [IFileReadText Vehicle SuspR.Spring]

CarMaker Programmer’s Guide Version 2.1.6

Page 256: IPG_CarMaker Programmers Guide

256ScriptControl

ScriptControl Command Reference

IFileModifyIFileModifyTxT – Set a parameter’s value

Syntax

IFileModify filetoken key valueIFileModifyTxt filetoken key value

Description

IFileModify sets the value of the specified string key.

IFileModifyTxt sets the value of the specified text key. In this case value should be a validTcl list; each list element will be stored in a separate line in the infofile.

If the key does not exist then one will be created, otherwise its value will be overwritten.

The filetoken parameter is a shortcut for the infofile in question, for legal values see thedescription of IFileRead and IFileReadTxt in this chapter.

Do not forget to invoke IFileFlush before starting the next testrun with StartSim.

Examples

IFileModify TestRun CarLoad.0.mass 50IFileModifyTxt Vehicle SuspR.Spring {

{ -0.001 250.0 }{ 0.0 0.0 }{ 1.0 25000.0 }

}

IFileFlush

Syntax

IFileFlush

Description

Writes the changes made to infofiles by the IFileModify commands to the actual files. Thisoperation is required since out of performance and resource considerations IFileModifyoperations are cached in memory.

Always call this command after having made changes to infofiles and before starting thenext testrun using StartSim.

CarMaker Programmer’s Guide Version 2.1.6

Page 257: IPG_CarMaker Programmers Guide

257ScriptControl

ScriptControl Command Reference

11.4.6 Managing Simulation Results

The quantities which CarMaker write to a simulation results file are called output quantities.They are stored in the Data/Config/OutputQuantities file that is read by the CarMakersimulation program at the beginning of a testrun.

Result storage itself can be done in number of ways. Save all results, save only the last 30seconds, etc. Saving can be done during a simulation or after the simulation stopped.

Finally results files can be read into memory for postprocessing purposes.

OutQuantsAdd – Add to output quantities

Syntax

OutQuantsAdd quantity_listOutQuantsAdd quantity ?quantity...?

Description

Adds quantities to the list of output quantities that will be buffered by CarMaker and savedto the result file when requested. Quantities may be specified either as a list or individually,but not both ways at the same time.

Examples

set quants {Time Car.v Car.ax Car.ay}OutQuantsAdd $quants

OutQuantsAdd DM.Gas DM.Cluch

OutQuantsDel

Syntax

OutQuantsDel quantity_listOutQuantsDel quantity ?quantity...?

Description

Deletes the specified quantities from the OutputQuantities file. Quantities may be spec-ified either as a list or individually, but not both ways at the same time.

Examples

set quants {Time Car.v Car.ax Car.ay}OutQuantsDel $quants

OutQuantsDel DM.Gas DM.Cluch

OutQuantsDelAll

Syntax

OutQuantsDelAll

CarMaker Programmer’s Guide Version 2.1.6

Page 258: IPG_CarMaker Programmers Guide

258ScriptControl

ScriptControl Command Reference

Description

Deletes all quantities from the OutputQuantities file.

OutQuantsRestoreDefs

Syntax

OutQuantsRestoreDefs

Description

OutQuantsRes to reDefs res to res the de fau l t quan t i t i es de f ined in theOutputQuantities.default file. The default file is created the first time any change ismade to OutputQuantities using one of these functions, and can be modified manuallyat any point after it was created.

SaveMode

Syntax

SaveMode mode

Description

Specifies the saving mode that is entered when a save is started with the SaveStart func-tion. Legal values for mode are:

don’t_save – do not save any of the results

save_all – save all results

hist_10s – save the last 10 seconds

hist_30s – save the last 30 seconds

hist_60s – save the last 60 seconds

hist_max – save all results recorded in the results buffer

This function corresponds to the CarMaker GUI’s Mode menubutton in the Storage ofResults part of the GUI’s main window.

Example

SaveMode hist_10s

SaveStart

Syntax

SaveStart

Description

Starts saving the simulation results to a results file.

CarMaker Programmer’s Guide Version 2.1.6

Page 259: IPG_CarMaker Programmers Guide

259ScriptControl

ScriptControl Command Reference

This function corresponds to the CarMaker GUI’s Save button in the Storage of Results partof the GUI’s main window.

SaveStop

Syntax

SaveAbort

Description

Stops the saving of the simulation results previously initiated with the SaveStart command.No more data is written to the results file but the file is kept.

This function corresponds to the CarMaker GUI’s Stop button in the Storage of Results partof the GUI’s main window.

SaveAbort

Syntax

SaveAbort

Description

Aborts the saving of the simulation results previously initiated with the SaveStart command.No more data is written to the results file and the file is deleted.

This function corresponds to the CarMaker GUI’s Abort button in the Storage of Results partof the GUI’s main window.

ImportResFile – Read a CarMaker results file

Syntax

ImportResFile path channels varname

Description

Reads the values for the specified channels. CarMaker’s resutil utility must be installed cor-rectly for this command to work. Upon success, an array is created/modified with the namespecified in the varname parameter. The array elements will be the channel names speci-fied in the Tcl-list channels, and the element values will be the list of result values for therespective channel.

For example, if varname is “Results” and the channels read are “Car.v” and “DM.Gas”, thearray created will be Results and it will contain two elements called Results(Car.v) andResults(DM.Gas). The value of each element will be the channel’s list of values that is readfrom the result file.

The command returns 0 on success and -1 in case of an error.

Example

set fname SimOutput/Offline/20040121/Examples_Hockenheim_132054.erg

CarMaker Programmer’s Guide Version 2.1.6

Page 260: IPG_CarMaker Programmers Guide

260ScriptControl

ScriptControl Command Reference

ImportResFile $fname [list DM.Gas Car.vFL] Results

Log “Number of values in Car.vFL: [llength $Results(Car.vFL)]“Log “Example value from Car.vFL: [lindex $Results(Car.vFL) 5]”

GetLastResultFName

Syntax

GetLastResultFName

Description

Returns the name of the last results file written by CarMaker during your current CarMakersession.

Note: At least one simulation producing a results file must have been run. Otherwise awarning is issued and the function returns an empty string.

Example

set fname [GetLastResultFName]ImportResFile $fname {DM.Gas Car.vFL} Results

CarMaker Programmer’s Guide Version 2.1.6

Page 261: IPG_CarMaker Programmers Guide

261ScriptControl

ScriptControl Command Reference

11.4.7 Direct Variable Access (DVA)

Direct Variable Access (DVA) allows quantities to be modified during a simulation. The com-mands listed below are used for DVA with ScriptControl.

DVAWrite

Syntax

DVAWrite name ?val0? ?count? ?mode? ?when? ?val1? ?val2?

Description

Change a quantity’s value specified by name and according to mode and parameters val0,val1 and val2 given, for a duration of count cycles.

The mode parameter determines how the quantity’s value should be manipulated. Possiblevalues for mode are:

Abs or 0 – Absolute value val0

Off or 1 – Offset val0

Fac or 2 – Factor val0

FacOff or 3 – Factor val0,offset val1

AbsRamp or 4 – Absolute value val0, ramp during val1 cycles

OffRamp or 5 – Offset val0, ramp during val1 cycles

FacRamp or 6 – Factor val0, ramp during val1 cycles

FacOffRamp or 7 – Factor val0, offset val1, ramp during val2 cycles

when determines where in the simulation cycle the quantity should be updated. Possiblevalues for where are:

IO_In or 0

IO_Out or 1

DM or 2

Except for name all parameters are optional. Defaults are val0 = 0.0, count = 1, mode = Abs,when = IO_In, val1 = 0.0, val2 = 0.0.

Example

DVAWrite DM.Steer.Ang 5 100

DVAReleaseQuants

Syntax

DVAReleaseQuants

Description

Releases the quantities from DVA control. The quantities are not reset, and unless they aremodified by some internal function, they will keep the value they were given.

CarMaker Programmer’s Guide Version 2.1.6

Page 262: IPG_CarMaker Programmers Guide

262ScriptControl

ScriptControl Command Reference

11.4.8 Executing Matlab Commands

MatlabEval – Execute Matlab Command

Note: This command is only available in CarMaker for Simulink.

Syntax

MatlabEval ?options? cmd ?arg...?

Description

Execute a Matlab command cmd, possibly with one ore more arguments arg, in the runningMatlab interpreter currently connected to the CarMaker GUI.

cmd and all arg(s) will be concatenated using Tcl’s join command before being sent to theMatlab interpreter, without further treatment of interpretation. As in normal Matlab com-mand execution a semicolon (";") at the end of a command must be used if output of theresult in the Matlab console is to be suppressed.

Possible options are:

-async – Return immediately, don’t wait for completion of the command.

-timeout ms – Wait for completion of the Matlab command, but at most ms millisec-onds. Negative values mean "wait forever", a zero value means "don’t wait", i.e. -async.

Default behaviour, if no option is specified, is to wait until completion of cmd (with no time-out, i.e. possibly forever).

On success, the function returns the content of Matlab’s ans variable as a string or the errormessage issued by Matlab if the command failed. On timeout or communication failure, anempty string is returned.

Limitations

The maximum allowed length of cmd is currently limited by the maximum length of an APOapplication defined message, i.e. about 700 characters. If cmd is too long it will be truncatedin length.

Examples

MatlabEval “alpha = 42.0;”MatlabEval “SomeFunction(3.1, 2.7);”

MatlabEvalCancel – Cancel Matlab Command Execution

Note: This command is only available in CarMaker for Simulink.

Syntax

MatlabEvalCancel ?result?

Description

Force the MatlabEval function currently running (waiting for the Matlab interpreter to finishthe execution of a Matlab command) to stop waiting and return immediately. If no MatlabEv-al is currently running just do nothing.

CarMaker Programmer’s Guide Version 2.1.6

Page 263: IPG_CarMaker Programmers Guide

263ScriptControl

ScriptControl Command Reference

Please note that there is no way to interrupt Matlab’s execution of the command itself, i.e.the Matlab interpreter will continue to work on the current command until it completes.

An optional result argument may be specified as the value to be returned by MatlabEval. Ifnot specified, MatlabEval will return an empty string.

Example

MatlabEvalCancelMatlabEvalCancel “CANCELED”

CarMaker Programmer’s Guide Version 2.1.6

Page 264: IPG_CarMaker Programmers Guide

264ScriptControl

ScriptControl Command Reference

11.4.9 Power Control (KL15)

PowerOn

Syntax

PowerOn

Description

Sends a KL15-power-on message to the CarMaker simulation program.

PowerOff

Syntax

PowerOff

Description

Sends a KL15-power-off message to the CarMaker simulation program.

TogglePower

Syntax

TogglePower

Description

Sends a KL15-toggle-power message to the CarMaker simulation program.

CarMaker Programmer’s Guide Version 2.1.6

Page 265: IPG_CarMaker Programmers Guide

265ScriptControl

ScriptControl Command Reference

11.4.10 FailSafeTester Commands

FST_Init

Syntax

FST_Init

Description

Initializes the FailSafeTester. Must be called before any other FST commands are used.

FST_ChAdd – Add channel

Syntax

FST_ChAdd group channel

Description

Adds channel to group.

The term “group” is synonymous with the term “interconnection lines” and can be visualizedas a single wire running perpendicular to a channel/signal. When you add the channel/sig-nal to the group/interconnection line the wires are connected. Any number of signals/chan-nels can be added to the same group, effectively shorting the signals in a controlled way.

FST_ChCut – Cut channel

Syntax

FST_ChCut channel

Description

Cuts a channel. The channel’s input pin is then disconnected from the output pin.

FST_ChCon – Connect channel

Syntax

FST_ChCon channel

Description

Reconnects a cut channel.

CarMaker Programmer’s Guide Version 2.1.6

Page 266: IPG_CarMaker Programmers Guide

266ScriptControl

ScriptControl Command Reference

FST_ChRem – Remove channel

Syntax

FST_ChRem group channel

Description

Removes the specified channel from a group of signals.

The term “group” is synonymous with the term “interconnection lines” and can be visualizedas a single wire running perpendicular to a channel/signal. When you add the channel/sig-nal to the group/interconnection line the wires are connected. Any number of signals/chan-nels can be added to the same group, effectively shorting the signals in a controlled way.

FST_GrpRem – Remove group

Syntax

FST_GrpRem group

Description

Removes a group of channels.

The term “group” is synonymous with the term “interconnection lines” and can be visualizedas a single wire running perpendicular to a channel/signal. When you add the channel/sig-nal to the group/interconnection line the wires are connected. Any number of signals/chan-nels can be added to the same group, effectively shorting the signals in a controlled way.

FST_Reset

Syntax

FST_Reset

Description

Resets all plugged in cards to their initial state.

FST_ContactCare

Syntax

FST_ContactCare

Description

Initiates a contact care operation on the FailSafeTester.

CarMaker Programmer’s Guide Version 2.1.6

Page 267: IPG_CarMaker Programmers Guide

267ScriptControl

ScriptControl Command Reference

FST_SCAdd – Add signal connector

Syntax

FST_SCAdd sc group

Description

Adds signal connector sc to group.

FST_SCRem – Remove signal connector

Syntax

FST_SCRem sc group

Description

Removes signal connector sc from group.

FST_SetRstr – Set resistor value

Syntax

FST_SetRstr rstr value

Description

Sets resistor rstr to value on a programmable resistor card.

CarMaker Programmer’s Guide Version 2.1.6

Page 268: IPG_CarMaker Programmers Guide

268ScriptControl

ScriptControl Command Reference

11.4.11 Miscellaneous Commands

RunScript – Run a ScriptControl script

Syntax

RunScript path

Description

Runs the ScriptControl script specified by path.

Relative path names are interpreted in a special way, so as to make running scripts fromwithin other scripts simpler. Specifying a relative path to a script will cause the script to besearched relative to the directory where the calling script resides. If no script with this namecan be found at this place, RunScript tries makes a second attempt searching the script rel-ative to the current working directory.

Simply stated, this treatment of relative paths makes it easy for you to organize your testshierarchically, as shown in the following figure:

Note how the subordinate scripts DoBasicTests.tcl , DoAdvancedTests.tcl , etc. canbe written without depending on the location of the calling script. If Tcl’s source commandwould have been used instead, more scripts were needed and, because one is forced tospecify the complete path to the individual scripts, they would depend on each other. As aconsequence few changes in script organization would result in changing lots of paths inlots of files.

It should be noted, however, when invoking RunScript interactively from the ScriptControlconsole window, relative pathnames are interpreted relative to the Data/Script directory.

RunScript is intended as a handy alternative to Tcl’s source command.

Examples

RunScript /space/TestCollection/TypeB/SpecificTypeBTest.tclRunScript Stability/TypeA/RunTypeATests.tclRunScript SpecificTypeATest_1.tcl

Data‘-- Script |-- QuickCheck.tcl |-- CompleteCheck.tcl | |-- Basic | |-- DoBasicTests.tcl | |-- TestA1.tcl | ‘-- TestA2.tcl | |-- Advanced | |-- DoAdvancedTests.tcl | |-- TestB1.tcl | ‘-- TestB2.tcl | ‘-- Complex |-- DoComplexTests.tcl |-- TestC1.tcl ‘-- TestC2.tcl

...RunScript Basic/DoBasicTests.tclRunScript Advanced/DoAdvancedTests.tcl...

...RunScript TestA1.tclRunScript TestA2.tcl...

...RunScript Basic/DoBasicTests.tclRunScript Advanced/DoAdvancedTests.tclRunScript Complex/DoComplexTests.tcl

...

CarMaker Programmer’s Guide Version 2.1.6

Page 269: IPG_CarMaker Programmers Guide

269ScriptControl

ScriptControl Command Reference

CheckBreak – Check for user interrupt

Syntax

CheckBreak

Description

Checks whether the user pressed the ScriptControl Stop button in order to interrupt scriptexecution.

Normally a press on the Stop button can only be detected while the Tcl interpreter is ableto process input/output requests or when a ScriptControl command is executed. However,when Tcl is busy with execution of e.g a loop to do a longer running, complicated postpro-cessing calculation of your test script, i.e. a loop in which no ScriptControl commands areused, the press of the Stop button will go unnoticed. You will not be able to interrupt yourscript, the GUI will apear to be blocked.

A CheckBreak command executed regularly inside the loop solves this problem.

AbortScript – Stop script execution

Syntax

AbortScript

Description

Aborts script execution. No further commands of the script will be executed.

GetTime – Obtain the current date and/or time

Syntax

GetTime ?format?

Description

Returns the current date and/or time. GetTime serves as a shortcut to Tcl’s more elaborate[clock] function. The format option determines value and format to be returned.Valid format options are:

-d current date as “yyyy-mm-dd”

-D current date in country specific format (“mm/dd/yyyy” for example)

-t current time as “hh:mm:ss”(24-hour format)

-T current time in country specific format(12-hour format with AM/PM appended or 24-hour format)

-a current date and time like “yyyy-mm-dd hh:mm:ss”

-A current date and time like “Thu Jun 23 12:15:01 PM CEST 2005”.

If no format option is specified, or the format specified is not valid, then -a is assumed.

CarMaker Programmer’s Guide Version 2.1.6

Page 270: IPG_CarMaker Programmers Guide

270ScriptControl

ScriptControl Command Reference

Example

set now [GetTime -T]

Sleep – Delay execution for a certain amount of time

Syntax

Sleep ms

Description

Causes the script to sleep/wait for ms milliseconds.

This command should be used in favour of Tcl’s built-in [after ms] since it does not keep theTcl interpreter from doing input/output during the waiting time.

Example

Sleep 2000

CarMaker Programmer’s Guide Version 2.1.6

Page 271: IPG_CarMaker Programmers Guide

271ScriptControl

ScriptControl Command Reference

11.4.12 Deprecated Commands

During the major overhaul of ScriptControl for CarMaker 2.1 and in an effort to consolidateseveral specially customized versions in use, a number of ScriptControl commands havebeen found to be either

• inconsistent in naming,

• superseded by other, more flexible functions,

• merely duplicating functionality of already existing commands,

• or simply of dubious value.

The reasons for this unfortunate situation lie in the the history of ScriptControl developmentand the way ScriptControl was integrated in previous CarMaker versions.

The functions in question are herewith declared deprecated. The current CarMaker versionstill contains support for these functions, but expect them to disappear in the next majorrelease. Do not use them in new scripts and consider updating existing scripts. This chapterwill help you on how to make the transition.

SimStartStampSimStopStamp

Syntax

SimStartStampSimStopStamp

Description

SimStartStamp is identical to the following sequence of commands:

StartSimWaitForStatus runningLog "$::Qu(Time.Global): Simulation Started"

Likewise for SimStopStamp:

StopSimWaitForStatus idleLog "$::Qu(Time.Global): Simulation Stopped"

Printexec – Log Tcl command and execute it

Syntax

Printexec ?where? cmd

Description

This command is identical in beviour to the LogExec command.

CarMaker Programmer’s Guide Version 2.1.6

Page 272: IPG_CarMaker Programmers Guide

272ScriptControl

ScriptControl Command Reference

Prints

Syntax

Prints ?where? msg

Description

This command is identical in beviour to the Log command.

WriteCMLog

Syntax

WriteCMLog msg

Description

This command is identical in beviour to the SessionLogMsg command.

IFileReadData

Syntax

IFileReadData filetoken key

Description

This command is identical in beviour to the IFileRead command.

DVASetQuValue

Syntax

DVASetQuValue name value count ?mode? ?where?

Description

This command has been superseded by the more general DVAWrite command. For adescription of the parameters see DVAWrite.

sleep

Syntax

sleep ms

CarMaker Programmer’s Guide Version 2.1.6

Page 273: IPG_CarMaker Programmers Guide

273ScriptControl

ScriptControl Command Reference

Description

This command has been renamed to Sleep in an effort to make naming of the commandsmore consistent.

FST_ReqState

Syntax

FST_ReqState mode

Description

This command was completely out of date relative to existing FailSafeTester functionalityand has been removed without substitution.

CarMaker Programmer’s Guide Version 2.1.6

Page 274: IPG_CarMaker Programmers Guide

274Working With the FailSafeTester

Chapter 12

Working With the FailSafeTester

Safety, reliability, efficiency, performance: these are the terms used by design engineerswhen discussing the implementation and design of automotive control units. However, asthe knowledge and understanding in this field increases and new cutting edge ideas arebuilt from the established concepts of yesterday, increases are also made to the complexityof the controller and the control algorithms that are used. As a result, it becomes very diffi-cult or even impossible to predict the behavior of the controller in all situations, particularlywhen evaluated under real world conditions. Testing becomes necessary to determinewhether or not the system’s safety (and other) criteria can be met.

One important aspect of controller testing is the introduction of electrical faults into a sys-tem. This is necessary to simulate conditions that could occur with normal wear and tear,faulty installations, physical damage (e.g. from an accident), problematic sensors and actu-ators, or anything else that could potentially happen to a vehicle’s electrical system over thecourse of its life.

The idea of testing for system failures is not new, but work in this area has traditionally beendone by manually pulling and jumpering wires and cables, and more recently with the helpof breakout boxes that allow a bit more flexibility and incorporate some programmability andfault creation. But this sort of testing takes time, and time is money. IPG realized the needfor a solution that is fast, easy and effective, and the result was the creation of theFailSafeTester.

The idea is simple: create a product that can be used with little or no training, that is com-pletely programmable, generates fully reproducible fault conditions, has unlimited possibil-ities for expansion, and fits in a space that is smaller than a breadbox. It should be able to

Figure 12.1: The FailSafeTester

CarMaker Programmer’s Guide Version 2.1.6

Page 275: IPG_CarMaker Programmers Guide

275Working With the FailSafeTester

create short circuits, cable breaks, current leaks, high current flows, and other conditionsthat could arise due to changes in the controller’s electrical environment, and also have anintuitive graphical user interface and be fully integrated into the CarMaker tool suite. IPG’sFailSafeTester, as you might expect, does all of these things and more, and the rest of thissection describes how it can be used.

If used improperly the FailSafeTester can cause damage to electronics in the ECU, I/O mod-ules, etc. It should be used by someone who understands the effects that signal faulting willhave.Please refer to the FailSafeTester document for detailed information on installation, hard-ware specifications, and other technical information not directly related to usage.

CarMaker Programmer’s Guide Version 2.1.6

Page 276: IPG_CarMaker Programmers Guide

276Working With the FailSafeTester

How it Works

12.1 How it Works

12.1.1 Wiring Topology

Simple HIL Configuration

In a simple Hardware in the Loop (HIL) configuration using CarMaker/HIL, three hardwaredevices are connected with a series of cables or wires (see Figure 12.2).

• The first hardware device used in this simple setup is the host computer, which commu-nicates with the real time computer over a network, and allows messages to be passedbetween the host computer and the real time computer. The tools such as INSTRU-MENTS, etc. are able to send and receive information from the CarMaker executablerunning on the real time computer.

• The second piece of the puzzle is the real time computer that is running the CarMakerexecutable. The CarMaker executable has been configured in a way that allows com-munication through its I/O modules and network interface card.

• The third piece of hardware needed is the actual hardware in the loop element: one ormore ECUs wired and mounted to a test bench. The test bench wiring allows the sig-nals to be monitored and also connects the controller(s) to the I/O modules of the realtime computer.

Figure 12.2: Standard HIL Setup

Host Computer

Real-time computer

Hardware modules andECUs

CarMaker Vehicle Model(vehicle, road, tires, brake, …)

I/O-modules, DAC/ADC, CAN

Sensors, setting elements, ADC

mechanical, hydraulic,pneumatic, … components

electroniccomponents

Tools, such as IPG.Control, Instruments,CarMaker GUI and Development Env..

TCP/IP Network

Analog/DigitalSignals, CAN bus

Drivers, etc.

CarMaker Programmer’s Guide Version 2.1.6

Page 277: IPG_CarMaker Programmers Guide

277Working With the FailSafeTester

How it Works

HIL Configuration Including FailSafeTester (1)

In the standard HIL configuration the hardware controller(s) interfaced to the system sendand receive data exactly the same as if installed in a real vehicle. However, situations mayoccur in a real vehicle that effects the transmission of analog signals, power supplies,ground, etc. Wires could be damaged, corroded, shorted, crossed, cut, etc. and we want tobe able to simulate these conditions. So, in order to do that we place a forth piece of hard-ware between the real time computer (acting as a virtual vehicle) and the test bench withthe mounted and wired controller(s).

Through the fourth piece of hardware all signals chosen for testing can be run, and simula-tion of real world faults can be accomplished. The hardware used in this case is theFailSafeTester. Figure 12.3 shows the configuration of a CarMaker/HIL simulation environ-ment using the FailSafeTester.

• The first piece of hardware is the real time computer running the CarMaker executable.The executable is configured in way that not only allows communication between thehost computer (network card) and test bench (I/O modules), but a third part is config-ured for communication with the FailSafeTester over a CAN bus.

• The second piece of hardware is the host computer. It is set up exactly as in the simpleHIL configuration, except tools such as the FailSafeTester GUI or user defined scriptsare used to control the actions of the FailSafeTester.

• The third piece of hardware is the test bench, which has been modified to allow a directconnection to the real time computer, or to the FailSafeTester, or to a combination ofboth the FailSafeTester and the real time system. The modification is done by adding ormaking changes to the cabling.

• The fourth piece of hardware is the FailSafeTester, which is configured to allow theselected signals to be passed from the test bench to the real time system. The signalscan be unchanged and simply passed through unaffected, or modified in some way, as

CarMaker Programmer’s Guide Version 2.1.6

Page 278: IPG_CarMaker Programmers Guide

278Working With the FailSafeTester

How it Works

desired. The FailSafeTester is told what to do through CAN communication to the realtime computer, which gets its instructions from user defined commands. or from thehost computer through the FailSafeTester GUI controlled by mouse clicks.

HIL Configuration Including FailSafeTester (2)

The FailSafeTester is not limited to the configuration explained in the previous section.There are a number of different ways it can be connected, depending on what hardwareneeds to be interfaced, or what signals should be run through the FailSafeTester hardware.For example, when simulating with multiple ECUs or numerous hardware components theFailSafeTester could be placed between the ECUs to modify signals that are passesbetween them.

Figure 12.3: HIL setup w/ FailSafeTester

Host Computer

Real-time computer

Hardware mods / ECUs

CaMaker Vehicle Model(vehicle, road, tires, brake, …)

I/O-modules, DAC/ADC, CAN

Sensors, setting elements, ADC

mechanical, hydraulic,pneumatic, … components

electroniccomponents

Tools, such as IPG.Control, Instruments,CarMaker GUI and Development Env.

TCP/IP Network

Analog/DigitalSignals, CAN bus

Drivers, etc.

FailSafeTester

FailsafeTester Controller, Cards

Analog/DigitalSignals/ CAN bus

Resistors, etc.

FailSafeTester GUI and scripts

CarMaker Programmer’s Guide Version 2.1.6

Page 279: IPG_CarMaker Programmers Guide

279Working With the FailSafeTester

How it Works

12.1.2 Inside the FailSafeTester

Relays

The magic that happens inside the FailSafeTester is primarily done by opening and closingrelays. Open a relay and the signal is cut; close a relay and the signal is connected again.Like an on-off switch that toggles a light in your house, the relays allow or disallow the flowof electrons from one point to the next. The relays used, SPST (Single Pole Single Throw),can have a starting position of either open or closed. Figure 12.4 shows a signal line with aclosed relay and the same signal that has been opened (cut).

InterConnection Lines

Okay, so now it’s clear how signals are cut and reconnected inside the FailSafeTester. But,how do we do things like cross signals, create short circuits, etc.? To explain this we needto introduce the idea of InterConnection lines. An InterConnection line can be thought of asa wire that runs perpendicular to the signal wires, and has a relay at the intersection pointof the two wires. The relay is open at rest. Figure 12.5 shows an example of this. Signal Aand InterConnection Line 1 are shown perpendicular to one another, with relay IC1 at theintersection. A blow-up of relay IC1 is also shown.

Figure 12.5 shows an example of an InterConnection Line - signal - relay grouping. TheInterConnection Line and signal are not connected at rest, but when the relay is activatedthe two wires will be connected.

Now we have enough information to answer the question we asked in the previous para-graph: How do we cross signals, create short circuits, etc.? The answer, of course, is thatwe use InterConnection Lines to connect the signals. For every signal that is passed to theFailSafeTester, there are a certain number of InterConnection Lines that can be used to

Figure 12.4: Signal with closed relay

Signal A

Closed Relay

Signal A

Open Relay

Figure 12.5: Interconnection Lines

InterConnection L1

Signal A

Relay IC1

Relay IC1 Magnified

CarMaker Programmer’s Guide Version 2.1.6

Page 280: IPG_CarMaker Programmers Guide

280Working With the FailSafeTester

How it Works

connect them. Some of the InterConnection lines are placed on the test bench/ECU side ofthe FailSafeTester, and some on the real time computer side. Figure 12.6 shows an exam-ple of this.

The real time side, test bench side, output side, input side terminology is an arbitrary nam-ing convention that implies an enforced direction and can be a bit misleading. It might beeasier to think of the FailSafeTester as having two sides, Side A and Side B, because thedirection is only relevant in relation to the hardware devices that are connected by the sig-nals run through the FailSafeTester.

As Figure 12.6 shows, signals and InterConnection lines can be connected in a number ofways. Let’s see an example of this. The diagram in Figure 12.7 shows the same matrix thathas been modified slightly. Note the following changes:

• The IC2_RT - Signal 1 relay is closed (circle is filled).

• The IC2_RT - Signal 2 relay is closed.

The effect is a short circuit between signal 1 and signal 2. It is just as simple to switch sig-nals and do any number of other things by opening and closing relays in the InterConnec-tion Line/ Signal Matrix.

Figure 12.6: InterConnection Line/ Signal Matrix

Signal 1

Signal 2

Signal 3

IC1_RT IC3_RTIC2_RT IC1_TB IC2_TB IC3_TB

Real Time Side (RT) Test Bench Side (TB)

Signal Cut Relays

Signal N

...

Figure 12.7: Modified IC / Signal matrix

Signal 1

Signal 2

Signal 3

IC1_RT IC3_RTIC2_RT IC1_TB IC2_TB IC3_TB

Real Time Side (RT) Test Bench Side (TB)

Signal Cut Relays

Signal N

...

CarMaker Programmer’s Guide Version 2.1.6

Page 281: IPG_CarMaker Programmers Guide

281Working With the FailSafeTester

How it Works

Resistors

If one or more resistor cards are added to the FailSafeTester’s hardware configuration thenit is possible to add a resistance to one or more signals that are connected along any or allInterConnection Lines. The resistor can be used to simulate things like faulty insulation, cor-rosion, or other current leakage situation.

CarMaker Programmer’s Guide Version 2.1.6

Page 282: IPG_CarMaker Programmers Guide

282Working With the FailSafeTester

FailSafeTester Cards

12.2 FailSafeTester Cards

There are a few different types of cards that can be used with the FailSafeTester, each per-forming a different function. A brief description is provided, but for details please refer to theFailSafeTester manual.

Standard Relay Cards

The standard relay cards (SRCs) contain the relays that are needed to create the IC / Signalmatrix explained in section 12.1.2.2. They are suitable for handling normal signal currents.

High Current Relay Cards

High current relay cards (HRCs) perform the same action as the SRCs, but are built to with-stand high loads. Because of the size of the components, only four of the six normally avail-able InterConnection lines are available with HRCs. Please refer to the FailSafeTestermanual for more detailed information.

Resistor Card

Resistor cards, as the name implies, contain resistors that can be connected to signalsusing the FailSafeTester’s InterConnection Lines. Refer to the FailSafeTester manual fordetails.

CarMaker Programmer’s Guide Version 2.1.6

Page 283: IPG_CarMaker Programmers Guide

283Working With the FailSafeTester

Configuring the FailSafeTester

12.3 Configuring the FailSafeTester

In section 12.2 we discussed the types of cards that can be included/added to theFailSafeTester, and in this section we discuss how to configure those cards in the CarMakerenvironment. Configuring the FailSafeTester is done by editing the ECUParameters file thatis located in the CarMaker project directory under Data/Config/<Real TimeComputer’s Name>/ECUParameters . The settings are communicated to theFailSafeTester via CAN.

The ECUParameters file is read by CarMaker only when starting or stopping a testrun.When changing the settings be sure to start or stop a testrun to allow the changes to takeeffect.

12.3.1 FailSafeTester Cards Naming Convention

The following table shows the hex names that are given to the FailSafeTester cards. Thenames are used to specify the card type and sub type in the ECUParameters file. Refer tothe FailSafeTester manual for more details concerning the types (and subtypes) of cardsavailable.

Table 12.1: FailSafeTester Card types

CardType SubType Description

0x04 0x010x020x04

Relays Card, 8 channels

0x03 Relays Card, 16 channels

0x05 0x01 Relays Card, High Current

0x07 0x01 Resistor Card

CarMaker Programmer’s Guide Version 2.1.6

Page 284: IPG_CarMaker Programmers Guide

284Working With the FailSafeTester

Configuring the FailSafeTester

12.3.2 FailSafeTester Configuration Settings

The following settings are to be included, as needed, to the ECUParameters file. They areused to specify the necessary FailSafeTester configuration.

Required Configuration Settings

FST.UseIt = UseIt

If UseIt is 1 the FailSafeTester is initialized to be used.If UseIt is 0, CarMaker doesn’t handle the FailSafeTester.

FST.SkipNewIfCfgUnchanged = SkipNew

Optional, default is 0. If SkipNew == 1 the FailSafeTester is only initialized at test run startif it is its configuration parameters have changed.

FST.Cards = nCards

Number of cards to be used

Example FST.Cards = 5

FST.Crd<CardNo>.Slot =

Card is plugged in slot

Example FST.Crd0.Slot = 2

FST.Crd<CardNo>.Type

For card types, see section 12.3.1 ’FailSafeTester Cards Naming Convention’.

Example FST.Crd0.Type = 0x04

FST.Crd<CardNo>.Ch<No>

Name of channel number <No>. <No> = 0, 1, ...If the name is empty, default name is used.

CarMaker Programmer’s Guide Version 2.1.6

Page 285: IPG_CarMaker Programmers Guide

285Working With the FailSafeTester

Configuring the FailSafeTester

Optional Configuration Settings

FST.Crd<CardNo>.SubType

optionalCard subtype, see FailSafeTester manual.

FST.Crd<CardNo>.Chs

OptionalMaximum number of channels on this card.

ECUParameters ExampleListing 12.1: ECUParameters Example

1: ### Activate the FailSafeTester with 3 cards2: FST.UseIt = 13: FST.Cards = 34:5: ### First Card: Relais (0x04)6: ### in slot 0, with 8 channels; channel 2 is unused7: FST.Crd0.Slot = 08: FST.Crd0.Type = 0x049: FST.Crd0.Ch0 = WhlSpd.FL

10: FST.Crd0.Ch1 = WhlSpd.FR11: FST.Crd0.Ch3 = UBat12: FST.Crd0.Ch4 = CAN.Low13: FST.Crd0.Ch5 = WhlSpd.RL14: FST.Crd0.Ch6 = WhlSpd.RR15: FST.Crd0.Ch7 = CAN.High16:17:18: ### Second Card: RelaisHighCurrent (0x05)19: ### in slot 11, 4 channels,20: FST.Crd1.Slot = 1121: FST.Crd1.Type = 0x0522: FST.Crd1.Ch0 = RlsHC.023: FST.Crd1.Ch1 = RlsHC.124: FST.Crd1.Ch2 = RlsHC.225: FST.Crd1.Ch3 = RlsHC.326:27: ### Third Card: Resistor (0x07)28: ### in slot 5, 1 channel, named R429: FST.Crd2.Slot = 530: FST.Crd2.Type = 0x0731: FST.Crd2.Ch3 = R4

CarMaker Programmer’s Guide Version 2.1.6

Page 286: IPG_CarMaker Programmers Guide

286Working With the FailSafeTester

Addition FailSafeTester Configuration

12.4 Addition FailSafeTester Configuration

To make the FailSafeTester GUI available in the CarMaker GUI, the following statementshould be used in the file. CarMaker.tcl (located in the CarMaker project directory).

source FailSafeTester.tcl

CarMaker Programmer’s Guide Version 2.1.6

Page 287: IPG_CarMaker Programmers Guide

287Working With the FailSafeTester

FailSafeTester C-functions

12.5 FailSafeTester C-functions

It is necessary to include function calls inside the CarMaker executable to allow theFailSafeTester to be initialized, and also to facilitate communication (via CAN bus) betweenthe FailSafeTester and the real time computer.

12.5.1 Add the FST Global Variables

The following table shows the global (integer) variables that need to be assigned in theCarMaker application:

Example

12.5.2 Configure the M51 CAN module

Configure the M51 I/O module for 500kBaud and enable both CAN Ids as follows:

MIO_M51_SetCommParam (FST_CAN_Slot, FST_CAN_Ch, 500000, 70, 2, 0);MIO_M51_EnableIds (FST_CAN_Slot, FST_CAN_Ch, FST_CAN_Id, 2);

12.5.3 Add Functions to CarMaker

Inside the HilUser.c and IO.c source file, include the following functions in the appropriateplace. See the Car_Generic/src directory for example function placement.

Called once at program start:

FST_Clear()

Called when the application is starting,for example from HilUser_GetSystemParameters() :

FST_Init()

Called from IO_In() , has to be called each main cycle:

FST_MsgIn()

Called from IO_Out() , has to be called each main cycle:

FST_MsgOut()

FST_CAN_Slot the Slot of the M51 module

FST_CAN_Ch the CAN channel of the module

FST_CAN_Id the CAN id of the FailSafeTester.FST_CAN_Id and FST_CAN_Id+1 are used for communication.

FST_CAN_SendExt

FST_CAN_RecvExt

FST_CAN_SendStat

Listing 12.2: FST Global Variables

1: FST_CAN_Slot = 2;2: FST_CAN_Id = 0x1e8;3: FST_CAN_Ch = 0;4: FST_CAN_SendExt = MIO_M51_SendExt;5: FST_CAN_RecvExt = MIO_M51_RecvExt;6: FST_CAN_SendStat = MIO_M51_SendStat;

CarMaker Programmer’s Guide Version 2.1.6

Page 288: IPG_CarMaker Programmers Guide

288Working With the FailSafeTester

FailSafeTester C-functions

Called from HilUser_ApoMsgEval()

FST_ApoMsgEval(ch, msg, len)

CarMaker Programmer’s Guide Version 2.1.6

Page 289: IPG_CarMaker Programmers Guide

289Working With the FailSafeTester

Using the FailSafeTester

12.6 Using the FailSafeTester

Up to this point we have talked about how to configure the FailSafeTester in the CarMakerenvironment (Configuring the FailSafeTester on page 94) and briefly reviewed the currentlyavailable card types (FailSafeTester Cards on page 94). We have also explained the wiringtopology and the concept of switching relays and connecting signals to interconnection lines(How it Works on page 88), which are, when taken together, the fundamental conceptsneeded to understand how connections, short circuits, current leaks, etc. are realized withthe FailSafeTester hardware. We now turn our discussion to practical applications. In otherwords, how to use the FailSafeTester in the CarMaker environment.

There are currently two possible ways to use the FailSafeTester in the CarMaker environ-ment. First, by using the FailSafeTester GUI that is included and fully integrated into theCarMaker Tool Suite. The second method is by adding commands to mini-maneuver lines.We will discuss both of these approaches in turn.

12.6.1 The FailSafeTester GUI

A First Look

Okay. You have a FailSafeTester. It is connected between a test bench with one or moreECUs and the real time computer that is running the CarMaker vehicle model. All the sig-nals that you want to play with are running through the FailSafeTester. You have added theFailSafeTester card information to the ECUParameters file and the FailSafeTester C func-tions are included in the CarMaker executable. Everything is working correctly and you areready to create a mess with the signals to see if the ECU handles it as expected, or if thereis some unforeseen problem that causes the vehicle to drive backwards when two signalsare crossed. What’s next?

The next step is to start using the FailSafeTester GUI by opening it from the real time systemdrop down menu in the CarMaker GUI. Figure 12.8 shows the menu entry. Select it to openthe FailSafeTester GUI.

The command source FailSafeTester.tcl must be included in the .CarMaker.tcl file forthis option to be available.

Figure 12.8: FailSafeTester in the CarMaker GUI

CarMaker Programmer’s Guide Version 2.1.6

Page 290: IPG_CarMaker Programmers Guide

290Working With the FailSafeTester

Using the FailSafeTester

The result of the previous action will open the FaiSafeTester GUI. Figure 12.9 shows anexample.

The FailSafeTester GUI may look a little different depending on what cards are configuredin your system. If, for example, there is no resistor card installed or configured the resistorfields will not be included.

Now, let’s take a look at what we have here. Crosses, horizontal lines, arrows, buttons, entryfields; it all looks a little strange at first glance, but I assure you it is simple after a littleexplaining.

Figure 12.9: The FailSafeTester GUI

CarMaker Programmer’s Guide Version 2.1.6

Page 291: IPG_CarMaker Programmers Guide

291Working With the FailSafeTester

Using the FailSafeTester

Signals and InterConnection Lines

Figure 12.10 shows the same FailSafeTester GUI after being compartmentalized. Pleaserefer to it during this discussion.

• The GUI is laid out as a matrix. The first eight horizontal rows will contain the signalsthat we want to fault. The red box (labeled A) shows this section of the GUI.

The number of signals that are displayed can be changed by setting the global variableFST::Cfg in the .CarMaker.tcl file that is located in the CarMaker project directory to alarger or smaller value with the command:set FST::DefaultCfg(nRls) <number of signals displayed>

• The magenta box (labeled A.1) shows a single row inside this section that would repre-sent one signal that is wired through the FailSafeTester hardware. By clicking on thedown error in that row, a list of all the available signals will be shown and can be select-ed.

• The yellow box (labeled B) contains the SignalCut relays. They are used to cut andreconnect the signal that is selected in the respective row. Click the button to open andclose the relay that will open or close the connection. By default, these relays areclosed (button shows picture of a horizontal line) but when selected the relay will open(bottom shows picture of broken line).

• The cyan box (labeled C) represents the InterConnection Lines (ILs) that are describedin section 12.1.2 ‘InterConnection Lines’. The box shows one of the six possible ILsavailable with the standard relay cards (Only four InterConnection Lines are availablefor HRCs) : Interconnection Line O2. The ‘O’ stands for Output and the ‘2’ signifies thatit is the second Output IL. The term ‘Output’ usually refers to the side that is connected

Figure 12.10: The Parts of the FailSafeTester GUI

A

B

C

A.1

D

CarMaker Programmer’s Guide Version 2.1.6

Page 292: IPG_CarMaker Programmers Guide

292Working With the FailSafeTester

Using the FailSafeTester

to the ECU. By clicking on the cross button that is at the juncture of an InterConnectionLine and a signal, that relay will be closed and a connection between the two will bemade (a black dot over the cross represents a connection).

• The green box (labeled D) shows what could be termed an IL-Pairing Relay (Intercon-nection Line Pairing Relay). The only function it servers is to connect or disconnect aninput side InterConnection Line with the corresponding output side InterConnectionLine. So, I1 can be connected to O1, I2 can be connected to O2, and I3 can be con-nected to O3. Then, the six available InterConnection Lines available with the StandardRelay Cards (only four InterConnection Lines available with High Current Relay Cards)will effectively become three, since the input and output side lines are paired together(thus the IL.Pairing Relay name).

CarMaker Programmer’s Guide Version 2.1.6

Page 293: IPG_CarMaker Programmers Guide

293Working With the FailSafeTester

Using the FailSafeTester

FailSafeTester GUI Example 1

Let’s see an example. Figure 12.1 shows the FailSafeTester GUI with two signals selected:CAN.Low and UBat.

This is a dangerous signal combination! The example illustrates the need to be careful withthe signals that are connected to ensure that no damage is done to any of the hardwareconnected to the FailSafeTester, or the FailSafeTester itself.

• We can see from the picture that the first signal selected, CAN.Low, has two changesmade. The first is that the SignalCut relay has been opened, thereby cutting the signalbetween the input (real time) side and the output (ECU side). Second, a connectionhas been made to the InterConnection Line O3.

• The second signal selected, UBat, has one change made to it. The signal has beenconnected to InterConnection Line O3, the same InterConnection Line that CAN.Low isconnected to.

What is the result? The CAN.Low signal going to the ECU is replaced with UBat (12V),which as you might expect, is probably not a very good idea. (Doh!).

Figure 12.11: FailSafeTester Example 1

CarMaker Programmer’s Guide Version 2.1.6

Page 294: IPG_CarMaker Programmers Guide

294Working With the FailSafeTester

Using the FailSafeTester

Adding Resistors and Reading Signals

Resistors

The possibility exists to add a resistor to a signal or between two or more signals. When theresistance is added to one signal the effect could simulate corrosion or a similar decreasein the conductive properties of the wire. A resistor added between two or more signalswould simulate current leakage, caused by faulty insulation, water, etc. The red box(Labeled A) shows the area in the GUI that is used to set and connect the resistor.

• To set the resistor, enter the desired resistance in the entry field and press the Set but-ton.

• S1 is one end of the resistor and S2 is the other end.

• To add a resistor to one signal: set the resister value, connect the signal to the S1 andS2 rows of the resistor labeled R1 (we can label them R1.S1 and R1.S2) with two Inter-Connection Lines on opposite sides of the SignalCut relays and then open the appro-priate SignalCut Relay.

The order is important to consider. If, for example, the SignalCut Relay is cut before addingthe resistor to the signal, then an infinite resistance would be on the signal until the resistoris added.

• To add a resistor between two signals: use two separate InterConnection Lines to con-nect one signal to one side of the resistor (e.g. R1.S1) and connect the second signalto the opposite end of the resistor (e.g. R1.S2).

Figure 12.12: Resistors and Signal Readings

A

B

CarMaker Programmer’s Guide Version 2.1.6

Page 295: IPG_CarMaker Programmers Guide

295Working With the FailSafeTester

Using the FailSafeTester

Connecting Signals

Sometimes it is helpful to be able to see the signals with an external devise such as a oscil-loscope or multimeter. This is made possible by connecting a SignalConnect Channel(shown in the green box labeled B in Figure 12.12) to a signal with an InterConnection Line,and plugging the device into the corresponding banana jack connection on the front of theFailSafeTester hardware. If, for example, you have an oscilloscope plugged into the S1 jackon your FailSafeTester and would like to read the signal, Wheel Speed Front Left, you cansimply connect the Wheel Speed Front Left signal to an InterConnection Line, connect theS1 SignalConnect Channel to the same InterConnection Line, and see the signal displayedon your scope.

It is also possible to feed signals in, for example using a waveform generator, by goingthrough a similar process. However, care should be taken when doing this, as it is possibleto damage the electronic components if a signal is feed to a module that isn’t designed tohandle it. As an example, feeding a signal to the FailSafeTester’s resistor card my damagethe card and should be avoided.

CarMaker Programmer’s Guide Version 2.1.6

Page 296: IPG_CarMaker Programmers Guide

296Working With the FailSafeTester

Using the FailSafeTester

FailSafeTester GUI Example 2

Figure 12.13 shows how a resistor can be added along a signal, and how the signal can beconnected and read with an external device. By connecting a scope to the S1 input jack ofthe FailSafeTester the signal WhlSpd.Fl, with an added resistance of 100 ohms, can beread.

Figure 12.13: Resistor and SignalConnect example

CarMaker Programmer’s Guide Version 2.1.6

Page 297: IPG_CarMaker Programmers Guide

297Working With the FailSafeTester

FailSafeTester Commands with Mini-Maneuvers

12.7 FailSafeTester Commands with Mini-Maneuvers

The idea of the FailSafeTester is to be able to modify, in one way or another, the signals thatare wired through it. The changes made should only effect the signals that are selected fora particular test, and the effects should only occur when specified. In other words, we wantto be able to say which signal(s) we want to use, what we are going to do with them, andwhen we are going to do it. The first approach we took to do this was with the FailSafeTesterGUI. However, if you don’t want to control the FailSafeTester interactively, the alternative isto do things automatically during a CarMaker testrun. This is done by adding commands tothe mini maneuvers that define a testrun. This section explains how to use the mini maneu-ver command language to control the FailSafeTester.

Groups, InterConnection Lines and Signals

We have already discussed InterConnection lines and signals in section 12.1 of this docu-ment. Recall that an InterConnection line is used to connect the signals with other signals,resistors, or with external devices (e.g. multimeters and oscilloscopes). Normally there aresix available InterConnection lines, but in the case of High Current Relay cards there areonly four. Half of the InterConnection Lines are located on one side of the SignalCut Relays,and the other half of the InterConnection Lines are located on the opposite side of the Sig-nalCut Relays. The InterConnection Lines can be paired by connecting them with IL-PairingRelays, which simply join the InterConection Lines on one side with its corresponding Inter-Connection Line on the other side. Figure 12.14 presents this information in graphical form.

When the command language is used, in contrast to the FailSafeTester GUI, the IL-Pairingrelays are always closed (this will change in newer versions). Since the IL-Pairing relays areclosed, the six available InterConnection lines (only four available with High Current RelayCards) will effectively become three (two for High Current Relay Cards). This can be visu-alized in Figure 12.14 by either removing the IL-Pairing relays and connecting the corre-sponding InterConnectionLines to each other, or by simply viewing them as always closedwith no chance of opening.

For using the FailSafeTester with Mini-Maneuvers a high-level representation is used calleda group. All participants of a group are connected to each other. This is realized by choosinga InterConnectionLine of the FST and make the appropriate connections. Due to the limitednumber of InterConnectionLines only three simultaneous groups are possible with Stan-dard Relay Cards (six InterConnection Lines divided by two) and only two simultaneousgroups are possible with High Current Relay Cards (four InterConnection Lines divided bytwo).

Adding Signals, Resistors, and SignalConnection Channels to a Group

A Group can consist of a number of Signals, resistors (each side of a resistor is connectedto one group) and SignalConnection channels (connect the FST to external devices).

Group are distinguished by their names. The names:

• must start with a letter (alpha character)

• can contain both letters and numbers (alpha-numeric)

• should not contain any punctuation marks, special characters, etc.

• can be a maximum of 60 characters long

Add Signals to a Group

FSTChAd <Grp> <Ch1>,<Ch2>,...

CarMaker Programmer’s Guide Version 2.1.6

Page 298: IPG_CarMaker Programmers Guide

298Working With the FailSafeTester

FailSafeTester Commands with Mini-Maneuvers

The command FSTChAd takes as its first argument the name of a group. If the group doesn’texist then it will be created, and it should be named in a similar fashion as described above.The second argument is a comma separated list of channels (a channel in this sense is syn-onymous to a signal or a resistor). When added to a group, a channel is connected to allthe other channels that are in that group (i.e. that were previously or simultaneously added).

Add SignalConnection Channels to a Group

FSTSCAd <SCName> <Grp>

The command, FSTSCAdtakes as its first arguments the name of a SignalConnection Chan-nel. The three possibilities (S1, S2, and S3) correspond to the three female banana jackports located on the front of the FailSafeTester hardware. The second argument is the nameof a group. If the group doesn’t exist when this command is called, the group will be created.When used, the command will connect the specified SignalConnection Channel to thespecified group.

Removing channels from a Group

To remove a channel from a group, the following command is used:

Figure 12.14: The FailSafeTester Matrix

I1 I2 I3 O3 O2 O1Side A Side B

Sig 1

Sig 2

Sig 3

Sig 1

Sig 2

Sig 3

Sig n Sig n

SPST(normally closed),

SPST(normally open),

SPST = Single Pole Single Throw

IO-Signal 2

CrosspointsSignalCut Relay

IL-Pairing Relay

S1

S2

S3

Used to connect toexternal device(s)

InterConnection Lines

Used forConnectingToResistor

Resistor x

SignalConnectionChannel Relays

CarMaker Programmer’s Guide Version 2.1.6

Page 299: IPG_CarMaker Programmers Guide

299Working With the FailSafeTester

FailSafeTester Commands with Mini-Maneuvers

FSTChRm <Grp> <Ch1>,<Ch2>,...

The first argument is the group, and the second is a comma separated string that containsthe names of the channels that are to be removed.

Cutting and Connecting Signals

Cutting a signal (i.e. opening the SignalCut Relay) is done by using the command:

FSTChCt <Sig1>,<Sig2>,..

The argument is a comma separated list of the signals that should be cut.

Reconnecting a signal (i.e. closing the SignalCut Relay) is done by using the command:

FSTChCn <Ch1>,<Ch2>,...

The argument is a a comma separated list of the signals that should be connected.

12.7.1 Complete List of FailSafeTester Commands

Listed below are all of the commands that are available for controlling the actions of theFailSafeTester inside a mini maneuver.

FSTInt - Initialize FST

Syntax FSTInt

Before any other FST-commands are executed the FST needs to be initialized (usually atthe beginning of a simulation). See FST-Documentation on INIT instruction.

FSTRst - Reset FST

Syntax FSTRst

Resets all FST-cards to the default state. See FST-Documentation on RESET instruction.

FSTPng - Send Ping to FST

Syntax FSTPng

Sends a ping to the FailSafeTester and logs the answer to the session log. See FST-Docu-mentation on PING instruction.

FSTChAd - Add Channels to a Group

Syntax FSTChAd <Grp> <Ch1>,<Ch2>,...

Argument Description

<Grp> Name of the group.

<Ch1>, <Ch2>, ... List of channel names.

CarMaker Programmer’s Guide Version 2.1.6

Page 300: IPG_CarMaker Programmers Guide

300Working With the FailSafeTester

FailSafeTester Commands with Mini-Maneuvers

Adds the selected channels to a group. All channels of the group will be connected. If thegroup does not exist is will be created. If the number of groups limit is exceeded an errormessage is issued to the session log.

FSTSCAd - Add SignalConnector

Syntax FSTSCAd <SCName> <Grp>

Adds a signal connector on the controller board to a group. This command behaves like theadd channel command except that it refers to external signal connector plugs.

FSTChRm - Remove Channels from Group

Syntax FSTChRm <Grp> <Ch1>,<Ch2>,...

Remove the selected channels from a group. The channels will be disconnected (from theremaining channels). If a resistor signal is removed from a group all other group member-ships (input and output signals of the resistor) are removed as well. But the resistor keepsits resistor value.

FSTGrpRm - Remove Group

Syntax FSTGrpRm <Grp>

Remove all connections created by the group. Remove all channels from the group. Thanremove the group itself.

FSTChCt - Cut Channels

Syntax FSTChCt <Ch1>,<Ch2>,...

Argument Description

<SCName> Name of the signal connector (S1, S2, S3) to join the group.

<Grp> Name of the group.

Argument Description

<Grp> Name of the group.

<Ch1>, <Ch2>, ... List of channel names.

Argument Description

<Grp> Name of the group or ‘*’ to remove all groups.

Argument Description

<Ch1>, <Ch2>, ... List of channel names.

CarMaker Programmer’s Guide Version 2.1.6

Page 301: IPG_CarMaker Programmers Guide

301Working With the FailSafeTester

FailSafeTester Commands with Mini-Maneuvers

Cuts the selected channels. This means the signalcut.

FSTChCn - Connect Channels

Syntax FSTChCn <Ch1>,<Ch2>,...

(Re-)Connects the channels.

FSTR - Set Resistor Value

Syntax FSTR <RstName> <Value>

Sets a resistor value in Ohm.

FSTLGrp

List all groups and group members to the session log.

FSTLFST

Show relays positions. Output is the session log.

Argument Description

<Ch1>, <Ch2>, ... List of channel names or ‘*’ to connect all channels.

Argument Description

<RstName> Name of the resistor.

<Value> Set resistor value (Ohm).

CarMaker Programmer’s Guide Version 2.1.6

Page 302: IPG_CarMaker Programmers Guide

302Working With the FailSafeTester

FailSafeTester Commands with Mini-Maneuvers

12.7.2 Using a Command

To use one of the FailSafeTester commands in the CarMaker environment, the commandmust be added to the dialog box of the specified mini maneuver. Figure 12.15 shows theMini-Maneuver window.

The red box shows where the command is entered. Lines beginning with a hash symbol (#)are treated as comment.

It is also possible to specify the time or distance for command execution, in relation to themini maneuver. The syntax for a command or multiple commands entered in the entry fieldof the mini maneuver window would then be:

Time=x0 Dist=y0 <FST_Cmd0>....Time=xn Dist=yn <FST_Cmdn>

where the time (in seconds) and distance (in meters) attributes are optional.

Example of FailSafeTester Commands

The following are example commands that could be added to a testrun to control theFailSafeTester.

Figure 12.15: Driving Maneuver window

CarMaker Programmer’s Guide Version 2.1.6

Page 303: IPG_CarMaker Programmers Guide

303Working With the FailSafeTester

FailSafeTester Commands with Mini-Maneuvers

The Log command can be added to write comments to the log file.

Resistors

To specify which side of the resistor that will be connected, use the <resistor name>.S1,<resistor name>.S2 naming convention. For example, if the resistor is named R1 then usethe name R1.S1 to refer to the S1 side of the resistor. Similarly, use R1.S2 to refer to theother side of the resistor, as in:

FSTChAd g0 R1.S2

which adds the S2 side of resistor R1 to the group g0.

Listing 12.3: Example of FailSafeTester Commands

1: FSTRst2: FSTChCt WhlSpd.FL3: FSTChCt WhlSpd.FL,UBat,DA.abc4: FSTChCt *5: Log "/// Cut all channels"6: FSTChCn *7: Log "=== Connect all channels"8: FSTGrpRm g0,g1,g29:

10: FSTGrpRm *; Log "free all groups"11:12: FSTChAd g0 WhlSpd.FL/o,UBat13: Log "add out side of WhlSpd.FL and UBat”14: FSTChAd g0 WhlSpd.FL/i,UBat15: Log "add in side of WhlSpd.FL and UBat”16: FSTChAd g0 WhlSpd.FR,Ground17: Log "connect chls, in/out n.spec."18:19: Dist=1000 FSTChRm g0 UBat20:21: FSTSC S1 g022: FSTSC S2 i123: FSTSC S3 o324: FSTSC S2 025: Log "Disconnect S2"26:27: Time=10 FSTR R0 120

CarMaker Programmer’s Guide Version 2.1.6

Page 304: IPG_CarMaker Programmers Guide

304Working With the FailSafeTester

FailSafeTester Commands with Mini-Maneuvers

12.7.3 FailSafeTester Example 1

The Scenario

Let’s examine a hypothetical situation. Suppose the goal of your testing is to determine whathappens if an ESP is not sent the wheel speeds for the front tires during a breaking maneu-ver on a road with a low coefficient of friction. Your motivation is to check whether or not anew algorithm designed to handle this situation performs the way it was intended, by cuttingthe front wheel speed signal moments before the break is depressed, and analyzing theresults in the output file. You have a shiny new FailSafeTester configured in your CarMaker/HIL environment and would like to have some results on your bosses desk as soon as pos-sible so you can leave early and make it to the football game on time. What do you do?

The Solution

Step 1 - Define a testrun

Define a testrun with the desired road conditions, tires, etc. that also contains two minimaneuvers. The first is used to get the car to the desired velocity. The second would be theactual braking maneuver. (See the CarMaker manual for information about defining maneu-vers)

Step 2 - Add the Command

In the second mini maneuver’s dialog area, add a command that will cut both front wheelspeed signals after one second. Use the following command:

Time=1 FSTChCt WhlSpd.FL, WhlSpd.FR

Step 3 - Simulate

Run the simulation. One second into the braking maneuver the front wheel speed signalswill be cut.

Step 4 - Take a look

Take a look at the results to determine if the ESP algorithm performed as expected. Leavea copy on your boss’s desk, and you’re off to the game with plenty of time to spare.

CarMaker Programmer’s Guide Version 2.1.6

Page 305: IPG_CarMaker Programmers Guide

305

CarMaker Programmer’s Guide Version 2.1.6

CarMaker Graphical User Interfaces

CarMaker Main GUI

Chapter 13

CarMaker Graphical User Interfaces

13.1 CarMaker Main GUI

The CarMaker Main GUI can be configured by the configuraiton file ‘.CarMaker.tcl’ in theproject directory.

Configure the storage of results

Supported storage or save modes are: collect, complete, hist_10, hist_30, hist_60,hist_max

SetSaveMode collect

13.2 Car Parameter Editor

13.3 Instruments

• The filename of instruments scripts starts with “Instruments ”, for example Instruments-HIL.tcl , Instruments.tcl , Instruments-Engine.tcl .

Page 306: IPG_CarMaker Programmers Guide

306Vehicle Model Exchange

Exchange, Step by Step

Chapter 14

Vehicle Model Exchange

All references to CarMakers vehicle model can be removed. The core of CarMaker commu-nicates with the vehicle model by function calls and the structure Vehicle.

14.1 Exchange, Step by Step

To exchange the vehicle model you have to

• do some modifications on the Car_Generic source code or

• use the Car_Simple example.

When you use the Car_Simple example, just make a copy the directory Exmples/Car_Simple.

Remark: The following examples are for a linux environment, but can be used for windowsanalogical.

Starting from Car_Simple

Then change directory to “src.Car_c” and execute

make

Change directory to ../src and execute

make

make install

Change directory to “../” and start the CarMaker GUI

CM &

Load the test run “Examples/Hockenheim”.

Start the simulation.

CarMaker Programmer’s Guide Version 2.1.6

Page 307: IPG_CarMaker Programmers Guide

307Vehicle Model Exchange

Exchange, Step by Step

n

With respect to the given interfaces, modify the source code of the existing Car.c by insert-ing your own model behavior.

Starting from Car_Generic

When you use the Car_Generic example make sure that all references to CarMakers Carlibrary have been removed.

14.1.1 Vehicle Model coded in C

File: Makefile

• Assign your vehicle library to CAR_LIB variable

• Add your library include directory to the compilers include path:

INC_CFLAGS += -I../src.Car_c

File: CM_Vehicle.c

• remove:

#include "Car/Vehicle_Car.h"

and replace it with:

#include "CarGlobal.h"

• Function Vhcl_Init():

- assign NULL to the function pointers

- call the initialization function of your vehicle model, f.e. Car_Init()

• Function Vhcl_Register(): remove content

• Function Vhcl_DeclQuants(): reduced to

VehicleStruct_DeclQuants ();Car_DeclQuants ();Car_ExportConfig ();

• Function Vhcl_New (): reduced to

Vhcl_Delete ();if (Car_New(SimCore.Vhcl.Inf) < 0)

rv = -1;return rv;

• Function Vhcl_StaticCondCalc (): remove content

• Function Vhcl_Calc (): reduziert sich auf

if (Car_Calc(dt) < 0)rv = -1;

• SimCore.TS.Vehicle = SimCore.TS.Trailer = SimCore.TS.Brake = SimCore.TS.PowerTrai= SysGetUTime();

• Function Vhcl_Delete (): reduced to

Car_Delete ();

• Fcn Vhcl_Cleanup (): remove contents

File: User.h

• remove:

#include "Car/Car.h"

• insert

CarMaker Programmer’s Guide Version 2.1.6

Page 308: IPG_CarMaker Programmers Guide

308Vehicle Model Exchange

Exchange, Step by Step

#include "CarGlobal.h"

File: User.c

• remove:

#include "Car/Vehicle_Car.h"

• insert:

#include "CarGlobal.h"

• Function User_Check_IsIdle (): remove content, only return “Is Idle”

14.1.2 Vehicle Model coded in Simulink

File: Makefile

Make adaption to your environment:

• MatlabVersion

• Matlab Library

• Assign your vehicle library to CAR_LIB

• Add your library include directory to the compilers include path:

INC_CFLAGS += -I../src.Car_SL

CarMaker Programmer’s Guide Version 2.1.6

Page 309: IPG_CarMaker Programmers Guide

309Index

2

Index

AABSdata.m . . . . . . . . . . . . . . . . . . . . .118ABSdemo . . . . . . . . . . . . . . . . . . . . . .118ABSdemo.mdl . . . . . . . . . . . . . . . . . .118ABSplot.m . . . . . . . . . . . . . . . . . . . . .118Ambient. . . . . . . . . . . . . . . . . . . . . . . . . .15Ambient.Misc. . . . . . . . . . . . . . . . . . .108animation. . . . . . . . . . . . . . . . . . . . . . . . .16Apo. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .16Apo communication . . . . . . . . . . . . . . .23Apo library . . . . . . . . . . . . . . . . . . . . . . .12Apo message. . . . . . . . . . . . . . . . . . . . . .24

BBlockset

Ambient. . . . . . . . . . . . . . . . . . . . .108Block properties. . . . . . . . . . . . . .101Brake. . . . . . . . . . . . . . . . . . . . . . .109Car . . . . . . . . . . . . . . . . . . . . . . . . .113CarMaker dictionary blocks . . . 103CarMaker Model Configuration 102CarMaker subsystem . . . . . . . . . 107CarMaker utility blocks . . . . . . . 102Define CM Dict. . . . . . . . . . . . . .104DrivMan . . . . . . . . . . . . . . . . . . . .108External Suspension Forces. . . . 111Modeling principles . . . . . . . . . . 101Open GUI. . . . . . . . . . . . . . . . . . .102Powertrain. . . . . . . . . . . . . . . . . . .110Read CM Dict . . . . . . . . . . . . . . .103Steering. . . . . . . . . . . . . . . . . . . . .110Sync_In. . . . . . . . . . . . . . . . . . . . .102Sync_Out . . . . . . . . . . . . . . . . . . .102

Tire . . . . . . . . . . . . . . . . . . . . . . . . .115Trailer. . . . . . . . . . . . . . . . . . . . . . .116Trailer Sensor. . . . . . . . . . . . . . . .107Vehicle Sensor . . . . . . . . . . . . . . .106Write CM Dict . . . . . . . . . . . . . . .104

BodyCtrl. . . . . . . . . . . . . . . . . . . . . . . .119BodyCtrl.mdl . . . . . . . . . . . . . . . . . . .119Brake.IF.In. . . . . . . . . . . . . . . . . . . . . .109Brake.IF.Out . . . . . . . . . . . . . . . . . . . .109

CCalculations. . . . . . . . . . . . . . . . . . . . . .23Car.Aero. . . . . . . . . . . . . . . . . . . . . . . .113Car.Fr1. . . . . . . . . . . . . . . . . . . . . . . . .114Car.Hitch . . . . . . . . . . . . . . . . . . . . . . .116Car.Hitch.FrcTrq . . . . . . . . . . . . . . . .116Car.Load . . . . . . . . . . . . . . . . . . . . . . .113Car.Trq_T2W . . . . . . . . . . . . . . . . . . .114Car.Virtual. . . . . . . . . . . . . . . . . . . . . .113Car_Generic_SL. . . . . . . . . . . . . . . . . .93CarMaker/HIL . . . . . . . . . . . . . . . . . . .11CarMaker GUI . . . . . . . . . . . . . . . .10, 11

CM_Simulink. . . . . . . . . . . . . . . . .95Start button . . . . . . . . . . . . . . . . . . .95Starting the CarMaker GUI . . . . . 95Stop button . . . . . . . . . . . . . . . . . . .95

CarMaker library . . . . . . . . . . . . . . . . .14CarMaker Model Configuration

CarMakerModelConfigurationBlock . . . . . . . . . . . . . . . . . . . . . . . . . . 10

C code modulesuser accessible . . . . . . . . . . . . . . . .14

C language interface . . . . . . . . . . . . . .99CM_Simulink . . . . . . . . . . . . . . . . . . . .95

CarMaker Programmer’s Guide Version 2.1.6

Page 310: IPG_CarMaker Programmers Guide

310Index

cmenv.m . . . . . . . . . . . . . . . . . .57, 93, 97Upgrading. . . . . . . . . . . . . . . . . . . . .97

cminstdir . . . . . . . . . . . . . . . . . . . . . . . . .97cmread. . . . . . . . . . . . . . . . . . . . . . . . .130

Example usage. . . . . . . . . . . . . . .130cmstartcond. . . . . . . . . . . . . . . . . . . . . . .96Command line arguments . . . . . . . . 103Configuring the FailSafeTester. . . . 283Connecting Signals . . . . . . . . . . . . . .295cycle. . . . . . . . . . . . . . . . . . . . . . . . . . . . .23

DDataDict . . . . . . . . . . . . . . . . . . . . .16, 53

Current limitations . . . . . . . . . . . . .56Example code. . . . . . . . . . . . . . . . . .56General information . . . . . . . . . . . .53List of functions. . . . . . . . . . . . . . . .55Recommended use . . . . . . . . . . . . .54

DataDict.h. . . . . . . . . . . . . . . . . . . . . . . .56data dictionary . . . . . . . . . . . . . . . .16, 53Data file

organisation . . . . . . . . . . . . . . . . . . .11Data subdirectory. . . . . . . . . . . . . . . . . .11DDictDefChar(). . . . . . . . . . . . . . . . . . .55DDictDefCharMon(). . . . . . . . . . . . . . .55DDictDefDouble(). . . . . . . . . . . . . . . . .55DDictDefDoubleMon() . . . . . . . . . . . .55DDictDefFloat(). . . . . . . . . . . . . . . . . . .55DDictDefFloatMon() . . . . . . . . . . . . . .55DDictDefInt(). . . . . . . . . . . . . . . . . . . . .55DDictDefIntMon(). . . . . . . . . . . . . . . . .55DDictDefLong(). . . . . . . . . . . . . . . . . . .55DDictDefLongMon() . . . . . . . . . . . . . .55DDictDefShort() . . . . . . . . . . . . . . . . . .55DDictDefShortMon() . . . . . . . . . . . . . .55DDictDefUChar() . . . . . . . . . . . . . . . . .55DDictDefUCharMon() . . . . . . . . . . . . .55DDictDefUInt() . . . . . . . . . . . . . . . . . . .55DDictDefUIntMon() . . . . . . . . . . . . . . .55DDictDefULong(). . . . . . . . . . . . . . . . .55DDictDefULongMon(). . . . . . . . . . . . .55DDictDefUShort(). . . . . . . . . . . . . . . . .55DDictDefUShortMon(). . . . . . . . . . . . .55DemoCar_UserPowerTrain . . . . . . . 124Dictionary

Blocks . . . . . . . . . . . . . . . . . . . . . .103Initialization . . . . . . . . . . . . . . . . .105

-disablebrake . . . . . . . . . . . . . . . . . . .123-disablepowertrain. . . . . . . . . . . . . . .124-disablesteer . . . . . . . . . . . . . . . .126, 127DrivMan . . . . . . . . . . . . . . . . . . . . . . . . .15DrivMan.Brake . . . . . . . . . . . . . . . . .108DrivMan.PT . . . . . . . . . . . . . . . . . . . .108DrivMan.Steering . . . . . . . . . . . . . . .108DrivMan module . . . . . . . . . . . . . . . . . .23DT_CM4SL_UserTire . . . . . . . . . . .129

EEC_General. . . . . . . . . . . . . . . . . . . . . .31EC_Init. . . . . . . . . . . . . . . . . . . . . . . . . .31EC_Sim . . . . . . . . . . . . . . . . . . . . . . . . .31Environment.h. . . . . . . . . . . . . . . . . . . .36environmental conditions . . . . . . . . . .15erg files. . . . . . . . . . . . . . . . . . . . . . . . .130Errors . . . . . . . . . . . . . . . . . . .97, 103, 104ESPTemplate. . . . . . . . . . . . . . . . . . . .120ESPTemplate.mdl. . . . . . . . . . . . . . . .120event driven. . . . . . . . . . . . . . . . . . . . . .22event loop . . . . . . . . . . . . . . . . . . . . . . .23events . . . . . . . . . . . . . . . . . . . . . . . . . . .23Examples

ABSdemo . . . . . . . . . . . . . . . . . . .118BodyCtrl . . . . . . . . . . . . . . . . . . . .119ESPTemplate . . . . . . . . . . . . . . . .120SoftABS. . . . . . . . . . . . . . . . . . . . .121TractCtrl . . . . . . . . . . . . . . . . . . . .122UserBrake . . . . . . . . . . . . . . . . . . .123UserPowerTrain. . . . . . . . . . . . . .124UserSteer. . . . . . . . . . . . . . . . . . . .126UserTire. . . . . . . . . . . . . . . . . . . . .129

FFailSafeTester. . . . . . . . . . . . . . . . . . .274FailSafeTester Cards . . . . . . . . . . . . .282FDamp . . . . . . . . . . . . . . . . . . . . . . . . .112FSpring. . . . . . . . . . . . . . . . . . . . . . . . .112FStabi. . . . . . . . . . . . . . . . . . . . . . . . . .112FSTChAd. . . . . . . . . . . . . . . . . . . . . . .297FSTChCn. . . . . . . . . . . . . . . . . . . . . . .299FSTChCt . . . . . . . . . . . . . . . . . . . . . . .299FSTChRm . . . . . . . . . . . . . . . . . . . . . .299FSTSCAd. . . . . . . . . . . . . . . . . . . . . . .298

Ggeneric.mdl . . . . . . . . . . . . . . . . . . . . . .94geometry configuration. . . . . . . . . . . .12GetInfoErrorCount() . . . . . . . . . . . . . .35Global variables . . . . . . . . . . . . . . . . . .15graphical user interface. . . . . . . . . . . .10GUI

Starting the CarMaker GUI . . . . . 95

HHardware input/output. . . . . . . . . . . . .23High Current Relay Cards. . . . . . . . .282HilMain.c. . . . . . . . . . . . . . .15, 21, 22, 25HilUser.c . . . . . . . . . . . . . . . . . . . . . . . .15HRC . . . . . . . . . . . . . . . . . . . . . . . . . . .282

CarMaker Programmer’s Guide Version 2.1.6

Page 311: IPG_CarMaker Programmers Guide

311Index

IIdle . . . . . . . . . . . . . . . . . . . . . . . . . . . . . .24iGetTxtOpt(). . . . . . . . . . . . . . . . . . . . . .34IL-Pairing Relays. . . . . . . . . . . . . . . .297infoc.h . . . . . . . . . . . . . . . . . . . . . . . . . . .36Infofile . . . . . . . . . . . . . . . . . . . . . . .16, 33

Access functions . . . . . . . . . . . . . . .34Error handling . . . . . . . . . . . . . . . . .35Example code. . . . . . . . . . . . . . . . . .36Infofile format . . . . . . . . . . . . . . . . .33infofile handle . . . . . . . . . . . . . . . . .34key . . . . . . . . . . . . . . . . . . . . . . . . . . .34key-value pair. . . . . . . . . . . . . . . . . .34value . . . . . . . . . . . . . . . . . . . . . . . . .34

infofile handle . . . . . . . . . . . . . . . . . . . .34infofiles . . . . . . . . . . . . . . . . . . . . . . . . . .33InfoUtils.h. . . . . . . . . . . . . . . . . . . . . . . .36initialization . . . . . . . . . . . . . . . . . .24, 33Instruments. . . . . . . . . . . . . . . . . . . . . . .10InterConnection lines . . . . . . . . . . . .279IO.c. . . . . . . . . . . . . . . . . . . . . . . . . . . . . .15IPG-CONTROL. . . . . . . . . . .10, 11, 103IPG-MOVIE . . . . . . . . . . . . . . . . . .10, 11

Llibcar.a. . . . . . . . . . . . . . . . . . . . . . . . . . .14libcarmaker. . . . . . . . . . . . . . . . . . . . . . .14libcarmaker.a . . . . . . . . . . . . . . . . .16, 33libcarmaker4sl . . . . . . . . . . . . . . . . . . . .99libraries

special purpose. . . . . . . . . . . . . . . . .14Log . . . . . . . . . . . . . . . . . . . . . . . . . .16, 31

Errors. . . . . . . . . . . . . . . . . . . . . . . . .30General information . . . . . . . . . . . .30Informational messages . . . . . . . . .31List of functions. . . . . . . . . . . . . . . .31message categories . . . . . . . . . . . . .30Recommended use . . . . . . . . . . . . .31Warnings. . . . . . . . . . . . . . . . . . . . . .30

Log.h . . . . . . . . . . . . . . . . . . . . . . . .31, 32LogErrF. . . . . . . . . . . . . . . . . . . . . . . . . .31LogErrStr . . . . . . . . . . . . . . . . . . . . . . . .31log file . . . . . . . . . . . . . . . . . . . .11, 16, 30Logging Module . . . . . . . . . . . . . . . . . .30LogWarnF. . . . . . . . . . . . . . . . . . . . . . . .31LogWarnStr . . . . . . . . . . . . . . . . . . . . . .31lSpring. . . . . . . . . . . . . . . . . . . . . . . . .111lStabi . . . . . . . . . . . . . . . . . . . . . . . . . .111

MMain Loop. . . . . . . . . . . . . . . . . . . . . . . .26main loop . . . . . . . . . . . . . . . . . . . . . . . .21make. . . . . . . . . . . . . . . . . . . . . . . . . . . . .99

MatlabSearch path . . . . . . . . . . . . .57, 93, 97Starting. . . . . . . . . . . . . . . . . . . .57, 93Starting Matlab under Unix . . 57, 93Starting Matlab under Windows . 58,94Workspace variable. . . . . . . . . . .130

message . . . . . . . . . . . . . . . . . . . . . . . . .12Microsoft Visual C. . . . . . . . . . . . . . . .99Model

Creating a new model . . . . . . . . . .94Non-default model directory . . . . 97Running a simulation . . . . . . . . . .95Switching between models. . . . . . 96

Model library . . . . . . . . . . . . . . . . . . . .99Identification. . . . . . . . . . . . . . . . . .99Real-Time Workshop . . . . . . . . .100Rebuilding. . . . . . . . . . . . . . . . . . . .99Rebuilding under Unix . . . . . . . . .99Rebuilding under Windows . . . . . 99

Movie subdirectory . . . . . . . . . . . . . . .11

Nnmake. . . . . . . . . . . . . . . . . . . . . . . . . . .99

OOpen GUI

Open GUI block. . . . . . . . . . . . . .102

PPowerTrain.Misc . . . . . . . . . . . . . . . .110preparations. . . . . . . . . . . . . . . . . . . . . .24Program interaction . . . . . . . . . . . . . . .12Program setup. . . . . . . . . . . . . . . . . . . .23Project directory. . . . . . . . . . . . . . . . . .93project directory . . . . . . . . . . . . . . . . . .11

Qquantities . . . . . . . . . . . . . . . . . . . . . . . .12quantity

address. . . . . . . . . . . . . . . . . . . . . . .53monotone increasing . . . . . . . .53, 55name. . . . . . . . . . . . . . . . . . . . . . . . .53number of states. . . . . . . . . . . . . . .53unit . . . . . . . . . . . . . . . . . . . . . . . . . .53

Rreal-time conditions. . . . . . . . . . . . . . .30real-time performance. . . . . . . . . . . . .54Real-Time Workshop . . . . . . . . . . . .100

CarMaker Programmer’s Guide Version 2.1.6

Page 312: IPG_CarMaker Programmers Guide

312Index

relays . . . . . . . . . . . . . . . . . . . . . . . . . .279Resistor Card . . . . . . . . . . . . . . . . . . .282Resistors . . . . . . . . . . . . . . . . . . .281, 294Road data . . . . . . . . . . . . . . . . . . . . . . . .15

SSearch path . . . . . . . . . . . . . . . .57, 93, 97Server application name. . . . . . . . . . 103Shortcut. . . . . . . . . . . . . . . . . . . . . .58, 94SignalCut Relays. . . . . . . . . . . . . . . .297Signals

Ambient.Misc. . . . . . . . . . . . . . . .108Brake.IF.In . . . . . . . . . . . . . . . . . .109Brake.IF.Out. . . . . . . . . . . . . . . . .109Car.Aero . . . . . . . . . . . . . . . . . . . .113Car.Fr1 . . . . . . . . . . . . . . . . . . . . .114Car.Hitch. . . . . . . . . . . . . . . . . . . .116Car.Hitch.FrcTrq. . . . . . . . . . . . .116Car.Load. . . . . . . . . . . . . . . . . . . .113Car.Trq_T2W. . . . . . . . . . . . . . . .114Car.Virtual . . . . . . . . . . . . . . . . . .113DrivMan.Brake . . . . . . . . . . . . . .108DrivMan.PT. . . . . . . . . . . . . . . . .108DrivMan.Steering . . . . . . . . . . . .108FDamp. . . . . . . . . . . . . . . . . . . . . .112FSpring . . . . . . . . . . . . . . . . . . . . .112FStabi . . . . . . . . . . . . . . . . . . . . . .112lSpring. . . . . . . . . . . . . . . . . . . . . .111lStabi . . . . . . . . . . . . . . . . . . . . . . .111PowerTrain.Misc. . . . . . . . . . . . .110Steer.IF . . . . . . . . . . . . . . . . . . . . .110TireXX_In . . . . . . . . . . . . . . . . . .115TireXX_Out . . . . . . . . . . . . . . . . .115Trailer.Load . . . . . . . . . . . . . . . . .116vDamp. . . . . . . . . . . . . . . . . . . . . .111WheelCarrier.Misc . . . . . . . . . . .114

SimEnv . . . . . . . . . . . . . . . . . . . . . .15, 34SimInput subdirectory. . . . . . . . . . . . . .11SimOutput subdirectory . . . . . . . . . . . .11Simple HIL Configuration. . . . . . . . 276SimStart. . . . . . . . . . . . . . . . . . . . . . . . . .24SimStop. . . . . . . . . . . . . . . . . . . . . . . . . .24Simulate. . . . . . . . . . . . . . . . . . . . . . . . . .24Simulating. . . . . . . . . . . . . . . . . . . . . . . .95Simulation

Results files . . . . . . . . . . . . . . . . .130Simulation Parameters . . . . . . . . . . . . .95simulation program. . . . . . . . . . . .10, 11Simulation results . . . . . . . . . . . . . . .130simulation results. . . . . . . . . . . . . .11, 16SL_ABSdemo . . . . . . . . . . . . . . . . . .118SL_BodyCtrl . . . . . . . . . . . . . . . . . . .119SL_HockenheimUserSteerTorque . 127SL_HockenheimUserTire . . . . . . . . 129SL_TractCtrl. . . . . . . . . . . . . . . . . . . .122SoftABS . . . . . . . . . . . . . . . . . . . . . . .121

SoftABS.mdl. . . . . . . . . . . . . . . . . . . .121SoftABS_params.m. . . . . . . . . . . . . .121Solver. . . . . . . . . . . . . . . . . . . . . . . . . .101Solvers . . . . . . . . . . . . . . . . . . . . . . . . . .95Solver step size. . . . . . . . . . . . . . . . . . .97SPST. . . . . . . . . . . . . . . . . . . . . . . . . . .279SRC. . . . . . . . . . . . . . . . . . . . . . . . . . . .282Standard Relay Cards . . . . . . . . . . . .282Start button . . . . . . . . . . . . . . . . . . . . . .95startup.dict. . . . . . . . . . . . . . . . . . . . . .105Start values . . . . . . . . . . . . . . . . . . . . . .96states. . . . . . . . . . . . . . . . . . . . . . . . . . . .23static equilibrium position . . . . . . . . .24Steer.IF. . . . . . . . . . . . . . . . . . . . . . . . .110Stop button . . . . . . . . . . . . . . . . . . . . . .95Storage of results . . . . . . . . . . . . . . . . .23Storage of simulation results . . . . . . . 53struct

SimEnv . . . . . . . . . . . . . . . . . . . . . .34tInfos . . . . . . . . . . . . . . . . . . . . . . . .34

Sync_In . . . . . . . . . . . . . . . . . . . . . . . .102Sync_Out. . . . . . . . . . . . . . . . . . . . . . .102

Ttemperature . . . . . . . . . . . . . . . . . . . . . .15TireXX_In . . . . . . . . . . . . . . . . . . . . . .115TireXX_Out . . . . . . . . . . . . . . . . . . . .115TractCtrl. . . . . . . . . . . . . . . . . . . . . . . .122TractCtrl.mdl. . . . . . . . . . . . . . . . . . . .122Trailer.Load. . . . . . . . . . . . . . . . . . . . .116Troubleshooting . . . . . . . . . . . . . . . . . .97

UUpgrading CarMaker for Simulink. . 97UserBrake . . . . . . . . . . . . . . . . . . . . . .123UserBrake.mdl . . . . . . . . . . . . . . . . . .123user interface. . . . . . . . . . . . . . . . . . . . .10user interface programs. . . . . . . . . . . .10user interface tools. . . . . . . . . . . . . . . .12UserPowerTrain . . . . . . . . . . . . . . . . .124UserPowerTrain.mdl . . . . . . . . . . . . .124UserSteer . . . . . . . . . . . . . . . . . . . . . . .126UserSteer.mdl . . . . . . . . . . . . . . . . . . .126UserSteerTorque. . . . . . . . . . . . . . . . .127UserSteerTorque.mdl. . . . . . . . . . . . .127UserTire. . . . . . . . . . . . . . . . . . . . . . . .129UserTire.mdl. . . . . . . . . . . . . . . . . . . .129

Vvariable

Ambient. . . . . . . . . . . . . . . . . . . . . .15DrivMan . . . . . . . . . . . . . . . . . . . . .15SimEnv . . . . . . . . . . . . . . . . . . . . . .15

CarMaker Programmer’s Guide Version 2.1.6

Page 313: IPG_CarMaker Programmers Guide

313Index

VCVARS32.BAT . . . . . . . . . . . . . . . . .99vDamp. . . . . . . . . . . . . . . . . . . . . . . . .111vehicle module. . . . . . . . . . . . . . . . . . . .14Vhcl_DeclareQuantities() . . . . . . 54, 56Vhcl_NewInit() . . . . . . . . . . . . . . . . . . .34virtual driver. . . . . . . . . . . . . . . . . . . . . .15Visual C. . . . . . . . . . . . . . . . . . . . . . . . . .99

WWheelCarrier.Misc . . . . . . . . . . . . . .114wind . . . . . . . . . . . . . . . . . . . . . . . . . . . . .15Windows Explorer. . . . . . . . . . . . .58, 94Workspace variable. . . . . . . . . . . . . .130

CarMaker Programmer’s Guide Version 2.1.6