External Interface To The Real Time Kernel
External Interface To The Real Time Kernel
33-005-3M5
Matlab 5 Version
Feedback
Feedback Instruments Ltd, Park Road, Crowborough, E. Sussex, TN6 2QR, UK.
Telephone: +44 (0) 1892 653322, Fax: +44 (0) 1892 663719.
email: [email protected] website: http://www.fbk.com
Manual: 33-005-3M5 Ed02 062000 Printed in England by Fl Ltd, Crowborough
Feedback Part No. 1160–330053M5
Notes
DIGITAL PENDULUM SYSTEM
External Interface Preface
PRODUCT IMPROVEMENTS
We maintain a policy of continuous product improvement by incorporating the latest developments and components into our equipment,
even up to the time of dispatch.
All major changes are incorporated into up-dated editions of our manuals and this manual was believed to be correct at the time of
printing. However, some product changes which do not affect the instructional capability of the equipment, may not be included until it
is necessary to incorporate other significant changes.
COMPONENT REPLACEMENT
Where components are of a ‘Safety Critical’ nature, i.e. all components involved with the supply or carrying of voltages at supply
potential or higher, these must be replaced with components of equal international safety approval in order to maintain full equipment
safety.
In order to maintain compliance with international directives, all replacement components should be identical to those originally
supplied.
Any component may be ordered direct from Feedback or its agents by quoting the following information:
33-005-3M5 i
DIGITAL PENDULUM SYSTEM
Preface External Interface
This equipment, when operated in accordance with the supplied documentation, does not cause electromagnetic disturbance outside
its immediate electromagnetic environment.
COPYRIGHT NOTICE
ACKNOWLEDGEMENTS
Feedback Instruments Ltd acknowledge all trademarks.
MICROSOFT, WINDOWS 95, WINDOWS 3.1 , WINDOWS NT are registered trademarks of Microsoft Corporation.
ii 33-005-3M5
DIGITAL PENDULUM SYSTEM
External Interface Contents
TABLE OF CONTENTS
1. Introduction 1-1
33-005-3M5 TOC 1
DIGITAL PENDULUM SYSTEM
Contents External Interface
10. Example 4: Simulink Model for the 2-D Pid Controller 10-1
TOC 2 33-005-3M5
CHAPTER 1
DIGITAL PENDULUM SYSTEM
External Interface Introduction
1. Introduction
Although the Real-Time Kernel (RTK) for the inverted pendulum and the MATLAB
interface create a complete self-contained environment for real-time experiments, its
applicability is limited to a fixed number of embedded controllers.
The External Interface (EI) to the Real-Time Kernel was developed to extend the features
of the control software. The interface provides the way in which user-designed controllers
can be added to the RTK and implemented in real time. To more experienced users the
External Interface offers an access path to the RTK and makes the control technology
more open.
The external DLL library interface opens the way to add new
controllers to the Real Time Kernel. The main advantage of the
☞ external interface is that the user does not need to know the
implementation details of the real-time program.
The main part of this manual describes procedures for creating C-code DLL libraries. It
should be noted that it is also possible to develop similar procedures for FORTRAN or
other high level languages.
• C programming language
It is also assumed that the reader is a licensed user of a C language compiler suitable to
produce DLL executable files for MS-Windows/Windows95/Windows NT operating
system and that the compiler is properly installed , and one knows how to use it.
This manual begins with a short description of the Real-Time Kernel and presents both its
general structure and the principles of data exchange between modules of the system.
The manual continues with a discussion of the structure of a DLL external library which is
appropriate for the creation of external controllers and instructions how to compile and
link DLL libraries are given.
33-005-3M5 1-1
CHAPTER 1
DIGITAL PENDULUM SYSTEM
Introduction External Interface
In section 4 the shells of two basic functions exported from the external DLL for the
inverted pendulum are described in detail - the ExternalController and ExternalPC The C-
code template for the External DLL Library, which is a particularly useful tool for creating
control algorithms, is also included. In section 5 a reference list of functions associated
with the external DLL library is given and in section 6 a short overview of the external
controller is given. Finally, three examples of controller implementation are shown.
The version for MATLAB version 4 works in MS-Windows and Windows 95. There are
two versions of DLLs available: one for MATLAB 4 and another for MATLAB 5. The
differences in external DLL implementation for both versions are caused by the
differences between 16-bit and 32-bit DLL libraries. The C-sources of the DLL libraries
contain statements specific for 16-bit or 32-bit libraries and code common for both
versions. In this book it is assumed that the WIN32 pre-processor directive is declared
when the user creates the 32-dit DLL library.
The C-source code able to distinguish 16-bit and 32-bit DLL has the following form:
#ifdef WIN32
..........
#else
..........
#endif
This manual describes the creation and application of DLL libraries for both 16-bit and 32-
bit versions. Major differences in implementation and operation are distinguished in the
separate chapters.
The example files of external DLL libraries are installed in the directory containing the
software for Inverted Pendulum system in the EXTERNAL subdirectory.
1-2 33-005-3M5
CHAPTER 1
DIGITAL PENDULUM SYSTEM
External Interface Introduction
MK_BC16.BAT - file used to create 16-bit DLLs dedicated for Borland C/C++ compiler
version 3.1
MK_BC32.BAT - file used to create 32-bit DLLs dedicated for Borland C/C++ compiler
version 5.0
MK_MC16.BAT - file used to create 16-bit DLLs dedicated for Visual C/C++ compiler
version 1.5
MK_MC32.BAT - file used to create 32-bit DLLs dedicated for Visual C/C++ compiler
version 2.0
MK_WC16.BAT - file used to create 16-bit DLLs dedicated for Watcom C/C++ compiler
version 10.6
MK_WC32.BAT - file used to create 32-bit DLLs dedicated for Watcom C/C++ compiler
version 10.6
PD_2DPID.C - C-code used to create PID controller external DLL (see section 9 for
details)
33-005-3M5 1-3
CHAPTER 1
DIGITAL PENDULUM SYSTEM
Introduction External Interface
The EXTERNAL directory contains a collection of compiled DLLs both for 16-bit and 32-
bit versions. Remember to change the extensions of the selected *.D16 and *.D32 files in
the EXTERNAL directory to the extension DLL before usage.
IMPORTANT !!!
The correct place to locate all DLLs is the MATLAB root directory. Execute
the matlabroot command in the MATLAB Command Window to find the root
directory of the MATLAB program. Remember that during experiments with
☞
external DLLs the MATLAB current directory must be the same as the
MATLAB root directory. Use the pwd MATLAB command to check the name
of the current directory. If necessary, use the cd command in the MATLAB
Command Window to change the current directory.
1-4 33-005-3M5
CHAPTER 2
DIGITAL PENDULUM SYSTEM
External Interface Structure of the RTK DLL
The general structure of the 16-bit control system is shown in Fig.2.1. The main part is the
RTK DLL library (the pd_dll.dll file). It contains measurement procedures, digital filters,
data acquisition buffer, built-in control algorithms, software to control actuators, internal
excitation generator, set of controller parameters, MATLAB-to-RTK interface software and
interface for external DLL libraries.
The RTK controls the flow of all signals from and to the process and contains functions
performing analogue-to-digital and digital-to-analogue conversions. The RTK DLL library
is excited by timer interrupts. The main part of the RTK is executed during interrupt time.
The Interface software performs data format conversion between the RTK library and the
MATLAB environment (the interface procedures are included in the pd_call.dll file). The
Inter-Process Communication Protocol is used to set parameters of the RTK and to read
information from the RTK DLL library. Typically, the RTK library is monitored by a
MATLAB program, but any other MS-Windows or Windows 95 program can be used in
the supervisor layer. The RTK DLL library and the Interface software are designed to
support External DLL libraries. The external library contains controller and interface
software written by the user in the special form required by the RTK DLL library. As
opposed to the built-in RTK algorithms, usage of the external DLL allows the possibility for
the user to add new control algorithms, and provides the facility to extend the features of
the control software.
The RTK designed for the MATLAB 5 and Windows 95 uses only one DLL: pd_call.dll file,
which contains both the RTK and Interface Software (see Fig.2.2).
The RTK version for Windows NT operating system requires a special device driver
(RTKIO.SYS) to allow access to the I/O address space. The access to the I/O space is
limited in Windows NT and that is why the device driver is absolutely necessary. All “read”
and “write” operations for the I/O Board are performed using this driver (see Fig.2.3).
The basic information required to implement a new algorithm is described in this section.
33-005-3M5 2-1
CHAPTER 2
DIGITAL PENDULUM SYSTEM
Structure of the RTK DLL External Interface
* "' +
* "' +
& - " *
Fig.2.2. General structure of the control system for MATLAB 5 and Windows 95.
2-2 33-005M5
CHAPTER 2
DIGITAL PENDULUM SYSTEM
External Interface Structure of the RTK DLL
P R OCE S S
Device Driver
E x ternal DL L L ibrary
RT K
( pd_ call.dll )
T imer Interrupts
Fig.2.3. General structure of the control system for MATLAB 5 and Windows NT.
The RTK DLL library contains a set of built-in control algorithms selected by their
numbers. The open loop control, rule-based controller, PID controller and state-space
controller are implemented and included in the RTK. To start experiments, the RTK library
must be loaded into the memory first, followed by the external DLL library.
To call the controller from the external DLL the algorithm number 99 must be chosen
(see Fig.2.4). In this case the RTK library calls the external library controller procedure
during interrupt time. The RTK library passes the array of RTK parameters, current angle
and velocity of the pendulum, position and velocity of the cart, current time value and
reference value to the controller procedure as arguments. The controller procedure
returns the control value for the DC drive. The interface software is used to exchange
information between the external DLL library and the MATLAB environment (e.g. to set
and get parameters or to choose the operating mode of the external library).
33-005-3M5 2-3
CHAPTER 2
DIGITAL PENDULUM SYSTEM
Structure of the RTK DLL External Interface
T imer
Interrupt
Measurements
Data Acquisition
Digital filters
S ens ors
- R eference Value
Generator
P R OCE S S
Actuators
Inter-Process
Communication
R eturn from Procedure
Interrupt Handling
Procedure
Interface
S oftware
The external DLL library can be removed from the memory when the experiment is
finished. Another external DLL library can then be loaded end executed. However, it is not
necessary to unload the RTK library from the memory when changing the executed
external DLL. The external DLL operating mode is a fast way to test different versions of
control algorithms.
2-4 33-005M5
CHAPTER 3
DIGITAL PENDULUM SYSTEM
External Interface External DLL Library
There are several factors that need to be understood in order to create your own external
DLL libraries. This section describes the structure of such a library appropriate for the
development of user-defined controllers.
There are two different structures of the 16-bit and 32-bit DLL libraries. They are
described in the following sections.
The main components needed to create the 16-bit DLL are shown in Fig.3.1.
module definiton
file *)
DLL
External Library
C-code source file compiler ExternalController
LibMain
ExternalIPC
WEP**)
ExternalController
*)
ExternalIPC option
**)
required by
some compilers
The C-source of an external DLL library must contain the following functions:
LibMain - function called by Windows during DLL initialisation. Use this function to
initialise an external controller. For example, the following code creates a simple LibMain
function:
#include <windows.h>
#include <stdio.h>
int FAR PASCAL LibMain( HINSTANCE hInstance,
WORD wDataSegment,
WORD wHeapSize,
33-005-3M5 3-1
CHAPTER 3
DIGITAL PENDULUM SYSTEM
External DLL Library External Interface
LPSTR lpszCmdLine )
{
char msg_str[ 128 ];
sprintf( msg_str, "External DLL Library: %s", __FILE__ );
MessageBox( (HWND)NULL,
"Entry point to external DLL reached",
msg_str, MB_OK );
/* */
/* Insert your initialisation code here */
/* */
Double #include directives include function prototypes. The definition of the string variable
msg_str, the call of the sprintf function and the call of the MessageBox function are used
to display the following window:
The string __FILE__ contains the name of a current source file (PD_2DPID.C in the
following example). The window appears every time the external DLL library is loaded into
the memory (see description of the LoadExtAlg function below). If you do not want to
display the window remove the first three statements in the function LibMain.
If your controller requires initialisation, insert the appropriate statements before returning
from the LibMain function. For instance, if you want to allocate memory on the global
heap, call the GlobalAlloc and the GlobalLock functions, etc. (compare Example 3 in
section 8),
WEP - performs a cleanup of a dynamic-link library (DLL) before the library is unloaded.
This function is called by MS-Windows. Although the WEP function was required for
every dynamic-link library in the previous versions of the MS-Windows operating system,
3-2 33-005M5
CHAPTER 3
DIGITAL PENDULUM SYSTEM
External Interface External DLL Library
for version 3.1, the WEP function is optional. Use this function to terminate the external
controller operation safely. A simple example of a WEP function is shown below:
#pragma argsused
int FAR PASCAL WEP ( int bSystemExit )
{
char msg_str[ 128 ];
sprintf( msg_str, "External DLL Library: %s", __FILE__ );
MessageBox( (HWND)NULL,
"Exit point of external DLL reached",
msg_str, MB_OK );
/* */
/* Insert your termination code here */
/* */
return 1;
}
This WEP function displays the following window when the external DLL is removed from
the memory (see description of the UnloadExtAlg function below):
The above message window is not obligatory. You can remove it if you do not want any
additional messages during the removal of external DLL’s from the memory. If your
controller requires termination action, insert appropriate statements before returning from
the WEP function. For instance, if you have allocated memory on the global heap call the
GlobalUnlock and GlobalFree functions, etc.,
33-005-3M5 3-3
CHAPTER 3
DIGITAL PENDULUM SYSTEM
External DLL Library External Interface
ExternalIPC - function used to exchange information between an external DLL library and
MATLAB/Simulink environment. This function is called by the interface software
procedure pd_call from MATLAB, so it is not executed during the interrupt time. See
section 4 for implementation details, of additional user-defined application-dependent
functions.
Because the procedure of an external controller is located in the external library and is
executed during interrupt time, it must reside in the DLL, and its code memory segment
must be specified as FIXED. Any data used by the external controller must be located in a
FIXED data memory segment as well. The external controller can call ONLY the following
API functions: PostMessage, timeGetSystemTime, timeGetTime, timeSetEvent,
timeKillEvent, midiOutShortMsg, midiOutLongMsg, and OutputDebugStr.
The external inter-process procedure is not executed during interrupt time, so it may call
any system functions.
The parameters of memory modules are usually specified in the module definition files.
The module definition file usually contains information necessary to create a DLL library
with appropriate parameters of the memory segments. An example of the module
definition file is listed below.
LIBRARY PD_2DPID
DESCRIPTION 'Pendulum External Algorithm for Real-Time Task'
EXETYPE WINDOWS
CODE PRELOAD FIXED
DATA PRELOAD FIXED
HEAPSIZE 1024
STACKSIZE 1024
3-4 33-005M5
CHAPTER 3
DIGITAL PENDULUM SYSTEM
External Interface External DLL Library
EXPORTS
WEP @1 RESIDENTNAME
ExternalController @2 RESIDENTNAME
ExternalIPC @3 RESIDENTNAME
LIBRARY PD_2DPID
specifies the name of the library module. The linker uses the name to create pd_2pid.dll
file,
inserts text into the application module. It is useful for inserting the version number or
copyright information,
EXETYPE WINDOWS
specifies the header type of a generated executable file. It must be defined as WINDOWS
in the case of executable files intended for the MS-Windows environment,
indicate the attributes of the code and data segments. The PRELOAD option specifies
that the segment is loaded when the module is loaded for the first time. The FIXED option
indicates that the segment remains at a fixed memory location and can be used by
interrupt procedures,
HEAPSIZE 1024
specifies the number of bytes needed by an application for its local heap. The application
uses the local heap whenever it allocates local memory. The size of the local heap must
be large enough to allocate memory regions required by the external controller. The
default local heap size is zero. The minimum size is 256 bytes. The heap size must not
exceed 65536 bytes. If you do not intend to allocate memory or you do not want to use
local heap this statement may be omitted. In this case you are still able to use the global
heap,
STACKSIZE 1024
specifies the number of bytes needed by the DLL for its local stack. A DLL uses the local
stack whenever it makes function calls,
33-005-3M5 3-5
CHAPTER 3
DIGITAL PENDULUM SYSTEM
External DLL Library External Interface
EXPORTS
WEP @1 RESIDENTNAME
ExternalController @2 RESIDENTNAME
ExternalIPC @3 RESIDENTNAME
specifies the names and attributes of the functions to be exported to other applications.
The EXPORTS keyword marks the beginning of definitions. It can be followed by any
number of export definitions, each in a separate line. Three functions: WEP,
ExternalController and ExternalIPC must be implemented in C-code and exported.
Additional functions can be exported if necessary. The attribute @number defines the
location of the function name in its application string table. The attribute RESIDENTNAME
indicates that the function must be resident all the times. If necessary, you may add your
own functions to the EXPORTS directive.
The module definition file can be created by any text editor. The typical extension of this
file is DEF. The example given above is stored in the file pd_2dpid.def (the \EXT_DLL
directory on the installation diskette).
The use of a module definition file depends on the linker type. Some linkers do not require
a module definition file to create a DLL and to correctly set parameters of memory
segments. Consult the description of your compiler and linker for details.
3-6 33-005M5
CHAPTER 3
DIGITAL PENDULUM SYSTEM
External Interface External DLL Library
In this section we explain how to compile and link DLL libraries using Borland C++ v.3.1,
WATCOM C/C++ v.10.6 or Microsoft Visual C++ ver.1.5 compilers. If you want to use
another compiler consult the documentation for proper use of the compiler and linker.
Replace the E:\BCPP strings by the path to root directory of the Borland C++ compiler.
Replace the filename.c by the name of your C-code source file. The bcc program
performs both compiling and linking.
The presented command creates MS-Windows executable DLL file (option -WD ), with
code generated for 80386 microprocessor and for the 80287/80387 floating point unit
(options -3 and -f287 ). The command doesn't force compilation in C++ mode (option -P-
). It defines the names of directories containing header files and libraries (options -I and -
L). The code is generated in the large memory model (option -ml ).
The bcc program requires a module definition file accessible during the linking process.
The module definition file must have the same name as the source file. It must have the
extension DEF. For instance, if the name of your C-code source file is pd_2dpid.c the
module definition file must be stored in the file pd_2dpid.def.
The WATCOM C/C++ compiler does not require a module definition file. Instead, an
additional file with options for the linker must be created. The following batch file compiles
and links DLL library.
rem COMPILE
wcc filename.c -ml -zu -bd -bt=windows
33-005-3M5 3-7
CHAPTER 3
DIGITAL PENDULUM SYSTEM
External DLL Library External Interface
rem LINK
wlink @wc_10.lnk
del wc_10.lnk
The compiler wcc compiles the filename.c file in the large memory model (-ml), sets the
SS segment register to a different value than the DGROUP (-zu) and prepares the object
file for DLL in the MS-Windows system (-bd and -bt=windows). The wc_10.lnk file
contains options for the linker. The NAME filename and FILE filename.obj set the name of
DLL library and the name of the object file. The option stack=8k and option heapsize=8k
sets the size of the stack and the size of the local heap. The system windows_dll directive
is used to produce the DLL for MS-Windows library. Two segment directives set options
of the data and code segments. The export directives export function names.
3-8 33-005M5
CHAPTER 3
DIGITAL PENDULUM SYSTEM
External Interface External DLL Library
The cl command performs compilation. The link command links the DLL library. Replace
the file string with the name of your C-file in both commands.
The components needed to create the 32-bit DLL are shown in Fig.3.2.
The C-source code of the 32-bit external DLL library must contain the following functions:
DllMain - function called by Windows95 or Windows NT when the DLL library is:
• a thread is exiting cleanly in a process that has already loaded this DLL.
33-005-3M5 3-9
CHAPTER 3
DIGITAL PENDULUM SYSTEM
External DLL Library External Interface
Use this function to initialise and perform a cleanup for an external controller. For
example, the following code creates a simple DllMain function:
#include <windows.h>
#include <stdio.h>
switch (fdwReason)
{
case DLL_PROCESS_ATTACH:
// The DLL is being loaded for the first time by a given
// process. Perform per-process initialization here. If
// the initialization is successful, return TRUE; if
// unsuccessful, return FALSE.
/* */
/* Insert your initialization code here */
/* */
break;
3-10 33-005M5
CHAPTER 3
DIGITAL PENDULUM SYSTEM
External Interface External DLL Library
case DLL_PROCESS_DETACH:
// The DLL is being unloaded by a given process. Do any
// per-process clean up here, such as undoing what was
// done in DLL_PROCESS_ATTACH. The return value is
// ignored.
/* */
/* Insert your termination code here */
/* */
break;
case DLL_THREAD_ATTACH:
// A thread is being created in a process that has
// already loaded this DLL. Perform any per-thread
// initialization here. The return value is ignored.
//
// NOT USED in external DLLs
break;
case DLL_THREAD_DETACH:
// A thread is exiting cleanly in a process that has
// already loaded this DLL. Perform any per-thread
clean
// up here. The return value is ignored.
//
// NOT USED in external DLLs
break;
33-005-3M5 3-11
CHAPTER 3
DIGITAL PENDULUM SYSTEM
External DLL Library External Interface
}
return TRUE;
}
Double #include directives include function prototypes. The definition of string variable
msg_str, the call of the sprintf function and the call of the MessageBox function are used
to display the following window during loading the DLL:
and the following window during removing the DLL from the memory
The window appears every time the external DLL library is loaded to the memory (see
description of the LoadExtAlg function below). If you do not want to display the window
remove statements in the function DllMain.
If your controller requires initialisation, insert appropriate statements before the return
from the DllMain function in the DLL_PROCESS_ATTACH case statement. For instance, if
you want to allocate memory on the global heap call the GlobalAlloc and the GlobalLock
functions, etc. (compare Example 3 in section 8),
The DllMain function returns a BOOL value which is used only when fdwReason ==
DLL_PROCESS_ATTACH. The TRUE return value is used to signify that the DLL should
remain loaded. The FALSE value is used to signify that the DLL should be immediately
unloaded. For all other values of fdwReason, the return value is ignored.
3-12 33-005M5
CHAPTER 3
DIGITAL PENDULUM SYSTEM
External Interface External DLL Library
ExternalIPC - function used to exchange information between an external DLL library and
MATLAB/Simulink environment. This function is called by the interface software
procedure pd_call from MATLAB, so it is not executed during the interrupt time. The
external inter-process procedure is not executed during interrupt time, so it may call any
system functions. See section 4 for implementation details, of additional user-defined
application-dependent functions.
The procedure of an external controller is located in the external library and is executed
during interrupt time. The external controller can call ONLY the following API functions:
PostMessage, timeGetSystemTime, timeGetTime, timeSetEvent, timeKillEvent,
midiOutShortMsg, midiOutLongMsg, and OutputDebugStr.
In this section we explain how to compile and link DLL libraries using Borland C++ v.5.0,
WATCOM C/C++ v.10.6 and Microsoft Visual C++ ver.2.0 compilers. If you want to use
another compiler consult the documentation for proper use of the compiler and linker.
33-005-3M5 3-13
CHAPTER 3
DIGITAL PENDULUM SYSTEM
External DLL Library External Interface
To obtain a 32-bit DLL executable file execute the following command (see the
mk_bc32.bat file on the installation disk):
set BCR=J:\BC5
Replace the definition if the BCR variable by the path to root directory of the Borland C++
compiler. Replace the filename by the name of your C-code source file (without
extension).
The following batch file compiles and links 32-bit DLL library (see the mk_wc32.bat file
on the installation disk):
wcc386 filename.c -ih:\lang\watcom\h;h:\lang\watcom\h\nt -w4 -e25
-zq -otexan -bd -fp3 -4r -bt=nt -mf -dWIN32
3-14 33-005M5
CHAPTER 3
DIGITAL PENDULUM SYSTEM
External Interface External DLL Library
The compiler wcc386 compiles the filename.c file. Replace the h:\lang\watcom string
by the name of your WATCOM C/C++ root directory. Replace the filename string by the
name of your C-file.
To obtain a 32-bit DLL executable file execute the following command (see the
mk_mc32.bat file on the installation disk):
set MC_ROOT=g:\apps\msvc20
Replace the definition if the MC_ROOT variable by the path to root directory of the
Visual C++ compiler. Replace the filename by the name of your C-code source file
(without extension).
33-005-3M5 3-15
CHAPTER 3
DIGITAL PENDULUM SYSTEM
External DLL Library External Interface
Notes
3-16 33-005M5
CHAPTER 4
DIGITAL PENDULUM SYSTEM
External Interface Exported Functions
4. Exported Functions
Two functions from the external DLL must be implemented and exported. The first
one is named ExternalController. It contains "the body" of the implemented controller.
The interrupt handling procedure from RTK calls ExternalController at each sampling
period. The ExternalController procedure is accessed at interrupt time, so it may not call
any other operating system procedure except for: PostMessage, timeGetSystemTime,
timeGetTime, timeSetEvent, timeKillEvent, midiOutShortMsg, midiOutLongMsg, and
OutputDebugStr.
NOTICE:
The ExternalController function is executed during each sampling period. You can use
input arguments passed to this function to calculate control for the D/A converter. The
function is called by RTK when:
the external DLL library was loaded successfully (use pd_call( 'LoadExtAlg', DLL_name )
in MATLAB command window) and,
the algorithm number was set to 99 (execute pd_call( 'SetAlgNo', 99 ) in the MATLAB
command window).
33-005-3M5 4-1
CHAPTER 4
DIGITAL PENDULUM SYSTEM
Exported Functions External Interface
The shell of the ExternalController is listed below. Notice that the macro definition WIN32
is used to distinguish statements dedicated for 16-bit and 32-bit DLLs (or for MATLAB 4
and MATLAB 5).
#ifdef WIN32 /* for MATLAB 5 */
DLLEXPORT void __stdcall ExternalController(
double *Param,
double PendPos,
double PendVelocity,
double CartPos,
double CartVelocity,
double Time,
double DesValue,
double *Control )
#else /* for MATLAB 4 */
void FAR PASCAL ExternalController(
double far *Param, /* Parameters of the controller
*/
double far PendPos, /* Angle [rad]
*/
double far PendVelocity, /* Angular velocity [rad/s]
*/
double far CartPos, /* Cart's position [m]
*/
double far CartVelocity, /* Cart's velocity [m/s]
*/
double far Time, /* Time [s]
*/
double far DesValue, /* Desired value of the cart [m]
*/
double far *Control ) /* Calculated control value
*/
#endif
{
double ctrl = 0.0;
/* */
/* Put the source code of your controller here */
4-2 33-005M5
CHAPTER 4
DIGITAL PENDULUM SYSTEM
External Interface Exported Functions
*Control = ctrl;
}
Param - pointer to the array containing twenty parameters. The parameters may be set by
the pd_call( 'SetP', new_array ) function from the MATLAB command window. If the
values of the parameters are required in the MATLAB workspace execute the pd_call(
'GetP' ) command. Use both functions to tune parameters during real-time experiments,
in the on-line mode,
PendPos - angular position of the pendulum. The angle is expressed in radians. The
down position is equal to ±π rad. The upright position is equal to 0 rad. Notice, that before
starting your experiments you must execute pd_call( 'ResetEncoder' ) function when the
cart is placed in the centre of the rail and the pendulum is in its down position (the cart
and the pole are motionless). The angle changes by ±2π each full revolution of the
pendulum. For instance, if the pendulum has performed one full revolution the angle of
down position is equal to +3π rad or to −3π rad and the angle of the upright position is
equal to +2π rad or to −2π rad. The sign of the angular position depends on the direction
of motion,
CartPos - position of the cart on the rail relative to the position set by the execution of
pd_call( 'ResetEncoder' ) command. The position is expressed in meters. The working
range of the rail is approximately equal to ±0.6 m,
CartVelocity - linear velocity of the cart expressed in m/sec. The velocity is calculated
according to the following formula:
33-005-3M5 4-3
CHAPTER 4
DIGITAL PENDULUM SYSTEM
Exported Functions External Interface
Time - time calculated from the beginning of the experiment or from the executing of the
pd_call( 'ResetTime' ) command. Time is expressed in [s],
DesValue - desired position of the cart on the rail. This value can be set by the pd_call(
'SetDesPosition', new_des_position ) function and get by the call of the pd_call(
'GetDesPosition) function,
Control - pointer to control value for the DC drive. The control must be calculated by the
ExternalController function and assigned to variable pointed to by Control pointer in the
expression:
*Control = new_control_value;
The range of control value is ±1.0. The control equal to +1.0 yields full output action in
one direction, and the control equal to -1.0 yields full output action in the opposite
direction. The calculated control value is stored in the data buffer located in RTK and may
be accessed by the pd_call( 'GetHistory' ) function.
In the example given above the ExternalController function does not correspond to any
particular controller. It performs only range checking and assigning of control value. The
full implementation of a simple controller is shown in Example 1.
The ExternalController function can be called directly from MATLAB environment. In this
case the body of the function is not executed at the interrupt time (nonreal-time mode).
Such call can be useful as off-line testing before starting real-time experiments. See
description of the GetExtAlgOneStep function in section 5.
4-4 33-005M5
CHAPTER 4
DIGITAL PENDULUM SYSTEM
External Interface Exported Functions
The ExternalIPC function can be used to exchange information between the MATLAB
workspace and the external DLL library. Typically, it sets the parameters of the external
controller or gets the value of any variable located inside the external DLL.
External
IPC
IPC
External DLL in_arg MATLAB
Library
ACTION1
Control
Algorithm 99 pd_call(´CallExtIPC,
subfunction,
input_argument)
out_arg
no.of rows ACTION2
no.of columns
Auxiliary DATA ret=
data
out_arg ACTION3
Parameters
no.of rows
no.of columns ret=
DATA
33-005-3M5 4-5
CHAPTER 4
DIGITAL PENDULUM SYSTEM
Exported Functions External Interface
4-6 33-005M5
CHAPTER 4
DIGITAL PENDULUM SYSTEM
External Interface Exported Functions
33-005-3M5 4-7
CHAPTER 4
DIGITAL PENDULUM SYSTEM
Exported Functions External Interface
Notes
4-8 33-005M5
CHAPTER 5
Digital Pendulum System
External Interface Communications with MATLAB
The communication functions associated with the external DLL library have the following
form:
ret = pd_call( 'FunctionName’, [ arguments ] ), where:
ret - is the matrix returned from the function call,
pd_call - is the name of the interface between external DLL library and MATLAB
environment,
FunctionName - is the name of the operation performed by the pd_call interface. All the
operations associated with external DLL are given in the Table 5.1, and described in the
following sections. The operation name is passed as MATLAB string variable. The
FunctionName is not case sensitive. Arguments - are optionalarguments required by
some actions.
Operation Description
LoadExtLibrary Load external DLL library to the memory
and:
for MATLAB 4 execute the LibMain function,
for MATLAB 5 execute the statements
associated with the
DLL_PROCESS_ATTACH flag in the
DllMain function
UnloadExtLibrary For MATLAB 4 execute the WEP finction,
For MATLAB 5 execute the statements
associated with the
DLL_PROCESS_DETACH flag in the
DllMain function
and remove the external DLL library from the
memory
GetExtAlgName Return the name of a previously loaded DLL
library
CallExtIPC Execute the ExternalIPC procedure
ExtAlgOneStep Execute the ExternalController procedure.
The execution is initiated by MATLAB and is
performed in off-line mode
33-005-3M5 5-1
CHAPTER 5
DIGITAL PENDULUM SYSTEM
Communications with MATLAB External Interface
Arguments:
dll_name - is the full path and file name of the file containing external DLL library.
Typically, the file has the extension DLL. The dll_name is a string matrix in MATLAB
environment. If only the file name is specified the file is searched in:
the current directory,
the Windows directory (the directory containing WIN.COM),
the Windows system directory (the directory containing such system files as GDI.EXE),
the directories listed in the PATH environment variable.
The following error messages may be displayed in the MATLAB command window:
LoadExtAlg function requires two arguments - the LoadExtAlg function requires two
input arguments: the first is function name and the second is the name of external DLL,
LoadExtAlg function requires that the second argument is a string - the external DLL
library name must be a string.
After displaying an error message in the MATLAB command window the execution of the
function is terminated immediately.
The following messages may appear in the RTK message window:
5-2 33-005M5
CHAPTER 5
Digital Pendulum System
External Interface Communications with MATLAB
External library loaded. Unload it first - the external DLL library is already loaded. You
must remove the library from the memory first. Use the UnloadExtAlg function and next try
to load library once more,
Can not load xxxxx library - can not load DLL executable xxxxx. Consider one of the
following reasons for the error:
• system is out of memory, executable file is corrupt, or reallocations are invalid,
• file xxxxx is not found,
• path is not found,
• there is a sharing or network-protection error,
• application is designed for a different operating system,
• type of executable file is unknown,
• attempt is made to load a real-mode application developed for an earlier
version of Windows,
Can not find ExternalController function - there is no ExternalController function exported,
Can not find ExternalIPC function - there is no ExternalIPC function exported.
Example:
To load pd_2dpid.dll executable located in the D:\MATLAB\DLL directory execute the
following command:
ret = pd_call( 'LoadExtAlg', 'D:\MATLAB\DLL\PD_2DPID.DLL' )
33-005-3M5 5-3
CHAPTER 5
DIGITAL PENDULUM SYSTEM
Communications with MATLAB External Interface
Arguments: none.
Description: This function removes previously aa loaded external DLL from the
memory. Before removing it the WEP function (16-bit DLL) or the DllMain function (32-bit
DLL) is executed. If the number of the control algorithm in the RTK was equal to 99 then
the number of the control algorithm is set to zero. The function always returns a value of
1.
Example:
To remove the external DLL executable from the memory, execute the following
command:
ret = pd_call( 'UnloadExtAlg' )
5-4 33-005M5
CHAPTER 5
Digital Pendulum System
External Interface Communications with MATLAB
Purpose: Returns the full path and the name of loaded external DLL executable.
Arguments: none.
Description: This function returns a string matrix containing the full path and the name
of a previously loaded DLL library. The return value is equal to the second
argument of the LoadLibrary function. An empty matrix is returned if there
is no external library loaded or if the library was removed from the
memory.
Example:
33-005-3M5 5-5
CHAPTER 5
DIGITAL PENDULUM SYSTEM
Communications with MATLAB External Interface
5-6 33-005M5
CHAPTER 5
Digital Pendulum System
External Interface Communications with MATLAB
Description: This function calls the ExternalController function located in the external
DLL library. Unlike the ExternalController function executed by RTK this
function does not call the ExternalController at interrupt time. The control
value is calculated by the ExternalController function according to the
value of input_arguments and is returned to the MATLAB workspace as
ret value.
Typically, this function is used for non-real time testing of an external
control algorithm.
33-005-3M5 5-7
CHAPTER 5
DIGITAL PENDULUM SYSTEM
Communications with MATLAB External Interface
Example:
To obtain and plot a control value for different values of angle and angular velocity
execute the following commands:
i_ind = 1;
for i = -1 : 0.1 : 1
j_ind = 1;
for j = -1 : 0.1 : 1
surf( i_ind, j_ind ) = pd_call( 'ExtAlgOneStep', [ i j 0 0 0 0
] );
j_ind = j_ind + 1;
end
i_ind = i_ind + 1;
end
mesh( surf );
5-8 33-005M5
CHAPTER 6
DIGITAL PENDULUM SYSTEM
External Interface Basic Steps to implement an External Controller
The External Controller was developed to give you the ability to create and apply your
own control algorithm for the inverted pendulum system. In this section we present a short
summary of steps you must perform when you wish to add your control algorithm. The
section is an overview of information given in the previous sections. The applications are
given in sections 7,8, 9 and 10.
A user activity of creating its own controller consists of several obligatory and optional
steps. Several C-code files must be developed or adapted based on the given template
files. The structure of the external DLL is built of two parts: the ExternalController and the
ExternalIPC functions. The ExternalController provides a control routine and is accessed
at the interrupt time. The ExternalIPC consists of gateway routines and performs non real-
time communication with the MATLAB environment. Generally, a number of necessary C-
code files depends on complexity of the designed controller. For a simple control
algorithm one can minimise its effort creating only a source C-file on the basis of the C-
code template pd_tmf.c. If more complex algorithms are considered, e.g. neural, fuzzy,
adaptive etc. then it is recommended to create them as separate files and include into the
main source file.
Below are some recommendations which you should follow when developing and
executing external DLLs:
• Use the pd_tmf.c file as the template file of your external controller,
The DLL file containing an external controller must be located in the MATLAB
root directory. Execute the matlabroot command in the MATLAB Command
☞
Window to find out the MATLAB root directory. Remember, that during
experiments with external DLLs the MATLAB current directory must be this
same as the MATLAB root directory. Use the MATLAB command pwd to
check the name of the current directory and the cd to change it.
33-005-3M5 6-1
CHAPTER 6
DIGITAL PENDULUM SYSTEM
Basic Steps to implement an External Controller External Interface
The I/O structure of the ExternalIPC function is shown in section 4.2. Notice, that the
ExternalIPC function does not check the size of the input arguments. Therefore, you must
remember not to exceed the limits of input variables.
The SetP and GetP functions from Reference Manual implement the simple inter-process
communication between the MATLAB workspace and the RTK. These functions allow the
user to read/write from/to the array containing 20 numbers (see Reference Manual for the
detailed description of the SetP and GetP functions). This array is located in the RTK
workspace.
6-2 33-005M5
CHAPTER 6
DIGITAL PENDULUM SYSTEM
External Interface Basic Steps to implement an External Controller
The ExternalController operates in real-time (excited by the RTK timer) or in non real-time
mode (excited from MATLAB environment). Non-real time mode is used for testing and
debugging. The ExternalIPC establishes exchange of information between the workspace
of MATLAB and the ExternalController in both modes. Fig. 6.1 illustrates how to
communicate with the external DLL file.
TESTING MODE
ret = pd_call(‘LoadLibrary’) % RTK function
ret = pd_call(‘LoadExtAlg’, put dll.name here) % External
function
ret = pd_call(‘CallExtIPC’,’SetParam’,[.....]) % External
function
OPERATING MODE
33-005-3M5 6-3
CHAPTER 6
DIGITAL PENDULUM SYSTEM
Basic Steps to implement an External Controller External Interface
Notes
6-4 33-005M5
CHAPTER 7
DIGITAL PENDULUM SYSTEM
External Interface Example 1
Let us implement a controller to stabilise the pendulum near to the upright equilibrium
point. The assumed control law is:
4 4
U = 1 +
∑
i =1
D x 2
i i
∑K x
j =1
j j + friction _ compensation ,
The C-code source file is shown below (see pd_ss.c file on the installation disk). Notice,
that the ExternalIPC function is not performing any operation.
#include <windows.h>
#include <stdio.h>
#include <string.h>
#include <dos.h>
#include <math.h>
#ifdef WIN32
33-005-3M5 7-1
CHAPTER 7
DIGITAL PENDULUM SYSTEM
Example 1 External Interface
7-2 33-005M5
CHAPTER 7
DIGITAL PENDULUM SYSTEM
External Interface Example 1
case DLL_THREAD_DETACH:
break;
}
return TRUE;
}
return 1;
}
#endif
33-005-3M5 7-3
CHAPTER 7
DIGITAL PENDULUM SYSTEM
Example 1 External Interface
#ifdef WIN32
DLLEXPORT void __stdcall ExternalController(
double *Param,
double PendPos,
double PendVelocity,
double CartPos,
double CartVelocity,
double Time,
double DesValue,
double *Control )
#else
void FAR PASCAL ExternalController(
double far *Param, /* Parameters of the controller
*/
double far PendPos, /* Angle [rad]
*/
double far PendVelocity, /* Angular velocity [rad/s]
*/
double far CartPos, /* Cart's position [m]
*/
double far CartVelocity, /* Cart's velocity [m/s]
*/
double far Time, /* Time [s]
*/
double far DesValue, /* Desired value of the cart [m]
*/
double far *Control ) /* Calculated control value
*/
#endif
{
static double ctrl = 0.0;
static double x1, x2, x3, x4;
static double fc, K1, K2, K3, K4, D1, D2, D3, D4;
static double distance;
7-4 33-005M5
CHAPTER 7
DIGITAL PENDULUM SYSTEM
External Interface Example 1
/* Parameters */
fc = Param[ 0 ]; /* Friction compensation */
K1 = Param[ 1 ]; /* K1 */
K2 = Param[ 2 ]; /* K2 */
K3 = Param[ 3 ]; /* K3 */
K4 = Param[ 4 ]; /* K4 */
D1 = Param[ 5 ]; /* D1 */
D2 = Param[ 6 ]; /* D2 */
D3 = Param[ 7 ]; /* D3 */
D4 = Param[ 8 ]; /* D4 */
/* Auxiliary statements */
x1 = CartPos - DesValue; /* Error of the cart position */
x2 = PendPos;
x3 = CartVelocity;
x4 = PendVelocity;
/* Friction compensation */
if ( ctrl > 0.0 ) ctrl += fc;
if ( ctrl < 0.0 ) ctrl -= fc;
33-005-3M5 7-5
CHAPTER 7
DIGITAL PENDULUM SYSTEM
Example 1 External Interface
#ifdef WIN32
DLLEXPORT void __stdcall ExternalIPC(
char *str,
double *in_arg,
double *out_arg )
#else
void FAR PASCAL ExternalIPC(
char far *str, /* Function */
double far *in_arg, /* Input arguments */
double far *out_arg ) /* Output values */
#endif
{
*( out_arg + 0 ) = 1; *( out_arg + 1 ) = 1;
*( out_arg + 2 ) = -1; /* Always returns -1.0 */
}
Now, you can compile your DLL library. Next, start the experiment by executing the
following commands:
ret= pd_call('loadextalg', 'pd_ss.dll');
ret= pd_call('setp', [ ..... ] ); % Insert 9 parameters here
ret= pd_call('setalgno', 99 );
7-6 33-005M5
CHAPTER 8
DIGITAL PENDULUM SYSTEM
External Interface Example 2
The following set of commands loads the external DLL library pd_ss.dll , sets parameters
and calculates the value of control on the angle vs. angular velocity plane. The C-source
code of the DLL library is shown in the Example 1.
a= pd_call('loadlibrary');
a= pd_call('loadextalg', 'pd_ss.dll');
name = pd_call('getextalgname');
disp( [ 'Name: ' name ] );
p = pd_call( 'getp' );
p( 1 : 9 ) = [ 0.1 0.8 6.0 1.4 2.6 1.0 1.0 1.0 1.0 ];
ret = pd_call( 'setp', p );
surf = [];
i_ind = 1;
for i = -0.2 : 0.015 : 0.2
j_ind = 1;
for j = -0.4 : 0.03 : 0.4
surf( i_ind, j_ind ) = pd_call( 'ExtAlgOneStep',[ i j 0 0 0 0
]);
j_ind = j_ind + 1;
end
i_ind = i_ind + 1
end
a= pd_call('unloadextalg');
33-005-3M5 8-1
CHAPTER 8
DIGITAL PENDULUM SYSTEM
Example 2 External Interface
mesh( x, y, surf );
Control value
0.5
-0.5
-1
0.2
0.1 0.4
0 0.2
0
Angle of the pole -0.1 -0.2
-0.2 Angular velocity
-0.4
8-2 33-005M5
CHAPTER 9
DIGITAL PENDULUM SYSTEM
External Interface Example 3
We will implement the controller shown in figure 8.1. There are two PID controllers. The
first one controls the angular position of the pendulum. The second is used to control the
position of the cart. The outputs of the PID controllers are added to produce the final
control value for the D/A converter. Parameters of the controllers are exchanged using
the ExternalIPC function.
Desired
Pendulum Position
Pendulum
Position
- +
PIDPENDULUM
+ DC Drive Control
- +
PIDCART
Cart +
Position
Desired
Cart Position
33-005-3M5 9-1
CHAPTER 9
DIGITAL PENDULUM SYSTEM
Example 3 External Interface
I PENDULUM (t ) = K I _ PENDULUM ∫ eα dt ,
0
I CART (t ) = K I _ CART ∫ e S dt ,
0
where:
K I _ PENDULUM , K I _ CART - are gains of the I parts,
I PENDULUM _ SAT , I CART _ SAT - are the saturation values of the integrators.
The outputs from the PIDPENDULUM and PIDCART parts are equal to:
deα
U PENDULUM = K P _ PENDULUM eα + I PENDULUM (t ) + K D _ PENDULUM ,
dt
des
U CART = K P _ CART es + I CART (t ) + K D _ CART ,
dt
K P _ PENDULUM , K D _ PENDULUM , K P _ CART , K D _ CART - are parameters of the proportional and
derivative parts of the controller respectively.
Finally, the control for DC drive is:
U = U PENDULUM + U CART ,
if ( U < −U MAX ) thenU = −U MAX ,
if ( U > U MAX ) thenU = U MAX ,
where:
U MAX - is maximum value of the control.
9-2 33-005M5
CHAPTER 9
DIGITAL PENDULUM SYSTEM
External Interface Example 3
The C-code source file is shown below (see the pd_2dpid.c file on the installation disk).
#include <windows.h>
#include <stdio.h>
#include <string.h>
#include <dos.h>
#include <math.h>
#ifdef WIN32
#define DLLEXPORT __declspec(dllexport)
HINSTANCE hInstDLL;
#endif
33-005-3M5 9-3
CHAPTER 9
DIGITAL PENDULUM SYSTEM
Example 3 External Interface
case DLL_PROCESS_DETACH:
sprintf( msg_str, "External DLL Library: %s",
9-4 33-005M5
CHAPTER 9
DIGITAL PENDULUM SYSTEM
External Interface Example 3
ModuleName );
MessageBox( (HWND)NULL,
"Exit point of external DLL reached",
msg_str, MB_OK );
break;
case DLL_THREAD_ATTACH:
break;
case DLL_THREAD_DETACH:
break;
}
return TRUE;
}
33-005-3M5 9-5
CHAPTER 9
DIGITAL PENDULUM SYSTEM
Example 3 External Interface
return 1;
}
#endif
#ifdef WIN32
DLLEXPORT void __stdcall ExternalController(
double *Param,
double PendPos,
double PendVelocity,
double CartPos,
double CartVelocity,
double Time,
double DesValue,
double *Control )
#else
void FAR PASCAL ExternalController(
double far *Param, /* Parameters of the controller */
double far PendPos, /* Angle [rad] */
double far PendVelocity, /* Angular velocity [rad/s] */
9-6 33-005M5
CHAPTER 9
DIGITAL PENDULUM SYSTEM
External Interface Example 3
33-005-3M5 9-7
CHAPTER 9
DIGITAL PENDULUM SYSTEM
Example 3 External Interface
ErrAnglePrev = ErrAngle;
ErrPositionPrev = ErrPosition;
/* Control limits */
if( U > fabs( UMax ) ) U = fabs( UMax );
if( U < -fabs( UMax ) ) U = -fabs( UMax );
9-8 33-005M5
CHAPTER 9
DIGITAL PENDULUM SYSTEM
External Interface Example 3
*Control = U;
}
#ifdef WIN32
DLLEXPORT void __stdcall ExternalIPC(
char *str,
double *in_arg,
double *out_arg )
#else
void FAR PASCAL ExternalIPC(
char far *str, /* Function */
double far *in_arg, /* Input arguments */
double far *out_arg ) /* Output values */
#endif
{
char function[ 128 ];
33-005-3M5 9-9
CHAPTER 9
DIGITAL PENDULUM SYSTEM
Example 3 External Interface
TSample = *( in_arg + 9 );
RefAngle = *( in_arg + 10 );
RefPosition = *( in_arg + 11 );
*( out_arg + 0 ) = 1; *( out_arg + 1 ) = 1;
*( out_arg + 2 ) = 1;
return;
}
*( out_arg + 0 ) = 1; *( out_arg + 1 ) = 1;
*( out_arg + 2 ) = -1;
}
9-10 33-005M5
CHAPTER 9
DIGITAL PENDULUM SYSTEM
External Interface Example 3
Notice, that:
in the ExternalController we do not use the Param input argument. All parameters are
passed by the ExternalIPC function. You must set the parameters of the controller first
and start the controller next. Use the following commands:
pd_call( 'LoadLibrary' );
pd_call( 'LoadExtAlg', DLL_name );
par = [ your 12 parameter values ];
pd_call( 'CallExtIPC', 'SetParam', par );
pd_call( 'SetAlgNo', 99 );
the controller uses the desired values for the position of the cart and for the angle of the
pendulum. If the desired value of the angle is equal to zero the controller stabilises the
pendulum in the upright position. If the desired value is equal to ±π the cart-pendulum
system works as a crane.
Notice, that only two values for the pendulum's desired value
are admissible: 0 and ±π .
33-005-3M5 9-11
CHAPTER 9
DIGITAL PENDULUM SYSTEM
Example 3 External Interface
Notes
9-12 33-005M5
CHAPTER 10
DIGITAL PENDULUM SYSTEM
External Interface Example 4
There are two Simulink models available in MATLAB 5 - one for stabilising the pendulum
in the down position (crane mode) and the other for stabilising the pendulum in the upright
position (inverted pendulum mode). In both cases the controller described in the previous
section is used. It is obvious that the crane mode and the inverted pendulum mode
require different sets of controller parameters. A few different parameter sets were
prepared for both control modes and they are available in the Simulink models.
The names of the Simulink models for the crane mode and inverted pendulum mode are
pd_2ddn and pd_2dup respectively. They are stored in appropriate files on the installation
diskette. They files containing Simulink models have extension mdl.
The Simulink model for monitoring of the experiments with the pd_2dpid.dll library
operating in the crane mode is shown in Fig. 10.1. The main function of this model is not
to simulate the system but to transfer data to and from the Real Time Kernel. This is the
main difference between the model and a typical model in Simulink.
The main block of the presented Simulink model is Real Time Task. It contains the
S-function block calling the pd_2dsf.m S-function (see Fig. 10.2). The Real Time Task is
preceded by the signal generators, which act as references sources for the cart position.
The output of the Real Time Task is a vector which contains information about the
pendulum angle and angular velocity, the cart position, velocity and reference position,
and the control value for the DC drive. The values of the output vector can be shown on
Simulink scopes and are transferred to MATLAB workspace (To Workspace block) as the
hist variable. The hist matrix contains additionally the time vector (Clock block).
33-005-3M5 10-1
CHAPTER 10
DIGITAL PENDULUM SYSTEM
Example 4 External Interface
A n g le
C o n s ta n t R e d u c tio n
D o w n P o s itio n
o f A n g le
A n g u la r V e lo c i ty
P o s itio n
o f th e c a r t
C a r t's V e lo c ity
R e a l Ti m e T a s k
CART
( p o s & & d e s .p o s )
h is t C o n tr o l
P a ra m e te r S e ttin g s P a ra m e te r S e ttin g s
P a ra m e te r T u n in g
( d e fa u lt) ( a p e r io d ic a l)
P a ra m e te r S e ttin g s P a ra m e te r S e ttin g s
( o s c illa tio n s ) (c art only )
Fig. 10.1. Simulink model for the crane mode (pd_2ddn.m file).
1 pd_2dsf 1
in_1 out_1
INVERTED
External Algorithm
(pd_2dpid.dll)
The pd_2dsf.m file contains the S-function associated with the Real Time Task block. The
function has one parameter: down sampling ratio. This parameter decreases the rate of
output data flow from the output of the Real Time Task (see Fig. 10.3). For example, if the
downsampling coefficient is 10, for each ten sampling periods only one changes the
output of the block.
10-2 33-005M5
CHAPTER 10
DIGITAL PENDULUM SYSTEM
External Interface Example 4
The S-function block included in the Real Time Task block contains two parameters: the
S-function file name (pd_2dsf) and the downsampling coefficient value (ds) (see Fig.
10.4).
The name of the Real Time Task block parameter is set during masking of the Real-Time
Task block. See the Initialisation commands field in Fig. 10.5.
33-005-3M5 10-3
CHAPTER 10
DIGITAL PENDULUM SYSTEM
Example 4 External Interface
The Parameter Tuning block can be used to change parameters by using sliders (see Fig.
10.6). See the pd_2dsl.m file for implementation details of Fig. 10.6.
10-4 33-005M5
CHAPTER 10
DIGITAL PENDULUM SYSTEM
External Interface Example 4
Table 10.1.
Parameter Parameter Parameter Parameter
Settings Settings Settings Settings
(default) (aperiodical) (oscillations) (cart only)
KpAngle 7.0 5.0 6.0 0.0
KiAngle 0.0 0.0 0.0 0.0
KdAngle 0.0 0.0 0.0 0.0
KpPosition 10.0 10.0 16.0 10.0
KiPosition 2.8 1.0 2.0 1.0
KdPosition 3.0 5.0 1.0 5.0
IMaxAngle 0.8 0.8 0.8 0.8
IMaxPosition 0.8 0.8 0.8 0.8
UMax 0.8 0.8 0.8 0.8
TSample 0.01 0.01 0.01 0.01
RefAngle pi pi pi pi
RefPosition 0.0 0.0 0.0 0.0
33-005-3M5 10-5
CHAPTER 10
DIGITAL PENDULUM SYSTEM
Example 4 External Interface
The history of the experiment is transferred to the MATLAB workspace as the hist
experiment. The statements below can be used to display the history of the experiment.
The parameters were changed during data collection and you can notice different system
behaviour at the beginning and at the end of the experiment.
Angle
-2.7
-2.8
-2.9
-3
-3.1
-3.2
-3.3
-3.4
0 5 10 15 20 25 30 35 40
10-6 33-005M5
CHAPTER 10
DIGITAL PENDULUM SYSTEM
External Interface Example 4
0.2
0.1
-0.1
-0.2
-0.3
-0.4
0 5 10 15 20 25 30 35 40
33-005-3M5 10-7
CHAPTER 10
DIGITAL PENDULUM SYSTEM
Example 4 External Interface
Control
0.8
0.6
0.4
0.2
-0.2
-0.4
-0.6
-0.8
0 5 10 15 20 25 30 35 40
The "body" of the pd_2dsf.m S-function file is shown below. Notice that the S-function
uses the flag input argument in a different way from the usual. The flag equal to 0 is used
to set the size of the model (the number of continuous states, the number of discrete
states, the number of outputs and the number of inputs), to load the external library
containing the controller, to set default parameters of the controller, to set the sample
period, to start the experiment (set algorithm number to 99) and to set initial value of the
auxiliary variables used in the S-function. The flag equal to 2 is used to set a new value of
reference position of the cart. The value of the reference position is obtained from the
signal generator Position of the cart (Fig. 10.1) and is passed to the S-function as the
input argument u. The flag equal to 3 is used to read the history of the experiment from
the Real-Time Kernel and transfer it to the output of the Real Time Task block. The flag
equal to 4 is used to calculate the next discrete time point. This flag is used to
synchronise the time of the experiment and the time of Simulink model. The flag equal to
9 is used to terminate the experiment. The algorithm number is set to zero and the
external DLL controller is removed from the memory.
10-8 33-005M5
CHAPTER 10
DIGITAL PENDULUM SYSTEM
External Interface Example 4
global history
%
% The following outlines the general structure of an S-function.
%
switch flag,
case 0, % Initialization
% call simsizes for a sizes structure, fill it in and convert
it to a
% sizes array
sizes = simsizes;
33-005-3M5 10-9
CHAPTER 10
DIGITAL PENDULUM SYSTEM
Example 4 External Interface
sys = simsizes(sizes);
10-10 33-005M5
CHAPTER 10
DIGITAL PENDULUM SYSTEM
External Interface Example 4
% Wait for the first sample which may be send to the output
while ( eq( pd_call( 'GetNoOfSamples', 0 ), 0 ) )
;
end;
history=pd_call( 'GetHistory' )';
% Wait for the next sample transfered from the Real Time Task
to the
% output of the S-function
33-005-3M5 10-11
CHAPTER 10
DIGITAL PENDULUM SYSTEM
Example 4 External Interface
case 4, % GetTimeOfNextVarHit %
curr_len = size( history, 1 );
if( curr_len < downsamp )
while ( pd_call( 'GetNoOfSamples' ) + curr_len <= downsamp )
;
end;
history = [ history; pd_call( 'GetHistory' )' ];
end
sys = history( downsamp, 1 );
case 9, % Terminate
dummy = pd_call( 'SetAlgNo', 0 );
dummy = pd_call( 'UnloadExtAlg' );
sys = [];
10-12 33-005M5
CHAPTER 10
DIGITAL PENDULUM SYSTEM
External Interface Example 4
The Simulink model for the inverted pendulum mode is similar to the Simulink model for
the crane mode and is shown in Fig. 10.7.
Notice, that the controller cannot swing up the pendulum from a down position to
the upright position. The experiment must start with the pendulum placed in the
neighbourhood of the upright equilibrium point. If the pendulum falls down during the
experiment, it has to be turned up manually.
S e le c t S i m u la t io n / S t a r t
( N o t e : t h e p o le m u s t b e in t h e u p r ig h t p o s it i o n )
t o s t a r t m o n it o r in g
A n g le
C o n s ta n t R e d u c tio n
U p rig h t P o s itio n
o f A n g le
A n g u la r V e lo c ity
P o s itio n
o f th e c a rt
C a r t ' s V e l o c it y
R e a l T im e T a s k
CART
(p o s & d e s .p o s )
h is t
C o n tro l
T o W o rk s p a c e C lo c k
Fig. 10.7. Simulink model for the inverted pendulum mode (pd_2dup.m file).
The main differences between the controller for the crane mode and the controller for the
inverted pendulum mode are the sets of parameters. The parameters for the inverted
pendulum mode available in Simulink model ( blocks Parameter settings (default),
Parameter settings (cart pos. stabilisation) and Parameter settings (cart pos. neglected)
are shown in Table 10.2.
33-005-3M5 10-13
CHAPTER 10
DIGITAL PENDULUM SYSTEM
Example 4 External Interface
Table 10.2.
Parameter Parameter Parameter
Settings Settings Settings
(default) (cart. pos. (cart pos.
stabilisation) neglected)
KpAngle -40.0 -8.0 -8.0
KiAngle 0.0 0.0 0.0
KdAngle -1.0 -0.6 -0.6
KpPosition -10.0 -3.0 -0.8
KiPosition 0.0 0.0 0.0
KdPosition -2.0 -1.4 -1.4
IMaxAngle 0.8 0.8 0.8
IMaxPosition 0.8 0.8 0.8
UMax 0.8 0.8 0.8
TSample 0.01 0.01 0.01
RefAngle 0.0 0.0 0.0
RefPosition 0.0 0.0 0.0
10-14 33-005M5
CHAPTER 10
DIGITAL PENDULUM SYSTEM
External Interface Example 4
Angle
-3
-3.5
-4
-4.5
-5
-5.5
-6
-6.5
0 5 10 15 20 25 30
-6.22
-6.24
-6.26
-6.28
-6.3
-6.32
-6.34
0 5 10 15 20 25 30
33-005-3M5 10-15
CHAPTER 10
DIGITAL PENDULUM SYSTEM
Example 4 External Interface
0.25
0.2
0.15
0.1
0.05
-0.05
-0.1
-0.15
0 5 10 15 20 25 30
0.6
0.4
0.2
-0.2
-0.4
-0.6
-0.8
0 5 10 15 20 25 30
10-16 33-005M5