PID Algorithm

In the PID (Proportional-Integral-Derivative) controller, the setpoint is compared to the process variable to obtain the error

You can then calculate the controller action theoretically as

where Kc is controller gain. If the error and the controller output have the same range, that is –100% to 100%, controller gain is the reciprocal of proportional band. Ti is the integral time in minutes (also called reset time), and Td is the derivative time in minutes (also called rate time). The proportional action is

the integral action is

 and the derivative action is

The PID control implements the positional PID algorithm as described in the following topics.

PV Filtering

Error Calculation

Proportional Action

Trapezoidal Integration

Partial Derivative Action

Controller Output

Output Limiting

Gain Scheduling


PV Filtering

Process variable filtering minimizes the effects of noise.


Error Calculation

The current error used in calculating integral action and derivative action is

The error for calculating proportional action is

where SPrng is the range of the setpoint, β (beta) is the setpoint factor (for the Two Degree of Freedom PID algorithm described under Proportional Action), and L is the linearity factor that produces a nonlinear gain term in which the controller gain increases with the magnitude of the error. If L is 1, the controller is linear. A value of 0.1 makes the minimum gain of the controller 10% Kc. This use of a nonlinear gain term is referred to as an Error-Squared PID algorithm.


Proportional Action

In applications, setpoint changes are normally greater and more rapid than load disturbances, while load disturbances appear as a slow departure of the controlled variable from the setpoint. PID tuning for good load-disturbance responses often results in setpoint responses of unacceptable oscillation. On the other hand, tuning for good setpoint responses often yields sluggish load-disturbance responses. The factor β, when set to less than 1, reduces the setpoint-response overshoot without affecting the load-disturbance response. This is referred to as a Two Degree of Freedom PID algorithm. Intuitively, β is an index of the setpoint response importance, from 0 to 1. For example, if you consider load response the most important loop performance, set β to 0. Conversely, if you want the process variable to follow the setpoint change quickly, set β to 1.


Trapezoidal Integration

Trapezoidal integration is used to avoid sharp changes in integral action when there is a PV or SP jump; nonlinear adjustment of integral action is used to counteract overshoot. The larger the error, the smaller the integral action, as shown in the following formula and figure.


Partial Derivative Action

Because of abrupt changes in setpoint (SP), derivative action is applied only to a filtered PV (not the error e) to avoid derivative kick.


Controller Output

Controller output is the summation of the proportional, integral, and derivative action.


Output Limiting

The actual controller output is limited to the range specified for control output.

the practical model of the PID controller is

The PID control uses an integral sum correction algorithm that facilitates anti-windup and bumpless automatic to manual and manual to automatic transfers. Anti-windup is the upper limit of the controller output, for example, 100%. Once the error e decreases, the controller output decreases and steps out of the windup area. This algorithm prevents abrupt controller output changes when you switch from automatic to manual mode or from manual to automatic mode or change any other parameters.

The default ranges for the parameters setpoint, process variable, and output correspond to percentage values; however, you can use actual engineering units. Adjust corresponding ranges accordingly. Reverse acting (also called increase-decrease) is the normal controller mode in which the output decreases if the process variable is greater than the setpoint. The parameters Ti and Td are specified in minutes. Switching to hold mode or manual mode freezes the output at the current value. In the manual model, you can increase or decrease the output by changing the manual input. All transfers, from automatic to manual or automatic to hold, and from manual to automatic or hold to automatic, are bumpless.

Note	As a general rule, manually drive the process variable until it meets or approaches the setpoint before you perform the manual to automatic transfer.


Gain Scheduling

Gain scheduling describes a system where controller parameters are changed depending on measured operating conditions. For instance, the scheduling variable can be the setpoint, the process variable, a controller output, or an external signal. For historical reasons, the word gain scheduling is used even if other parameters such as derivative time or integral time change. Gain scheduling effectively controls a system whose dynamics change with the operating conditions.

In this software, you can define unlimited sets of PID parameters for gain scheduling. For each schedule you can run autotuning to update the PID parameters.


Autotuning Algorithm

Autotuning is used to improve performance. Often, many controllers are poorly tuned—some too aggressive, some too sluggish. When you are not sure about disturbance or process dynamic characteristics, tuning a PID controller is difficult; therefore, the need for autotuning arises.

The following figure illustrates the autotuning procedure excited by the setpoint relay experiment, which connects a relay and an extra feedback signal with the setpoint. The existing controller remains in the loop.

Note	Although it might be poorly tuned, a stable controller must be established before autotuning.
For most systems, a limiting cycle generates because of the nonlinear relay characteristic. From this cycle, the autotuning algorithm identifies the relevant information needed for PID tuning:

•	If the existing controller is proportional only, ultimate gain Ku and ultimate period Tu.

•	If the existing model is PI or PID, dead time  and time constant Tp, which are two parameters in the integral-plus-deadtime model

When autotuning PID parameters, you must select the appropriate tuning formula.


Tuning Formulas

When autotuning, select one of three types of loop performance: fast (1/4 damping ratio), normal (some overshoot), and slow (little overshoot).

P-only Control (fast)

P-only Control (normal)

P-only Control (slow)

PI Control (fast)

PI Control (normal)

PI Control (slow)

Tuning Formula under P-only Control (fast)

Controller	Kc	Ti	Td
P	0.5
PI	0.4	0.8
PID	0.6	0.5	0.12
Tuning Formula under P-only Control (normal)

Controller	Kc	Ti	Td
P	0.2
PI	0.18	0.8
PID	0.25	0.5	0.12
Tuning Formula under P-only Control (slow)

Controller	Kc	Ti	Td
P	0.13
PI	0.13	0.8
PID	0.15	0.5	0.12
Tuning Formula under PI Control (fast)

Controller	Kc	Ti	Td
P
PI	0.9	3.33
PID	1.1	2.0	0.5
Tuning Formula under PI Control (normal)

Controller	Kc	Ti	Td
P	0.44
PI	0.4	5.33
PID	0.53	4.0	0.8
Tuning Formula under PI Control (slow)

Controller	Kc	Ti	Td
P	0.26
PI	0.24	5.33
PID	0.32	4.0	0.8
Note	During tuning, the process remains under closed-loop (PID) control. You do not need to switch off the existing controller and perform the experiment under open-loop conditions. In the setpoint relay experiment, the SP signal mirrors the SP for the PID controller.


Building ComponentWorks Applications
Building ComponentWorks Applications in Development Environments

ComponentWorks is a collection of ActiveX controls for developing applications within any compatible ActiveX control container, such as Microsoft Visual Basic, Visual C++, or Borland Delphi.

The following steps prescribe an approach to creating an application with the ComponentWorks controls.

1.	Develop the application.

Visual Basic

Visual C++

Delphi

2.	Load the ComponentWorks controls into the development environment.

Visual Basic Toolbox

Visual C++ Controls Toolbar

Delphi Component Palette

3.	Build the user interface.

Place the controls.

Configure default properties with the property pages.

Visual Basic

Visual C++

Delphi

4.	Program with the ComponentWorks controls.

Visual Basic

Visual C++

Delphi


Developing Visual Basic Applications

The following procedure explains how you can start developing Visual Basic applications with ComponentWorks.

1.	Select the type of application you want to build. Initially select a Standard EXE for your application type.

2.	Design the form. A form is a window or area on the screen on which you place controls and indicators to create the user interface for your program. The toolbox in Visual Basic contains all of the controls available for developing the form.

3.	After placing each control on the form, configure the properties of the control using the default and custom property pages.

Each control on the form has associated code (event handler routines) in your Visual Basic program that automatically executes when the user operates that control.

4.	To create this code, double click on the control while editing your application and the Visual Basic code editor opens to a default event handler routine.


Developing Visual C++ Applications

Creating the Project

1.	Create a new workspace or project in Visual C++.

2.	To create a project compatible with the ComponentWorks ActiveX controls, use the Visual C++ MFC AppWizard to create a skeleton project and program.

3.	After building the skeleton project, add the ComponentWorks controls to the controls toolbar. From the toolbar, you can add the controls to the application itself.

4.	After adding a control to your application, configure its properties using its property pages.

5.	While developing your program code, use the control properties and methods and create event handlers to process different events generated by the control.

Create the necessary code for these different operations using the ClassWizard in the Visual C++ environment.

Creating the Application

When developing new applications, use the MFC AppWizard to create new project workspace so the project is compatible with ActiveX controls. The MFC AppWizard creates the project skeleton and adds the necessary code that enables you to add ActiveX controls to your program.

1.	Create a new project by selecting New from the File menu. The New dialog box opens.

2.	On the Projects tab, select the MFC AppWizard (exe) and enter the project name and the directory.

3.	Click on OK to setup your project.

Complete the next series of dialog windows in which the MFC AppWizard prompts you for different project options. If you are a new Visual C++ or the MFC AppWizard user, accept the default options unless otherwise stated in this documentation.

4.	In the first step, select the type of application you want to build. For this example, select a dialog-based application to make it easier to become familiar with the ComponentWorks controls.

5.	Click on the Next> button to continue.

6.	Enable ActiveX controls support. If you have selected a Dialog based application, step two of the MFC AppWizard enables ActiveX Controls support by default.

7.	Continue selecting desired options through the remainder of the MFC AppWizard. When you finish the MFC AppWizard, it builds a project and program skeleton according to the options you specified. The skeleton includes several classes, resources, and files, all of which can be accessed from the Visual C++ development environment.

8.	Use the Workspace window, which you can select from the View menu, to see the different components in your project.


Developing Delphi Applications

You start developing applications in Delphi using a form. A form is a window or area on the screen on which you can place controls and indicators to create the user interface for your programs. The Component palette in Delphi contains all of the controls available for building applications. After placing each control on the form, configure the properties of the control with the default and custom property pages. Each control you place on a form has associated code (event handler routines) in the Delphi program that automatically executes when the user operates the control or the control generates an event.

Note	To run the Delphi examples installed with ComponentWorks, you need to import the controls into the Delphi environment.


Loading ComponentWorks Controls into the Visual Basic Toolbox

Before building an application using ComponentWorks controls, you must add them to the Visual Basic toolbox. Use the following procedure to add ComponentWorks controls to the project toolbox.

1.	In a new Visual Basic project, right click on the toolbox and select Components.

2.	Place a checkmark in the box next to National Instruments CW PID.

If the ComponentWorks controls are not in the list, select the control files from the \Windows\System(32) directory by pressing the Browse button.

3.	Click OK.

If you need to use the ComponentWorks controls in several projects, create a new default project in Visual Basic 5 to include the PID controls and serve as a template.

1.	Create a new Standard EXE application in the Visual Basic environment.

2.	Add the ComponentWorks PID controls to the project toolbox as described in the preceding procedure.

3.	Save the form and project in the \Template\Projects directory under your Visual Basic directory.

4.	Give the form and project a descriptive name, such as CWForm and CWProject.

After creating this default project, you have a new option, CWProject, that includes the ComponentWorks IMAQ controls in the New Project dialog by default.


Loading ComponentWorks Controls into the Visual C++ Controls Toolbar

Before building an application using the ComponentWorks IMAQ controls, you must load the controls into the Controls toolbar in Visual C++ from the Component Gallery in the Visual C++ environment. When you load the controls using the Component Gallery, a set of C++ wrapper classes is generated automatically in your project. You must have wrapper classes to work with the ComponentWorks controls.

The Controls toolbar is visible in the Visual C++ environment only when the Visual C++ dialog editor is active. Use the following procedure to open the dialog editor.

1.	Open the Workspace window by selecting Workspace from the View menu.

2.	Select the Resource View (second tab along the bottom of the Workspace window).

3.	Expand the resource tree and double click on one of the Dialog entries.

4.	If necessary, right click on any existing toolbar and enable the Controls option.

By adding controls to your project, you create the necessary wrapper classes for the control in your project and add the control to the toolbox. Use the following procedure to add new controls to the toolbar.

1.	Select Project»Add To Project»Components and Controls and, in the following dialog, double click on Registered ActiveX Controls.

2.	Select one of the ComponentWorks PID controls and click the Insert button.

3.	Click on OK in the following dialog windows. Repeat Steps 1 through 3 to add other controls.

4.	When you have inserted the controls, click Close in the Components and Controls Gallery.


Loading ComponentWorks Controls into the Delphi Component Palette

Before you can use the ComponentWorks controls in your Delphi applications, you must add them to the Component palette in the Delphi environment. You need to add the controls to the palette only once because the controls remain in the Component palette until you explicitly remove them. When you add controls to the palette, you create Pascal import units (header files) that declare the properties, methods, and events of a control. When you use a control on a form, a reference to the corresponding import unit is automatically added to the program.

Note	Before adding a new control to the Component palette, make sure to save all your work in Delphi, including files and projects. After loading the controls, Delphi closes any open projects and files to complete the loading process.
Use the following procedure to add ActiveX controls to the Component palette.

1.	Select Import ActiveX Control from the Component menu in the Delphi environment. The Import ActiveX Control window displays a list of currently registered controls.

2.	Select National Instruments CW PID to add the PID control to the Component palette.

3.	After selecting the control group, click Install. Delphi generates a Pascal import unit file for the selected .OCX file, which is stored in the Delphi \Imports directory. If you have installed the same .OCX file previously, Delphi prompts you to overwrite the existing import unit file.

4.	In the Install dialog box, click on OK to add the controls to the Delphi user’s components package.

5.	In the following dialog, click on Yes to rebuild the user’s components package with the added controls. Another dialog box acknowledges the changes you have made to the user’s components package, and the package editor displays the components currently installed.

At this point, you can add additional ActiveX controls with the following procedure.

a.	Click on the Add button.

b.	Select the Import ActiveX tab.

c.	Select the ActiveX control you want to add.

d.	Click on OK.

e.	After adding the ActiveX controls, compile the user’s components package.

If your control does not appear in the list of registered controls, click the Add button. To register a control with the operating system and add it to the list of registered controls, browse to and select the OCX file that contains the control. Most OCX files reside in the \Windows\System(32) directory.

New controls are added to the ActiveX tab in the Components palette. You can rearrange the controls or add a new tab to the Components palette by right clicking on the palette and selecting Properties.


Placing ComponentWorks Controls on a Form

To place the controls on the form, select the icon in the toolbox and click and drag the mouse on the form. This step creates the corresponding control. After you create controls, move and size them by using the mouse.

To move a control, click and hold the mouse on the control and drag the control to the desired location. Notice that you cannot resize the PID, LeadLag, or Ramp controls after placing them on the form. They also are not visible during run time.

Note	To add ComponentWorks controls to the form in Visual C++, open the dialog editor by selecting the dialog form from the Resource View of the Workspace window. If the Controls toolbar is not displayed in the dialog editor, open it by right clicking on any existing toolbar and enabling the Controls option.


Using Property Pages in Visual_Basic
Using Property Pages in Visual Basic

Configure the control by setting its properties in the Visual Basic property pages and ComponentWorks custom control property pages. Visual Basic assigns some default properties, such as the control name and the tab order. When you create the control, you can edit these stock properties in the Visual Basic default property sheet.

To access this sheet, select a control and select Properties Window from the View menu, or press <F4>. To edit a property, highlight the property value on the right side of the property sheet and type in the new value or select it from a pull down menu. The most important property in the default property sheet is Name, which is used to reference the control in the program.

Edit all other properties of an ActiveX control in the custom property sheets. To open the custom property sheets, right click on the control on the form and select Properties or select the controls and press <Shift-F4>.


Using Property Pages in Visual C++

Configure the default properties of the control by right clicking the control and selecting Properties to display its custom property sheets.

So you can see immediately how different properties affect the control, a separate window displays a sample copy of the control that reflects the property changes as you make them in the property sheets.


Using Property Pages in Delphi

Set property values such as Name in the Object Inspector of Delphi. To open the Object Inspector, select Object Inspector from the View menu or press <F11>. Under the Properties tab of the Object Inspector, you can set different properties of the selected control.

To open the custom property pages of a control, double click on the control or right click on the control and select Properties. You can edit most control properties from the custom property pages.


Programming with ComponentWorks in Visual Basic

You can manipulate the ComponentWorks controls programmatically through individual properties, methods, and events. The following section describe how you can set properties, work with control methods, and develop event handler routines.

Properties

You can set and read the properties of your controls programmatically in Visual Basic. Use the name of the control with the name of the property as you would with any other variable in Visual Basic. The syntax for setting a property in Visual Basic is name.property = new value.

For example, you can set the Setpoint property of a PID control using the following line of code, where CWPID1 is the default name of the PID control.

CWPID1.Setpoint = 50

To access properties of sub-objects referenced by the top-level object, use the control name, followed by the name of the sub-object and the property name. For example, consider the following code for the PID control.

CWPID1.Parameters(1).ProportionalGain = 10

In the above code, Parameter is a property of the PID control and refers to a Parameter object. ProportionalGain is one of several Parameter properties.

You can retrieve the value of control properties from your program in the same way. For example, you can print the value of the PID Setpoint property.

Print CWPID1.Setpoint

You can display the proportional gain of a parameter in a Visual Basic text box with the following code.

Text1.Text = CWPID1.Parameters(1).ProportionalGain

Methods

Calling the methods of an ActiveX control in Visual Basic is similar to working with the control properties. To call a method, add the name of the method after the name of the control (and sub-object if applicable). For example, you can call the Reset method on the PID control.

CWPID1.Reset

Methods can have parameters that you pass to the method and return values that pass information back to your program. In Visual Basic, if you call a method without assigning a return variable, any parameters passed to the method are listed after the method name, separated by commas without parentheses. If you assign the return value of a method to a return variable, enclose the parameters in parentheses.

Output = CWPID1.NextOutput(ProcessVariable)

Events

After configuring controls in the forms editor, you can write Visual Basic code to respond to events on the controls. The controls generate these events in response to user interactions with the controls or in response to some other occurrence in the control.

To develop the event handler routine code for an ActiveX control in Visual Basic, double click the control to open the code editor, which automatically generates a default event handler routine for the control. The event handler routine skeleton includes the control name, the default event, and any parameters that are passed to the event handler routine.

The following code is an example of the event routine generated for the PID control. This event routine (AutotuneComplete) is called when the autotuning process has completed.

Private Sub CWPID1_AutotuneComplete(ByVal NewParameterPosition As Long)

End Sub

To generate an event handler for a different event of the same control, double click the control to generate the default handler, and select the desired event from the right pull-down menu in the code window. Use the left pull-down menu in the code window to change to another control without going back to the form window.


Visual Basic Tools

Microsoft Visual Basic 5 offers tools to help you manipulate the properties, methods, and events of the ComponentWorks controls.

Object Browser

Code Completion


Visual Basic Object Browser

Navigating through the Object Browser

Visual Basic includes a tool called the Object Browser that you can use to work with ActiveX controls while creating your program. The Object Browser displays a detailed list of the available properties, methods, and events for a particular control. It presents a three-step hierarchical view of controls or libraries and their properties, methods, functions, and events. To open the Object Browser, select Object Browser from the View menu, or press <F2>.

In the Object Browser, use the top left pull-down menu to select a particular ActiveX control file. You can select any currently loaded control or driver. The Classes list on the left side of the Object Browser displays a list of controls, objects, and function classes available in the selected control file or driver.

The Classes list shows all the PID controls and associated object types. Each time you select an item from the Classes list in the Object Browser, the Members list on the right side displays the properties, methods, and events for the selected object or class.

When you select an item in the Members list, the prototype and description of the selected property, method, or function are displayed at the bottom of the Object Browser dialog box. The prototype of a method or function lists all parameters, required and optional.

When you select a property of a control or object in the Members list which is an object in itself, the description of the property includes a reference to the object type of the property.

The question mark (?) button at the top of the Object Browser opens the help file to a description of the currently selected item.

Pasting Code into Your Program from the Object Browser

If you open the Object Browser from the Visual Basic code editor, you can copy the name or prototype of a selected property, method, or function to the clipboard and then paste it into your program. To perform this task, select the desired Member item in the Object Browser. Press the Copy to Clipboard button at the top of the Object Browser or highlight the prototype at the bottom and press <Ctrl-C> to copy it to the clipboard. Paste it into your code window by selecting Paste from the Edit menu or pressing <Ctrl-V>.

Use this method repeatedly to build a more complex reference to a property of a lower-level object in the object hierarchy. For example, you can create a reference to

CWPID1.Parameters.Item(1).ProportionalGain

by typing in the name of the control (CWIMAQ1) and then using the Object Browser to add each section of the property reference.


Visual Basic Code Completion

Visual Basic 5 supports automatic code completion in the code editor. As you enter the name of a control, the code editor prompts you with the names of all appropriate properties and methods. Try placing a control on the form and then entering its name in the code editor. After typing the name, add a period as the delimiter to the property or method of the control. As soon as you type the period, Visual Basic drops down a menu of available properties and methods.

You can select from the list or properties and events by scrolling through the list and selecting one or by typing in the first few letters of the desired item. Once you have selected the correct item, type the next logical character such as a period, space, equal sign, or carriage return to enter the selected item in your code and continue editing the code.


Programming with ComponentWorks in Visual C++

You can manipulate the ComponentWorks controls programmatically through individual properties, methods, and events. The following section describe how you can set properties, work with control methods, and develop event handler routines.

To program with ComponentWorks controls, use the properties, methods, and events of the controls as defined by the wrapper classes in Visual C++.

Before you can use the properties or methods of a control in your Visual C++ program, assign a member variable name to the control. This member variable becomes a variable of the application dialog class in your project.

To create a member variable for a control on the dialog form, right click on the control and select ClassWizard. In the MFC Class Wizard window, activate the Member Variables tab.

Select the new control in the Control IDs field and press the Add Variable button. In the dialog window that appears, complete the member variable name and press OK. Most member variable names start with m_, and you should adhere to this convention. After you create the member variable, use it to access a control from your source code.

Properties

Unlike Visual Basic, you do not read or set the properties of ComponentWorks controls directly in Visual C++. Instead, the wrapper class of each control contains functions to read and write the value of each property. These functions are named starting with either Get or Set followed by the name of the property. For example, to set the Setpoint property of a PID control, use the SetSetpoint function of the wrapper class for the PID control. In the source code, the function call is preceded by the member variable name of the control to which it applies.

m_CWPID1.SetSetpoint(50);

Some values passed to properties need to be of variant type. Convert the value passed to the property to a variant using COleVariant(). For example, set the Item property of the CWParameters object.

m_CWPID1.GetParameters().Item(COleVariant(1.0));

You can view the names of all the property functions (and other functions) for a given control in the ClassView of the Workspace window. In the Workspace window, select ClassView and then the control for which you want to view property functions and methods.

If you need to access a property of a control which is in itself another object, use the appropriate property function to return the sub-object of the control. Make a call to access the property of the sub-object. Include the header file in your program for any new objects. For example, use the following code to set the RelayAmplitude on the PID control.

#include "cwpidautotune.h"

CCWPIDAutotune Autotune;

Autotune = m_CWPID1.GetAutotune();

Autotune.SetRelayAmplitude(10);

You can chain this operation into one function call without having to declare another variable.

#include "cwpidautotune.h"

m_CWPID1.GetAutotune().SetRelayAmplitude(10);

If you need to access an object in a collection property, use the Item method with the index of the object. Remember to include the header file for the collection object. For example, to set the proportional gain of the first Parameter object on a PID control, use the following code.

#include "cwpidparameters.h"

#include "cwpidparameter.h"

m_CWPID1.GetParameters().Item(COleVariant(1.0)).SetProportionalGain(15);

Methods

Use the control wrapper classes to extract all methods of the control. To call a method, append the method name to the member variable name and pass the appropriate parameters. If the method does not require parameters, use a pair of empty parentheses.

m_CWPID1.Reset();

Some methods take some parameters as variants. You must convert any such parameter to a variant if you have not already done so. You can convert most scalar values to variants with COleVariant(). For example, the Remove method of the Parameters object requires a scalar value as variant.

m_CWPID1.GetParameters().Remove(COleVariant(1.0));

To call StartAutotune on the Autotune object, use the following line of code.

#include "cwpidautotune.h"

m_CWPID1.GetAutotune().StartAutotune(10);

Note	Consult Visual C++ documentation for more information about variant data types.
Events

After placing a control on your form, you can start defining event handler functions for the control in your code. Events generate automatically at run time when different controls respond to conditions.

Use the following procedure to create an event handler.

1.	Right click on a control and select ClassWizard.

2.	Select the Message Maps tab and the desired control in the Object IDs field. The Messages field displays the available events for the selected control.

3.	Select the event and press the Add Function button to add the event handler to your code.

4.	To switch directly to the source code for the event handler, click on the Edit Code button. The cursor appears in the event handler, and you can add the functions to call when the event occurs. You can use the Edit Code button at any time by opening the class wizard and selecting the event for the specific control.

The following code is an example of an event handler generated for the AutotuneComplete event of the PID control.

void CCWPIDDlg::OnAutotuneCompleteCwpid1(long NewParameterPosition)

{

m_CWPID1.SetActiveParameter(m_CWPID1.GetParameters(). Item(COleVariant(NewParameterPosition)));

}


Programming with ComponentWorks in Delphi

You can manipulate the ComponentWorks controls programmatically through individual properties, methods, and events. The following section describe how you can set properties, work with control methods, and develop event handler routines.

The code for each form in Delphi is listed in the Associated Unit (code) window. You can toggle between the form and Associated Unit window by pressing <F12>. After placing controls on the form, use their methods in your code and create event handler routines to process events generated by the controls at run time.

Properties

You can set or read control properties programmatically by referencing the name of the control with the name of the property, as you would any variable name in Delphi. The name of the control is set in the Object Inspector.

The syntax for setting the Value property in Delphi is

name.property := new_value;

For example, you can set the Setpoint property of a PID control using the following line of code, where CWPID1 is the default name of the PID control.

CWPID1.Setpoint := 50;

A property can be an object itself that has its own properties. To set properties in this case, combine the name of the control, sub-object, and property. For example, consider the following code for the PID control. Autotune is both a property of the PID control and an object itself. RelayAmplitude is a property of the Autotune object. As an object of the PID control, Autotune itself has several additional properties.

CWPID1.Autotune.RelayAmplitude := 2;

You can retrieve the value of a control property from your program in the same way. For example, you can assign the relay amplitude to a text box on the user interface.

Edit1.Text := CWPID1.Autotune.RelayAmplitude;

To use the properties or methods of an object in a collection, use the Item method to extract the object from the collection. Once you extract the object, use its properties and methods as you usually would.

CWPID1.Parameters.Item(1).ProportionalGain := 10;

Methods

Each control has defined methods that you can use in your program. To call a method in your program, use the control name followed by the method name.

CWPID1.Reset;

Some methods require parameters. In most cases, parameters passed to a method are of type variant. Simple scalar values can be automatically converted to variants and, therefore, might be passed to methods.

Events

Use event handler routines in your source code to respond to and process events generated by the ComponentWorks controls. Events are generated by user interaction with an object in response to internal conditions (for example, completed acquisition or an error). You can create a skeleton for an event handler routine using the Object Inspector in the Delphi environment.

To open the Object Inspector, press <F11> or select Object Inspector from the View menu. In the Object Inspector, select the Events tab. This tab lists all the events for the selected control. To create a skeleton function in your code window, double click the empty field next to the event name. Delphi generates the event handler routine in the code window using the default name for the event handler.

To specify your own event handler name, click the empty field in the Object Inspector next to the event, and enter the function name. After the event handler function is created, insert the code in the event handler. The following is an example of the event handler function for the AutotuneComplete event of the PID control.

procedure TForm1.CWPID1AutotuneComplete(Sender: TObject;NewParameterPosition: Integer);

begin

end;


Online_Overview
ComponentWorks Autotuning PID Online Reference

ComponentWorks Autotuning PID adds the instrumentation-specific tools for designing control strategies in Visual Basic, Visual C++, Delphi, Internet Explorer, and other ActiveX containers. To complete the examples in this online reference system, you should be familiar with Visual Basic and Windows 95.

Parts of this online reference system contain step-by-step instructions for building applications with ComponentWorks. You can modify these sample applications to suit your needs.

Contents
ComponentWorks Overview ComponentWorks Autotuning PID Overview PID Control LeadLag Control Ramp Control	Developing ComponentWorks Applications Building ComponentWorks Applications  in Development Environments Error Checking Error Codes Debugging Distribution and Redistributable Files
ComponentWorks Reference CWPID CWLeadLag CWRamp	PID Algorithms and Control Strategies PID Algorithm Autotuning Algorithm Control Strategies, Designing
ComponentWorks Autotuning PID Examples and Tutorial Search Examples ComponentWorks Autotuning PID Tutorial	Important Information Copyright Limited Warranty, Trademarks, and Warning Contacting National Instruments Using This Help File
© Copyright 1998, National Instruments Corporation.  All rights reserved.

August 1998 Edition.  Part Number 322065A-01


About_the_ComponentWorks_Autotuning_PID_Online_Reference
About the ComponentWorks Autotuning PID Online Reference

Under the copyright laws, this publication may not be reproduced or transmitted in any form, electronic or mechanical, including photocopying, recording, storing in an information retrieval system, or translating, in whole or in part, without the prior written consent of National Instruments Corporation.

For more information, see the Warranty, Trademarks, Medical Warning and Technical Support topics.

© Copyright 1998, National Instruments Corporation.  All rights reserved.

August 1998 Edition.  Part Number 322065A-01


How To Contact NI

National Instruments has technical assistance through electronic, fax, and telephone systems to quickly provide the information you need. Our electronic services include a bulletin board service, an FTP site, a Fax-on-Demand system, and e-mail support. If you have a hardware or software problem, first try the electronic support systems. If the information available on these systems does not answer your questions, we offer fax and telephone support through our technical support centers, which are staffed by applications engineers.

National Instruments Technical Support


National Instruments Technical Support

Bulletin Board Support

National Instruments has BBS and FTP sites dedicated for 24-hour support with a collection of files and documents to answer most common customer questions. From these sites, you can also download the latest instrument drivers, updates, and example programs. For recorded instructions on how to use the bulletin board and FTP services and for BBS automated information, call 512 795 6990. You can access these services at:

United States:  512 794 5422 Up to 14,400 baud, 8 data bits, 1 stop bit, no parity

United Kingdom:  01635  551422 Up to 9,600 baud, 8 data bits, 1 stop bit, no parity

France: 01 48 65 15 59 Up to 9,600 baud, 8 data bits, 1 stop bit, no parity

FTP Support

To access our FTP site, log on to our Internet host:

ftp://ftp.natinst.com

Enter anonymous and use your Internet address, such as joesmith@anywhere.com, as your password. The support files and documents are located in the /support directories.

WWW Support

Point your Web browser to:

http://www.natinst.com/support

Fax-on-Demand Support

Fax-on-Demand is a 24-hour information retrieval system containing a library of documents on a wide range of technical information. You can access Fax-on-Demand from a touch-tone telephone at 512 418 1111.

E-Mail Support (Currently USA Only)

You can submit technical support questions to the applications engineering team through e-mail at the Internet address listed below. Remember to include your name, address, and phone number so we can contact you with solutions and suggestions.

support@natinst.com

Telephone and Fax Support

National Instruments has branch offices all over the world. Use the list below to find the technical support number for your country. If there is no National Instruments office in your country, contact the source from which you purchased your software to obtain support.

Country	Phone	Fax
Australia	03 9879 5166	03 9879 6277
Austria	0662 45 79 90 0	0662 45 79 90 19
Belgium	02 757 00 20	02 757 03 11
Brazil	011 288 3336	011 288 8528
Canada (Ontario)	905 785 0085	905 785 0086
Canada (Québec)	514 694 8521	514 694 4399
Denmark	45 76 26 00	45 76 26 02
Finland	09 725 725 11	09 725 725 55
France	1 48 14 24 24	1 48 14 24 14
Germany	089 741 31 30	089 714 60 35
Hong Kong	2645 3186	2686 8505
Israel	03 6120092	03 6120095
Italy	02 413091	02 41309215
Japan	03 5472 2970	03 5472 2977
Korea	02 596 7456	02 596 7455
Mexico	5 520 2635	5 520 3282
Netherlands	0348 433466	0348 430673
Norway	32 84 84 00	32 84 86 00
Singapore	2265886	2265887
Spain	91 640 0085	91 640 0533
Sweden	08 730 49 70	08 730 43 70
Switzerland	056 200 51 51	056 200 51 55
Taiwan	02 377 1200	02 737 4644
United Kingdom	01635 523545	01635 523154
United States	512 795 8248	512 794 5678


Warranty, Trademarks, and Medical Warning

This topic contains very important information about your Limited Warranty, National Instruments Trademarks, and Medical Warning.

Limited Warranty

The media on which you receive National Instruments software are warranted not to fail to execute programming instructions, due to defects in materials and workmanship, for a period of 90 days from date of shipment, as evidenced by receipts or other documentation. National Instruments will, at its option, repair or replace software media that do not execute programming instructions if National Instruments receives notice of such defects during the warranty period. National Instruments does not warrant that the operation of the software shall be uninterrupted or error free.

A Return Material Authorization (RMA) number must be obtained from the factory and clearly marked on the outside of the package before any equipment will be accepted for warranty work. National Instruments will pay the shipping costs of returning to the owner parts which are covered by warranty.

National Instruments believes that the information in this document is accurate. The document has been carefully reviewed for technical accuracy. In the event that technical or typographical errors exist, National Instruments reserves the right to make changes to subsequent editions of this document without prior notice to holders of this edition. The reader should consult National Instruments if errors are suspected. In no event shall National Instruments be liable for any damages arising out of or related to this document or the information contained in it.

Except as specified herein, National Instruments makes no warranties, express or implied, and specifically disclaims any warranty of merchant ability or fitness for a particular purpose. Customer’s right to recover damages caused by fault or negligence on the part of National Instruments shall be limited to the amount theretofore paid by the customer. National Instruments will not be liable for damages resulting from loss of data, profits, use of products, or incidental or consequential damages, even if advised of the possibility thereof. This limitation of the liability of National Instruments will apply regardless of the form of action, whether in contract or tort, including negligence. Any action against National Instruments must be brought within one year after the cause of action accrues. National Instruments shall not be liable for any delay in performance due to causes beyond its reasonable control. The warranty provided herein does not cover damages, defects, malfunctions, or service failures caused by owner’s failure to follow the National Instruments installation, operation, or maintenance instructions; owner’s modification of the product; owner’s abuse, misuse, or negligent acts; and power failure or surges, fire, flood, accident, actions of third parties, or other events outside reasonable control.

Trademarks

ComponentWorks™, IMAQ™, National Instruments™, natinst.com™, and NI-IMAQ™ are trademarks of National Instruments Corporation.

Product and company names referenced in this document are trademarks or trade names of their respective companies.

WARNING REGARDING MEDICAL AND CLINICAL USE OF NATIONAL INSTRUMENTS PRODUCTS

National Instruments products are not designed with components and testing intended to ensure a level of reliability suitable for use in treatment and diagnosis of humans. Applications of National Instruments products involving medical or clinical treatment can create a potential for accidental injury caused by product failure, or by errors on the part of the user or application designer. Any use or application of National Instruments products for or involving medical or clinical treatment must be performed by properly trained and qualified medical personnel, and all traditional medical safeguards, equipment, and procedures that are appropriate in the particular situation to prevent serious injury or death should always continue to be used when National Instruments products are being used. National Instruments products are NOT intended to be a substitute for any form of established process, procedure, or equipment used to monitor or safeguard human health and safety in medical or clinical treatment.


Hints for Using this Help File

This topic explains how to navigate through an online help file. On each platform G supports, there are different features to help you navigate to the information you are seeking. The common information is included here. Click on the platform you use for information specific to it.

This is a hypertext help file. That means you navigate by clicking on buttons, such as those at the top of this window and on clickable items, or hotspots, in the text. Topic hotspots are green and have a solid underline. Click here for an example. Pop-up hotspots are green and have a dotted underline. Click here for an example.

Windows 95/NT Help

Windows 95 (and Windows NT 4.0) help files use a new interface featuring a contents, index and find tab. The contents tab gives you an expandable, collapsible hierarchical guide to all the topics in the help file. The index tab contains a keyword search engine that can span multiple help files in one help suite. The find tab is a full text search engine that you can use to find things not indexed. To learn how to use the features see the Windows 95 help file for a complete introduction.


Example Topic

Clicking on these spots send you to a new topic, like this one. Click on the Back button above to go back to the hints topic.


Pop-up Example

Information shows up in a floating window. Click anywhere to go back to the original topic.


PID Control Overview
PID Control

The PID control implements the PID algorithm and the Autotuning algorithm. The PID control, CWPID, is built from a hierarchy of object, as illustrated in the following figure.

You can view a complete list and description of all properties, methods, and events associated with the Autotuning PID control.


PID Object

The PID object contains several properties and methods you can use to configure the PID control, and you can set properties in the property pages during design and change them programmatically at run time. You need to set the proportional gain, derivative time, and integral time in the property pages before run time.

NextOutput returns the next output from the PID algorithm given the controls current settings and a process variable.

Output = CWPID1.NextOutput(ProcessVariable)

You can have the object automatically determine the amount of time between successive calls to the control, or specify it yourself using the DeltaT property. If you use the built-in time keeper, the object calculates new timing information at each call, measuring the time since the last call and using that difference in its calculations.

Note	If you use the built-in timer, remember that tick timer resolution is limited to 1 ms on Windows 95 and NT. Do not try to run the PID methods faster than 10 Hz when using the built-in timer.


Parameters Collection

The Parameters collection is a standard collection containing Parameter objects. The collection contains one property, Count, that returns the number of Parameter objects in the collection.

NumParameters = CWPID1.Parameters.Count

Use the Add, Remove, and RemoveAll methods to programmatically change the number of Parameter objects in the PID control. When calling the Remove method, include the index of the Parameter object to be removed.

CWPID1.Parameters.Add "param1", 10.0, 0.015, 0.001, 0

CWPID1.Parameters.Remove 3

Use the Item method of the Parameters collection to access a specific Parameter object in the collection.


Parameters Object
Parameter Object

The Parameter object represents an individual parameter in the PID control. The Parameter object contains a number of different properties that you can use to determine the next output of the control.

You can set IntegralTime, ProportionalGain, and DerivativeTime as shown in the following code.

CWPID1.Parameters.Item(1).ProportionalGain = 10.0

CWPID1.Parameters.Item(1).Integraltime = 0.015

CWPID1.Parameters.Item(1).DerivativeTime = 0.001


Autotune Object

The Autotune object has four properties needed to autotune the PID parameters.

•	NoiseLevel is the amount of noise in the system.

•	RelayAmplitude is the amplitude the Autotune object should use when modifying the setpoint during the relay process.

•	ControlDesign is the design of the controller for which the Autotune object should calculate new PID parameters. Valid values include Fast, Normal, and Slow.

•	ControlType is the type of controller for which the Autotune object should calculate new PID parameters. Valid values include PID, PI, and P.

Several methods can help you autotune PID parameters:

•	ShowDialog displays the Autotune Wizard that steps you through the autotune process.

•	StartNoiseEstimate begins a process that determines the amount of noise in the system.

•	StartRelay begins the relay process and stabilizes it.

•	StartAutotune tunes the PID parameters.

Note	You must call the StartRelay method before you can call the StartAutotune method.


Autotune Wizard

The Autotune Wizard performs the following steps to guide you through the following autotuning process, which you can cancel anytime without affecting the current control state.

1.	Determine the amount of noise in the system. If you know the amount of noise, you can specify it, and the wizard will not calculate it.

2.	Begin the relay process. The wizard prompts you for information needed to autotune the PID parameters. After you enter this information, the wizard starts the relay process.

3.	Autotune the PID parameters. When you specify that the relay process is stabilized, the wizard begins autotuning the PID parameters.

4.	Display the new PID parameters. At this point, you can accept the new PID parameters or cancel the process.


PID Events

To signal when the noise estimate and autotuning process has finished, the CWPID object generates two events: AutotuningComplete and NoiseEstimateComplete. The control also generates an event every time the relay process completes a cycle.


LeadLag Control Overview
LeadLag Control

The LeadLag control, CWLeadLag, calculates the dynamic compensator in feedforward control schemes. Properties of CWLeadLag include Gain, LagTime, and LeadTime. The NextOutput method returns the next value given the current state of the control.

You can have the object automatically determine the amount of time between successive calls to the control, or specify it yourself using the DeltaT property. If you use the built-in time keeper, the object calculates new timing information at each call, measuring the time since the last call and using that difference in its calculations.

Note	If you use the built-in timer, remember that tick timer resolution is limited to 1 ms on Windows 95 and NT. Do not try to run the PID methods faster than 10 Hz when using the built-in timer.
You can view a complete list and description of all properties, methods, and events associated with the LeadLag control.


Ramp Control Overview
Ramp Control

The Ramp control, CWRamp, generates a setpoint ramp. Use the Rate property to determine how fast the value is ramped to the Setpoint property.

You can have the object automatically determine the amount of time between successive calls to the control, or specify it yourself using the DeltaT property. If you use the built-in time keeper, the object calculates new timing information at each call, measuring the time since the last call and using that difference in its calculations.

Note	If you use the built-in timer, remember that tick timer resolution is limited to 1 ms on Windows 95 and NT. Do not try to run the PID methods faster than 10 Hz when using the built-in timer.
You can view a complete list and description of all properties, methods, and events associated with the Ramp control.


Control Strategies, Designing

When designing a control strategy, sketch a process flowchart showing control elements (for example, valves) and measurements. Add feedback and any required computations. Then translate the flowchart into code using the ComponentWorks PID control. The following figure shows a process flowchart.

The following Visual Basic code implements the process shown in the previous figure.

SP1 = CWLeadLag1.NextOutput(FT1)

CWPID1.Setpoint = SP1

Output1 = CWPID1.NextOutput(LT1)

CWPID2.Setpoint = Output1 + SP1

Valve = CWPID2.NextOutput(FT2)

You can handle the inputs and outputs through data acquisition (DAQ) boards, FieldPoint I/O modules, GPIB instruments, or serial I/O ports.

Related Topics

Timing

Manual Tuning Techniques


Timing

The PID, LeadLag, and RampGenerator methods are time dependent. These methods can acquire timing information through a value you supply or through a built-in time keeper. With the built-in time keeper, the methods calculate new timing information each time they are called. At each call, the method measures the time since the last call and uses that difference in its calculations. Tick timer resolution is limited to 1 ms on Windows 95 and NT. Because of this limitation, do not try to run the PID methods faster than 10 Hz when using the built-in time keeper.

If you specify the timing information manually, the method uses the value you specify in the calculations, regardless of the elapsed time. This method should be used for fast loops, such as when controller input is timed with acquisition hardware.

According to control theory, a sampled control system must run about 10 times faster than the fastest time constant in the plant under control. For example, a temperature control loop is probably quite slow—a time constant of 60 s is common in a small system. In this case, a cycle time of about 6 s is sufficient. Faster cycling offers no improvement in performance.

If the control application does not contain graphics that must update frequently, the PID control can execute at kilohertz (kHz) rates. Remember that actions such as mouse activity and window scrolling interfere with these rates.


Manual Tuning Techniques

The following controller tuning procedures are based on the work of Ziegler and Nichols, the developers of the Quarter-Decay Ratio tuning techniques derived from a combination of theory and empirical observations. For different processes, one method might be easier or more accurate than the other. Some techniques you can use with online controllers cannot stand the gross upsets described here.

To perform these tests, set up your control strategy with the process variable (PV), setpoint, and output displayed on a large strip chart with the axes showing the values versus time. Perturb the loop as described in Closed-Loop (Ultimate Gain) Tuning Procedure and Closed-Loop (Ultimate Gain) Tuning Procedure and determine the response from the graph.


Closed-Loop (Ultimate Gain) Tuning Procedure

Although the closed-loop (ultimate gain) tuning procedure is very accurate, you must put your process in steady-state oscillation and observe the process variable on a strip chart. To perform the closed-loop tuning procedure, complete the following steps:

1.	With the controller in automatic mode, carefully increase the proportional gain (Kc) in small steps. Disturb the loop after each step by making a small change in the setpoint. The process variable should start oscillating as you increase the Kc. Keep making changes until the oscillation is perfectly sustained, neither growing nor decaying over time.

2.	Record the controller proportional band as PBu as a percent, where PBu = 100 / Kc.

3.	Record the period of oscillation as Tu in minutes.

4.	Multiply the measured values by the factors shown in the following table, and enter the new tuning parameters into your controller. The table provides the proper values for a quarter-decay ratio.

If you want less overshoot, reduce the gain Kc.

Controller	PB (percent)	Reset(minutes)	Rate (minutes)
P	2.00
PI	2.22	0.83
PID	1.67	0.50	0.125
Note	Proportional gain (Kc) is related to proportional band (PB) as Kc = 100 / PB.


Open-Loop (Step Test) Tuning Procedure

The open-loop (step test) tuning procedure assumes that you can model any process as a first-order lag and a pure deadtime. This method requires more analysis than the closed-loop tuning procedure, but your process does not need to reach sustained oscillation. Therefore, the open-loop tuning procedure might be quicker and less hazardous for many processes. Observe the output and the process variable (PV) on a strip chart that shows time on the X axis. To perform the open-loop tuning procedure, complete the following steps:

1.	Put the controller in manual mode, set the output to a nominal operating value, and allow the PV to settle completely. Record the PV and output values.

2.	Make a step change in the output. Record the new output value.

3.	Wait for the PV to settle. From the chart, determine the values as derived from the sample displayed in the following figure.

The values are as follows:

−	Td—Deadtime in minutes

−	T—Time constant in minutes

−	K—Process gain = change in output

change in PV

4.	Multiply the measured values by the factors shown in the previous figure, and enter the new tuning parameters into your controller. The table provides the proper values for a quarter-decay ratio.

If you want less overshoot, reduce the gain Kc.

Controller	PB (percent)	Reset (minutes)	Rate (minutes)
P	100
PI	110	3.33
PID	80	2.00	0.50


ComponentWorks Autotuning PID Overview

ComponentWorks Autotuning PID is a collection of ActiveX controls for developing PID control applications within any compatible ActiveX control container. ActiveX controls also are known as OLE (Object Linking and Embedding) controls, and the two terms can be used interchangeably in this context. Use the online reference for specific information about the properties, methods, and events of the individual ActiveX controls. You can access this information by selecting Programs»National Instruments ComponentWorks»Autotuning PID»ComponentWorks PID Reference from the Windows Start menu.

PID (Proportional-Integral-Derivative) is the most common control algorithm used in industry. PID is often used to control processes such as heating and cooling systems, fluid level monitoring, flow control, and pressure control. The system parameter being controlled is referred to as the process variable (for example, temperature, pressure, or flow rate). The operator must specify a setpoint or desired value for the process variable that is to be controlled. A PID controller determines a controller output value (for example, heater power or valve position). The controller output value is applied to the system which in turn affects the process variable and drives it toward the setpoint value.

With ComponentWorks Autotuning PID, you can develop control applications based on proportional-integral-derivative (PID) controllers:

•	Proportional (P); proportional-integral (PI); proportional-derivative (PD); and proportional-integral-derivative (PID) algorithms

•	Gain-scheduled PID

•	PID autotuning

•	Error-squared PID

•	Lead-Lag compensation

•	Setpoint ramp generation

•	Multiloop cascade control

•	Feedforward control

•	Override (minimum/maximum selector) control

•	Ratio/bias control

The ComponentWorks Autotuning PID package contains the following components:

•	PID Control—ActiveX control for implementing PID process control algorithms in a physical system.

•	LeadLag Control—ActiveX control for calculating the dynamic compensator in feedforward control schemes.

•	Ramp Control—ActiveX control for generating setpoint ramps.

The ComponentWorks ActiveX controls are designed for use in Visual Basic, a premier ActiveX control container application. Some ComponentWorks features and utilities have been incorporated with the Visual Basic user in mind. However, you can use ActiveX controls in other applications that support them, including Visual C++ and Delphi.

Before you begin developing ComponentWorks applications, you should understand the following concepts as they relate to ComponentWorks:

Properties, Methods, and Events

Object Hierarchy

Collection Objects

Setting ActiveX Control Properties with Property Pages

Changing ActiveX Control Properties Programmatically

Item Method

Working with Control Methods

Developing Event Handler Routines


Properties, Methods, and Events

ActiveX controls consist of three different parts (properties, methods, and events) used to implement and program the controls.

Properties are the attributes of a control. These attributes describe the current state of the control and affect the display and behavior of the control. The values of the properties are stored in variables that are part of the control.

Methods are functions defined as part of the control. Methods are called with respect to a particular control and usually have some effect on the control itself. The operation of most methods is affected by the current property values of the control.

Events are notifications generated by a control in response to some particular occurrence. Events are passed to the control container application to execute a particular subroutine in the program (event handler).


Object Hierarchy

The three parts of an ActiveX control (properties, methods, and events) are stored in a software object. Because some ActiveX controls are very complex and contain many properties, ActiveX controls are often subdivided into different software objects, the sum of which make up the ActiveX control. Each individual object in a control contains specific parts (properties) and functionality (methods and events) of the ActiveX control. The relationships among different objects of a control are maintained in an object hierarchy. At the top of the hierarchy is the actual control itself.

This top-level object contains its own properties, methods, and events. Some of the top-level object properties are actually references to other objects that define specific parts of the control. Objects below the top-level have their own methods and properties, and their properties can be references to other objects. The number of objects in a hierarchy is not limited.

Another advantage of subdividing controls is the re-use of different objects between different controls. One object might be used at different places in the same object hierarchy or in several different object hierarchies.

The PID control object hierarchy demonstrates how a control is divided into different objects.


Collection Objects

One object can contain several objects of the same type. The number of objects in the group of objects might not be defined and might change while the program is running (that is, you can add or remove images as part of your program). To handle these groups of objects more easily, an object called a collection is created.

A collection is an object that contains or stores a varying number of objects of the same type. You can consider a collection as an array of objects. The name of a collection object is usually the plural of the name of the object type contained within the collection. For example, a collection of Image objects is referred to as Images. In the ComponentWorks software, the terms object and collection are rarely used, only the type names Image and Images are listed.

Each collection object contains an Item method that you can use to access any particular object stored in the collection.


Setting ActiveX Control Properties with Property Pages

Property pages are common throughout the Windows 95/98 and Windows NT interface. When you want to change the appearance or options of a particular object, right click on the object and select Properties. A property page or tabbed dialog box appears with a variety of properties that you can set for that particular object. You customize ActiveX controls in exactly the same way. Once you place the control on a form in your programming environment, right click on the control and select Properties to customize the appearance and operation of the control.

Use the property pages to set the property values for each ActiveX control while you are creating your application. The property values you select at this point represent the state of the control at the beginning of your application. You can change the property values from within your program as shown in the next section.

In some programming environments (such as Visual Basic and Delphi), you have two different property pages. The property page common to the programming environment is called the default property sheet; it contains the most basic properties of a control.

Your programming environment assigns default values for some of the basic properties, such as the control name and the tab order. You must edit these properties through the default property sheet.


Changing ActiveX Control Properties Programmatically

Each control you create in your program has a name (like a variable name) which you use to reference the control in your program. You can set the value of a property on a top-level object with the following syntax.

name.property = new_value

For example, you can set the ControllerType property using the following line of code, where cwpidPID is a constant specifying the PID controller.

CWPID1.ControllerType = cwpidPID

To access properties of sub-objects referenced by the top-level object, use the control name, followed by the name of the sub-object and the property name. For example, consider the following code for the PID control.

CWPID1.Autotune.ControlDesign = cwpidNormal

In the above code, Autotune is a property of the PID control and refers to an Autotune object. ControlDesign is one of several Autotune properties.

You can retrieve the value of control properties from your program in the same way. For example, you can print the value of the PID ControllerType property.

Print CWPID1.ControllerType

You can display the setpoint of the PID control in a Visual Basic text box with the following code.

Text1.Text = CWPID1.Setpoint


Item Method

To access an object or its properties in a collection, use the Item method on the collection object. For example, you can set the proportional gain of a PID control with the following code.

CWPID1.Parameters.Item(2).ProportionalGain= 10

The term CWPID1.Parameters.Item(2) refers to the second Parameter object in the Parameters collection of the PID object. The parameter of the Item method is an integer representing the (one-based) index of the object in the collection.

Because the Item method is the most commonly used method on a collection, it is referred to as the default method. Therefore, some programming environments do not require you to specify the .Item method. For example, in Visual Basic

CWPID1.Parameters(2).ProportionalGain = 10

is programmatically equivalent to

CWPID1.Parameters.Item(2).ProportionalGain= 10


Working with Control Methods

ActiveX controls and objects have their own methods, or functions, that you can call from your program. Methods can have parameters that are passed to the method and return values that pass information back to your program.

Methods can have required and optional parameters in some programming environments, such as Visual Basic. You can omit these optional parameters if you want to use their default values. Other programming environments require all parameters to be passed explicitly.

Depending on your programming environment, parameters might be enclosed in parentheses. If the function or method is not assigned a return variable, Visual Basic does not use parentheses to pass parameters. When returning a value to a variable, enclose parameters in parentheses, as in the following example.

output = CWPID1.NextOutput(ProcessVariable)


Developing Event Handler Routines

After configuring your controls on a form, you can create event handler routines in your program to respond to events generated by the controls. For example, the PID control has an AutotuneComplete event that fires (occurs) when the autotuning process has completed.

To develop the event routine code, most programming environments generate a skeleton function to handle each event. For example, the Visual Basic environment generates the following function skeleton into which you insert the functions to call when the AutotuneComplete event occurs.

Private Sub CWPID1_AutotuneComplete (ByVal NewParameterPosition As Long)

End Sub

In most cases, the event also returns some data to the event handler that can be used in your event handler routine.


Count
Count Property (Read Only)

Syntax

Object.Count

Data Type

Long

Purpose

Returns the number of objects in the collection.

Example

' same syntax applies to other collections

numParams = CWPID1.Parameters.Count

foo


Item Method, Reference
Item Method

Syntax

Object.Item( Item)

Return Type

Object

Purpose

Returns the specified object from the collection.

Return Value

The object specified.

Parameter	Type	Description

Item	Variant	Specifies either the name of the object or the index of the object in the collection. If you use the index, it is one-based.

Example

' assign object in collection to variable

Dim Parameter as CWParameter

Set Parameter = CWPID1.Parameters.Item(1)

' call property or method on object in collection

CWPID1.Parameters.Item(1).Name = "Param1"


Remove
Remove Method

Syntax

Object.Remove Item

Purpose

Removes the specified item from the collection.

Parameter	Type	Description

Item	Variant	Represents either the name of the object or the index of the object in the collection.

Example

' remove third Parameter from the collection

CWPID1.Parameters.Remove 3


RemoveAll
RemoveAll Method

Syntax

Object.RemoveAll

Applies To

Purpose

Removes all objects from the collection.

Example

' remove all parameter objects from the control

CWPID1.Parameters.RemoveAll


CWLeadLag

Contains all the properties and methods necessary for calculating the dynamic compensator in feedforward control schemes.

Properties

DeltaT	Gain	LagTime

LeadTime	UseInternalTimer

Methods

AboutBox	NextOutput	Reset


CWLeadLag.DeltaT
DeltaT Property

Syntax

CWLeadLag.DeltaT

Data Type

Double

Purpose

The interval (in seconds) at which the NextOutput method is called. This value is used only if the UseInternalTimer property is set to FALSE.

Example

' Disable System Clock and set DeltaT to 100 ms.

CWLeadLag1.UseInternalTimer = False

CWLeadLag1.DeltaT = 0.1

See Also

UseInternalTimer

NextOutput


CWLeadLag.Gain
Gain Property

Syntax

CWLeadLag.Gain

Data Type

Double

Purpose

The gain is expressed in percent. The range is - ∞ to ∞.

Example

' Set the gain to 1

CWLeadLag1.Gain = 1

See Also

NextOutput


CWLeadLag.LagTime
LagTime Property

Syntax

CWLeadLag.LagTime

Data Type

Double

Purpose

The lag time is expressed in minutes. The range is 0 to  ∞. Zero turns the lag time off.

Example

' Set the lag time to 3 ms.

CWLeadLag1.LagTime = 0.03

See Also

NextOutput


CWLeadLag.LeadTime
LeadTime Property

Syntax

CWLeadLag.LeadTime

Data Type

Double

Purpose

The lead time is expressed in minutes. The range is 0 to ∞. Zero turns the lead time off.

Example

' Set the lead time to 1 ms.

CWLeadLag1.LeadTime = 0.01

See Also

NextOutput


CWLeadLag.UseInternalTimer
UseInternalTimer Property

Syntax

CWLeadLag.UseInternalTimer

Data Type

Boolean

Purpose

Specifies whether to use the Internal Timer to determine the amount of time since the last call to NextOutput or whether to use the DeltaT property as the value assumed for the amount of time since the last call to NextOutput.

If the UseInternalTimer value is FALSE, the DeltaT value is used in the calculations regardless of the elapsed time.

Remarks

The tick timer resolution on Windows 95 and NT is 1 ms. Because of this limitation, you should not try to run the LeadLag control faster than 10 Hz when using the Internal Timer.

Example

' Enable the use of the Internal Timer

CWLeadLag1.UseInternalTimer = True

See Also

DeltaT

NextOutput


CWLeadLag.AboutBox
AboutBox Method

Syntax

CWLeadLag.AboutBox

Purpose

Displays the About Box for the control.

Remarks

The About Box displays the version number of the controls and information about contacting National Instruments. You can access the About Box from a separate tab on the property pages.

Example

' Display the LeadLag control's About Box

CWLeadLag1.AboutBox


CWLeadLag.NextOutput
NextOutput Method

Syntax

CWLeadLag.NextOutput( Input)

Return Type

Double

Purpose

Calculates the next output for the lead-lag based on the Input value.

Return Value

The next output value given the input value.

Parameter	Type	Description

Input	Double	The input is expressed in percent. The range is 0 to 100%.

Example

' Call NextOutput passing in 50%.

output = CWLeadLag1.NextOutput 50


CWLeadLag.Reset
Reset Method

Syntax

CWLeadLag.Reset

Purpose

Resets the CWLeadLag control so that previous calls to the control do no affect the next call.

Example

' Reset the LeadLag Control

CWLeadLag1.Reset

See Also

NextOutput


CWPID

Contains all the properties and methods necessary to calculate the NextOutput given a process variable. CWPID is the main control in the ComponentWorks Autotuning PID software.

Properties

ActiveParameter	AutomaticSelectionCriteria	Autotune

Beta	ControllerType	DeltaT

GainSchedulingVariable	HoldCurrentOutput	InitialOutput

LimitOutputRate	Linearity	ManualControlValue

OutputMax	OutputMin	OutputRate

Parameters	ReverseActing	SelectionMode

Setpoint	SetpointMax	SetpointMin

UseInternalTimer	UseManualControlValue	UseProportionalBand

Methods

AboutBox	NextOutput	Reset

Events

AutotuneComplete	NoiseEstimateComplete	RelayCycle

See Also

NextOutput


CWPID.ActiveParameter
ActiveParameter Property

Syntax

Set CWPID.ActiveParameter

Data Type

CWPIDParameter

Purpose

Specifies which parameter in the CWPIDParameters collection is the parameter that will be used when calling NextOutput. ActiveParameter gets updated as the gain scheduling algorithm selects parameters to use.

Example

' Set the ActiveParameter to the third parameter in the CWPIDParameters collection

CWPID1.ActiveParameter = CWPID1.Parameters.Item(3)

See Also

CWPIDParameter

CWPIDParameters

NextOutput


CWPID.AutomaticSelectionCriteria
AutomaticSelectionCriteria Property

Syntax

CWPID.AutomaticSelectionCriteria

Data Type

CWPIDAutomaticSelectionCriteriaTypes

You can use the following constants with this data type.

−	cwpidControllerOutput - The controller uses the output from the previous call to NextOutput as the criteria to select the appropriate PID parameters.

−	cwpidGainSchedulingVariable - The controller uses the value specified in the GainSchedulingVariable as the criteria to select the appropriate PID parameters.

−	cwpidProcessVariable - The controller uses the value passed in as the process variable as the criteria to select the appropriate PID parameters.

−	cwpidSetpoint - The controller uses the value specified by the setpoint as the criteria to select the appropriate PID parameters.

Purpose

Defines the variable that should be used when determining which CWPIDParameter to use when calling NextOutput. This value is used only if the SelectionMode property is set to cwpidAutomatic.

Example

' Set the Automatic Selection Criteria to the Setpoint

CWPID1.AutomaticSelectionCriteria = cwpidSetpoint

See Also

GainSchedulingVariable

CWPIDParameter

SelectionMode

NextOutput


CWPID.Autotune
Autotune Property

Syntax

Get CWPID.Autotune

Data Type

CWPIDAutoTune

Purpose

Returns the CWPIDAutotune sub-object associated with the CWPID object.

Example

' Get the Autotune object

Dim a as CWPIDAutotune

Set a = CWPID1.Autotune

See Also

CWPID

CWPIDAutotune


CWPID.Beta
Beta Property

Syntax

CWPID.Beta

Data Type

Double

Purpose

The relative emphasis of disturbance rejection to setpoint tracking. The default of 1 is appropriate for most applications. A smaller value between 0 and 1 can be used to specify emphasis on disturbance rejection (such as process load changes).

Example

' Set the beta to 1

CWPID1.Beta = 1


CWPID.ControllerType
ControllerType Property

Syntax

CWPID.ControllerType

Data Type

CWPIDControllerTypes

You can use the following constants with this data type.

−	cwpidP - Specifies that the controller use only the proportional gain to calculate the next output.

−	cwpidPD - Specifies that the controller use only the proportional gain and derivative time to calculate the next output.

−	cwpidPI - Specifies that the controller use only the proportional gain and integral time to calculate the next output.

−	cwpidPID - Specifies that the controller use the proportional gain, integral time, and derivative time to calculate the next output.

Purpose

Specifies whether the PID control should be proportional-integral-derivative, proportional-integral, or proportional only.

Example

' Set the controller type to Proportional-Integral

CWPID1.ControllerType = cwpidPI


CWPID.DeltaT
DeltaT Property

Syntax

CWPID.DeltaT

Data Type

Double

Purpose

The interval (in seconds) at which the NextOutput method is called. This value is used only if the UseSystemClock property is set to FALSE.

Example

' Disable System Clock and set DeltaT to 100 ms.

CWPID1.UseInternalTimer = False

CWPID1.DeltaT = 0.1

See Also

UseInternalTimer

NextOutput


CWPID.GainSchedulingVariable
GainSchedulingVariable Property

Syntax

CWPID.GainSchedulingVariable

Data Type

Double

Purpose

If the AutomaticSelectionCriteria is set to cwpidGainSchedulingVariable, this value is used to determine which CWPIDParameter to use when calling NextOutput.

Example

' Set the gain scheduling variable to 20

CWPID1.GainSchedulingVariable = 20

See Also

CWPIDParameter

NextOutput

AutomaticSelectionCriteria


CWPID.HoldCurrentOutput
HoldCurrentOutput Property

Syntax

CWPID.HoldCurrentOutput

Data Type

Boolean

Purpose

Indicates whether to hold the current output. If HoldCurrentOutput is TRUE, the Reset action stops and the output freezes. Bumpless transfer is used from run to hold.

Example

' Hold the current output

CWPID1.HoldCurrentOutput = True


CWPID.InitialOutput
InitialOutput Property

Syntax

CWPID.InitialOutput

Data Type

Double

Purpose

Specifies the previous output value that will be used when limiting the OutputRate while calling NextOutput for the first time. This value is used only if the UseOutputRateLimiter is TRUE.

Remarks

An initial value is needed when calling NextOutput while limiting the output rate.

Example

' Limit the output rate and set the initial output to 0

CWPID1.LimitOutputRate = True

CWPID1.InitialOutput = 0

See Also

NextOutput

LimitOutputRate


CWPID.LimitOutputRate
LimitOutputRate Property

Syntax

CWPID.LimitOutputRate

Data Type

Boolean

Purpose

Specifies whether to limit the rate of change for the NextOutput method. If LimitOutputRate is TRUE, the OutputRate property determines how fast the output can change.

Example

' Limit the output rate

CWPID1.LimitOutputRate = True

See Also

NextOutput

OutputRate

InitialOutput


CWPID.Linearity
Linearity Property

Syntax

CWPID.Linearity

Data Type

Double

Purpose

Sets the linearity of error response, ranging from zero to one. 1.0 gives a plain linear response, while 0.1 gives an approximately parabolic (square law) response.

Example

' Set the linearity to 1

CWPID1.Linearity = 1


CWPID.ManualControlValue
ManualControlValue Property

Syntax

CWPID.ManualControlValue

Data Type

Double

Purpose

A relative controller output value used when UseManualControlValue is set to TRUE.

Example

' Set the manual control value and use it.

CWPID1.ManualControlValue = 10

CWPID1.UseManualControlValue = True

See Also

UseManualControlValue


CWPID.OutputMax
OutputMax Property

Syntax

CWPID.OutputMax

Data Type

Double

Purpose

The maximum value for the controller output.

Example

' Set the max output to 50

CWPID1.OutputMax = 50

See Also

OutputMin

NextOutput


CWPID.OutputMin
OutputMin Property

Syntax

CWPID.OutputMin

Data Type

Double

Purpose

The minimum value for the controller output.

Example

' Set the min output to 25

CWPID1.OutputMin = 25

See Also

OutputMax

NextOutput


CWPID.OutputRate
OutputRate Property

Syntax

CWPID.OutputRate

Data Type

Double

Purpose

The maximum rate of change of the controller output.

Remarks

The OutputRate property is used only when the LimitOutputRate property is TRUE.

Example

' Set the output rate to 100

CWPID1.OutputRate = 100

See Also

LimitOutputRate


CWPID.Parameters
Parameters Property

Syntax

Get CWPID.Parameters

Data Type

CWPIDParameters

Purpose

The CWPIDParameters collection sub-object.

Example

' Get the CWPIDParameters collection

Dim p as CWPIDParameters

Set p = CWPID1.Parameters

See Also

CWPIDParameter

CWPIDParameters


CWPID.ReverseActing
ReverseActing Property

Syntax

CWPID.ReverseActing

Data Type

Boolean

Purpose

Specifies if the control is reverse acting. Reverse acting is the usual mode for controllers where the output decreases if the input is greater than the setpoint.

Example

' Turn on Reverse Acting

CWPID1.ReverseActing = True

See Also

Setpoint


CWPID.SelectionMode
SelectionMode Property

Syntax

CWPID.SelectionMode

Data Type

CWPIDSelectionModeTypes

You can use the following constants with this data type.

−	cwpidManual - Specifies that the controller use the PID parameter specified by the ActiveParameter when calling NextOutput.

−	cwpidUseAutomaticGainScheduling - Specifies that the controller automatically select the PID parameter using the automatic selection criteria when calling NextOutput.

Purpose

If SelectionMode is TRUE, the controller automatically determines which CWPIDParameter to use in the CWPIDParameterArray collection. Otherwise, the CWPIDParameter specified by the ActiveParameter property is used.

Example

' Set the Selection mode to manual

CWPID1.SelectionMode = cwpidManual

See Also

ActiveParameter

CWPIDParameter

CWPIDParameters


CWPID.Setpoint
Setpoint Property

Syntax

CWPID.Setpoint

Data Type

Double

Purpose

The desired value for the process variable.

Example

' Set the setpoint to 50

CWPID1.Setpoint = 50


CWPID.SetpointMax
SetpointMax Property

Syntax

CWPID.SetpointMax

Data Type

Double

Purpose

The maximum value for the process variable and the setpoint.

Example

' Set the max value for the setpoint

CWPID1.SetpointMax = 100

See Also

SetpointMin

Setpoint


CWPID.SetpointMin
SetpointMin Property

Syntax

CWPID.SetpointMin

Data Type

Double

Purpose

The minimum value for the process variable and the setpoint.

Example

' Set the min value for the setpoint

CWPID1.SetpointMin = 0

See Also

SetpointMax

Setpoint


CWPID.UseInternalTimer
UseInternalTimer Property

Syntax

CWPID.UseInternalTimer

Data Type

Boolean

Purpose

Specifies whether to use the Internal Timer to determine the amount of time since the last call to NextOutput or whether to use the DeltaT property as the value assumed for the amount of time since the last call to NextOutput.

If the UseInternalTimer value is FALSE, the DeltaT value is used in the calculations regardless of the elapsed time.

Remarks

The tick timer resolution on Windows 95 and NT is 1 ms. Because of this limitation, you should not try to run the PID control faster than 10 Hz when using the Internal Timer.

Example

' Enable the use of the Internal Timer

CWPID1.UseInternalTimer = True

See Also

DeltaT


CWPID.UseManualControlValue
UseManualControlValue Property

Syntax

CWPID.UseManualControlValue

Data Type

Boolean

Purpose

Specifies whether to use the ManualControlValue as the relative controller output or have it generated automatically.

Example

' Use the manual control value

CWPID1.UseManualControlValue = True

See Also

ManualControlValue


CWPID.UseProportionalBand
UseProportionalBand Property

Syntax

CWPID.UseProportionalBand

Data Type

Boolean

Purpose

Selects whether the proportional value of the PID Parameters is proportional gain or proportional band. The default value is FALSE, specifying proportional gain. Proportional gain is 100/PB where PB is proportional band.

Example

' Use the proportional band

CWPID1.UseProportionalBand = True


CWPID.AboutBox
AboutBox Method

Syntax

CWPID.AboutBox

Purpose

Displays the About Box for the control.

Remarks

The About Box displays the version number of the controls and information about contacting National Instruments. You can access the About Box from a separate tab on the property pages.

Example

' Display the PID control's About Box

CWPID1.AboutBox


CWPID.NextOutput
NextOutput Method

Syntax

CWPID.NextOutput( ProcessVariable)

Return Type

Double

Purpose

Generates the next output value given the process variable and the current PID control state. (The PID algorithm)

Return Value

The output of the control algorithm.

Parameter	Type	Description

ProcessVariable	Double	The ProcessVariable is the value of the feedback control loop.

Example

' Determining the next output with a process variable of PV

Dim Output as Double

Output = CWPID1.NextOutput(PV)

See Also

Reset

PID Algorithm


CWPID.Reset
Reset Method

Syntax

CWPID.Reset

Purpose

Resets the PID control so that previous calls to the NextOutput method do not affect the next call.

Example

' Reset the control

CWPID1.Reset

See Also

NextOutput


CWPID.AutotuneComplete
AutotuneComplete Event

Syntax

Sub ControlName_AutoTuneComplete( NewParameterPosition As Long)

Applies To

CWPID

Purpose

Fires when the CWPIDAutotune object has finished the autotune process.

Parameter	Type	Description

NewParameterPosition	Long	The position where the calculated PID parameters are stored in the CWPIDParameters collection.

Example

Private Sub CWPID1_AutotuneComplete(ByVal NewParameterPosition As Long)

 CWPID1.ActiveParameter = CWPID1.Parameters.Item(NewParameterPosition)

 UpdateActiveParameters

End Sub

See Also

CWPIDAutotune

CWPIDParameter

CWPIDParameters


CWPID.NoiseEstimateComplete
NoiseEstimateComplete Event

Syntax

Sub ControlName_NoiseEstimateComplete()

Applies To

CWPID

Purpose

Fires when the CWPIDAutotune object has finished the Noise Estimate process. The CWPIDAutotune sub-object's NoiseLevel property contains the estimated noise level.

Example

Private Sub CWPID1_NoiseEstimateComplete()

 If CWPID1.Autotune.NoiseLevel < 0.1 Then

  ' perform some operation

 End If

End Sub

See Also

CWPIDAutotune.NoiseLevel


CWPID.RelayCycle
RelayCycle Event

Syntax

Sub ControlName_RelayCycle()

Applies To

CWPID

Purpose

Event that fires every time the relay goes through a complete cycle.

Remarks

If you know how many relays are needed for the process to become stable, you can use this event to determine when to start the autotune process.

Example

Private Sub CWPID1_RelayCycle()

 relayCount = relayCount + 1

  If relayCount > numToStabalize Then

    CWPID1.Autotune.StartAutotune 5

  End If

End Sub


CWPIDAutotuningControllerTypes
CWPIDAutotuningControllerTypes Enumeration

CWPIDAutotuningControllerTypes are the constants for the ControlTypes property on CWPIDAutotune.

You can use the following constants with this data type.

−	cwpidAutotuneP - Specifies that the controller use only the proportional gain to calculate the next output.

−	cwpidAutotunePI - Specifies that the controller use only the proportional gain and integral time to calculate the next output.

−	cwpidAutotunePID - Specifies that the controller use the proportional gain, integral time, and derivative time to calculate the next output.

See Also

CWPIDAutotune


CWPIDAutomaticSelectionCriteriaTypes
CWPIDAutomaticSelectionCriteriaTypes Enumeration

CWPIDAutomaticSelectionCriteria are the constants for the AutomaticSelectionCriteria property on CWPID.

You can use the following constants with this data type.

−	cwpidControllerOutput - The controller uses the output from the previous call to NextOutput as the criteria to select the appropriate PID parameters.

−	cwpidGainSchedulingVariable - The controller uses the value specified in the GainSchedulingVariable as the criteria to select the appropriate PID parameters.

−	cwpidProcessVariable - The controller uses the value passed in as the process variable as the criteria to select the appropriate PID parameters.

−	cwpidSetpoint - The controller uses the value specified by the setpoint as the criteria to select the appropriate PID parameters.


CWPIDAutotune

Contains all the properties and methods necessary to autotune PID Parameters. See also Autotuning Algorithm.

Properties

ApplyToActiveParameter	ControlDesign	ControlType

NoiseLevel	RelayAmplitude

Methods

CloseDialog	ShowDialog	StartAutotune

StartNoiseEstimate	StartRelay	StopAutotune

StopNoiseEstimate	StopRelay

See Also

CWPIDParameter

CWPID


CWPIDAutotune.ApplyToActiveParameter
ApplyToActiveParameter Property

Syntax

CWPIDAutotune.ApplyToActiveParameter

Data Type

Boolean

Purpose

Specifies whether to apply the new PID parameters calculated by the autotuning to the current PID parameters. If this value is FALSE, a new CWPIDParameter object is created and the results stored there.

Example

' Do not apply the results to the Active Parameters

CWPID1.Autotune.ApplyToActiveParameters = False

See Also

CWPIDParameter


CWPIDAutotune.ControlDesign
ControlDesign Property

Syntax

CWPIDAutotune.ControlDesign

Data Type

CWPIDAutotuningControlDesignTypes

You can use the following constants with this data type.

−	cwpidAutotuneFast - Specifies the controller as a fast controller.

−	cwpidAutotuneNormal - Specifies the controller as a normal controller.

−	cwpidAutotuneSlow - Specifies the controller as a slow controller.

Purpose

Specifies what type of controller for which the Autotune object should calculate new PID parameters. Valid values include Normal, Fast or Slow.

Remarks

Depending on the control design, use different settings to autotune the control .

Example

' Set the control design to fast

CWPID1.Autotune.ControlDesign = cwpidAutotuneFast

See Also

Tuning Formulas


CWPIDAutotune.ControlType
ControlType Property

Syntax

CWPIDAutotune.ControlType

Data Type

CWPIDAutotuningControllerTypes

You can use the following constants with this data type.

−	cwpidAutotuneP - Specifies that the controller use only the proportional gain to calculate the next output.

−	cwpidAutotunePI - Specifies that the controller use only the proportional gain and integral time to calculate the next output.

−	cwpidAutotunePID - Specifies that the controller use the proportional gain, integral time, and derivative time to calculate the next output.

Purpose

Specifies what type of PID parameters the Autotune object should create: PID, PI, or P.

Remarks

Depending on the control design, use different settings to autotune the control .

Example

' Set the control type to PI

CWPID1.Autotune.ControlType = cwpidAutotunePI

See Also

Tuning Formulas


CWPIDAutotune.NoiseLevel
NoiseLevel Property

Syntax

CWPIDAutotune.NoiseLevel

Data Type

Double

Purpose

Specifies the amount of noise in the system.

Example

' Set the amount of noise in the system to 0.25

CWPID1.Autotune.NoiseLevel = 0.25

See Also

StartNoiseEstimate

StopNoiseEstimate


CWPIDAutotune.RelayAmplitude
RelayAmplitude Property

Syntax

CWPIDAutotune.RelayAmplitude

Data Type

Double

Purpose

Specifies the amplitude the Autotune object should use when modifying the setpoint during the relay process.

Example

' Set the relay amplitude to 2

CWPID1.Autotune.RelayAmplitude = 2

See Also

StartRelay

StopRelay


CWPIDAutotune.CloseDialog
CloseDialog Method

Syntax

CWPIDAutotune.CloseDialog

Purpose

Closes the Autotune Wizard Dialog box if open.

Example

' Close the Autotune Wizard dialog

CWPID1.Autotune().CloseDialog()

See Also

ShowDialog


CWPIDAutotune.ShowDialog
ShowDialog Method

Syntax

CWPIDAutotune.ShowDialog GraphUpdateRate

Purpose

Shows the Autotune Wizard dialog box that leads users through the autotuning process.

Parameter	Type	Description

GraphUpdateRate	CWPIDAutoTuningGraphUpdateRateTypes	Specifies the rate at which the Graph is updated on the autotune dialog. The faster the update, the more time it takes away from PID algorithm.

Example

' Start the Autotune Wizard

CWPID1.Autotune().ShowDialog(cwpidAutotune100ms)

See Also

CloseDialog


CWPIDAutotune.StartAutotune
StartAutotune Method

Syntax

CWPIDAutotune.StartAutotune NumCycles

Purpose

Starts the autotuning process. The StartRelay method must be called before you can call this method.

Parameter	Type	Description

NumCycles	Long	The number of cycles the Autotune algorithm should use to calculate the new PID Parameters

Example

' Start the autotuning process using 3 cycles

CWPID1.Autotune().StartAutotune(3)

See Also

StopAutotune

StartRelay


CWPIDAutotune.StartNoiseEstimate
StartNoiseEstimate Method

Syntax

CWPIDAutotune.StartNoiseEstimate NumCycles

Purpose

Starts the process for estimating the noise.

Parameter	Type	Description

NumCycles	Long	The number of cycles to use when calculating the noise in the system.

Example

' Start the Noise Estimate using 100 cycles

CWPID1.Autotune().StartNoiseEstimate(100)

See Also

StopNoiseEstimate


CWPIDAutotune.StartRelay
StartRelay Method

Syntax

CWPIDAutotune.StartRelay

Purpose

Starts the relay process.

Example

' Start the Relay Process

CWPID1.Autotune().StartRelay()

See Also

StopRelay


CWPIDAutotune.StopAutotune
StopAutotune Method

Syntax

CWPIDAutotune.StopAutotune

Purpose

Stops the autotune process before it completes.

Remarks

The control will still be in a relay state. To stop the relay, you must call StopRelay after calling StopAutotune.

Example

' Stop the autotuning process

CWPID1.Autotune().StopAutotune()

See Also

StartAutotune

StopRelay


CWPIDAutotune.StopNoiseEstimate
StopNoiseEstimate Method

Syntax

CWPIDAutotune.StopNoiseEstimate

Purpose

Stops the noise estimate process before it completes.

Example

' Stop the noise estimate

CWPID1.Autotune().StopNoiseEstimate()

See Also

StartNoiseEstimate


CWPIDAutotune.StopRelay
StopRelay Method

Syntax

CWPIDAutotune.StopRelay

Purpose

Stops the relay process.

Example

' Stop the relay process

CWPID1.Autotune().StopRelay()

See Also

StartRelay


CWPIDAutotuningGraphUpdateRateTypes
CWPIDAutotuningGraphUpdateRateTypes Enumeration

CWPIDAutotuningGraphUpdateRateTypes are the constants for the GraphUpdateRate parameter on the CWPIDAutoTune.ShowDialog method.

You can use the following constants with this data type.

−	cwpidAutotune100ms - Updates the Autotune Wizard dialog graph every 100ms.

−	cwpidAutotune20ms - Updates the Autotune Wizard dialog graph every 20ms.

−	cwpidAutotune500ms - Updates the Autotune Wizard dialog graph every 500ms.

−	cwpidAutotuneMax - Updates the Autotune Wizard dialog graph as fast as it can.


CWPIDAutotuningControlDesignTypes
CWPIDAutotuningControlDesignTypes Enumeration

CWPIDAutotuningControlDesignTypes are the constants for the ControlDesign property on CWPIDAutoTune.

You can use the following constants with this data type.

−	cwpidAutotuneFast - Specifies the controller as a fast controller.

−	cwpidAutotuneNormal - Specifies the controller as a normal controller.

−	cwpidAutotuneSlow - Specifies the controller as a slow controller.


CWPIDControllerTypes
CWPIDControllerTypes Enumeration

CWPIDControllerTypes are the constants for the ControllerTypes property on CWPID.

You can use the following constants with this data type.

−	cwpidP - Specifies that the controller use only the proportional gain to calculate the next output.

−	cwpidPD - Specifies that the controller use only the proportional gain and derivative time to calculate the next output.

−	cwpidPI - Specifies that the controller use only the proportional gain and integral time to calculate the next output.

−	cwpidPID - Specifies that the controller use the proportional gain, integral time, and derivative time to calculate the next output.


CWPIDParameter

Contains the properties needed by the CWPID object to calculate the NextOutput.

Properties

Active	DerivativeTime	GainSchedulingVariable

IntegralTime	Name	ProportionalGain

See Also

CWPID

CWPID.NextOutput


CWPIDParameter.Active
Active

Syntax

CWPIDParameter.Active

Data Type

Boolean

Purpose

Specifies whether the parameter is the ActiveParameter.

Example

' Set the parameter to be the active parameter

dim p as CWPIDParameter

set p = CWPID.Parameters.Item(1)

p.Active = true

See Also

CWPID.ActiveParameter


CWPIDParameter.DerivativeTime
DerivativeTime Property

Syntax

CWPIDParameter.DerivativeTime

Data Type

Double

Purpose

Specifies the derivative time.

Example

' Set the derivative time to 0.001

dim p as CWPIDParameter

Set p = CWPID1.Parameters.Item(1)

p.DerivativeTime = 0.001

See Also

CWPID.NextOutput


CWPIDParameter.GainSchedulingVariable
GainSchedulingVariable Property

Syntax

CWPIDParameter.GainSchedulingVariable

Data Type

Double

Purpose

Compares against the AutomaticSelectionCriteria when the SelectionMode is set to Automatic.

Remarks

The control uses the CWPIDParameter that has the largest GainSchedulingVariable value less than the value specified by the AutomaticSelectionCriteria. For example, if three parameters have GainSchedulingVariables equal to 10, 20, and 30 and the value specified by the AutomaticSelectionCriteria is 25, then the second parameter is used.

If the value specified by the AutomaticSelectionCriteria is less than the smallest parameter's GainSchedulingVariable, the parameter with the smallest GainSchedulingVariable is used.

Example

' Set the GainSchedulingVariable to 10

dim p as CWPIDParameter

Set p = CWPID1.Parameters.Item(1)

p.GainSchedulingVariable = 10

See Also

CWPID.AutomaticSelectionCriteria

CWPID.SelectionMode


CWPIDParameter.IntegralTime
IntegralTime Property

Syntax

CWPIDParameter.IntegralTime

Data Type

Double

Purpose

Specifies the integral time.

Example

' Set the integral time to 0.015

dim p as CWPIDParameter

Set p = CWPID1.Parameters.Item(1)

p.IntegralTime = 0.015

See Also

CWPID.NextOutput


CWPIDParameter.Name
Name Property

Syntax

CWPIDParameter.Name

Data Type

String

Purpose

String representation for the CWPIDParameter object.

Example

' Set the name to "Param1"

dim p as CWPIDParameter

Set p = CWPID1.Parameters.Item(1)

p.Name = "Param1"


CWPIDParameter.ProportionalGain
ProportionalGain Property

Syntax

CWPIDParameter.ProportionalGain

Data Type

Double

Purpose

Specifies the proportional gain.

Example

' Set the proportional gain to 10

dim p as CWPIDParameter

Set p = CWPID1.Parameters.Item(1)

p.ProportionalGain = 10

See Also

CWPID.NextOutput


CWPIDParameters

The Collection object is a container for groups of objects of the same type, such as PID parameters. The name of the collection is the plural of the object name in the collection. For example, CWPIDParameters is a collection of CWPIDParameter objects. To reference an object in the collection, you must specify the object as part of the collection, usually by index. For example, CWPID.Parameters.Item(2) is the second parameter in the CWPIDParameters collection of a graph.

Properties

Count

Methods

Add

Item

Remove

RemoveAll

See Also

CWPIDParameter


Add
Add Method

Syntax

Object.Add( Name, ProportionalGain, IntegralTime, DerivativeTime, GainSchedulingVariable)

Return Type

CWPIDParameter

Applies To

Purpose

Adds an object to the collection and returns the new object.

Return Value

The newly created object.

Parameter	Type	Description

Name	String	Name of the CWPIDParameter to add to the collection.

ProportionalGain	Double	The ProportionalGain value for the CWPIDParameter to add to the collection.

IntegralTime	Double	The IntegralTime value for the CWPIDParameter to add to the collection.

DerivativeTime	Double	The DerivativeTime value for the CWPIDParameter to add to the collection.

GainSchedulingVariable	Double	The GainSchedulingVariable value for the CWPIDParameter to add to the collection.

Example

' Add a PID Parameter to the control

CWPID1.Parameters.Add "Param1", 10, 0.015, 0.001, 0

See Also

CWPIDParameter


CWPIDSelectionModeTypes
CWPIDSelectionModeTypes Enumeration

CWPIDSelectionModeTypes are the constants for the SelectionMode property on CWPID.

You can use the following constants with this data type.

−	cwpidManual - Specifies that the controller use the PID parameter specified by the ActiveParameter when calling NextOutput.

−	cwpidUseAutomaticGainScheduling - Specifies that the controller automatically select the PID parameter using the automatic selection criteria when calling NextOutput.


CWRamp

Contains all the properties and methods needed for generating a setpoint ramp.

Properties

DeltaT	InitialOutput	Rate

Setpoint	UseInternalTimer

Methods

AboutBox	NextOutput	Reset


CWRamp.DeltaT
DeltaT Property

Syntax

CWRamp.DeltaT

Data Type

Double

Purpose

The interval (in seconds) at which the NextOutput method is called. This value is used only if the UseInternalTimer property is set to FALSE.

Example

' Disable System Clock and set DeltaT to 100 ms.

CWRamp1.UseInternalTimer = False

CWRamp1.DeltaT = 0.1

See Also

UseInternalTimer

NextOutput


CWRamp.InitialOutput
InitialOutput Property

Syntax

CWRamp.InitialOutput

Data Type

Double

Purpose

Specifies the last output value used when NextOutput is called for the first time.

Remarks

The CWRamp control uses the Output from previous calculations to determine the results when calling NextOutput. This value specifies what the control can assume as the initial output.

Example

' Specify 0 as the initial output for the control

CWRamp1.InitialOutput = 0

See Also

NextOutput


CWRamp.Rate
Rate Property

Syntax

CWRamp.Rate

Data Type

Double

Purpose

Specifies the ramp slope in percentage per minute. Positive values make the ramp increase with time.

Example

' Set the rate to 100

CWRamp1.Rate = 100

See Also

NextOutput


CWRamp.Setpoint
Setpoint Property

Syntax

CWRamp.Setpoint

Data Type

Double

Purpose

Specifies the desired value for the process variable. The setpoint is specified in percent. The range is 0 to 100%.

Example

' Set the setpoint to 50

CWRamp1.Setpoint = 50

See Also

NextOutput


CWRamp.UseInternalTimer
UseInternalTimer Property

Syntax

CWRamp.UseInternalTimer

Data Type

Boolean

Purpose

Specifies whether to use the Internal Timer to determine the amount of time since the last call to NextOutput or whether to use the DeltaT property as the value assumed for the amount of time since the last call to NextOutput.

If the UseInternalTimer value is FALSE, the DeltaT value is used in the calculations regardless of the elapsed time.

Remarks

The tick timer resolution on Windows 95 and NT is 1 ms. Because of this limitation, you should not try to run the Ramp control faster than 10 Hz when using the Internal Timer.

Example

' Enable the use of the Internal Timer

CWRamp.UseInternalTimer = True

See Also

DeltaT

NextOutput


CWRamp.AboutBox
AboutBox Method

Syntax

CWRamp.AboutBox

Purpose

Displays the About Box for the control.

Remarks

The About Box displays the version number of the controls and information about contacting National Instruments. You can access the About Box from a separate tab on the property pages.

Example

' Display the Ramp control's About Box

CWPID1.AboutBox


CWRamp.NextOutput
NextOutput Method

Syntax

CWRamp.NextOutput()

Return Type

Double

Purpose

Calculates the next output for the ramp.

Return Value

The next output value given the current state of the control.

Example

' Get the next output from the control

output = CWRamp1.NextOutput


CWRamp.Reset
Reset Method

Syntax

CWRamp.Reset

Purpose

Resets the CWRamp control so that previous calls to the control do no affect the next call.

Example

' Reset the control

CWRamp1.Reset

See Also

NextOutput


Data Types

Visual Basic	C/C++	Description

Boolean	BOOL	Has the value True (-1) or False (0).

Color	OLECOLOR	A color. In many containers, colors are treated as 32-bit integers.

Double	double	64-bit floating point number.

Double Array	An array of doubles.

Font	LPFONTDISP	An OLE Automation Interface to a font.

Integer	short	16-bit signed integer.

Long	long	32-bit signed integer.

Object	LPDISPATCH	A generic OLE Automation Interface.

OLE_XPOS_PIXELS	long

OLE_YPOS_PIXELS	long

Picture	LPPICTUREDISP	An OLE Automation Interface to a picture or image.

Single	single	32-bit floating point number.

String	BSTR	A string.

Variant	LPVARIANT	A variant.

Void	void	Nothing.

Window	OLE_HANDLE	A handle to a window.


Examples
Search Examples

You can find examples related to the following subjects:

PID

PID


PID Examples

AutotunePID	Demonstrates the PID controls Autotune Wizard feature.

CascadeAndSelector	Demonstrates a cascade and selector control.

GeneralPID	Shows a simple example of how to use the PID control in a simple Plant Simulator scenario.

LeadLag	Demonstrates the use of the LeadLag control.

PIDwMIO	Demonstrates the use of the PID control with a DAQ MIO board.

RampDemo	Demonstrates the use of the Ramp control.

TankLevel	Simulates a simple process for tank level.


AutotunePID
Example: AutotunePID

Summary

Demonstrates the PID control's Autotune Wizard feature.

Group

Description

This example is an extension of the GeneralPID example. See the GeneralPID description for more information.

Press the Autotune button to display the Autotune Wizard. The Autotune Wizard leads you through the autotuning process. When the autotuning process is complete, the parameter controls are updated with the new PID settings.

Controls Used

CWLeadLag

CWPID

Containers Supported

Visual Basic 5.0

Visual C 5.0

Borland Delphi

Visual Basic 5.0

Open this example

Path

\samples\visual basic\autotuning pid\autotunepid

Visual C 5.0

Open this example

Path

\samples\visual c++\autotuning pid\autotunepid

Borland Delphi

Open this example

Path

\samples\delphi\autotuning pid\autotunepid


CascadeAndSelector
Example: CascadeAndSelector

Summary

Demonstrates a cascade and selector control.

Group

Description

This example demonstrates a cascade and selector control, which simulates a compressor driven by a motor with a tachometer requiring a PID loop to control the speed (the downstream loop). The flow and pressure from the compressor pass to individual PID controllers.

You want to control the flow, but if the pressure exceeds a specified setpoint, the pressure becomes the controlled variable. This calls for a low select function to combine the two upstream controller outputs. The lower of the two outputs becomes the setpoint for the compressor speed.

All variables in this simulation are percentages. In a real application, you might want to normalize all the input and setpoint values to percentages before passing them to the PID controllers.

The downstream loop (also known as the inner loop), which is the compressor speed control, must be faster than the outer loops. You should use a factor of 10 to prevent oscillation. In this simulation, the compressor lag is smaller (faster) than that of the outer loops.

Controls Used

CWLeadLag

CWPID

Containers Supported

Visual Basic 5.0

Visual C 5.0

Borland Delphi

Visual Basic 5.0

Open this example

Path

\samples\visual basic\autotuning pid\CascadeAndSelector\

Visual C 5.0

Open this example

Path

\samples\visual c++\autotuning pid\CascadeAndSelector\

Borland Delphi

Open this example

Path

\samples\delphi\autotuning pid\CascadeAndSelector\


GeneralPID
Example: GeneralPID

Summary

Shows a simple example of how to use the PID control in a simple Plant Simulator scenario.

Group

Description

The General PID example demonstrates how to use the PID control in a simple Plant Simulator scenario. Like the Tank Level example, this pressure controller simulation uses the Plant Simulator subroutines.

Controls Used

CWLeadLag

CWPID

Containers Supported

Visual Basic 5.0

Visual C 5.0

Borland Delphi

Visual Basic 5.0

Open this example

Path

\samples\visual basic\autotuning pid\generalpid

Visual C 5.0

Open this example

Path

\samples\visual c++\autotuning pid\generalpid

Borland Delphi

Open this example

Path

\samples\delphi\autotuning pid\generalpid


LeadLag
Example: LeadLag

Summary

Demonstrates the use of the LeadLag control.

Group

Description

The LeadLag example uses the LeadLag method. Excitation for the LeadLag example is either a sine wave or a square wave. The waveform is synchronized to the cycle time you choose. By varying the tuning parameters, you can see the time-domain response of the LeadLag example. A large lead setting causes a wild ringing on the output, while a large lag setting heavily filters the signal, almost making it disappear.

Controls Used

CWLeadLag

Containers Supported

Visual Basic 5.0

Visual C 5.0

Borland Delphi

Visual Basic 5.0

Open this example

Path

\samples\visual basic\autotuning pid\leadlag

Visual C 5.0

Open this example

Path

\samples\visual c++\autotuning pid\leadlag

Borland Delphi

Open this example

Path

\samples\delphi\autotuning pid\leadlag


PIDwMIO
Example: PIDwMIO

Summary

Demonstrates the use of the PID control with a DAQ MIO board.

You must have the appropriate hardware to run this example. Connect the analog output to the analog input through the resistor-capacitor network shown on the front panel.

Group

Description

The PID with MIO Board Example turns your computer into a single-loop PID controller through the use of a National Instruments data acquisition board.

This example adjusts the analog output so that the input (process variable or PV) equals the setpoint (SP). The example displays SP and PV on a strip chart. You can experiment with different controller tuning methods and try for the fastest settling time with the least overshoot. The default tuning parameters are optimum for the network used.

The input span is -10 to 10V, and the output span is 0 to 10V. PV and SP are expressed in volts. Set your I/O board for differential input to ±10V range, and the output to bipolar 10V range (these are all factory defaults). If you use other settings, change the example constants for the data acquisition board configuration.

The recommended network has a DC gain of 0.33, an effective deadtime of about 5 s, and an effective time constant of about 30s.

To customize this demonstration example, add alarm limits that set the digital output lines on the I/O board, remote setpoint (by using one of the analog inputs), and remote automatic to manual switching (by using one of the digital inputs).

Controls Used

CWPID

Containers Supported

Visual Basic 5.0

Visual C 5.0

Borland Delphi

Visual Basic 5.0

Open this example

Path

\samples\visual basic\autotuning pid\pidwmio

Visual C 5.0

Open this example

Path

\samples\visual c++\autotuning pid\pidwmio

Borland Delphi

Open this example

Path

\samples\delphi\autotuning pid\pidwmio


RampDemo
Example: RampDemo

Summary

Demonstrates the use of the Ramp control.

Group

Description

The RampDemo example uses the Ramp control to drive an initial value to a setpoint using a specified rate and cycle time. While the initial value is driven to the setpoint, you can change the rate and cycle time to vary the response of the control.

Controls Used

CWRamp

Containers Supported

Visual Basic 5.0

Visual C 5.0

Borland Delphi

Visual Basic 5.0

Open this example

Path

\samples\visual basic\autotuning pid\rampdemo

Visual C 5.0

Open this example

Path

\samples\visual c++\autotuning pid\rampdemo

Borland Delphi

Open this example

Path

\samples\delphi\autotuning pid\rampdemo


TankLevel
Example: TankLevel

Summary

Simulates a simple process for tank level.

Group

Description

The Tank Level example is a process simulation for tank level. A level controller adjusts the flow into a tank. To represent a change in process loading, click the on/off value that serves as a drain. With this example, you also can switch between having the controller automatically determine the output or using the manual control to select the output.

The Plant Simulator subroutine, which simulates this process, reads and delays the previous valve position and scales it according to the process gain. The gain represents how fast the tank fills versus the position of the valve. The process load value depends on the state of HV-101, the drain valve. When you open the valve, the tank level drops.

Controls Used

CWLeadLag

CWPID

Containers Supported

Visual Basic 5.0

Visual C 5.0

Borland Delphi

Visual Basic 5.0

Open this example

Path

\samples\visual basic\autotuning pid\tanklevel

Visual C 5.0

Open this example

Path

\samples\visual c++\autotuning pid\tanklevel

Borland Delphi

Open this example

Path

\samples\delphi\autotuning pid\tanklevel


CWLeadLag Property Page

CWLeadLag

All Property Pages


CWPID Parameters Property Page

CWPID

All Property Pages


CWPID General Property Page

CWPID

All Property Pages


CWPID Advanced Property Page

CWPID

All Property Pages


CWPID Autotune Property Page

CWPID

All Property Pages


CWRamp Property Page

CWRamp

All Property Pages


Property Pages

CWLeadLag

CWLeadLag

CWPID

CWPID Parameters

CWPID General

CWPID Advanced

CWPID Autotune

CWRamp

CWRamp


CWPID Autotune Dialog Step 1
CWPID Autotune Wizard Step 1

CWPIDAutotune

Autotuning Algorithm


CWPID Autotune Dialog Step 2
CWPID Autotune Wizard Step 2

CWPIDAutotune

Autotuning Algorithm


CWPID Autotune Dialog Step 2.1
CWPID Autotune Wizard Step 2.1

CWPIDAutotune

Autotuning Algorithm


CWPID Autotune Dialog Step 2.2
CWPID Autotune Wizard Step 2.2

CWPIDAutotune

Autotuning Algorithm


CWPID Autotune Dialog Step2.3
CWPID Autotune Wizard Step 2.3

CWPIDAutotune

Autotuning Algorithm


CWPID Autotune Dialog Step 3
CWPID Autotune Wizard Step 3

CWPIDAutotune

Autotuning Algorithm


CWPID Autotune Dialog Step4
CWPID Autotune Wizard Step 4

CWPIDAutotune

Autotuning Algorithm


CWPID Autotune Dialog Step 4.1
CWPID Autotune Wizard Step 4.1

CWPIDAutotune

Autotuning Algorithm


CWPID Autotune Dialog Step 5
CWPID Autotune Wizard Step 5

CWPIDAutotune

Autotuning Algorithm


CWPID Autotune Dialog Graph
CWPID Autotune Wizard Graph

The graph on the Autotune Wizard shows the Setpoint, Process Variable, and Output of the Controller over time. This information is useful for determining when the process has stabalized.

CWPIDAutotune

Autotuning Algorithm


CWPID Autotune Dialog Help
CWPID Autotune Wizard Help

Displays this help information.

CWPIDAutotune

Autotuning Algorithm


CWPID Autotune Dialog Finish
CWPID Autotune Wizard Finish

Finishes the Autotune process. The calculated PID parameters are applied to the PID control.

CWPIDAutotune

Autotuning Algorithm


CWPID Autotune Dialog Cancel
CWPID Autotune Wizard Cancel

Cancels the Autotune process at any time. All changes are canceled.

CWPIDAutotune

Autotuning Algorithm


CWPID Autotune Dialog Number of Relay Cycles
CWPID Autotune Wizard Number of Relay Cycles

Specifies the number of cycles to average when calculating the new PID parameters.

CWPIDAutotune

Autotuning Algorithm


CWPID Autotune Dialog Number of Noise Cycles
CWPID Autotune Wizard Number of Noise Cycles

Specifies the number of cycles to average when calculating the amount of noise in the system.

CWPIDAutotune

Autotuning Algorithm


Error Checking

ComponentWorks controls can report error information to you and to the application in a number of different ways:

•	Return an error code from a function or method call

•	Generate an error or warning event

•	Throw an exception handled by your programming environment

The type of error reporting depends on the type of application and the preference of the programmer.

By default, the ComponentWorks controls generate exceptions when errors occur, rather than returning error codes from the methods.

Related Topics

Exceptions

Return Codes

Debugging


Exceptions

Exceptions are error messages returned directly to your programming environment. Usually, exceptions are processed by displaying a default error message. The error message allows you to end your application or to enter debug mode and perform certain debugging functions. Part of the exception returned is an error number and error description, displayed as part of the error message.

Depending on your programming environment, you might be able to insert code that can catch exceptions being sent to your application and handle them in another manner. In Visual Basic, you can do this by using the On Error statement.

•	On Error Resume Next disables automatically generated error messages. The program continues running at the next line. To handle an error in this mode, you should check and process the information in the Err object in your code.

•	On Error GoTo disables automatically generated error messages and causes program execution to continue at a specified location in the subroutine. You can define one error handler in your subroutine.

If you are not using Visual Basic, consult the documentation for your programming environment for information about handling exceptions.


Return Codes

If the ExceptionOnError property is set to False, the control methods return a status code to indicate whether an operation completed successfully. If the return value is something other than zero, it indicates a warning or error. A positive return value indicates a warning, signifying that a problem occurred in the operation, but that you should be able to continue with your application. A negative value indicates an error, a critical problem that has occurred in the operation, and that all other functions or methods dependent on the failed operation also will fail.

To retrieve the return code from a method call, assign the value of the function or method to a long integer variable and check the value of the variable after calling the function or method.

In Visual Basic, you can use the MsgBox popup window to display error information. Normally, you can write one error handler for your application instead of duplicating it for every call to a function or method.

To use the LogError subroutine, call LogError before every function or method call. The return code is passed to LogError and processed.


Debugging

If you experience some unexpected behavior in your program, use the following debugging tools to locate and correct the problem in your application.

Debug Print

Breakpoint

Watch Window

Single Step, Step Into, and Step Over

Debug Print

One of the most common debugging methods is to print out or display important variables throughout the program execution. You can monitor critical values and determine when your program varies from the expected progress. Some programming environments have dedicated debugging windows that are used to display such information without disturbing the rest of the user interface. For example, you can use the Debug.Print command in Visual Basic to print information directly to the debug window.

Breakpoint

Most development environments include breakpoint options so you can suspend program execution at a specific point in your code. Breakpoints are placed on a specific line of executable code in the program to pause program execution.

Stopping at a breakpoint confirms that your application ran to the line of code containing the breakpoint. If you unsure whether a specific section of code is being called, place a breakpoint in the routine to find out. Once you have stopped at a specific section of your code, you can use other tools, such as a watch window or debug window, to analyze or even edit variables.

In some environments, breakpoints might include conditions so program execution halts if certain other conditions are met. These conditions usually check program variables for specific values. Once you have completed the work at the breakpoint, you can continue running your program, either in the normal run mode or in some type of single-step mode.

Watch Window

Use a watch window to display the value of a variable during program execution. You can use it to edit the value of a variable while the program is paused. In some cases, you can display expressions, which are values calculated dynamically from one or more program variables.

Single Step, Step Into, and Step Over

Use single stepping to execute a program one line at a time. This way, you can check variables and the output from your program during execution. Single stepping is commonly used after a breakpoint to slowly step through a questionable section of code.

If you use step into, the program executes any code available for subroutines or function calls and steps through it one line at a time. Use this mode if you want to check the code for each function called. The step over mode assumes that you do not want to go into the code for functions being called and runs them as one step.

In some cases, you might want to test a limited number of iterations of a loop but then run the rest of the iterations without stopping again. For this type of debugging, several environments include an option step to cursor or run to cursor options. Under this option, you can place your cursor at a specific point in the code, such as the first line after a loop, and run the program to that point.


Distribution and Redistributable Files

Redistributable Files

The files in the \Setup\redist directory of the ComponentWorks Autotuning PID CD are necessary for distributing applications and programs that use ComponentWorks controls. You need to distribute only those files needed by the controls you are using in your application.

ComponentWorks Distribution

When installing an application using ComponentWorks controls on another computer, you also must install the necessary control files and supporting libraries on the target machine. In addition to installing all necessary OCX files on a target computer, you must register each of these files with the operating system. This allows your application to find the correct OCX file and create the controls.

If your application performs any I/O operations requiring separate driver software, such as image acquisition, you must install and configure the driver software and corresponding hardware on the target computer. For more information, consult the hardware documentation for the specific driver used.

When distributing applications with the ComponentWorks controls, do not violate the license agreement (section 5) provided with the software. If you have any questions about the licensing conditions, contact National Instruments.

Related Topics

Installing your ComponentWorks Applications

Run-Time Licenses


Installing your ComponentWorks Applications

Automatic Installers

Many programming environments include some form of a setup or distribution kit tool. This tool automatically creates an installer for your application so that you can easily install it on another computer. To function successfully, this tool must recognize which control files and supporting libraries are required by your application and include these in the installer it creates. The resulting installer also must register the controls on the target machine.

Some of these tools, such as the Visual Basic 5 Setup Wizard, use dependency files to determine which libraries are required by an OCX file. The ComponentWorks PID OCX file includes a corresponding dependency file located in the \Windows\System directory (\Windows\System32 for Windows NT) after you install the ComponentWorks Autotuning PID software.

Some setup tools might not automatically recognize which files are required by an application but provide an option to add additional files to the installer. In this case, verify that all necessary OCX files (corresponding to the controls used in your application) as well as all the DLL and TLB files from the \redist directory are included. You also should verify that the resulting installer does not copy older versions of a file over a newer version on the target machine.

If your programming environment does not provide a tool or wizard for building an installer, you may use third-party tools, such as InstallShield. Some programming environments provide simplified or trial versions of third-party installer creation tools on their installation CDs.

Manual Installation

If your programming environment does not include a setup or distribution kit tool, you must build your own installer and perform the installation task manually. To install your application on another computer, follow these steps:

1. 	Copy the application executable to the target machine.

1.	Copy the ComponentWorks PID OCX file to the System directory (\Windows\System for Windows 95 or \Windows\System32 for Windows NT) on the target machine.

1.	Copy all DLL and TLB files in the \redist directory to the System directory on the target machine.

1.	Copy any other DLLs and support files required by your application to the System directory on the target machine.

Some of these files might already be installed on the target machine. If the file on the target machine has an earlier version number than the file in the \redist directory, copy the newer file to the target machine.

After copying the files to the target machine, you must register all OCX files with the operating system. To register an OCX file, you need a utility such as REGSVR32.EXE. You must copy this utility to the target machine to register the OCX files, but you can delete it after completing the installation. Use this utility to register each OCX file with the operating system, as in the following example.

regsvr32 c:\windows\system\cwpid.ocx

Troubleshooting

Try the following suggestions if you encounter problems after installing your application on another computer.

The application is not able to find an OCX file or is not able to create a control.

•	The control file or one of its supporting libraries is not copied on the computer. Verify that the correct OCX files and all their supporting libraries are copied on the machine. If one control was built using another, you might need multiple OCX files for one control.

•	The control is not properly registered on the computer. Make sure you run the registration utility and that it registers the control.

Controls in the application run in evaluation (demo) mode.

•	The application does not contain the correct run-time license. When developing your application, verify that the controls are running in a fully licensed mode. Although most programming environments include a run-time license for the controls in the executable, some do not.

If you are developing an application in Visual C++ using SDI (single document interface) or MDI (multiple document interface), you must include the run-time license in the program code for each control you create. Consult the ComponentWorks documentation, National Instruments Knowledgebase (www.natinst.com/support) or technical support if you are not familiar with this operation.


Run-Time Licenses

For each copy of your ComponentWorks PID-based application that you distribute, you must have a valid run-time license. A limited number of run-time licenses are provided with the ComponentWorks development systems. You can purchase additional ComponentWorks run-time licenses from National Instruments. Consult the license agreement (section 5) provided with the software for more detailed information. If you have any questions about the licensing conditions, contact National Instruments.


Error Codes

Error Code	Description
-30000	Unexpected error.
-30002	You have passed an invalid value for one of the parameters to the function, method, or property.
-30003	You have passed an invalid type into a parameter of a Variant type.
-30004	Divide by zero error.
-30005	Result of a calculation is an imaginary number.
-30006	Overflow error.
-30007	Out of memory.
-30008	You have called a function or method requiring a ComponentWorks product for which you do not have a license. For example, you might be using a method that is not supported in the base or standard Analysis package. To upgrade your product, contact National Instruments.


Glossary

Symbols
°	Degrees.
	Infinity.
Ω	Ohms.
%	Percent.
A
A	Amperes.
ActiveX	Set of Microsoft technologies for reusable software components. Formerly called OLE.
ActiveX control	Standard software tool that adds additional functionality to any compatible ActiveX container. The PID, DAQ, and UI tools in ComponentWorks are all ActiveX controls. An ActiveX control has properties, methods, objects, and events.
algorithm	A prescribed set of well-defined rules or processes for the solution of a problem in a finite number of steps.
anti-reset windup	A method that prevents the integral term of the PID algorithm from moving too far beyond saturation when an error persists.
B
bias	The offset added to a controller’s output.
bumpless transfer	A process in which the next output always increments from the current output, regardless of the current controller output value; therefore, transfer from automatic to manual control is always bumpless.
C
C	Celsius.
cascade control	Control in which the output of one controller is the setpoint for another controller.
closed loop	A signal path which includes a forward path, a feedback path, and a summing point and which forms a closed circuit. Also called a feedback loop.
collection	Control property and object that contains a number of objects of the same type, such as PID parameters. The type name of the collection is the plural of the type name of the object in the collection. For example, a collection of CWPIDParameter objects is called CWPIDParameters. To reference an object in the collection, you must specify the object as part of the collection, usually by index. For example, CWPID.Parameters.Item(2) is the second parameter in the CWPIDParameters collection of the control.
controller output	See manipulated variable.
D
damping	The progressive reduction or suppression of oscillation in a device or system.
DC	Direct current.
dead time (Td)	The interval of time, expressed in minutes, between initiation of an input change or stimulus and the start of the resulting observable response.
derivative (control) action	Control response to the time rate of change of a variable. Also called rate action.
deviation	Any departure from a desired value or expected value or pattern.
device	Plug-in data acquisition board that can contain multiple channels and conversion devices.
downstream loop	In a cascade, the controller whose setpoint is provided by another controller.
driver	Software that controls a specific hardware device, such as a data acquisition board.
E
EGU	Engineering units.
event	Object-generated response to some action or change in state, such as a mouse click or x number of points being acquired. The event calls an event handler (callback function), which processes the event. Events are defined as part of an OLE control object.
exception	Error message generated by a control and sent directly to the application or programming environment containing the control.
F
FC	Flow controller.
feedback control	Control in which a measured variable is compared to its desired value to produce an actuating error signal that is acted upon in such a way as to reduce the magnitude of the error.
feedback loop	See closed loop.
form	Window or area on the screen on which you place controls and indicators to create the user interface for your program.
G
gain	For a linear system or element, the ratio of the magnitude (amplitude) of a steady-state sinusoidal output relative to the causal input; the length of a phasor from the origin to a point of the transfer locus in a complex plane. Also called the magnitude ratio.
General Purpose Interface Bus (GPIB)	The common name for the communications interface system defined in ANSI/IEEE Standard 488.1-1987 and ANSI/IEEE Standard 488.2-1987.
H
Hz	Hertz.
I
Instrument Society of America (ISA)	The organization that sets standards for process control instrumentation in the United States.
integral action rate	See reset rate.
integral (control) action	Control action in which the output is proportional to the time integral of the input. That is, the rate of change of output is proportional to the input.
I/O	Input/output.
K
K	Process gain.
Kc	Controller gain.
kHz	Kilohertz.
L
lag	A lowpass filter or integrating response with respect to time.
loop cycle time	Time interval between calls to a control algorithm.
M
magnitude ratio	See gain.
manipulated variable	A quantity or condition that is varied as a function of the actuating error signal so as to change the value of the directly controlled variable. Also called controller output.
MB	Megabytes of memory.
method	Function that performs a specific action on or with an object. The operation of the method often depends on the values of the object properties.
ms	Milliseconds.
N
noise	In process instrumentation, an unwanted component of a signal or variable. Noise may be expressed in units of the output or in percent of output span.
O
object	Software tool for accomplishing tasks in different programming environments. An object can have properties, methods, and events. You change an object’s state by changing the values of its properties. An object’s behavior consists of the operations (methods) that can be performed on it and the accompanying state changes. See property, method, event.
Object Browser	Dialog window that displays the available properties and methods for the controls that are loaded. The object browser shows the hierarchy within a group of objects. To activate the object browser in Visual Basic, press <F2>.
OCX	OLE Control eXtension. Another name for ActiveX controls, reflected by the .OCX file extension of ActiveX control files.
OLE	Object Linking and Embedding. See ActiveX.
OLE control	See ActiveX control.
output limiting	Preventing a controller’s output from travelling beyond a desired maximum range.
overshoot	The maximum excursion beyond the final steady-state value of output as the result of an input change. Also called transient overshoot.
P
P	Proportional.
P controller	A controller which produces proportional control action only; that is, a controller that has only a simple gain response.
PC	Pressure controller.
PD	Proportional, derivative.
PD controller	A controller that produces proportional plus derivative (rate) control action.
PI	Proportional, integral.
PI controller	A controller that produces proportional plus integral (reset) control action.
PID	Proportional, integral, derivative.
PID controller	A controller that produces proportional plus integral (reset) plus derivative (rate) control action.
process gain (K)	For a linear process, the ratio of the magnitudes of the measured process response to that of the manipulated variable.
process variable (PV)	The measured variable (such as pressure or temperature) in a process to be controlled.
property	Attribute that controls the appearance or behavior of an object. The property can be a specific value or another object with its own properties and methods. For example, a value property is the setpoint (property) of a Ramp (object), while an object property is the Autotune (property) on the PID (object). Autotune itself is another object with properties, such as noise level and controller type.
proportional band (PB)	The change in input required to produce a full range change in output due to proportional control action. PB = 100/Kc
proportional kick	The response of a proportional controller to a step change in the setpoint or process variable.
Q
Quarter Decay Ratio	A response in which the amplitude of each oscillation is one-quarter that of the previous oscillation.
R
ramp	The total (transient plus steady-state) time response resulting from a sudden increase in the rate of change from zero to some finite value of the input stimulus. Also called ramp response.
rate action	Control response to the time rate of change of a variable. Also called derivative control action.
reference	Link to an external code source in Visual Basic. References are anything that add additional code to your program, such as OLE controls, DLLs, objects, and type libraries. You can add references by selecting the Tools»References… menu.
reset rate	Of proportional plus integral or proportional plus integral plus derivative control action devices: for a step input, the ratio of the initial rate of change of output due to integral control action to the change in steady-state output due to proportional control action. Of integral control action devices: for a step input, the ratio of the initial rate of change of output to the input change. Also called integral action rate.
reverse acting (increase-decrease) controller	A controller in which the value of the output signal decreases as the value of the input (measured variable) increases.
S
s	Seconds.
scope chart	Chart indicator modeled on the operation of an oscilloscope.
selector control	The use of multiple controllers and/or multiple process variables in which the connections may change dynamically depending on process conditions.
setpoint (SP)	An input variable that sets the desired value of the controlled process variable.
skeleton function	Applies a succession of thinning operations to an object until its width becomes one pixel.
span	The algebraic difference between the upper and lower range values.
strip chart	A plotting indicator modeled after a paper strip chart recorder, which scrolls as it plots data.
T
thickening	Alters the shape of objects by adding parts to the object that match the pattern specified in the structuring element.
time constant (T)	In process instrumentation, the value T (in minutes) in an exponential response term, A exp (–t/T), or in one of the transform factors, such as 1+sT.
transient overshoot	See overshoot.
V
V	Volts.
valve dead band	In process instrumentation, the range through which an input signal may be varied, upon reversal of direction, without initiating an observable change in output signal.
W
While Loop	Post-iterative-test loop structure that repeats a section of code until a condition is met. Comparable to a Do loop or a Repeat-Until loop in conventional programming languages.


ComponentWorks Autotuning PID Tutorial

This tutorial shows you how to configure the PID control and autotune the PID parameters. This tutorial is divided into two parts:

Developing a PID System

Autotuning PID Parameters

Although the code and examples in the tutorial use Visual Basic syntax, you can apply the concepts and implement the steps in any programming environment. Remember to adjust all code to your specific programming language.


Developing a PID System
Part 1: Developing a PID System

In the first part of this tutorial, you use a CWPID object to control a known process.

Designing the Form

1.	Open a new project and form. In Visual C++, select a dialog-based application and name your project SimplePIDExample.

2.	Load the ComponentWorks PID control into your programming environment.

3.	Place a CWPID control on the form. Keep its default name, CWPID1. You configure its properties in the next section, Setting the PID Properties.

4.	Place three Visual Basic TextBoxes on the form and name them ProcessVariable, Setpoint, and ControllerOutput. Add a corresponding label to each text box.

5.	Set ProcessVariable to 0 and Setpoint to 50.

6.	Place a Visual Basic Timer control on the form and set its Interval to 100 ms.

Setting the PID Properties

You normally configure the default property values of the different controls before you develop your program code. When using the PID control, you will set most properties, if not all, during design and will not change them during program execution. Use this program to start and stop the PID process only. If necessary, you can edit the properties of the PID control at run time.

1.	Open the custom property pages for the CWPID control on the form by right clicking on the control and selecting Properties.

2.	On the Parameters page, click the Add button in the Parameters group, and set the following parameters.

Proportional Gain (Kc)	10

Integral Time (Ki)	0.015

Derivative Time (Kd)	0.001

3.	On the General page, change the Setpoint value to 50.

Developing the Code

In the following steps, you add the code to apply the PID algorithm. Normally, the PID control calculates a new output (controller output) that you apply to your physical system. In this tutorial, you simulate a real process by calculating a new process variable using the controller output and a simple formula. In real systems the process variable is measured from the physical system after applying the controller output.

1.	Create an event handler for the Change event of the Setpoint textbox. Add the following code to the event handler to update the setpoint when it changes.

CWPID1.Setpoint = Val(Setpoint.Text)

2.	Create the event handler for the Timer event of the Timer control. In the Timer event, calculate the next controller output using the PID control and current process variable. Then calculate the corresponding process variable using a simulation formula. Add the following code to the event handler.

' Calculate controller output

ControllerOutput = CWPID1.NextOutput(ProcessVariable)

' Calculate new (simulated) process variable from controller output

ProcessVariable = ProcessVariable + (ControllerOutput * 0.02) + (Rnd – 0.5)

If you have a graph control to display the data, you can add a line of code to display the current values of the three variables. For example, if you have the ComponentWorks graph control, you can use the following code:

CWGraph1.ChartY Array(ProcessVariable, ControllerOutput, Setpoint), 1, False

Testing Your Program

Run your program. Once the program starts, the PID control drives the process variable to the setpoint. Your application should look similar to the following figure. Notice the process variable converging on the setpoint and oscillating around the setpoint when it reaches the setpoint value. Better PID parameters decrease the amplitude of the oscillation.

When you change the setpoint value, the PID controller drives the process variable to the new setpoint value.


Autotuning PID Parameters
Part 2: Autotuning PID Parameters

In the second part of this tutorial, you add autotuning to improve the PID parameters for your system or process.

Designing the Form

Add a button and change its caption to Autotune.

Setting PID Properties

1.	On the Autotune property page for the PID control, change Noise level to 0.25 and Relay amplitude to 2.

2.	Check the Apply autotune results to the active parameters box.

Developing the Code

Define an event handler routine for the Click event of the Autotune button. In the event handler, call the ShowDialog method of the CWPIDAutotune property object with the parameter cwpid20ms.

CWPID1.Autotune.ShowDialog cwpid20ms

Testing Your Program

Run your program. Allow the process to settle and then press the Autotune button. The Autotune Wizard is displayed, and you can follow the directions in the wizard to optimize the PID parameters.