Products & Services Solutions Academia Support User Community Company

Learn more about xPC Target   

Example Visual Basic GUI Using COM Objects

Introduction

For demonstration purposes this chapter uses the Simulink model xpctank.mdl and requests that you enter tags for signals and parameters to create the Simulink model xpc_tank1.mdl. You will then build the real-time target application xpc_tank1.dlm and the GUI xpc_tank1_COM.exe application using the xPC Target COM API library and Microsoft® Visual Basic®.

Description of Simulink Water Tank Model

The xPC Target software includes the Simulink model xpctank.mdl. This is a model of a water tank with a pump, drain, and valve controller.

TankLevel — The water level in the tank is modeled using a limited integrator named TankLevel.

PumpSwitch — The pump can be turned off manually to override the action of the controller. This is done by setting PumpSwitch to 0. When PumpSwitch is 1, the controller can use the control valve to pump water into the tank.

ValveSwitch (drain valve) — The tank has a drain valve that allows water to flow out of the tank. Think of this as water usage or consumption that reduces the water level. This behavior is modeled with the constant block named ValveSwitch, the gain block Gain2, and a summing junction. The minus sign on the summing junction has the effect of producing a negative flow rate (drain), which reduces the water level in the tank.

When ValveSwitch is 0 (closed), the valve is closed and water cannot flow out of the tank. When ValveSwitch is 1 (open), the valve is open and the water level is reduced by draining the tank.

Controller — The controller is very simple. It is a bang-bang controller and can only maintain the selected water level by turning the control valve (pump valve) on or off. A water level set point defines the desired median water level. Hysteresis enables the pump to avoid high-frequency on and off cycling. This is done using symmetric upper and lower bounds that are offsets from the median set point. As a result, the controller turns the control valve (pump valve) on whenever the water level is below the set point minus the offset. The summing junction compares this lower bound against the tank water level to determine whether or not to open the control valve. If the pump is turned on (PumpSwitch is 1) water is pumped into the tank. When the water level reaches or exceeds the set point plus the upper bound, the controller turns off the control valve. When the water level reaches this boundary, water stops pumping into the tank.

Scope blocks — A standard Simulink Scope block is added to the model for you to view signals during a simulation. xPC Target Scope blocks are added to the model for you to view signals while running the target application. Scope id:1displays the actual water level and the selected water level in the tank. Scope id:2 displays the control signals. Both scopes are displayed on the target PC using a scope of type target.

The xpctank.mdl model is built entirely from standard Simulink blocks and scope blocks from the xPC Target software. It does not differ in any way from a model you would normally use with the software.

Creating a Simulink Target Model

A target application model is a Simulink model that describes your physical system and its behavior. You use this model to create a real-time target application, and you use this model to select the parameters and signals you want to connect to a custom graphical interface.

You do not have to modify this model when you use it with Simulink® 3D Animation™ or other third-party graphical elements.

Create a target application model before you tag block parameters and block signals to create a custom graphical interface:

  1. In the MATLAB Command Window, type

    xpctank

    A Simulink model for a water tank opens. This model contains a set of equations that describe the behavior of a water tank and a simple controller.

    The controller regulates the water level in the tank. This model contains only standard Simulink blocks and you use it to create the xPC Target application.

  2. From the File menu, click Save as and enter a new filename. For example, enter xpc_tank1 and then click OK.

Your next task is to mark the block properties and block signals. See Tagging Block Parameters and Tagging Block Signals. Building an xPC Target application that has been tagged generates a model-specific COM library, model_nameifaceCOM.dll, which you can later reference when writing your xPC Target COM API application.

Tagging Block Parameters

Tagging parameters in your Simulink model enables you to generate a model-specific COM library to provide access to model parameter IDs via the xPC Target COM API library. These interface blocks contain the parameters you connect to control devices (such as sliders) in your model. Tagging parameters makes it easier for you to refer to these parameters later, when you write your xPC Target COM API application.

This procedure uses the modelxpc_tank1.mdl (or xpctank.mdl) as an example. See Creating a Simulink Target Model.

  1. Open a Simulink model. For example, in the MATLAB window type xpc_tank1 or xpctank.

  2. Point to a Simulink block, and then right-click. For example, right-click the SetPoint block.

  3. From the menu, click Block Properties.

    A block properties dialog box opens.

  4. In the Description box, delete the existing tag and enter a tag to the parameters for this block.

    For example, the SetPoint block is a constant with a single parameter that selects the level of water in the tank. Enter the tag shown below.

    The tag has the following format:

    xPCTag(1, . . . index_n)= label_1 . . . label_n;
    • index_n — Index of a block parameter. Begin numbering parameters with an index of 1.

    • label_n — Name for a block parameter to connect to a property for the parameter you tag in the model. Separate the labels with a space, not a comma.

    label_1...label_n must consist of the same identifiers as those used by C/C++ to name functions, variables, and so forth. Do not use names like -foo.

    You can assign multiple labels to one tag, such as

    xPCTag(1)=label;xPCTag(1)=label2;

    You might want to assign multiple labels if you want to tag a parameter for different purposes. For example, you can tag a parameter to create a model-specific COM library. You might also want to tag a parameter to enable the function xpcsliface to generate a user interface template model.

    You can also issue one tag definition per line, such as

    xPCTag(1)=label;
    xPCTag(2)=label2;
  5. Repeat step 4 for the remaining parameters you want to tag.

    For example, for the Controller block, enter the tag

    For the PumpSwitch and ValveSwitch blocks, enter the tags

    To tag a block with four properties, use the following syntax:

    xPCTag(1,2,3,4)=label_1 label_2 label_3 label_4;

    To tag a block with at least four properties for the second and fourth properties, use the following syntax:

    xPCTag(2,4)=label_1 label_2;
  6. From the File menu, click Save as. Enter a filename for your model. For example, enter

    xpc_tank1

You next task is to tag block signals, if you have not already done so; then, create the model. See Tagging Block Signals.

Tagging Block Signals

Tagging signals in your Simulink model enables you to generate a model-specific COM library to provide access to model signal IDs via the COM API library. These interface blocks contain the signals you connect to display devices (such as labels) in your model. Tagging signals makes it easier for you to refer to these signals later, when you write your xPC Target COM API application. After you tag signals, you will be ready to build your xPC Target application.

This procedure uses the model xpc_tank1.mdl (or xpctank.mdl) as an example. See Creating a Simulink Target Model.

Notice that you cannot select signals on the output ports of any virtual blocks such as Subsystem and Mux blocks. Also, you cannot select signals on any function call signal output ports.

  1. Open a Simulink model. For example, in the MATLAB window type xpc_tank1 or xpctank.

  2. Point to a Simulink signal line, and then right-click.

  3. From the menu, click Signal Properties. For example, right-click the signal line from the TankLevel block.

    A Signal Properties dialog box opens.

  4. Select the Documentation tab.

  5. In the Description box, enter a tag to the signals for this line.

    For example, the TankLevel block is an integrator with a single signal that indicates the level of water in the tank. Enter the tag shown.

  6. Repeat step 5 for the remaining signals you want to tag.

    For example, for the signal from the ControlValve block, enter the tag pump_valve.

    Signal tags have the following syntax:

    xPCTag(1, . . . index_n)=label_1 . . . label_n;
    • index_n — Index of a signal within a vector signal line. Begin numbering signals with an index of 1.

    • label_n — Name for a signal to connect to a property for the signal you tag in the model. Separate the labels with a space, not a comma.

    label_1...label_n must consist of the same identifiers as those used by C/C++ to name functions, variables, and so forth. Do not use names like -foo.

    For single-dimension ports, the following syntax is also valid:

    XPCTag=label;

    You can assign multiple labels to one tag, such as

    xPCTag(1)=label;xPCTag(1)=label2;

    You might want to assign multiple labels if you want to tag a signal for different purposes. For example, you can tag a signal to create a model-specific COM library. You might also want to tag a signal to enable the function xpcsliface to generate a user interface template model.

    You can also issue one tag definition per line, such as

    xPCTag(1)=label;
    xPCTag(2)=label2;

    To tag a signal line with four signals (port dimension of 4) use the following syntax:

    xPCTag(1,2,3,4)=label_1 label_2 label_3 label_4;

    To tag the second and fourth signals in a signal line with at least four signals, use the following syntax:

    xPCTag(2,4)=label_1 label_2;
  7. From the File menu, click Save as. Enter a filename for your model. For example, enter

    xpc_tank1

Create the target application. See Creating the Target Application and Model-Specific COM Library.

Creating the Target Application and Model-Specific COM Library

Use this procedure to create a target application that you want to connect to a GUI application and the model-specific COM interface library (model_nameCOMiface.dll).

After you copy a Simulink model and tag the block parameters and block signals, you can create a target application and download it to the target PC. This procedure uses the Simulink model xpc_tank1.mdl (or xpctank.mdl) as an example (see Creating a Simulink Target Model).

  1. Start or reset the target PC with an xPC Target boot disk in the floppy drive. Ensure that there is no other application currently loaded on the target PC.

  2. If this is a new release of the product, ensure that you have configured the host PC with the appropriate settings, including the compiler.

  3. In the MATLAB window, type xpc_tank1 or xpctank.

    A Simulink window opens with the model.mdl file.

  4. From the Simulation menu, click Configuration Parameters.

    The Configuration Parameters dialog is displayed for the model.

  5. In the left pane, click the Real-Time Workshop node.

  6. In the Target selection section, click the Browse button at the RTW system target file list. Click xpctarget.tlc if it is not already selected, then click OK.

  7. In the left pane, click the xPC Target options node.

    The xPC Target options pane is displayed.

  8. Select the Build COM objects from tagged signals/parameters check box.

  9. Click the Solver node.

    The Solver pane is displayed.

  10. Check that the Stop time is long enough for you to interact with the target application.

  11. Click OK to save and exit.

  12. From the Tools menu, point to Real-Time Workshop, and then click Build model.

    Th e Real-Time Workshop, xPC Target, and a third-party C compiler create the target application xpc_tank1.dlm and the COM object library xpc_tank1COMiface.dll. The target application is also downloaded to the target PC.

  13. If you want, you can close the MATLAB Command Window.

Your next task is to create a Microsoft Visual Basic API application using COM objects. This API application connects and controls the target application. See Creating a New Microsoft Visual Basic Project. For more information about model-specific COM interface library, refer to Model-Specific COM Interface Library (model_nameCOMiface.dll).

Model-Specific COM Interface Library (model_nameCOMiface.dll)

The generated model-specific COM interface library is a DLL component server library that enhances programming using the xPC Target COM API library. A model-specific COM interface library is specific to the model from which it is generated; do not reference a model-specific library for another model. If you choose not to generate a model-specific COM interface library, refer to Referencing Parameters and Signals Without Using Tags for a description of how to otherwise reference parameters and signals in the xPC Target COM API application.

The mode-specific COM interface library allows users easy access to preselected tagged signals and desired tagged parameters for use in conjunction with the xPC Target COM API xPC Target and xPCScope object signal monitoring and parameter member functions such as xPCTarget.GetParam, xPCTarget.SetParam, and xPCTarget.GetSignal.

The xPC Target COM generated objects are of two types:

where model_name is the name of the Simulink model. The model_namebio type is for tagged block I/O signals and the model_namept type is for tagged parameters.

Model-Specific COM Signal Object Classes

Model-specific COM signal classes have two types of members in which you are interested, the Init function and class properties. You will find these members in the model_namebio class, where model_name is the name of your model.

The Init function invokes the Init method once, passing it the Ref property from the xPCProtocol class. This method initializes the object to communicate with the appropriate target PC to access the signal identifiers when accessing the object's properties. Refer to the call in the Microsoft Visual Basic code example in Creating the Load Procedure.

Each class has a list of properties (specified in the Tag syntax in the Description field of the signal property). These properties return the xPC Target signal identifiers or signal numbers of the tagged signals. The generated property name is the name specified in the tagged signal description using the following syntax:

xPCTag=Property name;

For example, in the model xpc_tank1.mdl, there are two signal tags in the Description field:

Model-Specific COM Parameter Object Classes

Model-specific COM signal classes have two types of members in which you are interested, the Init function and class properties. You will find these members in the model_namept class, where model_name is the name of your model.

The Init function invokes the Init method once, passing it as input the Ref property from the xPCProtocol class. This method initializes the object to communicate with the appropriate target PC to access the parameter identifiers when accessing the object's properties. Refer to the call in the Microsoft Visual Basic code example in Creating the Load Procedure.

Each class has a list of properties (specified in the Tag syntax in the Description field of the block property). These properties return the xPC Target parameter identifiers of the tagged parameters. The generated property name is the name specified in the tagged signal description using the following syntax:

xPCTag(1)=Property name;

For example, in the model xpc_tank1.mdl, there are two parameter tags in the Description field:

Creating a New Microsoft Visual Basic Project

The following procedures describe how you can create a Microsoft Visual Basic project to take advantage of the xPC Target COM API to create a custom GUI for the xPC Target application. The procedures build on the xpctank (xpc_tank1) model you saved earlier (see Creating the Target Application and Model-Specific COM Library). The Microsoft Visual Basic environment allows you to interact with your target application using a GUI while the target application is running in real time on the target PC.

The procedures for the following topics apply to Microsoft® Visual Studio® 6.0. To use Microsoft Visual Studio 7.1 or 8.0 instead, see Creating a New Visual Basic Project Using Microsoft Visual Studio 7.1 or 8.0.

  1. Create a new project directory.

    From the directory matlabroot\toolbox\rtw\targets\xpc\api, copy the file xpcapi.dll (API library) to this new project directory. Alternatively, you can copy the file xpcapi.dll into the Windows system directory.

    You do not need to copy xpcapiCOM.dll (the COM API library) into the current directory, but ensure that it is registered in your system (see Registering Dependent Dynamic Link Libraries.)

  2. From your MATLAB working directory, copy the files model_name.dlm (target application) and model_nameCOMiface.dll (model-specific COM library) to the new project directory.

  3. While in this project directory, open Microsoft Visual Basic. From the File menu, click New Project.

    The New Project dialog box opens.

      Note   Be sure to open the Microsoft Visual Basic project from the project directory itself, not from Microsoft Visual Basic.

  4. Select Standard EXE, and then click OK.

    The Microsoft Visual Basic Integrated Development Environment opens with a blank form.

  5. From the File menu, click Save Project As and enter a filename for the form and the project. For example, for the form, enter

    xpc_tank1_COM.frm

    At the project prompt, enter

    xpc_tank1_COM.vbp

Referencing the xPC Target COM API and Model-Specific COM Libraries

You need to reference the xPC Target COM API and model-specific COM libraries so that Microsoft Visual Basic will use them in the current project. Assuming that you created the Visual Basic project as described in the preceding procedure, reference the library as described in this procedure:

  1. From the Project menu, click References.

    The References dialog box opens.

  2. Select the COM tab.

  3. Scroll down the Component Name list to the bottom. Select the xPC Target API COM Type Library check box.

  4. Click Select.

  5. Click OK.

    The xPC Target COM API Type library (xpcapiCOM.dll) is now available for use in your project.

  6. To add the model-specific COM library, click References again from the Project menu.

    The References dialog box opens.

  7. Scroll to find your model name. Select the check box xpc_tank1COMiface 1.0 Type Library.

  8. Click Select.

  9. Click OK.

    The model-specific COM API Type Library (xpc_tank1COMiface.dll) is now available for use in your project. Sections Viewing Model-Specific COM Signal Object Classes and Viewing Model-Specific COM Parameter Object Classes describe how to look at class objects.

Because the xPC Target COM API is an add-on to Visual Basic, it might help to know a bit about Visual Basic before going much farther with using the COM API. The section Creating the Graphical Interface guides you through using Visual Basic to create a project for the xpctank or (xpc_tank1) model.

Viewing Model-Specific COM Signal Object Classes

After you create a Visual Basic project and reference the xPC Target COM API and model-specific COM libraries, you can use the Visual Basic Object browser (click the View menu and select Object Browser) to look at the objects for the xpctankbio or xpc_tank1bio class:

  1. From the View menu, select Object Browser.

    A dialog box pops up with a drop-down list containing all the type library information for a project.

  2. Select the drop-down list for the project/library.

    A list of the project libraries appears.

  3. Select model_nameCOMIFACELib.

    The classes in your model appear.

  4. To view the objects of a class, select that class.

    The objects in your class appear.

The xpctankbio (or xpc_tank1bio) class contains the function Init and the two properties

Viewing Model-Specific COM Parameter Object Classes

After you create a Visual Basic project and reference the xPC Target COM API and model-specific COM libraries, you can use the Visual Basic Object browser (click the View menu and select Object Browser) to look at the objects for the xpctankpt or xpc_tank1pt class:

  1. From the View menu, select Object Browser.

    A dialog box pops up with a drop-down list containing all the type library information for a project.

  2. Select the drop-down list for the project/library.

    A list of the project libraries appears.

  3. Select model_nameCOMIFACELib.

    The classes in your model appear.

  4. To view the objects of a class, select that class.

    The objects in your class appear.

The xpctankpt (or xpc_tank1pt) class contains the method Init and the member properties

Creating the Graphical Interface

Forms are the foundation for creating the interface of a Visual Basic application. You can use forms to add windows and dialog boxes to your Visual Basic application. You can also use them as containers for items that are not a visible part of the application's interface. For example, you might have a form in your application that holds a timer object.

The first step in building a Visual Basic application is to create the forms that are the basis for your application's interface. Then you create the objects that make up the interface on the forms. This section assumes that you have a Visual Basic project (see Creating a New Microsoft Visual Basic Project). For this first application, you will use four types of controls from the toolbox:

  1. Open xpc_tank1_COM.vbp.

  2. On the left, from the General tool panel, click and drag the Button icon to the form to create a button.

  3. Repeat for a second button.

  4. If you want to view signal data on the host, return to the General tool panel and click and drag the Timer icon to the form to create a timer.

  5. If you want to view signal data on the host, add a Label control to the form. Return to the General tool panel and click and drag the Label icon to the form to create a label.

  6. If you want to be able to vary the parameter input to the target, return to the General tool panel and click and drag the HScrollBar icon to the form.

  7. Next, name your new form objects. Right-click the first button and select Properties. This brings up the Properties dialog box. In the Caption box, enter Load. Repeat for the second button, but enter Start. Repeat for the third button, but enter Stop. (If you are unsure about how to work with properties, refer to the procedure Setting Properties.) After you name your new form objects and set whatever other parameters you want (for example, if you use a timer you must increase the Interval parameter), you can write the code behind these objects using the Visual Basic code editor window (refer to Writing Code).

    If you added a scroll bar to your project, it should look similar to the figure below.

    If you added a timer and label to your project, it should look similar to the figure below.

      Note   If you add a timer, remember to increase the interval of the timer to a value greater than the default value of 0. Right-click the timer and select Properties. This brings up the Properties dialog box. In the Interval box, enter a value greater than 0, for example, 100.

Setting Properties

This procedure describes how to set properties for the Visual Basic objects you created on your form. If you already know how to set properties for Visual Basic objects, proceed to Writing Code.

The Properties window in the following figure provides an easy way to set properties for all objects on a form. To open the Properties window, choose the Properties Window command from the View menu, click the Properties Window button on the toolbar, or use the context menu for the control.

The Properties window consists of the following elements:

To set properties from the Properties window,

  1. From the View menu, choose Properties, or click the Properties button on the toolbar.

    The Properties window displays the settings for the selected form or control.

  2. From the properties list, select the name of a property.

  3. In the right column, type or select the new property setting.

    Enumerated properties have a predefined list of settings. You can display the list by clicking the down arrow at the right of the settings box, or you can cycle through the list by double-clicking a list item.

You can also set object properties directly in the code by using the following dot notation: Object.propertyname=value.

Writing Code

The code editor window is where you write Visual Basic code for your application. Code consists of language statements, constants, and declarations. Using the code editor window, you can quickly view and edit any of the code in your application.

The code editor window has three panes. The top leftmost pane is the object list box. It is a dropdown list that contains all the form controls in your project, plus a general section for generic declarations. The top rightmost pane contains a procedure list box. For the selected or active control in the object list box, the procedure list box displays the available procedures, or events. Visual Basic predefines the possible procedures. The third pane contains the code for the Visual Basic application. See the following figure for a sample code editor window.

In the general declarations section, declare a reference to the xPC Target COM objects that you are using to interface with the xPC Target objects. The following are the objects you need to declare:

Creating the General Declarations

This procedure describes how to create the general object declarations for the xpctank (or xpc_tank1) model:

  1. Double-click the form or, from the View menu, select Code.

    The code editor window box opens for the control.

  2. Select the General object.

  3. Select Declarations in the procedure list box.

    A template for the declarations procedure is now displayed in the code editor window.

  4. Enter declarations for the xPC Target COM objects you are using.

    Public protocol_obj As xPCProtocol
    Public target_obj As xPCTarget
    Public scope_obj As xPCScopes
    
  5. Enter declarations for the model-specific COM objects you are using.

    Public parameters_obj As xpc_tank1pt
    Public signals_obj As xpc_tank1bio

Creating the Load Procedure

This procedure describes how to program a load target application procedure for the form. You might or might not want to allow users to download target applications to the target PC. However, if you do want to allow this action, you need to provide a control on the GUI for the user to do so. Creating Event Procedures to Load Applications describes how to provide such a control.

  1. In the project window, double-click the Form object.

    The code editor window opens.

  2. In the procedure list box, select Load.

  3. Create and initialize the objects for the Load method in the form. Note that the following code also checks that the initialization of the protocol_obj succeeds. If it does not succeed, an error message is returned and the application will exit.

    Private Sub Form_Load()
        Set protocol_obj = New xPCProtocol
        Set target_obj = New xPCTarget
        Set scope_obj = New xPCScopes
        Set parameters_obj = New xpc_tank1pt
        Set signals_obj = New xpc_tank1bio
        stat = protocol_obj.Init
            If stat < 0 Then
                MsgBox("Could not load api") 'We can no longer continue.
                End
            End If
        stat = protocol_obj.RS232Connect(0, 0)
        stat = target_obj.Init(protocol_obj)
        stat = scope_obj.Init(protocol_obj)
        stat = parameters_obj.Init(protocol_obj.Ref)
        stat = signals_obj.Init(protocol_obj.Ref)
    End Sub

    You can add more code to the Load method. This is the minimum code you should enter for this method.

    Your code editor window should look similar to the following.

Creating Event Procedures

Code in a Visual Basic application is divided into smaller blocks called procedures. Event procedures, such as those you create here, contain code that mainly calls the xPC Target API component methods. For example, when a user clicks a button, that action starts the xPC Target application.

This code is also responsible for the feedback action (such as enabling a timer control, disabling/enabling controls) when an event occurs. An event procedure for a control combines the control's name (specified in the Name property), an underscore (_), and the event name. For example, if you want a command button named Command1 to invoke an event procedure when it is clicked, call the procedure Command1_Click. The following procedures illustrate how to create event procedures, using the xpctank (or xpc_tank1) model as an example.

Creating Event Procedures to Load Applications

This procedure describes how to program the command button Command1 to load an application to the target PC through a serial connection. Provide a procedure like this to allow users to download target applications to the target PC.

  1. Double-click the form or, from the View menu, select Code.

  2. From the object list box, select the name of an object in the active form. (The active form is the form that currently has the focus.) For this example, choose the command button Command1.

  3. In the procedure list box, select the name of an event for the selected object.

    Here, the Click procedure is already selected because it is the default procedure for a command button.

  4. To load the target application, enter the path to the target application. If the target application is in the same folder as the API application, enter ".". Enter the name of the target application without the extension.

    stat = target_obj.LoadApp(".", "xpc_tank1")

When you are done, the contents of your code editor window should look similar to the code below:

Private Sub Command1_Click()
    stat = target_obj.LoadApp(".", "xpc_tank1")
End Sub

Creating Event Procedures to Start and Stop Applications

This procedure describes how to program the command buttons Command2 and Command3 to start and stop an application on a target PC:

  1. If you are not already in the code editor window, double-click the form or, from the View menu, select Code.

  2. From the object list box, select the name of an object in the active form. (The active form is the form that currently has the focus.) For this example, choose the command button Command2.

  3. In the procedure list box, select the name of an event for the selected object. Here, select the Click procedure.

  4. To start the target application, select the StartApp method for the command button Command2 (this is the button you named Start).

    stat = target_obj.StartApp
  5. To stop the target application, select the StopApp method for the command button Command3 (this is the button you named Stop). Be sure to select the Click procedure in the procedure list box.

    stat = target_obj.StopApp

When you are done, the contents of your code editor window should look similar to the code below:

Private Sub Command2_Click()
    stat = target_obj.StartApp
End Sub

Private Sub Command3_Click()
    stat = target_obj.StopApp
End Sub

Creating Event Procedures to Vary Input Values

You can provide controls to allow users to vary the parameters of their applications. The Scroll procedure is one way of varying input. The following code uses the Visual Basic HScrollBar object to vary the water_level parameter. It takes the value from the HScrollBar object and sends that value to the target as a parameter change.

  1. If you are not already in the code editor window, double-click the form or, from the View menu, select Code.

  2. From the object list box, select the name of an object in the active form. (The active form is the form that currently has the focus.) For this example, select the HScroll1 object.

    The cursor jumps to the HScroll1 object template of the code editor window.

  3. In the procedure list box, select the name of an event for the selected object. Here, select the Scroll procedure.

  4. Declare the slideVal variable as a double. The slideVal variable will contain the value of the scrollbar.

    Dim slideVal(0) As Double
  5. Assign to the slideVal variable the result of CDbl. The CDbl function reads the value of an object property. In this example, the object HScroll1 has the property slideVal(0). CDbl reads the value of HScroll1.Value and returns that value to slideVal.

    slideVal(0) = CDbl(HScroll1.Value)
  6. Set the value of water_level to the scroll bar value slideVal, which is from HScrollBar. The COM object target_obj has the method SetParam, which has the syntax SetParam(parIdx, newparVal). The SetParam method references parIdx from the model-specific COM object (type xpc_tank1pt). To set the value of water_level to the scroll bar value slideVal, select SetParam and continue typing. A list of the parameters you tagged in the Simulink model then pops up, and you can select the parameter water_level and continue typing.

    The call to SetParam should look like the following:

    stat = target_obj.SetParam(parameters_obj.water_level, 
    slideVal)

When you are done, the contents of your code editor window should look similar to the code below:

Private Sub HScroll1_Scroll()
    Dim slideVal(0) As Double
    
    slideVal(0) = CDbl(HScroll1.Value)
    stat = target_obj.SetParam(parameters_obj.water_level, 
slideVal)
End Sub

Creating Event Procedures to Display Signal Values at the Host

You can provide controls to view signal values at the host. To do this, use a combination of the timer and label controls. The following code uses the Visual Basic timer control to display the water_level signal on the label control.

Before you start, check that the Timer1 Interval property is greater than 0.

  1. From the object list box, select the Timer1 object.

  2. Assign to the Label1.Caption object the value of the water_level signal. The COM object target_obj has the method GetSignal(sigNum). Reference the sigNum parameter by passing it signals_obj.water_level. The CStr function converts the returned value to a string so that it can be displayed on the Label1 object.

When you are done, the contents of your code editor window should look similar to the code below:

Private Sub Timer1_Timer()
    Label1.Caption = 
CStr(target_obj.GetSignal(signals_obj.water_level))
End Sub

Creating Unload and Termination Procedures

You should write Form Unload and Termination procedures to ensure that users are able to stop and unload the application appropriately, and to close the communication between the host PC and target PC.

The Terminate procedure controls the behavior of the Visual Basic Run menu End option. The Unload procedure controls the behavior of the Visual Basic Close button.

  1. From the object list box, select the Form object.

  2. From the procedure list box, select Terminate.

  3. You are going to close the connection with the target PC, so type protocol_obj and select the Close method for that object.

    protocol_obj.Close
  4. From the procedure list box, select Unload.

  5. Repeat step 3

When you are done, the contents of your code editor window should look similar to the code below:

Private Sub Form_Terminate()
   protocol_obj.Close
End Sub
Private Sub Form_Unload(Cancel As Integer)
   protocol_obj.Close
End Sub

Referencing Parameters and Signals Without Using Tags

The sample code in Creating Event Procedures to Vary Input Values and Creating Event Procedures to Display Signal Values at the Host illustrates how to reference parameters that you tagged before building the Simulink model. This section describes how to reference these same parameters and signals from the COM API application code if you did not opt to tag signals and parameters.

Getting Parameter IDs with the GetParamIdx Method

When working with parameters in the context of varying input values, you use the SetParam and GetParamIdx methods. The SetParam method has the syntax

SetParam(ByVal parIdx As Integer, ByRef newparVal As 
System.Array) As Long

where parIdx is the identifier that corresponds to the parameter you want to set. To obtain the parameter ID, parIdx, for SetParam, you need to call the GetParamIdx method. This method has the syntax

GetParamIdx(ByVal blockName As String, ByVal paramName As 
String) As Long

The following procedure describes how to obtain the appropriate GetParamIdx block name and parameter name for the Visual Basic HScrollBar object. You need to reference the block name and parameter from the model_namept.m file.

  1. Open a DOS window.

  2. Change the directory to the directory that contains your prebuilt model.

  3. Open the file model_namept.m. For example, you can use the notepad text editor.

    notepad xpc_tank1pt.m

    The editor opens for that file. If you are not in the directory in which the xpc_tank1pt.m file resides, be sure to type the full path for xpc_tank1pt.m.

  4. Search for and copy the string for the block of the parameter you want to reference. For the xpc_tank1 example, search for the SetPoint block if you want to reference the water level. For example,

    SetPoint
  5. Return to the code editor window for your project.

  6. In the line that contains the call to GetParamIdx, enter the path for the blockName variable.

  7. Return to the editor window for model_namept.m.

  8. Search for and copy the string for the name of the parameter you are interested in. For example,

    Value

    If you do not know the name of the block parameter you are interested in, refer to Model and Block Parameters of the Simulink Reference documentation.

  9. Return to the code editor window for your project.

  10. In the line that contains the call to GetParamIdx, enter the path for the paramName variable. For example,

    stat = target_obj.SetParam(target_obj.GetParamIdx
    ("SetPoint", "Value"), slideVal)

When you are done, the contents of your code editor window should look similar to the code below:

Private Sub HScroll1_Scroll()
    Dim slideVal(0) As Double

    slideVal(0) = CDbl(HScroll1.Value)
    stat = 
target_obj.SetParam(target_obj.GetParamIdx
("SetPoint", "Value"), slideVal)
  
End Sub

Note, if you want to retrieve the full block path and parameter name of a block, use the GetParamName method. The GetParamName method returns a variant data type object with two elements. The first element contains the full block path, the second element contains the parameter name. The following example illustrates how to use the GetParamName method to get the block path and parameter name:

Dim Pname As Variant
Pname=xpc_tank1.GetParamName(GetParamIdx(Idx)
BlockPathString=CStr(Pname(0))
ParameterNameString=CStr(Pname(1))

In this example,

Getting Signal IDs with the GetSignalIdx Method

When working with signals in the context of displaying signal values, you use the GetSignal and GetSignalIdx methods. The GetSignal method has the syntax

GetSignal(sigNum As Long) As Double

where sigNum is the identifier that corresponds to the signal you want to set.

To obtain the signal ID sigNum for GetSignal, you call the GetSignalIdx method. This method has the syntax

GetSignalIdx(sigName As String) As Long

The following procedure describes how to obtain the appropriate GetSignalIdx block name for the Visual Basic timer object. You need to reference the block name and signal from the model_namebio.m file.

  1. Open a DOS window.

  2. Change the directory to the directory that contains your prebuilt model.

  3. Open the file model_namebio.m. For example,

    notepad xpc_tank1bio.m

    The editor opens for that file. If you are not in the directory in which the xpc_tank1bio.m file resides, be sure to type the full path for xpc_tank1bio.m.

  4. Search for and copy the string for the block of the signal you want to reference. For the xpc_tank1 example, search for the TankLevel block to reference the tank level. For example,

    TankLevel
  5. Return to the code editor window for your project.

  6. In the line that contains the call to GetSignalIdx, enter the path for the SigName variable.

When you are done, the contents of your code editor window should look similar to the code below:

Private Sub Timer1_Timer()
   Label1.Caption = 
CStr(target_obj.GetSignal(target_obj.GetSignalIdx("TankLevel"
)))
End Sub

Testing the Visual Basic Application

While creating your Visual Basic application, you might want to see how the application is progressing. Visual Basic allows you to run your application while still in the Visual Basic project. From the Visual Basic task bar, you can click the Run button . Alternatively, you can follow the procedure:

  1. If you have the MATLAB interface and a target object connected, close the port. For example, at the MATLAB command line, type

    tg.close
  2. From within the project, go to the Run menu.

  3. Select Start or Start with Full Compile. The Start option starts your application immediately. The Start with Full Compile option starts the application after compilation.

The form you are working on pops up. Test your application. Ensure that only one version of the application is running at any given time. To stop the application from within Visual Basic, you can click the End button from the task bar. Alternatively, you can go to the Run menu and select End.

Building the Visual Basic Application

After you finish designing, programming, and testing your Visual Basic GUI application, build your application. You can later distribute the GUI application to users, who can then use it to work with target applications.

  1. From within the project, go to the File menu.

  2. Select Make project_name_COM.exe, where project_name is the name of the Visual Basic project you have been working on.

  3. At the pop-up box, select the directory in which you want to save the executable. Optionally, you can also rename the executable.

    The compiler generates the project_name_COM.exe file in the specified directory.

Deploying the API Application

This section assumes that you have built your xPC Target application and your Visual Basic xPC Target COM GUI application. If you have not yet done so, refer to Creating the Target Application and Model-Specific COM Library and Building the Visual Basic Application, respectively.

When distributing the Visual Basic model application to users, provide the following files:

Have the user ensure that all the files are located in the same directory before he or she executes the Visual Basic application.

You must also ensure that the user knows how to register the application-dependent dynamic link libraries (refer to Registering Dependent Dynamic Link Libraries).

To run the application and download an xPC Target application, users need to have project_name_COM.exe and model_name.dlm, if provided, in the same directory.

Registering Dependent Dynamic Link Libraries

This procedure uses xpc_tank1 as an example.

  1. Open a DOS window.

  2. Change the directory to the directory containing the API application files.

  3. From the directory in which xpcapiCOM.dll resides, register the xPC Target COM API DLL by typing

    regsvr32 xpcapiCOM.dll

    DOS displays the message

    DllRegisterServer in xpcapiCOM.dll succeeded

Creating a New Visual Basic Project Using Microsoft Visual Studio 7.1 or 8.0

The procedures for the preceding topics apply to Microsoft Visual Studio 6.0 (Creating a New Microsoft Visual Basic Project). The procedures to use Microsoft Visual Studio 7.1 (.NET 2003) and 8.0 are similar, with the following exceptions. Note that references toMicrosoft Visual Studio 7.1 or .NET 2003 also apply to Microsoft Visual Studio 8.0.

  


Related Products & Applications

Learn more about Simulink through this collection of videos, articles, technical literature and the Getting Started with Simulink Guide.

 © 1984-2009- The MathWorks, Inc.    -   Site Help   -   Patents   -   Trademarks   -   Privacy Policy   -   Preventing Piracy   -   RSS