Sie sind auf Seite 1von 33

University of Stuttgart Institute of Industrial Automation and Software Engineering

Prof. Dr.-Ing. Dr. h. c. P. Ghner

Laboratory Course Industrial Automation Experiment No. 1 Introduction to CAN


Experiment Instructions
Document Version Management Version Author
1.0 1.1 1.2 2.0 2.1 2.2 Linder Linder Serrano Eberhard Eberhard Mubarak Li Li Li Li

QA Datum
02.01.01 10.12.01 31.07.02 30.09.03 30.09.04 21.10.05

Status
accepted accepted accepted accepted accepted accepted

Changes
reformatting Corrections Chapter 3.4 Complete revision Corrections, Chapter 3.4 added Corrections

Document name: Print date:

fpat-v1-can_anleitung-eng_ws04-05.doc 07/12/2011 14:59:00

Introduction to CAN

Table of Contents
1 Introduction........................................................................................................................... 3 1.1 Field Bus Systems ........................................................................................................... 3 1.2 The ISO/OSI Reference Model ....................................................................................... 3 1.3 Contents and Goal of the Experiment ............................................................................. 4 CAN Basics ............................................................................................................................ 5 2.1 General Features of CAN................................................................................................ 5 2.2 Bit Transfer (OSI-layer 1) ............................................................................................... 6 2.3 Message Formats and Bus Access (OSI-layer 2) ............................................................ 6 2.4 Error Detection and Error Handling................................................................................ 9 2.5 CAN-Modules............................................................................................................... 10 Analysis of the CAN Message Format............................................................................... 11 3.1 The Tool CANscope ..................................................................................................... 11 3.2 Working with CANscope.............................................................................................. 12 3.3 Example of a CANscope Measurement ........................................................................ 13 3.4 Interpretation of CAN-messages................................................................................... 14 Laying out CAN Networks ................................................................................................. 16 4.1 Procedure of Laying out CAN Networks ...................................................................... 16 4.2 The Software-Tool CANoe........................................................................................... 17 4.3 Introduction to CAPL.................................................................................................... 19 4.4 Example of a CANoe Simulation Model ...................................................................... 20 4.5 Working with CANoe ................................................................................................... 21 Tasks and Experiments ...................................................................................................... 24 5.1 Conducting the Experiment .......................................................................................... 24 5.2 Introductory Tasks......................................................................................................... 25 5.3 Analysis of the CAN Message Format.......................................................................... 25 5.4 Interpretation of CAN Messages................................................................................... 25 5.5 Layout of CAN-Networks............................................................................................. 28 Literature............................................................................................................................. 30 Appendix.............................................................................................................................. 31 7.1 CAN Interface of the Car Door ..................................................................................... 31 7.2 Short CAPL Language Description............................................................................... 32

6 7

Introduction to CAN

1 Introduction
1.1 Field Bus Systems
A bus is a serial data communication system. A field bus is a bus system to work in the so-called field area, which designated the part of an automation system which is spatially near or directly connected to the actual process. It includes all devices and equipment (field devices) that directly interact with a process. Field devices are similar to the sensors and measuring devices required for measuring process quanties and the equipment such as switches and positioners, controller or operator panels which directly affect a process. Field devices are increasingly being designed in the form of intelligent control units. Field bus systems enable simplified connection and wiring technology and guarantee high system flexibility regarding changes and expansions when used instead of conventional wiring connection technology. This opens up a substantial potential for saving planning and installation costs in many branches of industrial automation. As triggers for the rapid development of data communication systems in the field area three types of application-specific development trends can be determined. That is open source code communication platforms to be used in the field area of installation automation communication systems for the use in vehicles communication systems for the use in electrical installation engineering of buildings

Depending on the area of application and the various demands resulting out of that, more than 50 types of field bus systems were developed all over the world. Examples are the PROFIBUS (Process Field Bus), INTERBUS-S, and CAN (Controller Area Network). Because of the increasing number of electronic components in vehicles, the Robert Bosch GmbH designed CAN in the early 1980s. Due to standardisation and low production costs, today CAN is used in various industrial applications that are concerned with all kinds of automation tasks.

1.2 The ISO/OSI Reference Model


A basis for characterization of communication system is the Basic Reference Model for Open System Interconnection (OSI) developed by the International Standard Organisation (ISO). The OSI Reference Model describes communication systems using seven layers. Every layer performs a specific task within the communication and has interfaces to both the upper and lower layer. The communication is controlled by protocols, i.e. a set of rules for the exchange of data (see Figure 1). Field bus systems do not use all functionalities described by the Reference Model. On the other hand a high efficiency is needed because of strict temporal requirements. Therefore, typically only the layers 1, 2, and 7 of the model are implemented to minimize the administrative costs of communication. However, on account of the complexity of modern communication processes a trend towards the utilization of further layers can be seen (e.g. in automotive electronics).

Introduction to CAN

Figure 1: Reference Model of data communication.

1.3 Contents and Goal of the Experiment


Because of the increasing decentralisation in modern automation engineering, field bus systems are more and more used. The most important one is CAN. The reason for this are the special features and the standardization of the CAN protocol as well as the low production costs of CAN controller. When developing distributed automation systems the layout of CAN-networks is an important aspect. The goal of this experiment is to enable insight into the CAN protocol as well as the possibilities of using field bus systems in industrial automation. For this, CAN messages will be recorded, analyzed, and evaluated using the soft- and hardware tool CANscope. On the other hand a basic distributed automotive body electronic system based on a CAN (Controller Area Network) field bus will be developed and simulated using the software tool CANoe. A car door, whose actuators (automatic windows, etc.) are controlled by CAN, will be used as a network node. For successful execution of this experiment, a thorough preparation should take place. Thereto, the preparatory tasks in chapter 5 have to be completed in written form before beginning the experiment.

Introduction to CAN

2 CAN Basics
2.1 General Features of CAN
In modern automotive electronics an increasing number of electronic control units is used to realize open- and closed-loop control tasks (engine management, ABS, comfort electronics, etc., see Figure 2). A large volume of data exchange between those control units is performed in an environment with electromagnetic disturbances at high levels. The data exchange is characterized by a large number of communication processes with rather low data volume per message (cyclic transmission of characteristic process data, e.g. engine speed).

Figure 2: Example of a modern interconnection of electronic control units in vehicles. Especially developed for such applications the layer- 1/2-protocol CAN, standardized in ISO-DIS 11898 and ISO-DIS 1119-1, is characterized by a high speed data interchange including short latency times and high interference resistance of data transfer. General features of CAN are: linear topology message-oriented priority-controlled protocol multimaster system with non-destructive bus arbitration easy communication services, short block length sophisticated error detection and error handling mechanisms system-wide data consistency low latency times, low error recovery times international standardization

The CAN architecture defines the lowest two layers of the model: the data link and physical layer. The application levels are linked to the physical medium by the layers of various protocols, dedicated to particular industry areas plus any number of propriety schemes defined by individual CAN users. Since the establishment of a standardized application layer would enable a complete isolation of the application and the communication processes (see Figure 1) some organisations (e.g. OSEK) forces a consistent definition.

Introduction to CAN

2.2 Bit Transfer (OSI-layer 1)


In the international standard (ISO) the physical layer is defined as follows: Transmission medium: Normally twisted wire pair (impedance 120 ) with a differential signal (between 5V) for noise rejection. Bus topology: Linear topology with terminating resistors at each end of the bus. Maximum number of participants (nodes) dependent on bus driver. Maximum bus length dependent on data rate. Bit coding: NRZ-method (non-return-to-zero) but differentiation between dominant level (logic Zero) and recessive level (logic One). Achieved by wired-and mechanism (see Figure 3). Bit synchronisation: Continuous post-synchronization of the transmitted bit stream using edges. Due to the fact that NRZ-encoding is used and therefore long periods without edges might occur, this has to be prevented using appropriate message formats. Data rate: To ensure a secure bit synchronization the bit time intervals has to be larger than the double maximum group delay. Means: the longer the bus the lower the maximum data rate. Absolute maximum value: 12 Mbit/s. Maximum bus lengths by 100kbit/s: 640 m.
level S1 S2 S3 bus 0 0 0 0 1 0 0 0 0 1 0 0 1 1 0 0 0 0 1 0 1 0 1 0 0 1 1 0 1 1 1 1

5V

bus

S1

R1

S2

R2

S3

R3

Figure 3: Achievement of a dominant and a recessive level on the basis of a wired-and mechanism.

2.3 Message Formats and Bus Access (OSI-layer 2)


The main task of the data link layer is to transmit and receive data within a local network. Thereto, all data have to be bundled into conveyable units (messages), the bus access has to be arranged among multiple participants ready to send, and the transmission of data has to be ensured using error detection and error correction mechanisms. CAN transmits data using data frames. The structure of such a data frame is shown in Figure 4. An essential part is that the identifier determines the priority of the message instead of defining the address of a receiver.

Introduction to CAN

A data frame transmits a specific message, that is characterized by its identifier. Every participant checks the identifier of the message received to see whether it is relevant or not (acceptance filtering). The message acceptance filtering principle also enables messages to be accepted by all or multiple nodes at one time (multicasting). This ability is very useful for many things including application process synchronization.
RTR-Bit (Remote-Transmission-Request) recessive "one"-level delimiter bits

dominant "zero"-level

number 1 of bits

1 1 1 Object Identifier

0 ... 64 data field control field CRCSegment CRC-field Data Frame

1 5

1 1 1

7 End-ofFram e field ACK-Slot ACK-field

3 Interfram e Space

arbitration field Start-of-Frame-Bit

start-of-frame ....... dominant bit to identify the start of a message arbitration field ..... 11 bit identifier 1 RTR-bit (to request data, see end of this chapter) control field .......... 2 bit reserved for extended CAN (standard CAN: dominant) 4 bit to indicate the length of the data field (DLC) data field .............. 0 - 8 data bytes, starting with the MSB 15 14 10 8 7 4 3 CRC-field ............. 15 bit CRC-check code polynomial (x +x +x +x +x +x +x +1) 1 CRC-delimiter bit (recessive) ACK-field .............. 1 bit ACK-slot (acknowledgement mechanism) 1 ACK-delimiter bit (recessive) end of frame ........ 7 bit end of frame identification (recessive)

Figure 4: Data frame format. The minimum length is 44 bits joined by 0-64 data bits and if necessary stuff bits. The lower the value of the identifier assigned to a message the higher the priority of this message. This mechanism is used to control the bus access. Bus access in the CAN protocol takes place locally according to the CSMA/CA method (carrier sense multiple access / collision avoidance). Each bus participant checks the bus state (carrier sense) and starts transmitting a message as soon as the bus is not occupied for a certain time. Whenever multiple participants want to use the bus simultaneously (multiple access) this conflict will be solved by an arbitration process. Each transmitting participant compares the value of the bits it has sent with the value that is actually present on the bus. If it is not, the participant stops the arbitration attempt immediately (see Figure 5). Due to the fact that messages with high priority have lower identifiers and according to this the arbitration field starts with more dominant bits, these messages will remain on the bus without destroying data (collision avoidance).

Introduction to CAN

Figure 5: Example of an arbitration process in the CAN protocol. Participants 1, 2 and 3 are simultaneously starting an arbitration attempt (1). Participant 2 loses bus access authorization at point (2), participant 1 at point (3). Both participants therefore go into receiving mode; at the end of the arbitration phase (4), only participant 3 has bus access authorization and sends its message to the bus. The CAN protocol uses NRZ bit encoding. The disadvantage of this is that there are no edges available for synchronizing individual network nodes during a longer sequence of equal bits (see chapter 2.2). For this reason, bit stuffing is used in the identifier, in the control field, in the data field, and in the CRC field. This means that an additional bit with the opposite polarity is inserted after 5 bits of the same polarity. This enables post-synchronization using additional edges. These stuff bits are then removed by the recipient (see Figure 6).

Figure 6: The bit stuffing principle. In this example, the transmitter inserts a complementary bit after a bit sequence of 5 bits of the same polarity, after the 7th and the 19th bits of this preceding bit sequence. The recipient always removes the bit following a sequence of 5 identical bits within the frame section encoded by bit stuffing so that the original bit stream is recovered. To request a message from a transmitter node, a remote frame is used. The composition of the remote frame is the same as that of the data frame with the exception that the RTR bit is

Introduction to CAN

transferred recessively and there is no data field. The identifier of the data required is the same as the one of the remote frame. The value of the DLC is the one of the requested data frame.

2.4 Error Detection and Error Handling


High data transfer safety requirements result from the original area of use, in automobiles. In order to guarantee this, the following steps are used as a base in the CAN protocol to recognize corrupt messages. Bit Monitoring: Each transmitting network node monitors whether or not the bus level it has transmitted is actually present on the bus. A recessive bus level can only be overwritten by a dominant one during the arbitration phase as well as in the acknowledge slot. Otherwise there is a bit error. This leads to recognition of faults with global effects as well as all errors with local effects at the transmitting node. Message Frame Check: The message formats of the CAN protocol contain fixed format elements (e.g. recessive delimiter bits) which are checked by all network nodes. Also the correct realization of the bit stuffing rule is checked. Cyclic Redundancy Check (CRC): The CRC safeguards the information in the frame by adding redundant check bits at the transmission end. The CRC contains a checksum resultant from the division of the preceding data and a polynomial (x15+x14+x10+x8+x7+x4+x3+1). At the receiver the check bits are re-computed and tested against the received bits. Acknowledgement Monitoring by the Transmitter: All recipients that have recognized the message as error-free after a CRC check put the acknowledge slot bit on the dominant level. The transmitter itself switches to the recessive level. So, if the acknowledge slot bit is on a dominant level, the transmitter knows that its message has been correctly received by at least one bus participant.

After detection of an error using the above mechanisms the current transmission is aborted by sending an error frame consisting of a sequence of 6 dominant bits (error flag primary) possibly followed by 6 additional dominant bits (error flag secondary) and 8 recessive bits (error delimiter) which selectively violates the code. Figure 7 shows an error frame format containing the error flags (6-12 bits) and the error delimiter (8 bit).The next transmission starts using another arbitration process.

Figure 7: Error frame format.

10

Introduction to CAN

Error handling using error frames involves the bus becoming blocked, if a faulty functioning network node decodes messages incorrectly. For this reason, every node carries out a selfsupervision. If a certain number of messages are recognized faulty, the network node switches to the so-called error passive mode. Now messages from other bus components can no longer be destroyed. To delay transmission of a data or remote frame, an overload frame can be sent. The overload frame is a special error frame that is transmitted during a frame interval.

2.5 CAN-Modules
Caused by the large number of pieces reached in car industry, a lot of noted manufacturers offer CAN-controller or microcontroller with an integrated CAN-interface (see following table). All modules do frame encoding and data saving independently. According to the protocol version an 11-bit identifier (version 2.0A) or a 29-bit identifier (extended CAN-version 2.0B) is used. Moreover, the two versions differ in the realization of acceptance filtering method. manufacturer Philips Siemens Intel Philips Siemens Motorola Intel Motorola name 82C200 81C90 82527 8XC592 51C806 68HC05 87C196 68HC16 68300 PC500 protocol 2.0 A 2.0 A 2.0 B 2.0 A 2.0 A 2.0 A 2.0 B 2.0 B high acceptancefiltering x x x x x x CANcontroller x x x integrated in microcontroller

x x x x x

Introduction to CAN

11

3 Analysis of the CAN Message Format


3.1 The Tool CANscope
CANscope is a measurement instrument for recording and evaluating the signal level on the CAN bus. Information is provided on both, the physical and the logical CAN levels. On the physical level the voltage applied to the CAN lines are depicted as a signal response. The logical level provides information in form of individual bits. This allows you to analyze the physical properties of the CAN bus and to recognize errors. CANscope consists of a recording module and an evaluating software for windows. The measurement is performed with various measurement and operating modes and is controlled by a number of parameters and trigger sources. Several windows are provided for evaluating the recordings acquired by a measurement. Figure 8 shows the CANscope screen.

representation of signal levels and stuff bits

analysis of CAN-messages

selection and display of trigger sources

Figure 8: The CANscope screen. Several trigger sources are available for triggering like message triggering, triggering on CAN level or wire detect, triggering on voltage level, and external triggering. Triggering to messages occurs in the end-of-frame bit field. Therefore, the trigger time point lies at the end of a message (see Figure 11).

12

Introduction to CAN

3.2 Working with CANscope

To record and evaluate signal levels on the CAN bus, proceed as follows: 1. Configuration and Performance of a Measurement First you have to configure a CANscope measurement. Thereto, all connection parameters have to be determined. These parameters are the selection of the serial interface used to connect the recording module to the PC and the data rate used for communication. The next step is to define the measurement parameters. They are subdivided into three parts: the definition of the analog parameters, the configuration of the trigger input, and the setting of the measurement mode. You have to define the buffer depth, i.e. the number of measurement values, and the pretrigger in the dialog of analog parameters. The pretrigger indicates the region to be recorded before the trigger time. In the next step the parameters for the CAN controllers have to be set in the channel configuration. In this dialog it is important to set the baud rate for the CAN controllers of the recording module. Finally the configuration of the signals in the Oscilloscope window and the definition of the trigger sources in the belonging window is to be set. If a data base is assigned to the CANscope configuration, the possibility exists to define messages to which triggering should occur using their numeric ID or their symbolic name. After the start of a CANscope measurement the recordings are transferred to the evaluation software automatically for display, analysis, and evaluation. 2. Display and Evaluation of the recorded Data Display and evaluation of a recording takes place in the Oscilloscope and Trace window. The Oscilloscope window displays the selected signal levels and the stuff bits. The Trace window contains logical information on the messages of the current displayed recording. To obtain this information the recording is analyzed according to the CAN messages and error frames it contains. The messages and error frames are listed together with all available information (see Figure 9).

Figure 9: Oscilloscope window and Trace window in CANscope.

Introduction to CAN 3. Data saving

13

Recordings can be saved individually and then integrated into an archive. Thereto, the Recording window is available containing all currently available recordings.

3.3 Example of a CANscope Measurement


Figure 11 exemplifies a CANscope recording. A message with ID 420 was sent using an Interactive Generator block in CANoe and recorded using CANscope. Figure 10 shows the parameters and the data field of this message.

Figure 10: Message parameters and data field of a message. After the recording by the recording module the data is analyzed and displayed by the evaluation software (see Figure 11). The initiated trigger can now be seen in the Trigger window. The Trace window displays all detected messages with further details like identifier (hex), state, DLC, data bytes, and all parts of the message beginning with the start-of-frame bit. On selecting a message or a detail the area belonging to it will be highlighted with the difference measurement cursors in the Oscilloscope window. The number of bits between the difference cursors will be shown as well as the trigger time point.
difference cursors

number of bits between difference cursors

CAN-High

CANdiff (Low-High)

Stuffbits

trigger time message details

trigger source

Identifier

Status of a message

DLC

data bytes

Figure 11: CANscope recording of a message.

14

Introduction to CAN

3.4 Interpretation of CAN-messages


Beside recording and evaluating of CAN-messages the interpretation of these plays an important role during the analysis of the CAN message format. The recorded and analyzed (regarding to their correctness) messages also have to be evaluated, which means the transmitted data must be interpreted. To interpret a message, first of all, the message on the CAN bus must be recorded and the stuffbits must be removed afterwards. Then the data field of the message is divided into the different signals which are then evaluated. This procedure is considered exemplary in the following by means of the electronic stability program (ESP). The ESP prevents skidding of a vehicle by specific intervention in braking in order to correct driving errors resulting in over- or under-steering. From the steering angle and the wheel speeds ESP calculates what manoeuvres the driver intends to perform. From the signals of the yaw-rate (rotation of the vehicle about the normal axis) and lateral acceleration sensors ESP recognises whether the vehicle threatens to skid off course. The ESP compares both information and in case of a deviation, the ESP "steers" the vehicle into the desired direction by selectively applying braking pressures at each wheel. The following illustration shows the data field of a recorded CAN-message for the electronic stability program (ESP).

The message and its signals are defined as follows: esp: Identifier = 120; DLC = 4 Signals: - lateral acceleration [m/s]: - yaw rate [/s]: - wheel speed [U/s]: - steering angle []:

number of bits = 8; start bit = 0 number of bits = 8; start bit = 8 number of bits = 8; start bit = 16 number of bits = 8; start bit = 24

The lateral acceleration and the steering angle are measured in steps of 0,1. To interpret this message, first of all, the stuff-bits of the message have to be identified and afterwards removed.

Figure 12: Data field of the recorded message with and without stuff-bits.

Introduction to CAN

15

Now, the obtained data field without stuff-bits is divided into the different data bytes and the signals are determined.

Figure 13: Determination of the data bytes and the signals of the data field. Finally, the values must be computed. Therefore, the binary values are converted into decimal ones and if necessary evaluated. Thus, the resulting values are: lateral acceleration: 45 * 0.1 = 4,5 m/s yaw rate: 0 /s wheel speed: 20 U/s steering angle: 10 * 0,1 = 1 (measured in 0.1 steps) (measured in 0.1 m/s steps)

16

Introduction to CAN

4 Laying out CAN Networks


4.1 Procedure of Laying out CAN Networks
Laying out the utilized field bus is an elementary aspect in the development process of distributed automation systems. Since bit transmission and data frame construction is usually performed by integrated CAN components, the main work of laying out a CAN network is to determine the so-called communication frame, which specifies the CAN messages to be transmitted as well as the sending and receiving network nodes. First, all application-specific signals have to be determined. Based on this analysis, the CAN messages of the systems have to be defined (determination of the communication frame) by grouping the previously determined signals together with a priority sensitive identifier (Figure 14). To minimize the bus-load and the administration overhead, related signals should be grouped and transmitted simultaneously. The behaviour of the single network nodes is now specified, e.g. in form of cyclic transmission of messages or more complex protocols (reaction on received message etc.), and the baud rate is determined by estimating the expected bus load and the thereby resulting latency times for high priority messages.
Signal 1 Signal 2 Signal 3

Identifier

DLC

Data Field

CAN Message

Figure 14: Merging application-specific signals in a CAN message. Thus, one can distinguish three phases when developing CAN based automation systems: Phase 1: Requirements analysis and design of the networked system First, the team responsible of the design determines the network's topology and refines the design to the level of the network nodes. This includes defining the messages and selecting the bus baud rate. For a more accurate study, a functional model of the overall system is created. This involves specifying the behaviour of the network nodes regarding input and output variables as well as the messages to be received and transmitted. Phase 2: Implementation with remaining bus simulation After the first phase has been completed, the design and development of the individual network nodes is usually performed independently and in parallel by all participating parties. The models for the other network nodes can now be used to simulate the remainder of the bus for testing a developed network node. CANoe has an interface to the real bus for this purpose. The simulation is conducted in real time (Figure 15).

Introduction to CAN Phase 3: Integration of the overall system

17

In this last development phase, all real network nodes are connected to the bus step-by-step. The network node models can be shut off one by one in the simulation of the remainder of the bus segment (Figure 15). CANoe is increasingly used as an intelligent tool for analysis comparing the message traffic between the real network nodes on the bus and the results to the specified requirements.
Bus Monitor

Real Node 1

Simul. Node 3

Physik. Bus

Real Node 2

Simul. Node 4

Figure 15: Remaining bus simulation with two real and two simulated CAN nodes.

4.2 The Software-Tool CANoe


CANoe is a universal development, testing and analysis environment for CAN bus systems which helps observing, analyzing, and simulating data traffic on the bus line. Figure 16 shows the CANoe main program. High-performance functions and free programmability cover all CAN bus system simulation and implementation needs. All network nodes connected to the bus can be simulated. Windows can be generated for operating the network nodes whose operating elements can be triggered using environmental variables. There is also a conversion of message data into physical characteristics. As shown in Figure 15, a simulation in CANoe can contain both, real and simulated network nodes. The coupling to the real bus is realized via a PC card. CANoe clarifies this detail through representing the bus-coupling of simulated nodes by red lines and the bus-coupling of real nodes by black lines Figure 16. Furthermore, it is possible to add a Generator block to the simulation model, which transmits messages if a certain triggering condition (e.g. press of a key) occurs. These blocks can be configured in the simulation model.

18

Introduction to CAN

Figure 16: The software tool CANoe. To model the dynamic behaviour of a simulated node, the modelling language CAPL can be used. CAPL is a C-like modelling language. It is used to specify the behaviour of a node regarding CAN messages and its interaction with the environment, e.g. external input and output signals. External input and output signals are modelled using so-called environment variables. To modify or visualize environment variables, panels can be used as seen in Figure 16. CANoe consists of four independent programs, which dependencies are shown in Figure 17. The use of a central database containing all existing CAN messages, environment variables, and network nodes facilitates the creation of a behaviour model, using the CAPL browser, the creation of panels using the Panel editor and the configuration of a simulation model using the CANoe main program.
Database Editor candb32.exe

CAPL Browser canbr32.exe

Database (*.dbc)

Panel Editor vpanel32.exe

CAPL Modell (*.can)

CANoe canoe32.exe

Panel (*.cnp)

Figure 17: CANoe programs.

Introduction to CAN

19

4.3 Introduction to CAPL


CANoe's universal application is given among other things by the possibility of programming with the C-like programming language CAPL. A CAPL program consists of two parts: 1. Declaration of global variables Integers (in the form of "dword", "long", "word", "int", "byte," and "char"), floating-point numbers ("float" and "double"), CAN messages ("message"), and timers ("timer") are available as data types for variables. With exception of Timers these can be initialized right at declaration. Integers and floating-point numbers are used as in other programming languages. Variables of the "timer" type are used for generating time events, while "Message" type is used to declare CAN objects (messages) that should be the output from the CAPL program. Example:
variables { long upperlimit = 123456; /* declaration of the variable upperlimit and initialization with 123456 */ message 123 temp = { dlc=2, word(0)=100 }; /* declaration of temp. as CAN message with the Identifier 123. Initialization of the DLC with 2. Initialization the data bytes 0 and 1 with the data word 100. * / timer time; /* declaration of time as Timer in seconds */ }

2. Declaration of event-driven procedures A reaction can come in procedures when events occur (event procedures). Possible procedures are: Receipt of a CAN message (on message) Press of a key (on key) Program start (on start) Elapse of a timer (on timer) Occurrence of an error frame ("on errorFrame) Change of an environment variable ("on envVar)

If the specified event occurs, the corresponding procedural field is executed. This can contain the declaration of local variables, C-like arithmetical and control stream instructions (if-then queries, while and case loops, etc.), and the initiation of standard procedures. The "this" variable helps by in accessing the triggering event. Access can be gained to the message using an "on message" procedure, to the environment variable using an "on envVar" procedure or the actual key code using the "on Key" procedure. An event procedure cannot contain another event procedure. You can find an overview of the most important CAPL functions in the appendix of this document. More information to the CAPL Modeling language is to be found [6]. In addition, further procedures and functions can be written using a C-like syntax to supplement the event procedures.

20

Introduction to CAN

4.4 Example of a CANoe Simulation Model


Figure 18 clarifies the principle structure of a CANoe simulation model. The depicted model consists of two simulated nodes named NodeA and NodeB. If the switch attached to NodeA is closed, the light attached to NodeB is to turn on. If the switch is opened, the light is to go out. Switch and light represent thus external input and output signals which are represented by the environment variables evSwitch and evLight.
impact environment variable "evSwitch" environment variable "evLight"

CAPL Model "NodeA" Signal in CAN message "Msg1.bsSwitch"

CAPL Model "NodeB"

Figure 18: Example of a CANoe simulation model. Communication between the nodes happens using the CAN message Msg1. Within this CAN message the signal bsSwitch exists transferring the actual information. At this, bsSwitch=1 may represent the condition switch closed and bsSwitch=0 the condition switch open. The CAN message needs a unique identifier which is to be selected according to the priority of the message. Since the information is not significant, the identifier 125 can be used. Finally it has to be considered, at which times the CAN message is to be sent. A proven method is the cyclic dispatching of the message, e.g. every 2 seconds. Independently of the condition of the switch, the CAN message is to be dispatched every 2 seconds. The condition of the switch can be inferred from the current value of the contained signal bsSwitch. Altogether, following data is need: CAN messages: Msg1:Identifier = 125; DLC = 1 Signals: - bsSwitch: number of bits = 1; start bit = 0 Environment variables: evSwitch: evLight: Type = Integer; Values = 0..1 Type = Integer; Values = 0..1

Introduction to CAN The CAPL model for the node NodeA could be specified as follows:
variables { timer delayTimer; message Msg1 sendMsg; } on start { setTimer(delayTimer, 2); } on timer delayTimer { output(sendMsg); setTimer(delayTimer, 2); } on envVar evSwitch { sendMsg.bsSwitch = getValue(this); }

21

As variables, the timer delayTimer is defined and it is specified, that the CAN message Msg1 is used and called sendMsg within the program. Using the event procedure on start the timer is initialized to the beginning of the simulation with the value 2 (seconds). As soon as the timer ran off, the event procedure on timer delayTimer is called, which outputs the CAN message sendMsg (resp. Msg1) with the current value of the signal bsSwitch and reinitializes the timer afterwards. If the environment variable evSwitch is modified by the simulation environment (e.g. by interaction of the user with a panel), the event procedure on envVar evSwitch is called which changes the value of the signal bsSwitch. The keyword this is available within an event procedure to access the data of the object (message or environment variable) that has just been received. Finally, here is the CAPL model to the node NodeB:
variables { message Msg1 sendMsg; } on message Msg1 { putValue(evLight, this.bsSwitch); }

4.5 Working with CANoe


After CANoe has been started, a database must be assigned. Now the bus participants are defined in the Simulation Setup window. To do this, insert the network nodes containing the same names as the corresponding panel. Furthermore, the corresponding CAPL program is also entered. In addition to these complex network nodes it is also possible to define simple generator blocks which transmit a message at the push of a button or periodically. There are also statistics windows available which display the bus load, transceiver component mode and the frequency of individual messages. In the Trace window it is possible to protocol the chronological order of the messages. Data windows provide additional information. This helps setting the environment variables that should be displayed and allows the operating controls to be checked too. After the simulation setup has been completely entered, all CAPL programs must be compiled. If no error occurs during this process, the simulation can be started.

22

Introduction to CAN

1. Creating a Database All messages in a system are managed in a database. This database is generated using the program CANdb. Names are assigned to all messages and signals using this program (see Figure 19). These names can then be used in a CAPL program and in CANoe. Furthermore, the environment variables are also defined here. They are used in the Panel Editor to access the control elements.

Figure 19: Definition of a CAN message in the database editor. 2. Creating Panels Control panels can be integrated into CANoe to display discrete and continuous environment variables. The Panel Editor is used for creating these panels and is available as an independent program. After the Panel Editor has been opened, a database must be first assigned to the new control panel. The control panel can only access the environment variables defined in this database. Individual control elements can now be placed on the panel graphically. Doubleclicking on the control element opens a menu where the environment variables that are valid for that element can be selected. Operating panels serve for the interaction with environment variables during a simulation and are provided with the panel editor. Subsequently, operation and/or visualization elements can be located graphically on the operating panel and environment variables (context menu) can be assigned to them. As control elements various buttons, switches, automatic controllers and indication areas for discrete or continuous environment variables are available. Switches and buttons can be illustrated with bitmaps (see panel in Figure 16). 3. Nodes Modelling According to Figure 15 a simulation structure in CANoe consists of individual blocks representing real or simulated nodes. For each node to be simulated an appropriate

Introduction to CAN

23

behavioural model must be programmed with the help of the CAPL Browsers. A database containing the CAN messages and environment variables must be assigned to each new CAPL model. Further information on the preparation of behavioural models with CAPL as well as examples can be seen in chapter 4.2, 4.3 and 7.2. 4. Configuration and execution of a simulation The configuration and execution of a simulation happens in the CANoe main program. Also here a database must be assigned as the first step. Subsequently, in the window of simulations structure the bus participants will be defined (see Figure 16). In addition, it is possible to insert nodes and to assign them appropriate CAPL models. Finally the operating panels must be merged. Before starting a simulation, all CAPL programs must be compiled. For evaluation different statistics windows exist, where bus load, condition of the Transceiver components and frequency of the individual messages can be measured. In the "Trace window" it is possible to log the temporal sequence from messages. By means of data windows further information is available.

24

Introduction to CAN

5 Tasks and Experiments


5.1 Conducting the Experiment
The objective of this experiment is to analyse the CAN message format using the recording and evaluating tool CANscope as well as to layout the CAN network for a basic automotive body electronic system (indicators, electric window lifter) using the simulation and development tool CANoe. The experimental system consists of a PC with installed CANoe V4.0 and CANscope V2.1 plus the recording module CANscope transmitting the recorded data to the PC via a RS232 port with variable baud rate. The connection to the CAN bus is made via the CAN connector of the recording module. The model process car door is connected to a CAN I/O-card (see Figure 20). Both ports of this CAN I/O-card must be connected to the CAN bus. The window lifter and the mirror adjustment of the car door can be controlled over the CAN interface of the model process (see appendix). The seat adjustment buttons on the inside of the car door have no function.

Figure 20: Experimental system. Both programs CANoe and CANscope are started using the Windows start menu. The database editor, the CAPL browser, and the panel editor can be started directly from the CANoe main program. Data is to be saved into corresponding subdirectories under D:\CAN-data\lab_wsXX-XX\GroupX. You will find bitmaps to illustrate the panel buttons in your respective subdirectories under D:\CAN-data\lab_wsXX-XX\GroupX\lab_bitmaps. All CANoe and CANscope configurations necessary to execute the experiments are available under D:\CAN-data\lab_wsXX-XX\GroupX\lab_template. For successful execution of this experiment, a thorough preparation should take place. Thereto, the preparatory tasks have to be completed in written form before beginning the experiment. It is also necessary to prepare the experiments reasonable.

Introduction to CAN

25

5.2 Introductory Tasks


Preparatory task 1: General questions about CAN: - How many different messages and how many different nodes are allowed in a CAN network? - Two messages, the first with the identifier 300, the second with the identifier 301 are sent simultaneously. Which message will be on the bus? Why? - When is the acknowledge slot bit put on the dominant level? - What is bit stuffing and what is the reason for it? - Why is the maximal transmission rate dependent of the extension of the CAN bus?

5.3 Analysis of the CAN Message Format


Preparatory task 2: Determine the bit sequence appearing on the bus, if a message with the identifier 100 and one data-byte with the value 0 is transferred faultlessly. The CRC sequence may not be taken into account. Mark both the MSB and the LSB of this data-byte. How does the bit sequence look like if two data-bytes are transferred instead of one? Find out the positions of the LSB and the MSB in the data field. Preparatory task 3: Determine the bit sequence appearing on the bus, if a remote frame requesting a message with identifier 100 is transferred faultlessly. The CRC sequence may not be taken into account. Preparatory task 4: After detection of an error, an error frame will be transmitted immediately and the current transmission is aborted. Determine the bit sequence of an error frame. The error flag (secondary) consists of 6 bits. Experiment 1: Record the different messages determined in preparatory tasks 2, 3, and 4 and check your results of these tasks. Thereto, start the CANoe main program and open the configuration experiment1.cfg under \lab_template. After that start the program CANscope and open the configuration experiment1.csc under \lab_template. Now define the trigger sources in the Trigger window, start the recording, and perform a simulation. All recordings have to be saved in your respective subdirectory. Do the recorded messages match with your results of the preparatory tasks?

5.4 Interpretation of CAN Messages


5.4.1 Control of the Wing Mirror Adjustment Different signals of a message are available to control the mirror adjustment of the model process car door. The CAN message and its signals are fixed by the interface of the car door (see appendix). During the operation of the wing mirror the following three messages were recorded using CANscope. You can see both the recorded bus levels and below the stuff bits.

26

Introduction to CAN

Figure 21: Message 1. Length: 66 bit.

Figure 22: Message 2. Length: 66 bit.

Figure 23: Message 3. Length: 68 bit. Preparatory task 5: What kind of movement performs the mirror for these messages? Thereto, encode the bit sequences shown in figure 19-21. Pay special attention to the data bytes order (see Figure 10 and Figure 13).

Introduction to CAN

27

Experiment 2: Configure a simulation in CANoe to control the mirror adjustment and record the messages referring to the different movements of the wing mirror. Proceed as follows: 1. Open the CANoe configuration experiment2.cfg. 2. Create a data base based on the CAN messages and signals necessary to control the mirror. 3. Configure a simulation using an Interactive Generator block and define the messages and trigger events (press of a key). It is not necessary to design a CAPL model. 4. Open the CANscope configuration experiment2.csc. 5. Define the trigger sources and start the recording. 6. Perform a remaining bus simulation. Does the system behave as expected? Do the recorded messages match with the ones of the preparatory task?

5.4.2 Display of Data on the Driver Display To display measured data in vehicles all data measured by sensors are transferred via CAN messages to different indicator elements. Often, the data measured by a sensor is used for different applications. Therefore, the data has to be transmitted in a suitable format for every recipient. Afterwards the receiver can evaluate the data and display it. A CAN message with several signals is also used to display data on the dashboard of a car. A single shot measurement with a baud rate of 80k is performed using CANscope. The recorded message has the following data field:

The message and its signals are defined as follows: dashboard: Identifier = 100; DLC = 6 Signals: - carspeed [km/h]: number of bits = 16; start bit = 0 - enginespeed [1/min]: number of bits = 13; start bit = 16 - tank [l]: number of bits = 10; start bit = 29 - temperature [C]: number of bits = 4; start bit = 39

The car speed is measured in steps of 0.2 km/h, i.e. a signal value of 1000d corresponds to the speed of 200 km/h. The engine speed as well as the fill level of the tank is directly transmitted whereas the temperature is measured in steps of 10 Kelvin. Preparatory task 6: Determine the values of the car speed, engine speed, fill level of the tank, and temperature of this message. Experiment 3: Send a message using the values determined in preparatory task 6 and record this message. For this, open the CANoe configuration experiment3.cfg as well as the CANscope configuration experiment3.csc. First of all, configure a measurement in CANscope. Choose the maximum number of samples as buffer size and a suitable number of samples as pretrigger. After this, perform a remaining bus simulation and enter the values which you have determined in preparatory task 6. Finally you have to define the trigger sources and to start the measurement. Is the data field of the recording the same as the one of task 6?

28

Introduction to CAN

5.5 Layout of CAN-Networks


5.5.1 Creating a first Simulation Model The indicator system of a car shall be realized using a CAN-based distributed body electronic system. Because of the distance, each indicator lamp must be connected to another node (see Figure 24). The indicator lamps of the system shall indicate turn left, turn right or alarm (all lamps blink). The blinking frequency shall be 1 Hz. The transmission rate shall be 80 kBaud.

Figure 24: Principle of the indicator system. Preparatory task 7: Which CAN messages and environment variables are required to model the indicator system? For each CAN message, following data are to be fixed: - Name of the CAN message - Identifier (maximum 11 Bit) - Data-Length-Code - Per signal: Name, number of bits, start bit For environment variables, following data are to be fixed: - Name of the environment variable - Data type of the environment variable Preparatory task 8: Design a CAPL model for each node of the indicator system. Use the messages and environment variables determined in task 7. Also use a timer to realize the blink frequency (see example in chapter 4.4) Experiment 4: Model and simulate the indicator system with CANoe. Proceed as follows: 1. Create a database based on the CAN messages and environment variables defined in preparatory task 7. 2. Create panels to visualize the lamps and to represent both the pitman arm and the warning key. 3. Realize the CAPL models designed in task 8. 4. Configure a simulation. Perform a simulation. Does the system behave like expected?

Introduction to CAN 5.5.2 Coupling the Model Process "Car Door"

29

The produced model shall now also control the window lifter of the car door. The control itself can be integrated in the centrally represented node in Figure 24. The car door is to be integrated as a real node into the simulation configuration. Preparatory-task 9: Enlarge your CAPL model of the central node from task 8, so that it can control the car door. Think first which further environment variables are required (e.g. to model the window lifter keys). The CAN messages to be used are already fixed by the interface of the car door (see appendix). Take storing of and moving to certain window position as well as mirror positions into account in your CAPL model. Experiment 5: Realize the supplements designed in task 9. For this, enlarge the database of experiment 4 in accordance to your results of task 9 (you will need some additional CAN messages and environment variables to control the door). Integrate the designed extensions of the central node into the corresponding model from experiment 4. Create panels to model the window lifter keys. Perform a remaining bus simulation with the car door connected. Does the car door behave as desired?

30

Introduction to CAN

6 Literature
[1] [2] [3] [4] [5] [6] [7] BOSCH: CAN Spezifikation, Version 2.0. 1991. DIN: Austausch digitaler Informationen Steuergertenetz (CAN) fr schnellen Datenaustausch, DIN ISO 11898. Beuth-Verlag Berlin, 1995. Etschberger, Konrad: CAN Controller-Area-Network: Grundlagen, Protokolle, Bausteine, Anwendungen. Carl Hanser Verlag Mnchen Wien, 1994. Lauber, R.; Ghner, P.: Prozessautomatisierung 1. 3. vollst. berarb. Aufl., Springer-Verlag Berlin Heidelberg New York, 1999. Reienweber, B.: Feldbussysteme. R. Oldenbourg Verlag Mnchen Wien, 1998. Vector Informatik GmbH: CANoe Arbeitsbuch. Stuttgart, 2000. Vector Informatik GmbH: CANscope Handbuch. Stuttgart, o.J..

Introduction to CAN

31

7 Appendix
7.1 CAN Interface of the Car Door
The car door can be controlled using the following CAN messages. As transmission rate, 80 kBaud are to be set. Message Window lifter ID (hex) Cycle DLC Signals 300 < 200 ms 1 Bit 0: left door Bit 1: right door Bit 2: Bit 3: squeeze protection off Bit 4: move to saved position Bit 5: save position Bit 6: window up Bit 7: window down 308 < 200 ms 2 Bytes Bit 0: mirror up 1 Bit 1: mirror down Bit 2: mirror left Bit 3: mirror right Bit 4: retract mirror Bit 5: extend mirror Bit 6: Bit 7: Bytes Bit 0: 2 Bit 1: Bit 2: Bit 3: Bit 4: button position 1 Bit 5: button position 2 Bit 6: button position 3 Bit 7: switching save/restore

Mirror adjustment

32

Introduction to CAN

7.2 Short CAPL Language Description


Data types integers, as used by the programming language C 64 bits floating-point numbers CAN message Timer, can not be initialized within the declaration. dword, long, word, int, byte, char: float, double: message: timer, msTimer: Access to control information

The following selectors can be used to access control information: ID CAN DLC DIR Message identifier Component number Data length code Transfer direction, event classification; possible values: RX Message has been received (DIR==RX) TX Message has been transmitted (DIR==TX) TXREQUEST A transmission request has been set for the message RTR Remote transmission request; possible values: 0 = no RTR, 1 = RTR TIME Time, unit: 10 microseconds Important CAPL functions

output (message msg) output (errorFrame) Function: Sends a message or an error frame from the program block. Parameter: "message" or "errorFrame" type of variable Example: output (sendMsg); int getvalue (EnvVarName) float getvalue (EnvVarName) Function: Determines the value of the environment variable with the identifier EnvVarName. The type of returned value depends on the type of environment variable (int for discrete environment variables, float for continuous variables) Parameter: Name of the environment variable Example: val = getValue(Switch); putvalue (EnvVarName, int n) putvalue (EnvVarName, float f) Function: Assigns a value of n or f to the environment variables with the EnvVarName identifier. Discrete environment variables are assigned integers, continuous environment variables are assigned floating point numbers. Parameter: Name and new value of the environment variable Example: PutValue(Lamp, 1); //sets value of Lamp environment variable to 1

Introduction to CAN

33

setTimer (msTimer t, long duration) setTimer (timer t, long duration) Function: Sets a timer. Parameter: Timer and msTimer variables and an expression that specifies the duration of the timer. Example: msTimer t; timer t1;
setTimer (t, 200); /* Set timer t to 200ms */ setTimer (t1, 2); /* Set timer t1 to 2s */

cancelTimer (msTimer t) cancelTimer (timer t) Function: Stops a running timer Parameter: Timer or msTimer variable Example: timer t;
cancelTimer (t);

long timeDiff (message m1, now) long timeDiff(message m1, message m2) Function: Time difference between messages or a message and the current time in ms. Parameter: 1. "message"-type variable 2. "message" or "now"-type variable Example: diff = timeDiff(sendMsg, now); write (string format, ...) Function: Displays a text message in the Write window. Parameter: Format string, variables or expressions Write is based on the c-function "printf". Allowed format entries: %ld: decimal display %lx: hexadecimal display %lo: octal display %lf: floating point %c: character output Example: i = 10; j = 12;
write (d = %ld, h = 0%lxh, i, j) /* result:> d = 10, h = 0ch < */

dword keypressed() Function: This function delivers the key code of the key currently being pushed. If no key is being pushed, it delivers a 0.

Das könnte Ihnen auch gefallen