Você está na página 1de 87

INtelligent TEchnology for COntrol Ltd.

Krakow, POLAND, E-mail: inteco@kki.krakow.pl www.inteco.cc.pl

RT-CON Professional
Reference Guide
Version 4.2

Krakow 2002

NOTES

MATLAB, Simulink, RTW and RTWT are registered trademarks of The MathWorks, Inc. Windows 95/98,NT/2000 are registered trademarks of Microsoft Corporation WATCOM is a trademark of WATCOM International Corp.

Copyright INTECO 2002. All rights reserved. Copyright 2000 PLX Technology,Inc.

RT-CON PROFESSI0NAL Reference Guide

Page 2

Contents 1. 2. 3. 4. 5. 6. Introduction.................................................................................................................................5 System configuration ..................................................................................................................9 2.1 HARDWARE REQUIREMENTS: .............................................................................................9 2.2 SOFTWARE REQUIREMENTS:...............................................................................................9 Installation ...................................................................................................................................9 Implementation overview.........................................................................................................10 Sample rate limits .....................................................................................................................11 Device drivers ............................................................................................................................12 6.1 GENERAL PURPOSE DRIVERS ............................................................................................13 6.1.1 Drivers for RT-DAC & RT-DAC3 boards.................................................................13 6.1.2 Drivers for PCL-812 PG board ................................................................................16 6.1.3 Drivers for RT-DAC4/PCI board .............................................................................16 6.2 DEDICATED DRIVERS FOR INVERTED PENDULUM-CART SYSTEM .....................................24 6.2.1 Inverted pendulum-cart system.................................................................................24 Building the program ...............................................................................................................26 Running the Program ...............................................................................................................28 8.1 RTW INTERFACE WINDOW ...............................................................................................29 8.2 EXTERNAL SIMULATION MODE .........................................................................................33 First application example: IBM-PC speaker..........................................................................34 9.1 IBM PC SPEAKER CONTROL MODEL (GUI MODE) ...........................................................34 9.2 BUILDING THE REAL-TIME APPLICATION ..........................................................................35 9.3 REAL-TIME EXPERIMENTS ................................................................................................36 9.3.1 Starting and terminating the experiment ..................................................................36 9.3.2 Signals plotting .........................................................................................................36 9.3.3 Simulink monitor.......................................................................................................38 9.3.4 Parameters tuning.....................................................................................................39 9.3.5 External simulation mode .........................................................................................39 Simulink model as a graphical front-end to the RTW DLL executable ..............................43 10.1 THE SIMULINK MODEL. NORMAL SIMULATION MODE ..................................................43 Application example: Simulink model for the pendulum system ........................................47 11.1 RULE BASED CONTROLLER ...........................................................................................48 11.1.1 Building the real-time application ...........................................................................50 11.1.2 Real-time experiment................................................................................................50 Inter-process communication functions..................................................................................53 12.1 DESTROYACQSTRUCT ..................................................................................................54 12.2 GETACQFLAG ...............................................................................................................54 12.3 GETACQSTRUCT ...........................................................................................................55 12.4 GETACQVECTLEN ........................................................................................................56 12.5 GETCHECKSUM ............................................................................................................56 12.6 GETDECIMATION ..........................................................................................................57 12.7 GETHISTORY .................................................................................................................57 12.8 GETMESSAGELEVEL .....................................................................................................58 12.9 GETMODELNAME .........................................................................................................59 12.10 GETNOOFOUTPUTBLOCKS ...........................................................................................59 12.11 GETNOOFOUTPUTS ......................................................................................................60 12.12 GETNOOFPARAMBLOCKS ............................................................................................61 12.13 GETNOOFPARAMS ........................................................................................................61 12.14 GETNOOFSAMPLES ......................................................................................................62 12.15 GETNOOFVECT ............................................................................................................63 12.16 GETOUTPUT ..................................................................................................................63 12.17 GETOUTPUTBLOCKDSRP ..............................................................................................64 12.18 GETPARAM ...................................................................................................................65
Page 3

7. 8. 9.

10. 11.

12.

RT-CON PROFESSI0NAL Reference Guide

13. 14.

15.

12.19 GETPARAMBLOCKDSRP ...............................................................................................65 12.20 GETSAMPLEPERIOD ......................................................................................................66 12.21 GETTIME .......................................................................................................................66 12.22 GETTRIGGER .................................................................................................................67 12.23 GETVERSION .................................................................................................................68 12.24 LOADLIBRARY ..............................................................................................................68 12.25 RESETTIME ...................................................................................................................69 12.26 SETACQSTRUCT ............................................................................................................70 12.27 SETACQVECTLEN .........................................................................................................70 12.28 SETDECIMATION ...........................................................................................................71 12.29 SETMESSAGELEVEL .....................................................................................................71 12.30 SETPARAM ....................................................................................................................72 12.31 SETTRIGGER .................................................................................................................72 12.32 STARTACQ ....................................................................................................................74 12.33 STOPACQ ......................................................................................................................74 12.34 UNLOADLIBRARY .........................................................................................................75 The S-function ...........................................................................................................................76 I/O access functions ..................................................................................................................80 14.1 MEX_BASEADDRESS ......................................................................................................81 14.2 INPORTB ........................................................................................................................81 14.3 INPORTD ........................................................................................................................82 14.4 INPORT ..........................................................................................................................82 14.5 OUTPORTB .....................................................................................................................84 14.6 OUTPORTD ....................................................................................................................84 14.7 OUTPORT.......................................................................................................................85 14.8 STARTIO.........................................................................................................................86 The device driver example .......................................................................................................86

RT-CON PROFESSI0NAL Reference Guide

Page 4

1. Introduction
This documentation describes RT-CON Professional: an open-architecture software related to Real Time Workshop (RTW) applications in the Windows environment. The RT-CON Professional extends the RTW for seamless and automatic real-time implementation of Simulink models. Unique for this solution is that a single low-costs computer can be employed as a development and target platform. This approach reduces the cost and time of development of a new application. The documentation can be considered as a supplement or replacement of chapter 9 of the Simulink. RealTime Workshop. Users Guide [1], and describes how to create and execute a real-time program using Simulink models, device drivers and specialised user interfaces. The next sections include: description of the RT-CON architecture and data flow between its modules, description of the device drivers and examples how to use them, instruction how to build the program, description of user interfaces allowing on-line access to process data and on-line tuning of the parameters of the real-time application, description of the library of functions supporting on-line information flow between the real-time program and the MATLAB environment, description of the library of I/O function allowing direct access from MATLAB environment to the external hardware. It should be emphasis that RT-CON was designed for real-time control and monitoring in the Windows environment. One of the main features of this software is a proper timing ensuring that data read from an external process or data sent to an external hardware will never be lost. Notice also, that the distinction should be made between the real-time operation of the executable file (referred to as RTW DLL executable) and on-line data flow between RTK (Real-Time Kernel) and MATLAB/Simulink. Only the first mechanism guarantees a proper real-time information exchange. It is assumed that a user of this software is familiar with MATLAB, Simulink and RTW Toolbox from MathWorks. The following abbreviations are used in the next sections: RTW RT-CON RT-DAC DLL GUI IPC - Real-Time Workshop - Real-Time Connection - Real-Time Data Acquisition Card - Dynamically Linked Library - Graphical User Interface - Inter-Process Communication

The following descriptions will be consequently used to describe how the Simulink model works: Normal Simulation Mode Simulink model is only simulated (non real time mode), GUI Mode model works in real time mode and special GUI (part of the RT-CON toolbox) tunes the parameters of the real time task, External Mode user can modify and tune block parameters in real time directly from Simulink model without recompiling of the model. The external mode mechanism included in RTW is used in this case.

RT-CON PROFESSI0NAL Reference Guide

Page 5

Model of the process

Project
Model of the controller

Input Driver

Model of the controller

Output Driver

Adding I/O drivers

Building the program

Process
General Simulink monitor for RTW
Select Simulation/Start to start monitoring
Show parameters Show outputs Ref.Pos.\Value(3) Scope

Inverted Pendulum/Memory1\X0 Convert to Phisical Units/Sum1\PendPos Alfa Normalization/AlfaNorm\PendPosOut Demux Inverted Pendulum/Gain\CartVel Scope6-UNCONNECTED Scope7-UNCONNECTED

Real Time Task

rtw_hist

Real-time controller

To Workspace
0.00

Scope8-UNCONNECTED

Clock

Scope9-UNCONNECTED Scope10-UNCONNECTED

Simulink

Fig. 1.1 General concept of the RTW/RT-CON application for a rapid prototyping of controllers Fig. 1.1 shows the general concept that comes within the scope of RTW and RT-CON. We wish to use MATLAB and Simulink to design, test and analyse a model of control or data system. Once the project is complete we can add appropriate input/output device drivers and generate an executable code directly from the Simulink block diagram. When the real-time program is running we can communicate with MATLAB and Simulink to capture and analyse data or to change parameters of the currently running real-time program. RT-CON Professional is suitable for control of variety of systems if these systems meet the specified hardware and software requirements (see section 2). An example of the configuration used for the rapid prototyping of the inverted pendulum control system [2] is shown in Fig. 1.2. The purpose of the inverted pendulum control algorithm is to apply a sequence of forces of constrained magnitude to the cart such that the pendulum starts to swing with an increasing amplitude and the cart does not override the ends of the rail. The pendulum is swung up to achieve a vicinity of its

RT-CON PROFESSI0NAL Reference Guide

Page 6

upright position. Once this has been achieved, the controller is maintaining the pendulum in the vertical position and is bringing the cart back to the centre of the rail. The pendulum-cart control system consists of: PC computer equipped with I/O board, pendulum and cart, encoder interface and DC motor driver, real-time control software automatically generated from the Simulink model in the Windows 95/98/NT environment. Notice, that all software tools and the final application are installed on a single PC. Hence, an integrated, low-cost platform for development of the real-time control systems is created.

cart & angle sensor

DC motor & position sensor

measurements control

power interface

I/O board
Running Windows 95/NT, MATLAB, Simulink, RTW and RT-CON, C-compiler

Fig. 1.2 The example of a typical system controlled by the RT-CON software package. Fig. 1.2 shows the hardware and software configuration used for running a real-time program. The executable code of the project is embedded in the RTW DLL executable file. The data required by the control algorithm or data acquisition algorithm are provided from external peripherals by the data acquisition board (I/O Board). At each timer interrupt the RTW DLL library performs all realtime procedures associated with a single sampling period. Typically, in this step it reads inputs from the I/O board, calculates the control signals and writes them to the outputs of the I/O board. The rtw_call is one of the most important procedure included in the software. It converts the format of data, which are exchanged between the RTW DLL library and the MATLAB environment. InterProcess Communication Protocol (IPC) is used to manage transfer of data between these two processes.

RT-CON PROFESSI0NAL Reference Guide

Page 7

PROCESS
COMPUTER

I/O Board

Win NT Dev.Driv.

Device Driver(s)
Timer Interrupts

RTW DLL Executable

RTW DLL Interface ( rtw_call.dll )

Simulink external mode Interface Windows 95 / NT / 2000

RT-CON Toolbox

MATLAB / SIMULINK

Inter-Process Communication Protocol

Fig. 1.3 General structure of the control system for MATLAB 5 and Windows NT. The operation of the RTW DLL executable can be monitored from MATLAB using the RT-CON toolbox. This toolbox contains the M-files and MDL-files. They extend the MATLAB environment in order to tune parameters of the RTW DLL library and to collect data from the real-time program. The external mode operation of the Simulink is another possibility of monitoring of the operation of the RTW DLL. This data transfer channel is pointed out in Fig. 1.3. The block Win NT Dev. Driv is marked as optional in Fig. 1.3. This special driver is required only by the Windows NT and W2K operating systems. It is due to the fact that the Windows NT operating system by default protects the microprocessor I/O space. The Win NT Dev. Driv block enables access to the RTW DLL executable.

RT-CON PROFESSI0NAL Reference Guide

Page 8

2. System configuration
The following basic configuration of your PC is required:

2.1 Hardware requirements:


Pentium or AMD based personal computer Microsoft Windows 95, Windows 98 (original and Second Edition), Windows NT 4.0 (with Service Pack 5 for Y2K compliancy or Service Pack 6a), or Windows 2000 I/O data acquisition board, equipped with A/D, D/A converters, digital I/O ports, network communication ports - the appropriate input-output interface configuration for the process to be controlled, power interface and wiring allowing electrical connections to the external process.

2.2 Software requirements:


For development of the project and automatic building of the real-time program it is required that the following software is properly installed on the PC: MATLAB version 5x or 6 with Simulink to develop the project and to monitor operation of RTW DLL library, Real Time-Workshop and RT-CON Professional to generate the code and to communicate with a running executable, device drivers to handle communication with the I/O data acquisition board. RT-CON Professional includes a variety of device drivers, between them the drivers for the PCL812 and RT-DACx multi-purpose I/O boards, as well as the specialised drivers for the Inverted Pendulum System. Refer to section 6 for details, Watcom C/C++ compiler, version 10.6 or 11.0 or MS Visual C++ can be used to compile the generated code. RT-CON version for MATLAB 6.1 uses the TCP/IP protocol for communication tasks. Therefore the TCP/IP protocol must be installed in the computer system.

3. Installation
The installation procedure of the RT-CON software is described in Real-Time Connection RTCON Installation Guide.

RT-CON PROFESSI0NAL Reference Guide

Page 9

4. Implementation overview
Fig. 4.1 illustrates the steps performed when the Build tab in the RTW dialogue box is activated and shows the flow of data during the execution of the real-time program. Figure 4.1 shows also the code modules used or generated when the real-time program is built.

SIMULINK MODEL.mdl

STEP1

mex.bat

Dev. Driv. DLL-files

C-Code Generator MODEL.c

TLC-files (rtw_dll.tlc)

Dev. Driv. C-files

Additional C-files

RTW C-files

MODEL.h MODEL.prm MODEL.reg MODEL.bio MODEL.pt MODEL.rtw

Build (rtw_watc.tmf)

Run Simulation in External Mode

STEP2

.\MODEL.rtc

rtw_load.m

To File MAT files MODEL.mat MODEL.lou MODEL.ler Running RTW DLL ext_rtw.dll

STEP3

rtw_unload.m

rtw_call.dll

MATLAB

GUI Interface (rtw.m)

MODEL.mat

- data - user-defined components

MATLAB

- program

Fig. 4.1. Automatic real-time program building and execution: files and information flow.

RT-CON PROFESSI0NAL Reference Guide

Page 10

The building and execution of a real-time program consists of the following main steps: STEP 1: STEP 2: STEP 3: generating the Simulink model (project), building the program: creating running the RTW DLL library, loading and running the program.

The source files used to create the real-time program and the new files generated during this procedure can be divided into the following categories: Simulink model (MODEL.mdl file), the main project developed by the user for his particular application (see sections 9-11 for examples). The appropriate device driver blocks must be added to the model. Device divers files can be selected from existing libraries or defined by the user, the C-code files generated from the Simulink block diagram (MODEL.c, MODEL.h, MODEL.prm, MODEL.reg, MODEL.bio, MODEL.pt). These files are defined for the Simulink model from which they are generated, the supporting C-code files. These include three groups of files. The device driver C-files are special format C-language files compiled to the DLL file format. The additional Cfiles are the part of the RT-CON software. They are designed for special tasks, like data acquisition in a cyclic memory buffer or service routines for time events. Finally, the RTW C-files are delivered with the RTW software and they are used to implement the real-time program, the DLL type library (MODEL.rtc; the rtc extension is used to distinguish the Simulink model and the DLL library in MATLAB command window), built by the RTW package using the rtw_watc.tmf template file used for linking all the necessary files. The DLL library is stored in the special MATLAB directory (MATLABROOT\RTW_DLL), running executable (RTW DLL), loaded by call to the rtw_load.m function. This library co-operates in real-time with the rtw_call.dll library which is responsible for MATLAB interfacing, the files created as a result of termination of the real-time program. These files store the information from the To Workspace blocks and scopes (MODEL.mat). It happens only if the Save to Workspace flag was applied. The warnings (MODEL.lou) and error messages (MODEL.ler) can be issued during execution of the real-time program. If the To file Simulink blocks are used then the appropriate MAT-files are created after termination of the DLL executable.

When the real-time program is executed several files are applied in order to organise and control the proper information flow between the real-time program and the MATLAB/Simulink environment: the rtw.m Graphical User Interface (GUI) windows (GUI mode), the ext_rtw.dll file responsible for communication with the Simulink model running in the external simulation mode, the rtw_unload.m removes the RTW DLL library from memory and terminates the experiment,

5. Sample rate limits


The timing of the real-time program is a crucial factor determining the range of control and data acquisition experiments you can perform using the RT-CON/RTW software. Several real-time tasks must be completed during a single sampling period. Typically they are: communication with external hardware, calculation of control signals and updating the contents of the data buffer.
RT-CON PROFESSI0NAL Reference Guide Page 11

The sample rate limit is the fastest rate of handling the interrupts. For the RT-CON Professional software sample rate is from 1ms to 32,768 seconds. The accuracy of the timer events handling depends on the CPU load and is typically equal to 50us (see Fig. 5.1) for the RT-CON Professional applications. The experiments show that the intensive usage of the HDD or multimedia devices can influence the accuracy of the timer events handling.
Sampling period duration [ms] 4.1 4.08 4.06 4.04 4.02 4 3.98 3.96 3.94 3.92 3.9 3.5 4 4.5 Time [s] 5 5.5 6

Fig. 5.1. Sampling period duration vs. Time (results of an experiment). The desired sampling period has been established to 4ms. Notice, that the minimal sampling rate also depends on: execution speed of the PC which varies with the type of a processor and clock frequency; model of the I/O board. The RT-DAC board, dedicated for fast real-time implementations is recommended; execution time of the model code. It can increase with complexity of the model, number of signals collected in the data acquisition buffer.

6. Device drivers
The generated RTW DLL library communicates with the I/O boards using C-code files referred as the device drivers. The driver software is the part of software that directly operates on the registers of I/O boards, managing its operation and its integration with the computer resources. Several device drivers were developed to support different I/O hardware configurations. They are grouped into two libraries: general-purpose device drivers; device drivers dedicated to the laboratory model of the inverted pendulum system. These drivers exemplify how to use the general-purpose drivers.
RT-CON PROFESSI0NAL Reference Guide Page 12

Any driver block from the library can be added to the Simulink model. The program building procedure automatically includes the blocks into the generated RTW DLL library. The library of drivers is called from MATLAB Command Window. To display this library type: rtcon at the MALAB prompt. The library of drivers opens (see Fig. 6.1). The general-purpose drivers are dedicated to the PCL 812PG board of Advantech [4], and to the: RT-DAC, RT-DAC3 and RT-DAC4/PCI boards of INTECO. Additionally, the IBM speaker driver is available.

Fig. 6.1 Drivers library

The dedicated drivers are available for the inverted pendulum laboratory system. They are design to use with a specified I/O configuration compatible to the external hardware. This example demonstrates how to use the dedicated drivers for different real-time controlled peripheries. 6.1 General purpose drivers 6.1.1 Drivers for RT-DAC & RT-DAC3 boards. Description of drivers for the RTDAC and RTDAC3 boards is the same. One difference is PWM driver which exists for RTDAC3 board only. If you click on the RT-DAC drivers block the window containing drivers for the RT-DAC board opens (see Fig. 6.1). The library consists of:
analogue input and output drivers, digital input and output drivers, incremental encoder driver.
Page 13

RT-CON PROFESSI0NAL Reference Guide

RT-DAC Analog Outputs

RT-DAC Analog Inputs

RT-DAC Incremental Encoders

RT-DAC Digital Outputs

RT-DAC Digital Inputs

RT-DAC Reset Encoders

Fig. 6.1 RT-DAC drivers Each driver block has a dialogue box that can be used to configure its particular options. Double clicking the icon to display the dialog box. If you click the RT-DAC Analogue Outputs icon (Fig. 6.2), you have access to the following fields: Base Address- it is the beginning of the I/O address space assigned to the board. The value specified in this field must match to the value fixed on the board. Refer to the manual of the board for details. Sample Time- it determines how frequently the driver code is executed. Remember that the Sample Time, determined for any I/O blocks, and the Step Size parameter determined in the Simulation Parameters dialog box (see section 7) must have a common divider.

Fig. 6.2 RT-DAC Analogue Outputs mask Fig. 6.3 shows the interior of the RT-DAC Analogue Outputs block. Notice that the block has only one input. As the RT-DAC board has two analogue output channels the output of your Simulink model must be vectorised with the Mux block (see example in Fig. 6.19).
1 in_1 DAC rtdac_da

Fig. 6.3 RT-DAC Analogue Outputs interior The dialog box for the RT-DAC Analogue Inputs block contains four fields (Fig. 6.4):
RT-CON PROFESSI0NAL Reference Guide Page 14

Base Address and Sample Time fields have the same meaning as described for RT-DAC Analogue Outputs block, Select channel - selects channels to be scanned during a single sampling. The channel number can be an integer ranging from 0 to 15. If the number of channel is duplicated it means that for this channel the A/D conversion is performed more than once during a single sampling period, Select gain - specifies the gain applied to the analogue inputs. To each channel corresponds the input signal gain. Refer to the RT-DAC board documentation for the available gains.

Fig. 6.4 RT-DAC Analogue Inputs mask Fig. 6.5 shows the interior of the RT-DAC Analogue Inputs block. Notice, that the block has only one output. As the RT-DAC board has sixteen analogue input channels, so the output from the driver is a vector. The width of the vector relates to the number of channels selected in the Select channel field.

rtdac_ad Analog Inputs

1 Outport

Fig. 6.5 RT-DAC Analogue Inputs interior The dialog box for the RT-DAC Digital Outputs block includes similar parameters as the RT-DAC Analogue Outputs block. The input to the block is a scalar value, which is converted to the 16-bit integer number. This integer value is use to set or reset the digital outputs. Similar rule is applied to the RT-DAC Digital Inputs block. The output from the block is the 16bit integer number corresponding to the 16 digital inputs of the board. The incremental encoder blocks can be used for communication with the encoder-type position and angle sensors. The Incremental Encoders block returns a vector of two numbers, which are obtained from the pair of the HCT-2016 incremental encoders. The parameters of the block are the same as these described for the RT-DAC Digital Outputs block. The Reset Encoders block is used to set an initial position of the HCT-2016 incremental encoders. The encoders are reset when the input to the block is equal to one.

RT-CON PROFESSI0NAL Reference Guide

Page 15

6.1.2 Drivers for PCL-812 PG board The library of the drivers for PCL-812PG board is shown in Fig. 6.1. The dialog box for each block can be displayed by double clicking the appropriate icon.

PCL-812PG Analog Outputs

PCL-812PG Analog Inputs

PCL-812PG Incremental Encoders

PCL-812PG Digital Outputs

PCL-812PG Digital Inputs

PCL-812PG Reset Encoders

Fig. 6.1 PCL-812PG Drivers There are not significant differences between the PCL-812PG and RT-DAC drivers. The meaning of the fields in the configuration dialog boxes is similar, but the Base Address has to be different if two or more boards are installed on a single PC.

6.1.3 Drivers for RT-DAC4/PCI board


The RT-DAC4/PCI is a new generation data acquisition board equipped with a programmable XILINX FPGA chip and PLX chip for communication with the PCI computer bus. The default logic implemented in the FPGA chip includes: 32 digital I/O, 4 D/A channels, 16 A/D channels, 4 PWM output channels, 4 encoder input channels, 1 counter and 1 timer. The library of the drivers for the RT-DAC4/PCI board is shown in Fig. 6.1. The dialog box for each block can be displayed by double clicking the appropriate icon. The RT-DAC4/PCI board is of the PCI type and the base address of the board is set automatically by the system. The RT-DAC PCI IO Base Address driver is used to detect the base addresses of the PCI boards equipped with the PLX chips. Remark: The RT-DAC PCI IO Base Address driver can be used in Normal Simulation Mode only. It can not be included in any Simulink model which be build to work in real time mode.

RT-CON PROFESSI0NAL Reference Guide

Page 16

Fig. 6.1 RT-DAC4/PCI drivers The dialog box for the RT-DAC PCI IO Base Address block contains four fields (Fig. 6.2): Bus number - when is equal to -1 driver returns the base address of the board plugged in the slot which number is written in the next field. Slot number - when is equal to -1 driver returns the slot number of the board which bus number is written in the previous field. When the both fields are equal to -1 the driver returns base address, bus number and slot number of any board mounted in the computer. Device ID - it is the unique PLX device ID saved on the board. If equal to -1 the driver returns Device ID of the board which bus number and slot number are set in the previous fields. Vendor ID - it is the unique vendor ID stored on the board. When equals to -1 the driver returns Vendor ID of the board which bus number and slot number are set in the previous fields.

If computer contains only one board with PLX chip you can type -1 in the all fields and all data are detected. In the case when the system is equipped with several RT-DAC4/PCI boards you have to enter the slot number of the board to detect its base address. To communicate with one of the boards the user must write the appropriate address in the mask of each used driver. The Device ID of the RTDAC4/PCI board is equal to 2497 (hexadecimal) and Vendor ID is equal to 10B5 (hexadecimal).

RT-CON PROFESSI0NAL Reference Guide

Page 17

Fig. 6.2 RT-DAC PCI IO Base Address driver mask The RT-DAC PCI Digital Directions driver is designed for setting digital I/O directions. Each of the 32 digital lines of the board can work as input or output. This driver must be placed in the Simulink model, which uses digital I/O channels. If you click the RT-DAC PCI Digital Directions block then Fig. 6.3 appears. The base address of the board is automatically detected by the mex_baseaddress m-function. You must write I (input) or O (output) to set the direction of each digital line. Note that RT-DAC PCI Digital Directions has not got inputs and outputs.

Fig. 6.3 RT-DAC PCI Digital Directions driver mask The dialog box for the RT-DAC PCI I/O block contains three fields and one check box (see Fig.

6.4).

The IO Base Address and Sample Time fields do not require explanation. The base address of the board is automatically detected by the mex_baseaddress m-function. The digital outputs can be set to 0 or to 1 at the end of the experiment. The next option allows to set each line separately.
Page 18

RT-CON PROFESSI0NAL Reference Guide

Termination Outputs digital number sets the values for all output lines, when a model (containing the driver) terminates action. This option is active when Set Outputs At Termination check box is marked.

Fig. 6.4 RT-DAC PCI Digital I/O driver mask The dialog box for the RT-DAC PCI PWM block contains six fields and one check box (Fig. 6.5): Base Address and Sample Time fields have the same meaning as it has been described previously. Channel - selects channel to be used during a single sampling. The channel number can be an integer number from 0 to 4. Channel mode sets 8 or 12 bit PWM working mode. The 8 bit mode enables the high speed and the 12 bit mode enables the high accuracy of an output. Refer to the RT-DAC4/PCI documentation for details.

Fig. 6.5 RT-DAC PCI PWM driver mask Channel prescaler number from 0 to 65535 corresponding to the period of the PWM wave. Refer to the RT-DAC4/PCI documentation for details.
RT-CON PROFESSI0NAL Reference Guide Page 19

The output of PWM can be set to fixed value at the end of experiment (when a working Simulink model stops). It is necessary (for example) when a user want to stop the DC motor after the experiment. The next option allows to set an appropriate value. Termination Outputs duty cycle of output when the model (containing the driver) stops. This option is active when the Set Outputs At Termination check box is marked. The description of the dialog box for the RT-DAC PCI Analog Outputs (Fig. 6.6) is similar to previous one but some fields require an explanation. Voltage range allows to set the range of analog outputs. The user can set the fixed values of the outputs at the end of experiment. Because Analog Outputs driver contains four outputs therefore the four elements vector has to be written in the Termination Outputs field. Each element of the vector is related to the appropriate output. This option is active when the Set Outputs At Termination is checked. When the Set Outputs At Termination check box is empty the values of output are equal to the values existing in the moment of the experiment termination.

Fig. 6.6 RT-DAC PCI Analog Outputs driver mask To select one of the four incremental encoder channels placed on the board click the RT-DAC PCI ENCODERS block and select the correct number (see Fig. 6.7). Note, that the RT-DAC PCI ENCODERS block has the Reset input. If Reset is set to 1 the value of encoder is set to zero. The normal operation of the encoder begins when the Reset input is set to zero.

RT-CON PROFESSI0NAL Reference Guide

Page 20

Fig. 6.7 RT-DAC PCI Encoder driver mask The RT-DAC4/PCI board includes two 32-bit timer and counter channels. The timer counts pulses of the internal board clock. The counter counts external pulses. The dialog box for the RT-DAC PCI Counter block contains three fields (Fig. 6.8). Base Address and Sample Time fields have the same meaning as has been described previously. The Channel fields enables to choose one of the counter channel. The number of channels depends on a type of logic loaded into the FPGA chip on the board. The dialog box for the RT-DAC PCI Timer block is the same as has been described for the counter block.

Fig. 6.8 RT-DAC PCI Counter driver mask The descriptions of the RT-DAC PCI Analog Inputs and RT-DAC PCI Analog Outputs drivers are omitted here because there are similar in operation for both RT-DAC4/PCI and RT-DAC boards. If you like to see how to apply the RT-DAC PCI board drivers click the Device Drivers Examples block and Fig. 6.9 appears. The examples contain the Simulink models equipped with the previously defined drivers.

RT-CON PROFESSI0NAL Reference Guide

Page 21

Fig. 6.9 RT-DAC PCI Drivers Examples These examples may serve as testing tools for the installed RT-DAC4/PCI board. The Simulink models must operate in the Normal Simulation mode. It means that it is not necessary to build (to compile) the model because the real-time code is not required. The hardware such as a generator, an oscilloscope, a voltmeter and a power supply is required to generate the input signals and to measure the output signals. The models may show all input and output signals used by drivers. These models are very simple hence they are not described in detail. Fig. 6.10 presents the Simulink model for testing the analog outputs of the RT-DAC4/PCI board. To measure the analogue outputs you should connect the voltmeter to A/O 0, A/O 1, A/O 2 and A/O 3 pins of the CN2 connector on the board (see RT-DAC4/PCI Users Manual). Next click the Simulation/Start option in the model window and observe the measurements.

Fig. 6.10 RT-DAC PCI Analog Outputs

RT-CON PROFESSI0NAL Reference Guide

Page 22

Double click the IBM-PC Speaker Driver icon results in displaying the dialog box (Fig. 6.11). The driver controls the PC speaker which generates a sound of frequency corresponding to the value of the input signal. You have access to four fields: Sound type - selects the type of sound. In the case of the impulse mode the driver does not require any input signal; Continuous - specifies four parameters of the continuous sound. The following parameters are defined: minimum and maximum value of the driver input signal and upper and lower limits of its frequency; Impulse - specifies how often the sound of a given frequency is generated. For example, the parameters in Fig. 6.11 specify that the sound of the 1000Hz frequency is generated at every of 50 sampling periods.

Fig. 6.11 IBM PC Speaker Driver mask The C-source codes of all drivers from Fig. 6.1, Fig. 6.1 and Fig. 6.1 are available in the following C-files. Device drivers for RT-DAC* multi I/O board: RTDAC*_AD.C analogue input RTDAC*_DA.C analogue output RTDAC*_DI.C digital input RTDAC*_DO.C RTDAC*_IE.C RTDAC*_RE.C RTDAC3_DI.C digital output data from incremental encoders reset incremental encoders PWM control

Device drivers for PCL-812 PG multi I/O board: PCL_AD.C PCL_DA.C PCL_DI.C analogue input analogue output digital input PCL_DO.C PCL_IE.C PCL_RE.C digital output data from incremental encoders reset incremental encoders

Device drivers for RT-DAC4/PCI multi I/O board: RTDACPCI_AnalogInputs.C RTDACPCI_BaseAddress.C RTDACPCI_DigitalDirections.C RTDACPCI_DigitalOutput.C RTDACPCI_PWM.C RTDACPCI_AnalogOutputs.C RTDACPCI_Counter.C RTDACPCI_DigitalInput.C RTDACPCI_Encoder.C RTDACPCI_Timer.C

RT-CON PROFESSI0NAL Reference Guide

Page 23

6.2 Dedicated drivers for inverted pendulum-cart system


If you use the PCL-812PG Advantech board or RT-DAC INTECO board in your data acquisition or control applications then you can combine and use the drivers according to your needs. In this section we briefly describe how to build the peculiar drivers, dedicated for the inverted pendulum-cart system. The drivers developed for the inverted pendulum-cart system consist of the basic drivers taken from the drivers library and typical Simulink blocks. Finally, one obtains the models ready to handle the inputs and outputs in real time from the peripheral hardware.

6.2.1 Inverted pendulum-cart system


One analogue output signal (Control) is applied to DC motor and two digital inputs signals (Pend_pos and Cart_pos) i.e. pendulum position and cart position are measured by two encoders (see Fig. 6.1). The sensor driver generates two velocities (Pend_vel and Cart_vel) on the basis of the position signals. The unmasked driver blocks are shown: Sensors in Fig. 6.2 and Actuator in Fig. 6.3. For the Sensors driver the pendulum and cart position signals are multiplied by the resolution coefficients to obtain the pendulum angle measured in radians and cart position measured in meters. The following velocities are calculated: pendulum velocity in [rad/s] and the cart velocity in [m/s] (a difference of two successive position measurements is divided by the sampling time T0). For the Actuator driver there is one control input signal generated by the control algorithm. The second signal passed to the driver block is the reference signal equal to zero. Both signals are multiplied by the D/A converter constant value. The I/O boards are equipped with 12 bit D/A converters. Assuming that the Control signal in Fig.6.19 is in the range [1, +1] the multiplier coefficient is equal to 2047 and the D/A converter is excited by an integer in the range from 0 to 4094.
RES ET ENCODERS P CL-8 1 2

Pend _pos P end_v el

C ont rol

P E N DUL UM P C L -8 1 2 A ctu a to r

P E ND UL UM
C art _pos

P CL -8 1 2 S e n so rs

C art _v el

RES ET ENCODERS RT-DAC

Pe nd_pos C ont rol

P E NDUL U M RT -DA C _ A ctu a to r_

P E ND UL UM RT -DA C _ S e n so rs_

P end_v el C art _pos C art _v el

Fig. 6.1 Inverted pendulum drivers

RT-CON PROFESSI0NAL Reference Guide

Page 24

1 Pend_pos

Pend_pos

1 Gain1 Sum Memory

2 Pend_vel

Pend_v el

1/T0 Gain2 convert

3 Cart_pos

Cart_pos

1 Gain3 Sum1 Memory1

Demux

[ pi/1024 1.055/13292 ] PCL-812PG Incremental Encoders

4 Cart_vel

Cart_v el

1/T0 Gain4

Fig. 6.2 Interior of the Sensors driver

Fig. 6.3 Interior of the Actuator driver The encoders require a resetting action. The Reset Encoders driver is added (Fig. 6.4 and Fig. 6.5). The PCL-812PG Reset Encoders device driver resets the encoders when the input signal is equal to one. The model from Fig. 6.5 resets the encoders if only the input signal changes its value. This operation can be also performed using the mask presented in Fig. 6.4 (the field Trigger).

1 Trigger

~=

Reset

Relational Operator

PCL 812 PG Reset Encoders

Fig. 6.5 Interior of Reset Encoders block Fig. 6.4 Reset Encoders mask

RT-CON PROFESSI0NAL Reference Guide

Page 25

7. Building the program


Assume we made the following model:

Fig. 7.1 Simulink model (example) Once a system has been designed in Simulink the code for the real-time control can be generated, compiled, linked and downloaded into the processor. To perform that one uses the Target Language Compiler to generate the TLC code (see the Simulink Target Language [5]). The makefile is used to build and download the object files to the target hardware automatically. First, one must specify the simulation parameters of his Simulink model in the Simulation parameters dialog box. The RTW page appears when one select the RTW tab (Fig. 7.2). The RTW page allows one to set the real-time build options and then to start the RTW DLL executable file building process.

Fig. 7.2 RTW page of the Simulation parameters dialog box The rtw_dll.tlc is the system target file. It manages the code generation process.
RT-CON PROFESSI0NAL Reference Guide Page 26

The rtw_watc.tmf is the template makefile prepared for C code generation using the WATCOM compiler. For Microsoft Visual C/C++ compiler the rtw_vc6.tmf (Matlab 5) or rtw_vc.tmf (Matlab 6) template makefile must be used. In the window there are three options which must be properly marked, as presented in Fig. 7.2: Inline parameters - not to be used when building a real-time program, Retain.rtw file - if it is marked, an auxiliary information is stored in the file (with .rtw extension), Generate code only - if it is marked, a code is generated but compilation is not performed. The Solver page appears when one selects the Solver tab. (Fig. 7.3). The Solver page allows one to set the simulation parameters. Several parameters and options are available in the window.

Fig. 7.3 Solver page of the Simulation parameters dialog box The Fixed-step solver is obligatory for real-time applications. The Fixed-step size is a sampling period (in the example is set to 0.01 [s]). If one uses any block from the discrete Simulink library or a block from the driver library one must remember that different sampling periods must have a common divider. The Start time must be set to 0. One can select: ode5, ode4, ode3, ode2, ode1 or discrete integration method. In the example ode4, the fourth-order Runge-Kutta formula, was chosen. If all parameters are set properly one can start the building of the DLL executable process. For this purpose press the Build push button on the RTW page (Fig. 7.2). A successful compilation and linking process should be finished with the following announcements: ### Created executable: MODEL.RTC ### Successful completion of RTW build procedure for model: MODEL If not, error massages will be displayed in MATLAB Command Window.

RT-CON PROFESSI0NAL Reference Guide

Page 27

8. Running the Program


To load the generated real-time program click Start button in the Simulink model or the following command must be executed in MATLAB Command Window: rtw_load( ' model_name' ) where the model_name is the name of your Simulink model. After that the following window appears (Fig. 8.1).

Fig. 8.1 Loading a real-time program (PC-speaker example) When one press the OK push button the real-time application starts. To terminate the running real-time program execute the following command: rtw_unload (or click STOP button in your Simulink model) which terminates the experiment and displays the message box presented in Fig. 8.2.

Fig. 8.2 Terminating an experiment The data flow during the program execution is shown in Fig. 8.3. The RT-CON Toolbox contains ready-to-use Graphical User Interface (GUI) which allows the following on-line operations: rtw.m -the interface file: using this file one can define the outputs and parameters to be displayed or tuned, rtw_plot.m and rtw_tune.m files: GUI for plotting data and tuning the parameters, rtw_gm - Simulink general-purpose monitor. Fig. 8.3 illustrates how the rtw.m interface file (see Fig. 8.1) communicates with: the rtw_plot.m responsible for plotting file (see Fig. 8.2), the rtw_tune.m responsible for tuning file (see Fig. 8.3) and the rtw_gm.mdl general-purpose RT-CON monitoring file (see Fig. 8.4) which co-operate with the rtw_gmsf.m general-purpose RTW monitor S-function.

RT-CON PROFESSI0NAL Reference Guide

Page 28

External simulation

rtw_codf.m Running RTW DLL

MODEL.out

rtw_cpdf.m

MODEL.par

rtw_call.dll

rtw_unload.m

ToFile MAT-files MODEL.mat MODEL.lou MODEL.ler

rtw_plot.m

rtw.m

rtw_tune.m

rtw_gm.mdl

rtw_gmsf.m

Fig. 8.3 Graphical User Interface m-files Additionally, all parameters of the generated real-time program can be changed using the external simulation mode. This mode must be marked in the Simulink model window which has been used to generate ones real-time program. In this case, the external simulation mode available in the Simulation menu option allows to exchange parameter data between the Simulink model and the real-time application.

8.1 RTW Interface window


To open RTW Interface window (Fig. 8.1) type rtw command at the Matlab prompt. Execute this command when the real time program is loaded. In the RTW Interface window the user must select outputs and parameters to be visualised or available for tuning during the real-time session. The three push buttons are available in this window: Plot it starts the rtw_plot application, which displays time diagrams of the outputs and parameters selected in the RTW Interface window (see Fig. 8.2), Tune displays edit fields and sliders which can be used for modifications of the parameters selected in the RTW Interface window (see Fig. 8.3 for an example),

RT-CON PROFESSI0NAL Reference Guide

Page 29

Simulink monitor displays the Simulink model which must be executed in the normal simulation mode and is able to display the selected outputs and parameters using a typical Simulink display devices (see Fig. 8.4).

Fig. 8.1 RTW Interface window

Fig. 8.2 Example of the rtw_plot window

RT-CON PROFESSI0NAL Reference Guide

Page 30

Fig. 8.3 Example of the rtw_tune window

Fig. 8.4 Simulink monitor The Plot parameters menu option displays the window presented in Fig. 8.5 which selects the mode of data acquisition procedures. The fields from Fig. 8.5 have the following meaning: Plot length - defines the length of the time axis in the rtw_plot window, scaled in seconds. This parameter is used only in the Continuous mode, Buffer length - defines the number of samples in the data acquisition buffer. It is used in the Single and Triggered data acquisition modes,

RT-CON PROFESSI0NAL Reference Guide

Page 31

Fig. 8.5 Plot parameters window Trigger - defines the parameters of the software trigger. The trigger signal is selected from the list-box located on the top of the Trigger frame and is used to start data acquisition process. The trigger parameters are as follows: Mode - selects the data acquisition mode. In the Continuous mode the trigger signal is neglected and the data acquisition process must be started and terminated by the user. In the Single mode the Start option from the rtw_plot window is used to perform a single data acquisition operation. In the Triggered mode the single data acquisition is started when the triggering condition described bellow are fulfilled, Trigger event - determines the relations between the current value of the trigger signal and the value defined in the Signal level field which generates the trigger event. The occurrence of the trigger event starts data acquisition. For example, if the Signal level is equal to 0 and the Rising box is marked the trigger event will be generated only if the trigger signal crosses the zero level from negative to positive values, Signal level - determines the value of the trigger signal, which generates the trigger event, Trigger offset - defines how many samples will be collected in the data acquisition buffer before the trigger event will be generated. For example, let us assume that the length of the data acquisition buffer is 1000 samples. In such a case if the Trigger offset field is 200 it will result in storing only of 800 samples after the occurrence of the trigger event. The proceeding 200 samples will be stored after the data acquisition is started but before the trigger event is detected.

RT-CON PROFESSI0NAL Reference Guide

Page 32

8.2 External simulation mode (Matlab ver. 6 only)


The Simulink model which has been used to generate the real-time executable can be simulated in the external simulation mode. This mode enables to change all parameters directly from the Simulink model. In this case the tune window (e.g. Fig. 8.3) is not necessary. Before building and starting the simulation in the external mode the Tools/External Mode control panel/Target interface options must be set, as presented in Fig. 8.1.

Fig. 8.1 External Target interface dialog box On this page the ext_comm. mex-file name for the external interface is defined. This file manages communication between the Simulink model and the running RTW DLL program in the External simulation mode. These changes can be introduced by the use of MATLAB, which communicates with the DLL library. Next open Simulation/Simulation parameters/Real Time Workshop dialog box and select RT-CON code generation options in Category item and then mark External mode check box.

Fig. 8.2 Real Time Workshop dialog box Next, the Simulation/External option must be marked in the Simulation menu in the Simulink model window. To start the External mode simulation click Start button in the model window. In the external simulation mode the parameters may be changed immediately from the Simulink blocks. Any change of parameters in any of the Simulink block of your model is transferred immediately to the running real-time program.

RT-CON PROFESSI0NAL Reference Guide

Page 33

9. First application example: IBM-PC speaker


Each IBM PC computer is equipped with a speaker, which is controlled by electronic circuits located on the motherboard. This chapter explains how to build, execute and tune a RTW Simulink model, which controls a frequency of the generated sound. This example can be treated as a first practical with the RT-CON professional package. The example is simple because it does not require any I/O board plugged into your PC computer, but complex enough to test compilation, linking, running and tuning procedures.

9.1 IBM PC speaker control model (GUI mode)


The Simulink model used to control the PC speaker is presented in Fig. 9.1. It may be called from the rtcon window (Fig. 6.1) .

Fig. 9.1 Simulink model of the IBM-PC speaker The Simulink model from Fig. 9.1 consist of three important blocks: IBM PC Speaker Driver, START and STOP. The body of the IBM PC Speaker Driver block is presented in the Fig. 9.2. It contains the Sfunction block, which calls the pc_spkr S-function. The C-source code of the S-function is a part of the RT-CON software. The body of the S-function uses input values to set the frequency of the generated sound. The parameters of the IBM PC Speaker Driver block have been described in section 6.
1 in_1 SPEAKER
1 1

pc_spkr

Fig. 9.2 The IBM PC Speaker Driver block The START block is used to execute the real-time application created by the RTW/RT-CON package. The action of the block is the same as rtw_load(model_name) command from Matlab
RT-CON PROFESSI0NAL Reference Guide Page 34

Command Window. When the real-time application is created the double-click on this block starts an experiment. The function associated with the double-click action may be shown by executing the get_param command. The execution of the command: get_param( gcb, ' OpenFcn' ) for the selected START block returns: rtw_load( get_param( 0, ' CurrentSystem' ); ) This is the command which starts the execution of the real-time application. The STOP block is used to stop experiment and is built similarly to the START block.

9.2 Building the real-time application


To create an executable real-time application (working in GUI mode) of the pc_speaker Simulink model, the correct values of option in the Simulation Parameters/RTW menu must to be selected. The right set-ups are presented in Fig. 9.1.

Fig. 9.1 RTW Options set-ups Only the Solver and RTW tabs contain critical parameters. Note that Fixed-step size option is set, rtw_vc.tmf template file is used (VC++ compiler) and External mode is unchecked. To start the building process press the Build push button from the RTW tab. Messages associated with the building process are displayed in the MATLAB Command Window.
RT-CON PROFESSI0NAL Reference Guide Page 35

If the building process completes successfully the following messages are displayed: ### Created executable: pc_speaker.RTC ### Successful completion of RTW build procedure for model: pc_speaker

9.3 Real-time experiments


There is a set of tools available for parameter tuning and data acquisition, which may be used during real-time experiments.

9.3.1 Starting and terminating the experiment


To start an experiment double-click the START block. The window appears (Fig. 9.1).

Fig. 9.1 Starting the experiment Press the OK button to run the real-time program. To terminate the experiment double-click the STOP block. The message window appears (Fig. 9.2).

Fig. 9.2 Terminating the experiment Press the OK button to finish the real-time application. The actions presented above are equivalent to the application of the following commands in the MATLAB command window: rtw_load( ' pc_speaker' ); which starts the experiment and: rtw_unload; which terminates the experiment.

9.3.2 Signals plotting


The scopes included in the model do not work in the non-external mode. For reason of it the particular command (rtw) was designed to observe all signals of the real time task. The values of all parameters and all outputs from all the blocks of the Simulink model are available. The selected values may be displayed in the form of time diagrams. To display the list of all available parameters and outputs rtw command must be executed. This command can be used only when the RTW executable is running. The RTW window created by the rtw command for the pc_speaker example is presented in Fig. 9.1.

RT-CON PROFESSI0NAL Reference Guide

Page 36

Remark: in Matlab 6.1 Fig. 9.1 opens automatically.

Fig. 9.1 RTW Interface window for the IBM PC speaker The model contains 21 parameters and outputs. The names of all parameters are displayed in red and the names of all outputs are blue. The names of the outputs and parameters in the RTW Interface window are related to the blocks and parameters names in the Simulink model (Fig.9.1). Each parameter and output may be selected by marking an appropriate check-box. For example, select the Integrator1\x1, Integrator1\x1 and Sum\NULL elements and after that press the Plot push button. Such an action displays the window presented in Fig. 9.2. The time diagrams appear after pressing the Start menu option. Pressing the Autoscale option automatically changes the scale of all diagrams.

Fig. 9.2 Plot window for the IBM PC speaker The Plot parameters option from the rtw window gives the ability to change parameters of the plot window and to change parameters of the data acquisition procedure built into the real-time application. For example, the window presented in Fig. 9.3 sets the triggered data acquisition mode.

RT-CON PROFESSI0NAL Reference Guide

Page 37

The Integrator1\x1 signal is selected as the trigger signal. The rising Trigger event is selected so that the data acquisition starts when the Integrator1\x1 signal crosses the Signal level value from values smaller then 0.5 to values greater then 0.5. The data acquisition buffer length is set to 1000 points. The Trigger offset value equal to 250 means that 250 samples will be stored in the data acquisition buffer before the trigger event occurs.

Fig. 9.3 Plot parameters window for the IBM PC speaker The results of the selected data acquisition options are presented in Fig. 9.4.

Fig. 9.4 Result of the triggered mode data acquisition

9.3.3 Simulink monitor


The signals selected in the RTW window can be displayed in scopes of the Simulink monitor. Press the Simulink monitor push button. The displayed model contains the Scope blocks associated with the selected signals (Fig. 9.1).
RT-CON PROFESSI0NAL Reference Guide Page 38

The Simulink monitor and the Plot window are using the same data source, so they must not be executed simultaneously.

Fig. 9.1 Simulink monitor window for the IBM PC speaker Starting simulation of this model enables to display the values of selected signals. The simulation of this model is performed in Normal mode.

9.3.4 Parameters tuning


The RTW window creates an interface to the another window which enables tuning of parameter for the pc_speaker model. The interface is called by pressing the Tune push button. For example, if the Saturation/Lower and Upper Limit parameters were selected the tune window presented in Fig. 9.1 is displayed. It contains edit windows and sliders which may be used to change on-line the range and the current values of the selected parameters.

Fig. 9.1 Tune window for the IBM PC speaker

9.3.5 External simulation mode (Matlab ver. 6 only)


The pc_speaker can be simulated in the external simulation mode. This mode enables to change all parameters directly from the Simulink model. In this case the tune window (Fig. 9.1) is not necessary. Additionally in the external mode the scopes included in the Simulink model allows to observe all wanted signals. In the Simulink model the new Remove button appeared (Fig. 9.1) which removes real time task from memory when experiment is stopped. Open Simulation Parameters and click Real Time Workshop tag. The appropriate parameter set of compilation for Visual C++ is presented in Fig. 9.3. Note that Template makefile is named rtw_vc.tmf. For the Watcom compiler Template makefile is named rtw_watc.tmf. These files are loaded to the proper directory during the installation process of RT-CON. At the beginning set Simulation/External option. Before building the model right options of simulation in the mode RTW

RT-CON PROFESSI0NAL Reference Guide

Page 39

tab and in the Tools/External Mode control panel/Target interface must be set, as presented in Fig. 9.3.

Fig. 9.1 PC_speaker model for external mode

Fig. 9.2 Simulation Parameters/Real Time Workshop tag with the configuration for Visual C++ Open the Category list and choose RT-CON code generation options (Fig. 9.3). Now, you can set options of the generated code in the External mode checkbox. External simulation mode is selected instead of Normal mode.

RT-CON PROFESSI0NAL Reference Guide

Page 40

Fig. 9.3 RTW and Tools/External Mode control panel/Target interface To start the building process press the Build push button from the RTW tab. Messages which follow the building process are displayed in MATLAB Command Window. If the building process completes successfully the following messages are displayed: ### Created Real-Time Windows Target module pc_speaker_vc.rwd. ### Successful completion of Real-Time Workshop build procedure for model: pc_speaker_vc To start an experiment click the START block in the model window. The window given in Fig. 9.1 appears. Click OK and then and then real-time task starts. The scopes presented in Fig. 9.4 show the outputs from the Van der Pole equation and the sound from the PC speaker is heard. Attention: The plots in the scopes appear only if the Visual C++ compiler has been used. When you use the Watcom compiler these plots are not visible.

Fig. 9.4 Scopes of the PC-speaker model (external mode) In the external simulation mode the parameters may be changed immediately from the Simulink blocks. Click IBM PC Speaker Driver and the driver window presented in Fig. 9.5 appears. To change the sound from the impulse to continuous form write 1 (one) in the Sound type edit field. You should hear a modulated continuous sound of the PC speaker.

RT-CON PROFESSI0NAL Reference Guide

Page 41

Remarks: Remember you can change the parameters in the Simulink model window if the model operates in External mode . In this case the GUI interface, called by the rtw command, does not work. To stop the experiment, click the Stop Disconnect button in the model window. This action stops working model and disconnects real-time code from the MATLAB environment. The DLL library of the real-time code exists still in the memory and must be removed. Click the Remove button. If you do not perform the last action the next loading of the model is impossible.

Fig. 9.5 Options of the IBM PC Speaker Driver block

RT-CON PROFESSI0NAL Reference Guide

Page 42

10. Simulink model as a graphical front-end to the RTW DLL executable


This section contains the description of the rtw_gm Simulink model. This model is applied as a graphical front-end for the RTW DLL executable. It operates in the normal simulation mode and allows monitoring of parameters or signals, which are accessible in the RTW DLL running executable. The rtw_gm Simulink model allows data visualisation using the standard Simulink graphical blocks. It is very useful tool in Matlab 5.3 which version doesnt allow using Scope blocks in models working in the real-time mode. The Simulink rtw_gm model can be treated as a template for developing new graphical frontends. They may contain any Simulink blocks. The following blocks are especially useful for real-time monitoring: Scope, XY Graph, Display, To File, To Workspace, filters, etc. The Simulink graphical front-end to the RTW DLL executables consist of two main parts: the Simulink model and the S-function. The Simulink model is responsible for passing data to all the blocks and displaying the values of the selected signals and parameters. The S-function uses InterProcess Communication functions to read data from the running RTW DLL. It is also responsible for time synchronisation between the running RTW DLL and SIMULINK model. The time synchronisation guaranties that time of the running RTW DLL and the rtw_gm model are consistent. The rtw_gm Simulink model is called from the rtw GUI interface window. The rtw automatically modifies the model to plot the selected parameters and signals. Notice, that there is the significant difference between the basic Simulink model which was used to generate the RTW DLL and the rtw_gm Simulink model. The first one defines all the operations which are performed by the running RTW DLL executable. Typically, it contains the measurement algorithm, algorithm of the controller and algorithm used to control the actuators. These algorithms defined inside a typical Simulink model, are in the form of the set of blocks and connection between them. This model can be executed in the external simulation mode while the RTW DLL library is running. It allows parameter tuning by changing its values direct on the Simulink model. The rtw_gm Simulink model reads values of the selected parameters and signals and makes them available for the blocks included in the model. The rtw_gm model can be executed (executed means starting the Simulation in Normal mode) while the RTW DLL is running. The rtw_gm Simulink model can be run for all RTW DLL libraries. For each model the rtw_gm requires new definitions of signals and parameters in the rtw GUI window.

10.1 The Simulink model. Normal simulation mode


The rtw_gm Simulink model is presented in the Fig. 10.1. The main block of the rtw_gm model is the Real Time Task. It contains the S-function block which is responsible for the data exchange between the model and the running RTW DLL. Inside this block the user can define which parameters and outputs are sent to the output of the block (it is done automatically when the rtw_gm model is activated by the rtw window). The output of the Real Time Task contains values of all selected parameters and outputs. The Show parameters and Show outputs blocks display the windows containing the detailed information about sizes and indexes of parameters and outputs. This information is necessary to select appropriate parameters and outputs. The output of the Real Time Task is sent to the demultiplexer and then can be plotted on the scopes. Simultaneously, it is sent, together with time from the Clock block, to the To Workspace block. The data from the To Workspace block are available as the rtw_hist variable in the MATLAB workspace after termination of the simulation of the rtw_gm block.

RT-CON PROFESSI0NAL Reference Guide

Page 43

G e n e ra l S im u lin k m o d e l fo r R T W D L L s S e le c t S im ula tio n/S ta rt to s ta rt m o nito ring


S h o w p ar a m et e r s
S cope1 S cope

Sho w o utputs

S c op e 2

S cope3

S c op e 4

S cope5

R e a l Tim e Ta s k

S c op e 6

S cope7

rtw _ h is t
S c op e 8

T o W o rk s p a c e

C lo ck
S cope9

S c op e 10

Fig. 10.1 The rtw_gm Simulink model The contents of the Real Time Task block is presented in the Fig. 10.2. It contains the S-function block. The S-function block calls the rtw_gmsf function. This function is described in the next section.
rtw_gmsf 1 out_1 RTW DLL Real-Time Task

Fig. 10.2 The contents of the Real Time Task block The parameters for the S-function block are defined as presented in the Fig. 10.3. Except the S-function name it contains the three S-function parameters: out_par, out_out and ds. They define the indexes of parameters and outputs sent to the output of the S-function block and the decimation factor, respectively. The decimation factor decreases the amount of data on the output of the S-function block. For instance, if it is equal to 5 only one sample per five is sent to the output. It may be necessary to define this factor greater then 1 if the computer system is not able to plot the large data stream in a graphical manner.

RT-CON PROFESSI0NAL Reference Guide

Page 44

Fig. 10.3. Parameters of the Real Time Task block The Real Time Task block is masked. The definition of the mask is presented in the Fig. 10.4. It contains three variables. In the Fig. 10.5 definition of the variables is presented. It contains the indexes of two parameters, indexes of eight outputs and the decimation ratio. Such a definition causes that the rtw_gmsf S-function sends to the its output the values of two parameters and eight output signals. The order of signals in the output vector of the S-function is defined by the order of the indexes.

Fig. 10.4. The mask definition of the Real Time Task block

RT-CON PROFESSI0NAL Reference Guide

Page 45

Fig. 10.5 The definition of parameters of the Real Time Task block The Simulink model presented in Fig. 10.1 requires that the width of output vector from the Real Time Task is equal to 10. It requires that the number of all elements in the first two parameters presented in Fig. 10.5 must be exactly 10. If required another number you must change the number of outputs of the demultiplexer.

RT-CON PROFESSI0NAL Reference Guide

Page 46

11. Application example: Simulink model for the pendulum system


To open the application you must double click the Inverted Pendulum Controllers button in the rtcon window (Fig. 6.1). The window (Fig. 11.1) contains two sets of Simulink controllers: one for the PCL-812PG Advantech board, another for the RT-DAC INTECO board.

Fig. 11.1 Inverted Pendulum Controllers window

In the following sections there are three examples of different control problems illustrating how to prototype your own controllers for the pendulum system [2],[6] (see Fig. 1.2). Using the device drivers library blocks described in the section 6.2.1 and Simulink models, you can develop and test your own RTW/RT-CON real-time application.

RT-CON PROFESSI0NAL Reference Guide

Page 47

11.1 Rule based controller


After double clicking on the Rule Based Controller button the following window opens (Fig. 11.1).

Define the base address of the RT-DAC board as the BaseAddr MATLAB v ariable. Start the external mode simulation.

Generator Ref.Cart.Pos. Sum

Error

Control

Controller

PendPos Output PendVel CartPos CartVel

Pend_pos Pend_v el Cart_pos Cart_v el

PENDULUM PCL-812 Sensors

PENDULUM PCL-812 Actuator

Control

Alfa Normalization

RESET ENCODERS PCL-812

STAR T

STOP

Fig. 11.1 Rule based controller (for the PCL 812G board) We describe the blocks of the rule based controller in a more detailed way. The desired position of the cart is obtained from the reference cart position generator (Fig. 11.2 and Fig. 11.3).

Fig. 11.2 Interior of the reference cart position generator

RT-CON PROFESSI0NAL Reference Guide

Page 48

Fig. 11.3 Reference cart position generator mask

You can generate the desired cart position signal in the sinusoidal, square or sawtooth forms. You must also define constant values for the reminding three state variables. The default values: 0, 0, 0 define the control goal. It means that the algorithm should steer the pendulum up (to 0 pendulum position) tracking zero valued velocities and zero desired cart position.
The Normalisation of angle block (Fig. 11.4) converts the pendulum position (angle) to the normalised value inside the [ , + ) interval.

Fig. 11.4 Interior of the Normalisation of angle block The rule-based controller is applied see Fig. 11.5. The swinging rule has a very simple form. It is bang-bang with switching moments related to the sign of angular velocity and angle position, which points up, or down. To achieve soft landing in the vicinity of upright position, algorithm checks whether the kinetic energy of the pendulum minus energy loss due to friction forces is sufficient to rise up the centre of gravity of the pendulum to its upright position. If the pendulum is in its upright position inside a stabilisation cone then a linear controller is applied. If the rail is exceeded then the opposite to the direction of movement maximal steering force is applied to the cart.

RT-CON PROFESSI0NAL Reference Guide

Page 49

Fig. 11.5 Interior of the Controller block

11.1.1 Building the real-time application Refer to the section 7 how to build and run the real-time application. Remember to define the base address (BaseAddr) for the device drivers before starting the building process. 11.1.2 Real-time experiment
Now you are ready to experiment with the laboratory model. Proceed in the following way. Double click on the START button (Fig. 11.1). The system loads the DLL library containing the rulebased controller. The following window appears (see Fig. 11.1).

Fig. 11.1 Start button window

RT-CON PROFESSI0NAL Reference Guide

Page 50

Switch on the power interface of the pendulum system. Bring the cart to the middle of the rail and leave the pendulum motionless. Run the external mode simulation and double click on the Reset Encoders PCL-812 button. In the window Reset Encoders change the value of the Trigger parameter and press the Close button. The incremental encoders must be reset to define the initial value of the sensors. Now, you can switch the DC motor on and start swing-up experiment. You can monitor data during experiment. Simply write in the MATLAB Command Window: rtw

The following window appears (see Fig. 11.2). Three signals are marked in this example: Sensors\Gain1\Pend_Pos, Sensors\Gain3\Cart_Pos and Controller/CtrlSat\.

Fig. 11.2 RTW Interface window The selected signals can be plotted if you press the Plot push button (see Fig. 11.3).

RT-CON PROFESSI0NAL Reference Guide

Page 51

Fig. 11.3 Plots of the selected signals The selected signals may be also visible as scopes in the Simulink monitor window (see Fig. 11.4). To obtain this window press the Simulink monitor button in the RTW Interface window (Fig. 11.2).

Fig. 11.4 The Simulink monitor window for the inverted pendulum You can use the floating Scope. Select the Scope and desired signal lines to activate the signals visualisation process. Next, select Simulation/normal and execute the Simulation/Start menu option. Double click on the STOP button to stop the experiment. The system responds and the following window appears (see Fig. 11.5). The DLL inverted pendulum library is removed.
RT-CON PROFESSI0NAL Reference Guide Page 52

Fig. 11.5 Stop button window

12. Inter-process communication functions


This section contains the description of all functions that are used to exchange information between the generated RTW DLL library and the MATLAB environment. They are referred as the Inter-Process Communication (IPC) functions (compare Fig.1.3) The IPC functions can be divided into the following groups: functions used to load and remove the RTW DLL executable: LoadLibrary and UnloadLibrary, functions used to set the details of message levels which can appear during execution of the DLL executable: GetMessageLevel and SetMessageLevel, functions used to manage and read the state of the data acquisition buffer: DestroyAcqStruct, GetAcqFlag, GetAcqStruct, GetAcqVectLen, GetDecimation, GetNoOfSamples, GetNoOfVect, SetAcqStruct, SetAcqVectLen, SetDecimation, StartAcq and StopAcq, function used to read a contents of the data acquisition buffer: GetHistory, functions used to set and read the trigger conditions: GetTrigger and SetTrigger, functions which read information from the running RTW DLL executable or set parameters of the RTW DLL executable: GetOutput, GetParam, GetSamplePeriod, GetTime, GetVersion, ResetTime and SetParam, functions which return information about the Simulink model: GetCheckSum, GetModelName, GetNoOfOutputBlocks, GetNoOfOutputs, GetNoOfParamBlocks, GetNoOfParams, GetOutputBlockDsrp and GetParamBlockDsrp. The description of all functions given in this section is dedicated to more experienced users wishing to write his own GUI interface windows similar to rtw, rtw_plot and rtw_tune or for the users developing Simulink models which co-operate with a running executable DLL. For the beginners it is recommended to work with the rtw, rtw_plot and rtw_tune GUI interface windows and the rtw_gm Simulink model. All of them call the IPC functions. You can look inside the body of the appropriate M-files to understand the usage conditions of the IPC functions. All functions responsible for communication between the RTW executable and the MATLAB environment are in the following form: ReturnValue = rtw_call( FunctionName, [ Argument ] ) where: ReturnValue - value returned by the function, rtw_call - name of the DLL library responsible for communication, FunctionName - name of the desired IPC function. It has the string format. The FunctionName string is not case sensitive, Argument - argument passed to the rtw_call function (optional).

RT-CON PROFESSI0NAL Reference Guide

Page 53

12.1 DestroyAcqStruct

Purpose: Destroy the data acquisition buffer allocated in the RTW DLL. Synopsis: ret = rtw_call( ' DestroyAcqStruct' ) Description: The function destroys the data acquisition buffer allocated in the RTW DLL executable and frees the memory allocated for this buffer. The data acquisition process is terminated by the call to this function. The data collected in the buffer are lost. Return value: See: On success the function returns 1.

GetAcqStruct, SetAcqStruct

12.2 GetAcqFlag

Purpose: Return the status of the data acquisition procedure. Synopsis: ret = rtw_call( ' GetAcqFlag' ) Description: This function returns the status of the data acquisition procedure. They are two states of the data acquisition procedure: the procedure is in progress. It means that: for the continuous or single data acquisition modes data are being collected in the data acquisition buffer, for the triggered data acquisition mode the data are being collected in the data acquisition buffer or the data acquisition procedure is waiting for the trigger event. In the first case the value returned by the GeNoOfSamples function increases. In the second case the GeNoOfSamples function returns 0, the data acquisition procedure is stopped because it has finished collecting of data. It means that the data buffer is full. It can occur only in the single or triggered data acquisition modes. Return value: The function returns 1 if the data acquisition is going on or 0 if the data acquisition procedure is stopped.

RT-CON PROFESSI0NAL Reference Guide

Page 54

See:

StartAcq, StopAcq, SetTrigger, GetNoOfSamples

12.3 GetAcqStruct

Purpose: Read which outputs and parameters are acquired in the data acquisition buffer. Synopsis: ret = rtw_call( ' GetAcqStruct' ) Description: This function detects which values are acquired in the data acquisition buffer. The RTW DLL executable can store values of parameters and outputs. At each sample time the selected values are stored in the data acquisition buffer. To identify the signals which are acquired it is necessary to define the type of signals and the indexes associated with them. There are two types of signals: parameters and outputs. The parameter signal is denoted as 1, the output as 2. The indexes start from 0 and can be obtained by the call to the GetOutputBlockDsrp and the GetParamBlockDsrp functions. Return value: The function returns a matrix which contains two rows and number of columns equal to the number of acquired signals. The first element of each column includes the index of a parameter or output. The second element defines the type of the signal. The value 1 marks parameter and the value 2 marks the output. The function returns an empty matrix if the data acquisition buffer was not defined or was destroyed. See: SetAcqStruct, DestroyAcqStruct, GetOutputBlockDsrp, GetParamBlockDsrp

Example: The example call to the function: rtw_call( ' GetAcqStruct' ) returns: ans = 28 29 2 7 9 1 1 2 2 2 It means that the data acquisition buffer collects information about five signals. The first two are parameters and the next three are outputs. The indexes of parameters are 28 and 29. The indexes of signals are 2, 7 and 9. To obtain more information about signals execute the function: rtw_call( ' GetParamBlockDsrp'28 ) , ans = BlockName: ' rtw_tst4/Signal Generator5' ParamName: ' Amplitude' NRows: 1 NCols: 1 Offset: 10 which returns information about the parameter no. 28, or execute the function: rtw_call( ' GetOutputBlockDsrp'2 ) ,
RT-CON PROFESSI0NAL Reference Guide Page 55

ans = BlockName: ' rtw_tst4/Signal Generator' SignalName: ' ' PortNo: 0 Width: 1 Offset: 2 which returns information about the output no 2.

12.4 GetAcqVectLen

Purpose: Return length of the data acquisition buffer. Synopsis: ret = rtw_call( ' GetAcqVectLen' ) Description: The function returns the number of the memory elements allocated for each signal collected in the data acquisition buffer. For the continuous data acquisition mode the data buffer is a cyclic type. For the single and triggered data acquisition modes the data acquisition procedure is stopped when it reaches the end of the buffer. Return value: See: Length of the data acquisition buffer.

SetAcqVectLen

12.5 GetCheckSum

Purpose: Returns the checksum which identifies the executable RTW DLL. Synopsis: ret = rtw_call( ' GetChecksum' ) Description: This function can be used to identify the executable. Each Simulink model has its own checksum value. The RTW package copies this value to the generated code. Afterwards it is possible to find out from which Simulink model the given DLL executable was generated. Return value: The four element vector containing the checksum.

RT-CON PROFESSI0NAL Reference Guide

Page 56

See:

GetModelName

Example: To read the checksum from the DLL library execute the following commands: format hex rtw_call( ' Getchecksum' ) ans = 41ee0ee2c1600000 41eb773c5de00000 41e384060b200000 41b3fbfd8d000000

12.6 GetDecimation

Purpose: Return the decimation factor for the data acquisition procedure. Synopsis: ret = rtw_call( ' GetDecimation' ) Description: The decimation factor gives the ability to decrease the frequency of data acquisition. If this factor is greater then 1 the data are re-sampled with the lower frequency. For instance, if the factor is equal to 5 only one sample per each five is collected in the data acquisition buffer. Return value: See: Returns the decimation factor.

SetDecimation

12.7 GetHistory

Purpose: Return the contents of the data acquisition buffer. Synopsis: ret = rtw_call( ' GetHistory' )

RT-CON PROFESSI0NAL Reference Guide

Page 57

Description: The function reads and returns the contents of the data acquisition buffer. The call to this functions clears the contents of the data acquisition buffer. Remember, that the contents of the data acquisition buffer must be defined by the SetAcqStruct function. Return value: This function returns a matrix which contains the contents of the data acquisition buffer. The first row of the matrix contains time vector. The next rows include information about values of signals defined by the proceeding call to the SetAcqStruct function. See: SetAcqStruct, GetNoOfSamples, GetNoOfVect

Example: To check the contents of data acquisition buffer execute: rtw_call( ' GetAcqStruct' ) ans = 28 29 2 7 9 1 1 2 2 2 To plot the output associated with output number 7 execute the following commands: h=rtw_call(' gethistory' ); plot( h( 1, : ), h( 5, : ) ) The h( 1, : ) contains the time vector and the h( 5, : ) contains the history of the output with index 7 defined in the data acquisition buffer (see the fourth column in the result of the GetAcqStruct function).

12.8 GetMessageLevel

Purpose: Return the level of details displayed by the RTW DLL executable. Synopsis: ret = rtw_call( ' GetMessageLevel' ) Description: They are three levels of messages displayed during execution of the RTW DLL: basic, medium and detailed. They are marked by the numbers 0, 1 and 2 respectively. Immediately after starting the DLL the basic level is selected. Return value: The symbols of the current details level: 0, 1 or 2.

RT-CON PROFESSI0NAL Reference Guide

Page 58

See:

SetMessageLevel

12.9 GetModelName

Purpose: Get model name. Synopsis: ret = rtw_call( ' GetModelName' ) Description: The RTW creates the DLL executable based on a Simulink model. The name of the Simulink model is copied into the executable and can be read by the call to the GetModelName function. This function can be used to identify the running RTW DLL library. Return value: The string which contains the model name. If the RTW DLL executable was not loaded it returns an empty string. See: GetChecksum

12.10 GetNoOfOutputBlocks

Purpose: Return the number of output blocks. Synopsis: ret = rtw_call( ' GetNoOfOutputBlocks' ) Description: The function returns the number of all output blocks in the Simulink model used to generate the RTW DLL. It includes all output blocks in the main diagram, in all masked and in all grouped sub-blocks. Return value: See: Integer value equal to the number of output blocks. GetNoOfOutputs

RT-CON PROFESSI0NAL Reference Guide

Page 59

12.11 GetNoOfOutputs

Purpose: Return the number of outputs from all blocks. Synopsis: ret = rtw_call( ' GetNoOfOutputs' ) Description: The function returns the number of all outputs from all blocks in the Simulink model used to generate the RTW DLL. It represents all outputs in the main block, in all masked and in all grouped sub-blocks. The returned value may be different from the value returned by the GetNoOfOutputBlocks because the model may contain output signals which are vectors. Generally, the value returned by the GetNoOfOutputBlocks function is less or equal to the value returned by the GetNoOfOutputs function. They are equal if in the Simulink model they are only scalar outputs. The relation between the values returned by the GetNoOfOutputBlocks and the GetNoOfOutputs functions is presented bellow.
Elements of all outputs 0 1 2 3 4 2 3 EQUIVALENT ........ NO-5 NO-4 NO-3 NO-2 NO-1 Output index (offset in the vector of outputs) ........ NOB-4 NOB-3 NOB-2 NOB-1 1 Output data blocks 0

value = rtw_call( ' GetOutput'Output_index ) ,

Block index (offset in the output blocks)

Values of parameters

Values of outputs

NO = rtw_call( ' GetNoOfOutputs' ) NOB = rtw_call( ' GetNoOfOutputBlocks' ) OutputBlockDsrp = rtw_call( ' GetOutputBlockDsrp'Block_index ) ,

OutputBlockDsrp

OutputBlockDsrp.BlockName OutputBlockDsrp.SignalName OutputBlockDsrp.PortNo OutputBlockDsrp.Width OutputBlockDsrp.Offset

Return value:

Integer value equal to the number of outputs.

RT-CON PROFESSI0NAL Reference Guide

Page 60

See:

GetNoOfOutputBlocks

12.12 GetNoOfParamBlocks

Purpose: Return the number of parameters from all blocks. Synopsis: ret = rtw_call( ' GetNoOfParamBlocks' ) Description: The function returns the number of all parameters in the Simulink model used to generate the RTW DLL. It includes all parameters in the main diagram, in all masked and in all grouped sub-blocks. If the parameter is a matrix and contains more then one value it is treated as the single parameter. Return value: See: Integer value equal to the number of parameters.

GetNoOfParams

12.13 GetNoOfParams

Purpose: Get number of all values in all parameters. Synopsis: ret = rtw_call( ' GetNoOfParams' ) Description: The function returns the number of all elements in all parameters in the Simulink model used to generate RTW DLL. This number represents all elements in all parameters in the main Simulink diagram, in all masked and in all grouped sub-blocks. The returned value may be different from the value returned by the GetNoOfParamBlocks because the model may contain parameters which are matrices. Generally, the value returned by the GetNoOfParamBlocks function is less or equal to the value returned by the GetNoOfParams function. They are equal if the Simulink model contains only scalar parameters. The relation between the values returned by the GetNoOfParams and the GetNoOfParamBlock functions is presented in the figure bellow.

RT-CON PROFESSI0NAL Reference Guide

Page 61

Elements of all parameters 0 1

Parameter data blocks 0 1 2 3 EQUIVALENT

rtw_call( ' SetParam'Parameter_index, value ) ,

2 3 4

value = rtw_call( ' SetParam'Parameter_index ) ,

5 ........ NP-5 NP-4 NP-3 NP-2 NP-1 ........

NPB-4 NPB-3 NPB-2 NPB-1

Parameter index (offset in the vector of parameters)

Block index (offset in the parameter blocks) Values of parameters

Values of parameters

NP = rtw_call( ' GetNoOfParams' ) NPB = rtw_call( ' GetNoOfParamBlocks' ) ParamBlockDsrp = rtw_call( ' GetParamBlockDsrp'Block_index ) ,

ParamBlockDsrp

ParamBlockDsrp.BlockName ParamBlockDsrp.ParamName ParamBlockDsrp.NRows ParamBlockDsrp.NCols ParamBlockDsrp.Offset

Return value: Simulink model. See:

Integer value equal to the number of all values in all parameters of the

GetNoOfParamBlocks

12.14 GetNoOfSamples

Purpose: Return number of samples collected in the data acquisition buffer. Synopsis: ret = rtw_call( ' GetNoOfSamples' ) Description: The function returns the value which increases from 0 to the maximum length of the buffer (see the GetAcqVectLen function). The data acquisition buffer is cyclic. If the buffer is full and a new sample enters the oldest sample is removed from the buffer.
RT-CON PROFESSI0NAL Reference Guide Page 62

The call to the GetNoOfSamples function immediately after the call to the GetHistory function results in the return of value equal to 0 because the GetHistory flushes the buffer. Return value: buffer. See: Integer value equal to the number of samples collected in the data acquisition

GetHistory, GetAcqVectLen

12.15 GetNoOfVect

Purpose: Return number of rows collected in the data acquisition buffer. Synopsis: ret = rtw_call( ' GetNoOfVect' ) Description: The number of rows collected in the data acquisition buffer is defined by the SetAcqStruct. It is equal to the number of columns in the first argument passed to the function SetAcqStruct (or the value returned by the function GetAcqStruct) plus one. This additional row is always reserved for the time vector. Return value: See: Integer value equal to the number of rows collected in the data buffer.

GetHistory, GetAcqVectLen, SetAcqStruct

12.16 GetOutput

Purpose: Read current value of the given output signal. Synopsis: ret = rtw_call( ' GetOutput'output_index ) , Description: The function returns the current value of the signal pointed out by the output_index value. Use the GetOutputBlockDsrp functions to obtain more information about the signal identified by the output_index index. The GetNoOfOutputs function returns the number of signals. The output_index input argument may change from zero to the value returned by the GetNoOfOutputs function minus one.
RT-CON PROFESSI0NAL Reference Guide Page 63

Return value: Returns two-element vector. The first element is the value of the given output. The second element is the time value. The time value starts from zero at the execution of the LoadLibrary or ResetTime functions. See: GetNoOfOutputs, ResetTime

Example: The following statements collect and display the value of the output pointed by the index equal to 7: for i = 1 : 500 arr( i, 1:2 ) = rtw_call( ' GetOutput'7 ); , end % plot time diagram plot( arr( :, 2 ), arr( :, 1 ) )

12.17 GetOutputBlockDsrp

Purpose: Return information about the outputs from the block. Synopsis: ret = rtw_call( ' GetOutputBlockDsrp' ,) Description: Returns the detailed information about the given block output signals containing: block name, signal name, port number, width of the signal, offset of the signal. The block is identified by the block_index parameter. Return value: The function returns the structure containing the following fields:

BlockName - string containing the block name which is the source of the output, SignalName - string; contains the name of the signal, PortNo - port number of the signal, Width - signal width, Offset - offset of the block. See: GetOutput, GetNoOfOutputBlocks, GetNoOfOutputs

Example: The following functions returns the array of structures containing information about all blocks in the model: function ret = rtw_goba nob = rtw_call( ' GetNoOfOutputBlocks' );

RT-CON PROFESSI0NAL Reference Guide

Page 64

for i = 1 : nob ret( i ) = rtw_call( ' GetOutputBlockDsrp'i-1 ); , end

12.18 GetParam

Purpose: Read current value of the given parameter. Synopsis: ret = rtw_call( ' GetParam'param_index ) , Description: The function returns the current value of the parameter pointed out by the param_index value. Use the GetParamBlockDsrp functions to obtain more information about the signal identified by the param_index index. The GetNoOfParams function returns the number of parameters. The param_index input argument changes from zero to the value returned by the GetNoOfParams function minus one. Return value: Returns two-element vector. The first element is the value of the given parameter. The second element is the time value. The time value starts from zero at the execution of the LoadLibrary or resetTime functions. See: SetParam, GetNoOfParams

12.19 GetParamBlockDsrp

Purpose: Return information about the given parameter. Synopsis: ret = rtw_call( ' GetParamBlockDsrp'param_index ) , Description: Returns the detailed information about the given parameter containing: block name, parameter name, number of columns, number of rows of the parameter and offset of the parameter in the parameter array. The parameter is pointed out by the index value. If parameter has more then one value it occupies more then one element in the parameter array. In such a case the returned offset is the offset of the first element of the parameter. Return value: The function returns the structure containing the following fields:
Page 65

RT-CON PROFESSI0NAL Reference Guide

BlockName - name of the block in which the parameter is located, ParamName - parameter name, NRows - number of rows of the parameter, NCols - number of columns of the parameter, Offset - offset of the parameter. See: GetParam, GetNoOfParamBlocks, GetNoOfParams

Example: The following functions returns the array of structures containing information about all parameters in the model: function ret = rtw_gpba npb = rtw_call( ' GetNoOfParamBlocks' ); for i = 1 : npb ret( i ) = rtw_call( ' GetParamBlockDsrp'i-1 ); , end

12.20 GetSamplePeriod

Purpose: Get sample period. Synopsis: ret = rtw_call( ' GetSamplePeriod' ) Description: The function return the sample period of the running RTW DLL library. Refer to Simulink. Real-Time Workshop. User' Guide for details how the sample period for the given model s is selected. Return value: See: The sample period of the currently running RTW DLL executable.

GetModelName, GetTime

12.21 GetTime

Purpose: Get current time. Synopsis: ret = rtw_call( ' GetTime' )

RT-CON PROFESSI0NAL Reference Guide

Page 66

Description: The function returns the current time of the RTW DLL executable. The time value starts at the moment when the DLL library is loaded (call to the LoadLibrary function). The ResetTime functions can be used to set a time value to zero during execution of the DLL. Return value: See: The current RTW DLL time.

GetSamplePeriod, ResetTime, GetParam, GetOutput

12.22 GetTrigger

Purpose: Get trigger conditions. Synopsis: ret = rtw_call( ' GetTrigger' ) Description: The function returns a vector containing the current trigger conditions. The complete set of information about trigger conditions includes: data acquisition mode, index of the output signal applied to the trigger data acquisition, trigger level, trigger condition and offset of the trigger event. Return value: The ret value contains 5 elements:

ret( 1 ) - the data acquisition mode. The following values are allowed: 1 - continuous data acquisition, 2 - single data acquisition (when the data buffer is full the acquisition is terminated), 3 - triggered (waits for the trigger event and starts single data acquisition), ret( 2 ) - index of the signal used to detect the trigger event, ret( 3 ) - level of the signal used to detect the trigger event, ret( 4 ) - trigger condition. The following values are allowed: 1 - the value of the signal defined by ret( 2 ) is greater then the value of ret( 3 ), 2 - the value of the signal defined by ret( 2 ) is less then the value of ret( 3 ), 3 - the value of the signal defined by ret( 2 ) in the previous sample period was bellow and in the current sample period is above the value of ret( 3 ), 4 - the value of the signal defined by ret( 2 ) in the previous sample period was above and in the current sample period is bellow the value of ret( 3 ), 5 - during last sample period the value of the signal defined by ret( 2 ) has crossed the value ret( 3 ), ret( 5 ) - offset of the trigger event in the data acquisition buffer.

See:

SetTrigger, StartAcq, StopAcq, GetAcqFlag

RT-CON PROFESSI0NAL Reference Guide

Page 67

12.23 GetVersion

Purpose: Display version information. Synopsis: ret = rtw_call( ' GetVersion' ) Description: The function displays two windows containing information about the current version of the RTW DLL executable and the current version of the rtw_call program. The examples of the windows to be displayed are presented bellow.

Return value: See:

Returns value 1.

GetModelName

12.24 LoadLibrary

Purpose: Load the RTW DLL executable. Synopsis: ret = rtw_call( ' LoadLibrary' )
RT-CON PROFESSI0NAL Reference Guide Page 68

Description: The function loads the rtw_dll.dll DLL library to the memory and starts execution of the model. The rtw_dll.dll library contains the executable version of the RTW Simulink model. It must be located in the current working directory. The name of the current working directory can be obtained as a result of the call to the pwd MATLAB function. RT-CON creates the RTW DLL executable in the current working directory. The function displays the message window containing the basic information about the loaded DLL library. The example of the window is presented bellow:

Return value: Returns 1 if the library is loaded to the memory for the first time. If the LoadLibrary function is called more then ones the function returns 2. See: UnloadLibrary

12.25 ResetTime

Purpose: Set the RTW DLL executable time to zero. Synopsis: ret = rtw_call( ' ResetTime' ) Description: The function sets the time counter to zero. The counter is built into the RTW DLL library. It starts counting from zero after the first call to the LoadLibrary function. Return value: See: The function always returns 1.

GetTime

Example: The following sequence of commands presents the results of the ResetTime function application: rtw_call( ' gettime' ) ans = 159.2200
RT-CON PROFESSI0NAL Reference Guide Page 69

rtw_call( ' resettime' ); rtw_call( ' gettime' ) ans = 1.3800

12.26 SetAcqStruct

Purpose: Define which outputs and parameters are collected in the data acquisition buffer. Synopsis: ret = rtw_call( ' SetAcqStruct'acq_str ) , Description: This function defines which outputs and parameters are collected in the data acquisition buffer. At each sample time the selected values are stored in the data acquisition buffer. To determine the signals which are acquired it is necessary to define the type of signals and the indexes associated with them. There are two types of signals: parameter and output. The parameter signal is defined as 1, the output signal as 2. The indexes start from 0 and can be obtained by the GetOutputBlockDsrp and GetParamBlockDsrp functions. The acq_str input argument is a matrix which contains two rows and number of columns equal to the number of acquired signals. The first element of each column includes the index of a parameter or output. The second element defines the type of signal. Return value: See: Returns the number of defined signals.

GetAcqStruct

Example: Call to the function: acq_str = [ 28 29 2 7 9 ; 1 1 2 2 2 ]; rtw_call( ' GetAcqStruct' acq_str ); , defines that the data acquisition buffer collects information about five signals. The first two are parameters and the next three are outputs. The indexes of parameters are 28 and 29. The indexes of signals are 2, 7 and 9 respectively.

12.27 SetAcqVectLen

Purpose: Set length of the data acquisition buffer.

RT-CON PROFESSI0NAL Reference Guide

Page 70

Synopsis: ret = rtw_call( ' SetAcqVectLen'acq_len ) , Description: The function sets the number of memory points allocated for each signal in the data acquisition buffer. For the continuous data acquisition mode the data buffer has a cyclic type. For the single and triggered data acquisition modes the data acquisition procedure is terminated when it reaches the end of the buffer. The call to this function clears the contents of the data acquisition buffer. The memory for the buffer is released and reallocated for the new length. Return value: See: The function returns the length of the data acquisition buffer.

SetAcqVectLen

12.28 SetDecimation

Purpose: Set the decimation factor for the data acquisition procedure. Synopsis: ret = rtw_call( ' SetDecimation'dec_fact ) , Description: The decimation factor gives the ability to decrease frequency of data acquisition. If this factor is greater then 1 the data are re-sampled with the lower frequency. For instance, if the factor is equal to 5 only one sample per each five is collected in the data acquisition buffer. Return value: See: Returns the decimation factor.

GetDecimation

12.29 SetMessageLevel

Purpose: Set the level of details displayed by the RTW DLL executable. Synopsis: ret = rtw_call( ' SetMessageLevel'msg_lev ) ,

RT-CON PROFESSI0NAL Reference Guide

Page 71

Description: They are three levels of messages displayed during execution of the RTW DLL: basic, medium and detailed. They are marked by the numbers 0, 1 and 2 respectively. Immediately after starting the DLL the basic level is selected. Return value: See: The function returns the value 1. GetMessageLevel

12.30 SetParam

Purpose: Set current value of the given parameter. Synopsis: ret = rtw_call( ' SetParam'[ param_index value ] ) , Description: The function sets the value of the given parameter identified. The second input argument to the function is a two-elements array [ param_index value ]. The first element of the array contains the index of the parameter and the second element contains a new value. Use the GetParamBlockDsrp functions to obtain more information about the signal identified by the param_index index. The GetNoOfParams function returns the number of parameters. The param_index input argument changes from zero to the value returned by the GetNoOfParams function minus one. Return value: See: The function always returns 1. SetParam, GetParamBlockDsrp, GetNoOfParams

12.31 SetTrigger

Purpose: Set trigger conditions. Synopsis: ret = rtw_call( ' SetTrigger'trigger_cond ) ,

RT-CON PROFESSI0NAL Reference Guide

Page 72

Description: The function takes a vector containing the current trigger conditions. The complete set of information about trigger conditions includes: data acquisition mode, index of the output signal used to trigger data acquisition, trigger level, trigger condition and offset of the trigger event. The trigger_cond value contains 5 elements: trigger_cond( 1 ) - the data acquisition mode. The following values are allowed: 1 - continuous data acquisition, 2 - single data acquisition (when data buffer is full stop the acquisition), 3 - triggered (waits for the trigger event and starts single data acquisition), trigger_cond( 2 ) - index of the signal used to detect trigger event, trigger_cond( 3 ) - level of the signal. This level is used to detect trigger event, trigger_cond( 4 ) - trigger condition. The following values are allowed: 1 - the value of the signal defined by ret( 2 ) is greater then the value of ret( 3 ), 2 - the value of the signal defined by ret( 2 ) is less then the value of ret( 3 ), 3 - the value of the signal defined by ret( 2 ) in the previous sample period was bellow and in the current sample period is above the value of ret( 3 ), 4 - the value of the signal defined by ret( 2 ) in the previous sample period was above and in the current sample period is bellow the value of ret( 3 ), 5 - during last sample period the value of the signal defined by ret( 2 ) has crossed the value ret( 3 ), trigger_cond( 5 ) - offset of the trigger event in the data acquisition buffer. Return value: See: The function always returns 1. GetTrigger, StartAcq, StopAcq, GetAcqFlag

RT-CON PROFESSI0NAL Reference Guide

Page 73

12.32 StartAcq

Purpose: Start data acquisition process. Synopsis: ret = rtw_call( ' StartAcq' ) Description: This function starts data acquisition process. For the continuous data acquisition mode it starts data collection process in the cyclic data acquisition buffer. For the single and triggered data modes it starts collecting data in the buffer of a limited length. In the triggered working mode the data collection is proceeded by the trigger event. Return value: See: The function always returns 1.

StopAcq, GetAcqFlag, SetTrigger

12.33 StopAcq

Purpose: Stop data acquisition process. Synopsis: ret = rtw_call( ' StopAcq' ) Description: The function stops the data acquisition process. The collected data are available for the GetHistory function. Return value: See: The function always returns 1.

StartAcq, GetAcqFlag

RT-CON PROFESSI0NAL Reference Guide

Page 74

12.34 UnloadLibrary

Purpose: Remove the RTW DLL executable from the memory. Synopsis: ret = rtw_call( ' UnloadLibrary' ) Description: The function stops execution of the RTW DLL executable and removes it from the memory. The similar result is achieved by the call to the clear all or to the clear rtw_call functions. The RTW DLL is also removed when the MATLAB is terminated. During removing from the memory the RTW DLL displays the following message window:

Return value: If the DLL library is loaded the function returns 1. If not, it displays the following message in the MATLAB Command Window: The RTW DLL must be loaded before calling the UNLOADLIBRARY function. See: LoadLibrary

RT-CON PROFESSI0NAL Reference Guide

Page 75

13. The S-function


This section describes the example of S-function executing information exchange between the Simulink model and the running RTW DLL. The S-functions were developed to give Simulink the ability to make generic simulation block to handle in one standard form different roles, like continuous simulation, discrete simulation, systems embedded within systems, and so on. In our applications a special S-function performs information exchange between Simulink model and the running real-time program. It is important to realise that user-defined S-functions are at the heart of how your data flow is performed. The rtw_gmsf function presented bellow reads history of the experiment and transfers samples to the output of S-function. The lines written in italics are statements of the rtw_gmsf.m file. The lines marked on the left side contain comments added for explaining statements of the S-function. The rtw_gmsf function sets data acquisition conditions (based on the out_par and out_out input arguments) and starts the data transfer. The ds input is equal to the decimation factor and is used to decrease the amount of data sent to the output of the S-function. It is assumed that the user is familiar with the S-function definition, so we shall not go into details about it. If necessary refer to "Simulink. Dynamic System Simulation Software. User' Guide". s function [ sys, x0, str, ts ] = sfunc( t, x, u, flag, out_par, out_out, ds ) The function has following parameters: t - time, x - state vector, u - input to the S-function block. In our case the input is absent and the u is

empty,

flag - the value passed to S-function by Simulink to distinguish different actions. The arguments t, x, u and flag are set and passed to S-function by Simulink automatically, out_par- indexes of parameters, out_out - indexes of outputs, ds - decimation ratio. global history Global variable is used to store history of the experiment. The data history contains a few last samples and is needed for the decimation algorithm. switch flag, case 0, % Initialization % call simsizes for a sizes structure, fill it in and convert it to a % sizes array

sizes = simsizes;

RT-CON PROFESSI0NAL Reference Guide

Page 76

% Set number of continuous states, number of discrete states, number of % outputs and number of inputs. % 0 continuous states, 1 discrete state, 6 outputs, 1 inputs sizes.NumContStates = 0; sizes.NumDiscStates = 1; sizes.NumOutputs = length( out_par ) + length( out_out ); sizes.NumInputs = 0; sizes.DirFeedthrough = 0; sizes.NumSampleTimes = 1; % at least one sample time is needed Set number of continuous states, number of discrete states, number of outputs and number of inputs (0 continuous states, 1 discrete state, number of outputs is equal to the sum of number of elements in the out_par and out_out input parameters, 0 inputs, 0 direct feedthrough - without algebraic loops, 1 sample time) sys = simsizes(sizes); Set parameters of the data acquisition algorithm

Select continuous data acquisition mode % Set continuous data acquisition % AcqMode, SignalOffset, SignalLevel, TriggerCond, TriggerOffset dummy = rtw_call( ' SetTrigger' [ 1 0 0 1 0 ] ); , Set data structure for data acquisition procedure. Define which parameters and outputs are collected in the data acquisition buffer acqstr = [ out_par out_out; ... ones( size(out_par) ) 2*ones( size(out_out) )]; dummy = rtw_call( ' SetAcqStruct'acqstr ); , Start data acquisition and set time value to zero dummy = rtw_call( ' StartAcq' ); dummy = rtw_call( ' ResetTime' ); Wait for the first sample which may be sent to the output while ( eq( rtw_call( ' GetNoOfSamples' 0 ) ) ), ;
RT-CON PROFESSI0NAL Reference Guide Page 77

end; history = rtw_call( ' GetHistory' ; )' Set initial conditions x0 = history( 1 , 1 ); str = []; % str is always an empty matrix ts = [ -2 0 ]; % initialise the array of sample times % variable sample time The flag equal to 2 is not used. This flag can be used to set parameters. Such operation requires a source of signal connected to the input of S-function block case 2, % Update - not used sys = x; case 3, % Outputs - return last samples Calculate output from the S-function block. Returns the samples from the data acquisition buffer. Use the decimation ration to decrease the data stream if ds > 1 sys = history( ds , 2:size(history,2) ); curr_len = size( history , 1 ); history = history( ds + 1 : curr_len, : ); else while ( eq( rtw_call( ' GetNoOfSamples' 0 ) ) ), ; end; history = rtw_call( ' GetHistory' ; )' sys = history( size( history , 1 ) , 2:size(history,2) ); end case 4, % GetTimeOfNextVarHit % Calculate next discrete time point. The S-function block will be activated in this time point. Returns the time value from the data history. The next discrete time point is taken from real-time data acquisition buffer. This operation synchronises simulation time of the Simulink model and real time of the running RTW DLL executable. if ds > 1 curr_len = size( history , 1 ); if ( curr_len < ds ) while ( rtw_call( ' GetNoOfSamples' + curr_len <= ds ) ) ;
RT-CON PROFESSI0NAL Reference Guide Page 78

end history = [ history ; rtw_call( ' GetHistory' ]; )' end sys = history( ds , 1); else sys = history( size( history, 1 ) , 1 ); end case 9, % Terminate Terminate simulation. Stop data acquisition dummy = rtw_call( ' StopAcq' ); sys = []; case 1, % Unhandled flags %

The flag equal to 1 is not used. sys = []; otherwise % Unexpected flags % error([ ' Unexpected flag = ' num2str(flag)] ); , end

RT-CON PROFESSI0NAL Reference Guide

Page 79

14. I/O access functions


This of functions which give the used access to the Input/Output (I/O) address space of a microprocessor. The I/O write and read operations can be done directly from the MATLAB environment. The functions described in this section can be used separately from the RT-CON software. Simulink and Real Time Workshop are not necessary in this case. It gives the opportunity to communicate with I/O boards which are typically located in the computer I/O address space. Such solution opens the way to exchange information between the MATLAB Workspace and measurement and control equipment connected to the computer. The access to the I/O address space allows the user to write device drivers in the form of Mfiles. It is an unique solution. The example given at the end of this section gives more detailed description of the device driver. The following files are described in this section: inportb.c - C-source code of the inportb.dll file, inportb.dll - DLL file which can be called from MATLAB. It reads a series of bytes from an input ports, inport.c - C-source code of the inport.dll file, inport.dll - DLL file which can be called from MATLAB. It reads a series of words from an input ports, outportb.c - C-source code of the outportb.dll file, outportb.dll - DLL file which can be called from MATLAB. It writes a series of bytes to output ports, outport.c - C-source code of the outport.dll file, outport.dll - DLL file which can be called from MATLAB. It writes a series of words to output ports, startio.dll - DLL file which can be called from MATLAB. In the Windows NT environment this command allows the MATLAB application to access the I/O space. This command must be called before any call to I/O functions. Basically the supplied functions perform only simple I/O operations. The equipment controlled by your computer may have more complex requirements, for example a sequence of I/O commands. In such a case it may be necessary to create a special DLL which will contain all necessary commands. The C-code sources delivered with the RT-CON software may be a convenient template files to create new DLL files. Keep in mind that the delivered I/O function cover a wide range of applications and only a special hardware will require new DLLs. Generally, the approach proposed in this chapter do not guarantee a proper real-time information exchange in the sense as explained in the section 5. However, in many cases the application of I/O functions for monitoring and control of a slow processes is quite effective.

RT-CON PROFESSI0NAL Reference Guide

Page 80

14.1 mex_baseaddress

Purpose: Read base address of the PCI board. Synopsis: [IOBaseAddress,BusNo,SlotNo,VendorID,DeviceID]=mex_BaseAddress(-1,-1) or [IOBaseAddress,BusNo,SlotNo,VendorID,DeviceID]= mex_BaseAddress(BusNo,SlotNo ) Description: The function reads configuration of the RT-DAC4/PCI boards equipped with PLX chip. Only the IOBaseAddress return value is required. If single board is installed: When only two input arguments are used and both are equal to 1 and the function returns output arguments as listed. If one of input arguments is set the function returns output arguments for board which data fit to argument setting. When more than one board is installed: When only two input arguments are used and both are equal to -1 the function returns vectors as output arguments. Return value: The function returns IOBaseAddress,BusNo,SlotNo,VendorID,DeviceID but only the IOBaseAddress return value is required. Example: BaseAddress=mex_baseaddress(-1,1) The function returns base address of the board, which is installed in slot number 1. [BaseAddr,BusNo,SlotNo,VID,DID]=mex_address(-1,3) the function returns base address, bus number, 3, VendorID and DeviceID of board installed in slot number 3.

14.2 Inportb

Purpose: Read a series of bytes from input ports. Synopsis: value = inportb( address ) Description: The function reads a series of bytes from the input ports. The address input argument specifies the port numbers to be read. The address can be a scalar or a vector. In the first case the function returns a single value which was read from the port. In the second case the function reads so many ports as number of elements in the address argument and returns the appropriate return values. The ports are read in the same order as specified in the address input argument. For the IMB PC the valid range of I/O port is from 0 to 1023. For the Windows NT operating system it is necessary to proceed a call to the inportb function by the call to the startio function. If not, the Windows NT operating system protects the access to the I/O address space and does not allow any data to be read.

RT-CON PROFESSI0NAL Reference Guide

Page 81

Return value:

The function returns the values read from I/O port (or ports).

Example: The command: val = inportb( 97 ); reads a single byte from port number 97. The command: val = inportb( 97, 66, 67, 97 ); reads four ports. First it reads the port number 97, then 66, after that 67 and at finally reads the port 97 again. The command returns four values.

14.3 Inportd

Purpose: Read a series of double words from input ports. Synopsis: value = inportb( address ) Description: The function reads a series of double words from the input ports. The address input argument specifies the port numbers to be read. The address can be a scalar or a vector. In the first case the function returns a single value which was read from the port. In the second case the function reads so many ports as number of elements in the address argument and returns the appropriate return values. The ports are read in the same order as specified in the address input argument. For the IMB PC the valid range of I/O port is from 0 to 1023. For the Windows NT operating system it is necessary to proceed a call to the inportd function by the call to the startio function. If not, the Windows NT operating system protects the access to the I/O address space and does not allow any data to be read. Return value: The function returns the values read from I/O port (or ports).

Example: The command: val = inportd( 97 ); reads a single double word from port number 97. The command: val = inportb( 97, 66, 67, 97 ); reads four ports. First it reads the port number 97, then 66, after that 67 and at finally reads the port 97 again. The command returns four values.

14.4 Inport

RT-CON PROFESSI0NAL Reference Guide

Page 82

Purpose: Read a series of words from input ports Synopsis: value = inport( address ) Description: The function reads a series of words from input ports. The address input argument specifies the port numbers which are read. The address can be a scalar or a vector. In the first case the function returns a single word which was read from the port no. address (low-order byte) and from the port address+1 (high-order byte). In the second case the function reads so many values as number of elements in the address argument and returns the appropriate return values. The ports are read in the same order as order as specified in the address input argument. For the IMB PC the valid range of I/O port is from 0 to 1022. For the Windows NT operating system it is necessary to proceed the call of the inport function by the call to the startio function. If not, the Windows NT operating system protects the access to the I/O address space and does not allow any data to be read. Return value: The function returns the values read from I/O ports (or ports).

Example: The command: val = inport( 97 ); reads a single word read from ports number 97 and 98. The command: val = inport( 97, 66, 97 ); reads three values. First it reads the ports numbers 97 and 98, then 66 and 67and finally reads the ports 97 and 98 again. The command returns three values.

RT-CON PROFESSI0NAL Reference Guide

Page 83

14.5 outportb

Purpose: Write a series of bytes to output ports Synopsis: no = outportb( address, value ) Description: The function writes a series of bytes to output ports. The address input argument specifies the port numbers which are written. The address can be a scalar or a vector. In the first case the function writes a single value to the port. In the second case the function writes so many ports as defined in the address argument. The ports are written in the same order as the order of values in the address input argument. The values written to the ports are taken from the appropriate elements of the value input argument. For the IMB PC the valid range of I/O port is from 0 to 1023. For the Windows NT operating system it is necessary to proceed the call of the outportb function by the call to the startio function. In the other case the operating system protects the access to the I/O address space and does not allow any data to be read. Return value: The function returns the number of ports to which the new value was written.

Example: The command: no = outportb( 97, 253 ); writes value 253 to port number 97. It returns 1. The command: no = inportb( [ 97 66 67 97] [ 253 20 22 255] ); performs four write operations. First it writes 253 to the port number 97, then 20 to port number 66, after that the value 22 to port 67 and at the end writes ones more to the port 97 (value 255). The command returns 3.

14.6 Outportd

Purpose: Write a series of double words to output ports Synopsis: no = outportb( address, value ) Description: The function writes a series of double words to output ports. The address input argument specifies the port numbers which are written. The address can be a scalar or a vector. In the first case the function writes a single value to the port. In the second case the function writes so many ports as defined in the address argument. The ports are written in the same order as the order of
RT-CON PROFESSI0NAL Reference Guide Page 84

values in the address input argument. The values written to the ports are taken from the appropriate elements of the value input argument. For the IMB PC the valid range of I/O port is from 0 to 1023. For the Windows NT operating system it is necessary to proceed the call of the outportd function by the call to the startio function. In the other case the operating system protects the access to the I/O address space and does not allow any data to be read. Return value: The function returns the number of ports to which the new value was written.

Example: The command: no = outportd( 97, 253 ); writes value 253 to port number 97. It returns 1. The command: no = inportd( [ 97 66 67 97] [ 253 20 22 255] ); performs four write operations. First it writes 253 to the port number 97, then 20 to port number 66, after that the value 22 to port 67 and at the end writes ones more to the port 97 (value 255). The command returns 3.

14.7 Outport

Purpose: Write a series of words to output ports Synopsis: no = outport( address, value ) Description: The function writes a series of words to output ports. The address input argument specifies the port numbers to be written. The address can be a scalar or a vector. In the first case the function writes a single word to the couple of ports (the low-order byte to the port no. address and the high-order byte to the port no. address+1). In the second case the function writes so many words as given in the address argument. The ports are written in the same order as the order of values in the address input argument. The values written to the ports are taken from the appropriate elements of the value input argument. For the IMB PC the valid range of I/O port is from 0 to 1022. For the Windows NT operating system it is necessary to proceed the call of the outport function by the call to the startio function. In the other case the Windows NT operating system protects the access to the I/O address space and does not allow any data to be read. Return value: The function returns the number of written values.

Example: The command: no = outportb( 97, 253 ); writes value 253 to the port number 97 and the 0 value to the port 98. It returns 1. The command:
RT-CON PROFESSI0NAL Reference Guide Page 85

no = inportb( [ 97 66 ] [ 253 515] ); performs two write operations. First it writes 253 to the port number 97 and 0 to port 98 and then writes 3 to port number 66 and 2 to port 67. The command returns 2.

14.8 startio

Purpose: Enable access to the I/O address space Synopsis: startio Description: The functions enables access to the I/O address space for the MATLAB application. The call to any I/O function must be proceeded by the call to the startio. The function can be executed only in the Windows NT operating system. The call to the function can generate the following error messages:
Couldn't access RTKIO device, or Can not start IO access They are caused by absence of the RTKIO kernel mode device driver running in the operating system. See the description of installation procedure to solve this problem. Remember, that in the Windows NT operating system it is required to have administrator access rights to install the kernel mode device driver.

Return value:

None.

15. The device driver example


Here we present an example of device driver written as an M-file. The device driver controls a sound generated by the speaker built in an IBM PC computer. The driver can start generation of the sound of a given frequency and stop the sound generation. The body of the appropriate function is presented bellow. The function is stored in the beep.m file. function beep( action, frequency ) action = upper( action ); if( strcmp( action, ' STOP' == 1 ) ) port = inportb( 97 ); % 97 = 0x61 port = bitand( port, 253 ); % 253 = 0xFD outportb( 97, port );

RT-CON PROFESSI0NAL Reference Guide

Page 86

elseif( strcmp( action, ' START' == 1 ) ) if( frequency < 20.0 ) frequency = 20.0; end; div = floor( 1000.0 * 1193.0 / frequency ); lo = rem( div, 256 ); hi = ( div - lo ) / 256; outportb( 67, 190 ); % 67 = 0x43, mode = 190 = 0xBE outportb( 66, lo ); % 66 = 0x42 outportb( 66, hi ); port = inportb( 97 ); % 97 = 0x61 port = bitor( port, 3 ); outportb( 97, port ); else disp( [ ' Unrecognized action: ' action ] ); end The command: beep( ' , 1000 ) Start' starts the generation of the sound. The sound frequency is equal to 1000. The command: beep( ' Stop' ) stops generation of the sound:

References [1] Simulink. Real-Time Workshop. User' guide. MathWorks Inc., Natic, 1998 s [2] Kolek, M. Pauluk, M. Rosl, A. Turnau: Real time simulation environment for control of high-speed unstable mechanical systems. Proceedings of the II International Symposium on Methods and Models in Automation and Robotics, Miedzyzdroje, Poland, 1995, pp. 413-418. [3] RT-DAC multi I/O board. User' manual. INTECO Ltd., Krakw 1998 s [4] Model PCL-812 PG Enhanced multilab card. Users manual. Advantech. [5] Target Language Compiler for Simulink. Users guide. MathWorks Inc., Natic, 1998 [6] Pendulum Cart System. Teaching Manual 2. Rule-based and Fuzzy Controllers. Feedback Ltd., Crowborough 1998 [7] RT-DAC4/PCI multi I/O board. User' Manual. INTECO Ltd., Krakw 2002 s

RT-CON PROFESSI0NAL Reference Guide

Page 87

Você também pode gostar