MATLAB, Simulink
MATLAB, Simulink
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.
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.
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
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.
Page 5
Project
Model of the controller
Input Driver
Output Driver
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
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
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.
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.
Page 7
PROCESS
COMPUTER
I/O Board
Win NT Dev.Driv.
Device Driver(s)
Timer Interrupts
RT-CON Toolbox
MATLAB / SIMULINK
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.
Page 8
2. System configuration
The following basic configuration of your PC is required:
3. Installation
The installation procedure of the RT-CON software is described in Real-Time Connection RTCON Installation 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
TLC-files (rtw_dll.tlc)
Additional C-files
RTW C-files
Build (rtw_watc.tmf)
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
MODEL.mat
MATLAB
- program
Fig. 4.1. Automatic real-time program building and execution: files and information flow.
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,
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.
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
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.
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.
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.
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.
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).
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
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.
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.
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.
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
Page 23
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
P E ND UL UM RT -DA C _ S e n so rs_
Page 24
1 Pend_pos
Pend_pos
2 Pend_vel
Pend_v el
3 Cart_pos
Cart_pos
Demux
4 Cart_vel
Cart_v el
1/T0 Gain4
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
Fig. 6.5 Interior of Reset Encoders block Fig. 6.4 Reset Encoders mask
Page 25
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.
Page 27
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.
Page 28
External simulation
MODEL.out
rtw_cpdf.m
MODEL.par
rtw_call.dll
rtw_unload.m
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.
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).
Page 30
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,
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.
Page 32
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.
Page 33
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.
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
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.
Page 36
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.
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.
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.
Page 39
tab and in the Tools/External Mode control panel/Target interface must be set, as presented in Fig. 9.3.
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.
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.
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.
Page 42
Page 43
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.
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
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.
Page 46
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.
Page 47
Define the base address of the RT-DAC board as the BaseAddr MATLAB v ariable. Start the external mode simulation.
Error
Control
Controller
Control
Alfa Normalization
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).
Page 48
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.
Page 49
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).
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).
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
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.
Page 54
See:
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.
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' )
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.
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
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
Values of parameters
Values of outputs
NO = rtw_call( ' GetNoOfOutputs' ) NOB = rtw_call( ' GetNoOfOutputBlocks' ) OutputBlockDsrp = rtw_call( ' GetOutputBlockDsrp'Block_index ) ,
OutputBlockDsrp
Return value:
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.
Page 61
2 3 4
Values of parameters
NP = rtw_call( ' GetNoOfParams' ) NPB = rtw_call( ' GetNoOfParamBlocks' ) ParamBlockDsrp = rtw_call( ' GetParamBlockDsrp'Block_index ) ,
ParamBlockDsrp
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.
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' );
Page 64
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
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
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.
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:
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.
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
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
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 ) ,
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
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
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.
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
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
Page 75
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;
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
Page 79
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.
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
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.
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.
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
Page 87