Prévia do material em texto
Telemark University College
Department of Electrical Engineering, Information Technology and Cybernetics
Faculty of Technology, Postboks 203, Kjølnes ring 56, N-3901 Porsgrunn, Norway. Tel: +47 35 57 50 00 Fax: +47 35 57 54 01
LabVIEW Programming
Hans-Petter Halvorsen
10-May, 2010
Telemark University College
Department of Electrical Engineering, Information Technology and Cybernetics
Faculty of Technology, Postboks 203, Kjølnes ring 56, N-3901 Porsgrunn, Norway. Tel: +47 35 57 50 00 Fax: +47 35 57 54 01
INTRODUCTION TO LABVIEW
HANS-PETTER HALVORSEN, 2010.01.29
PREFACE
This document explains the basic concepts of LabVIEW.
You need to install the LabVIEW Professional Development System.
For more information about LabVIEW, visit my Blog: http://home.hit.no/~hansha/
http://home.hit.no/~hansha/
iii
INSTALLATION REQUIREMENTS
NI LabVIEW
Name Required
LabVIEW Professional Development System Yes
NI LabVIEW Core Components
Name Required
LabVIEW Control Design and Simulation Module
LabVIEW MathScript RT Module
NI Vision Development Module
Vision Builder for Automated Inspection
LabVIEW Digital Filter Design Toolkit
LabVIEW Modulation Toolkit
LabVIEW System Identification Toolkit
LabVIEW Desktop Execution Trace Toolkit
LabVIEW Report Generation for Microsoft Office Toolkit
LabVIEW Database Connectivity Toolkit
LabVIEW Internet Toolkit
NI LabVIEW SignalExpress
LabVIEW Basics 1 and 2 Computer Based Training
Extended Development Suite Components
Name Required
LabWindows/CVI Full Development System
LabWindows/CVI Real-Time Module
LabWindows/CVI PID Control Toolkit
LabWindows/CVI Signal Processing Toolkit
LabWindows/CVI Spectral Measurements Toolkit and Run-time Engine
LabWindows/CVI SQL Toolkit
Measurement Studio Enterprise Edition
DIAdem Professional
Control and Embedded Systems Option Components
Name Required
LabVIEW FPGA Module
LabVIEW Real-Time Module
LabVIEW Statechart Module
LabVIEW Mobile Module
LabVIEW Datalogging and Supervisory Control Module
LabVIEW PID and Fuzzy Logic Toolkit
NI Real-Time Execution Trace Toolkit
LabVIEW Simulation Interface Toolkit
NI Motion Assistant
NI-DAQ Base
Signal processing and Communications Option Components
Name Required
LabVIEW FPGA Module
LabVIEW Sound and Vibration Measurement Suite
LabVIEW Spectral Measurement Toolkit
LabVIEW Advanced Signal Processing Toolkit
LabVIEW Adaptive Filter Toolkit
NI Device Drivers
Name Required
FieldPoint
NI-DAQmx
NI LabVIEW SignalExpress
NI Instrument I/O Assistant
NI-IMAQ
NI Measurement & Automation Explorer
NI PXI
NI-VISA
vi
TABLE OF CONTENTS
Preface .................................................................................................................................................................... 2
Installation Requirements ....................................................................................................................................... iii
Table of Contents .................................................................................................................................................... vi
1 Introduction ................................................................................................................................................... 1
1.1 Dataflow programming.......................................................................................................................... 1
1.2 Graphical programming ......................................................................................................................... 1
1.3 Benefits .................................................................................................................................................. 2
2 Start using LabVIEW ...................................................................................................................................... 4
2.1 The LabVIEW Environment .................................................................................................................... 4
2.2 Front Panel ............................................................................................................................................ 5
2.3 Block Diagram ........................................................................................................................................ 7
2.4 Controls Palette ..................................................................................................................................... 9
2.4.1 Numeric Sub Palette ................................................................................................................... 10
2.4.2 Boolean Sub Palette .................................................................................................................... 11
2.4.3 String & Path Sub Palette ............................................................................................................ 11
2.5 Function Palette .................................................................................................................................. 12
2.6 Tools Palette ........................................................................................................................................ 13
2.7 Wiring .................................................................................................................................................. 15
2.8 Toolbar ................................................................................................................................................. 15
2.9 Execution ............................................................................................................................................. 16
2.10 The Objects short-cut menu ................................................................................................................ 17
2.11 Dataflow Programming........................................................................................................................ 17
2.12 Help...................................................................................................................................................... 18
Exercises ........................................................................................................................................................... 19
3 Sub VIs ......................................................................................................................................................... 23
3.1 Create New Sub VI from Scratch ......................................................................................................... 24
vii Table of Contents
Tutorial: An Introduction to LabVIEW
3.1.1 Input and Output SubVI Connectors ........................................................................................... 25
3.1.2 Icon Editor ................................................................................................................................... 27
3.2 Create Sub VI from existing code......................................................................................................... 28
3.3 Using Sub Vis ....................................................................................................................................... 29
Exercises ........................................................................................................................................................... 29
4 Customize LabVIEW ..................................................................................................................................... 32
Exercises ...........................................................................................................................................................33
5 Loops and Structures ................................................................................................................................... 34
5.1 Loops ................................................................................................................................................... 34
5.1.1 For Loop ...................................................................................................................................... 35
5.1.2 While Loop .................................................................................................................................. 36
5.2 Structures ............................................................................................................................................ 37
5.2.1 Case Structure ............................................................................................................................. 37
5.2.2 Sequence Structure ..................................................................................................................... 38
5.2.3 Event Structure ........................................................................................................................... 39
Exercises ........................................................................................................................................................... 41
6 Troubleshooting and Debugging ................................................................................................................. 44
6.1 How to find errors ............................................................................................................................... 44
6.2 Highlight Execution .............................................................................................................................. 44
6.3 Probes .................................................................................................................................................. 44
6.4 Breakpoints .......................................................................................................................................... 45
6.5 Step into/over/out debugging ............................................................................................................. 46
Exercises ........................................................................................................................................................... 46
7 Working with Data ....................................................................................................................................... 48
7.1 Arrays ................................................................................................................................................... 48
7.1.1 Auto-Indexing ............................................................................................................................. 48
7.1.2 Array Functions ........................................................................................................................... 48
7.2 Cluster .................................................................................................................................................. 51
viii Table of Contents
Tutorial: An Introduction to LabVIEW
7.2.1 Cluster Order............................................................................................................................... 51
7.2.2 Cluster Elements ......................................................................................................................... 52
Exercises ........................................................................................................................................................... 53
8 Working with Strings ................................................................................................................................... 55
Exercises ........................................................................................................................................................... 57
9 Error Handling.............................................................................................................................................. 59
9.1 finding Error ......................................................................................................................................... 59
9.2 Error Wiring ......................................................................................................................................... 59
9.3 Error handling in SubVIs ...................................................................................................................... 60
9.4 Error Handling ...................................................................................................................................... 61
Exercises ........................................................................................................................................................... 61
10 Working with Projects ................................................................................................................................. 62
10.1 Project Explorer ................................................................................................................................... 62
10.2 Deployment ......................................................................................................................................... 63
Exercises ........................................................................................................................................................... 65
11 Design Techniques ....................................................................................................................................... 66
11.1 Force Program Flow ............................................................................................................................. 66
11.2 Shift Register ........................................................................................................................................ 67
11.3 State Programming Architecture ......................................................................................................... 67
11.4 Multiple Loops/Parallell programming ................................................................................................ 70
11.5 Templates ............................................................................................................................................ 71
Exercises ........................................................................................................................................................... 73
12 User Interface .............................................................................................................................................. 75
12.1 VI Properties ........................................................................................................................................ 76
Exercises ........................................................................................................................................................... 79
13 Plotting Data ................................................................................................................................................ 80
13.1 Customizing ......................................................................................................................................... 81
Exercises ........................................................................................................................................................... 83
ix Table of Contents
Tutorial: An Introduction to LabVIEW
14 Tips & Tricks .................................................................................................................................................85
14.1 10 functions you need to know about ................................................................................................. 85
14.2 The 10 most useful Short-cuts ............................................................................................................. 89
15 Additional Exercises ..................................................................................................................................... 91
16 Whats Next? ................................................................................................................................................ 96
16.1 My Blog ................................................................................................................................................ 96
16.2 Training ................................................................................................................................................ 96
16.3 Additional Resources ........................................................................................................................... 96
16.4 Examples .............................................................................................................................................. 96
16.5 Documentation .................................................................................................................................... 97
16.6 LabVIEW Wiki....................................................................................................................................... 97
16.7 LabVIEW on YouTube .......................................................................................................................... 98
Quick Reference .................................................................................................................................................... 99
1
1 INTRODUCTION
LabVIEW (short for Laboratory Virtual Instrumentation Engineering Workbench) is a platform and development
environment for a visual programming language from National Instruments. The graphical language is named
"G". Originally released for the Apple Macintosh in 1986, LabVIEW is commonly used for data acquisition,
instrument control, and industrial automation on a variety of platforms including Microsoft Windows, various
flavors of UNIX, Linux, and Mac OS X. The latest version of LabVIEW is version LabVIEW 2009, released in
August 2009. Visit National Instruments at www.ni.com.
The code files have the extension “.vi”, which is an abbreviation for “Virtual Instrument”. LabVIEW offers lots of
additional Add-Ons and Toolkits.
This paper is part of a series with LabVIEW papers:
Introduction to LabVIEW
Data Acquisition in LabVIEW
Control and Simulation in LabVIEW
LabVIEW MathScript
Linear Algebra in LabVIEW
Datalogging and Supervisory Control in LabVIEW
Wireless Data Acquisition in LabVIEW
Intermediate Topics in LabVIEW
Advanced Topics in LabVIEW
Each paper may be used independently of each other.
1.1 DATAFLOW PROGRAMMING
The programming language used in LabVIEW, also referred to as G, is a dataflow programming language.
Execution is determined by the structure of a graphical block diagram (the LV-source code) on which the
programmer connects different function-nodes by drawing wires. These wires propagate variables and any
node can execute as soon as all its input data become available. Since this might be the case for multiple nodes
simultaneously, G is inherently capable of parallel execution. Multi-processing and multi-threading hardware is
automatically exploited by the built-in scheduler, which multiplexes multiple OS threads over the nodes ready
for execution.
1.2 GRAPHICAL PROGRAMMING
LabVIEW ties the creation of user interfaces (called front panels) into the development cycle. LabVIEW
programs/subroutines are called virtual instruments (VIs). Each VI has three components: a block diagram, a
front panel, and a connector panel. The last is used to represent the VI in the block diagrams of other, calling
VIs. Controls and indicators on the front panel allow an operator to input data into or extract data from a
running virtual instrument. However, the front panel can also serve as a programmatic interface. Thus a virtual
instrument can either be run as a program, with the front panel serving as a user interface, or, when dropped
as a node onto the block diagram, the front panel defines the inputs and outputs for the given node through
the connector pane. This implies each VI can be easily tested before being embedded as a subroutine into a
larger program.
http://www.ni.com/
2 Introduction
Tutorial: An Introduction to LabVIEW
The graphical approach also allows non-programmers to build programs simply by dragging and dropping
virtual representations of lab equipment with which they are already familiar. The LabVIEW programming
environment, with the included examples and the documentation, makes it simple to create small applications.
This is a benefit on one side, but there is also a certain danger of underestimating the expertise needed for
good quality "G" programming. For complex algorithms or large-scale code, it is important that the
programmer possess an extensive knowledge of the special LabVIEW syntax and the topology of its memory
management. The most advanced LabVIEW development systems offer the possibility of building stand-alone
applications. Furthermore, it is possible to create distributed applications, which communicate by a
client/server scheme, and are therefore easier to implement due to the inherently parallel nature of G-code.
1.3 BENEFITS
One benefit of LabVIEW over other development environments is the extensive support for accessing
instrumentation hardware. Drivers and abstraction layers for many different types of instruments and buses
are included or are available for inclusion. These present themselves as graphical nodes. The abstraction layers
offer standard software interfaces to communicate with hardware devices. The provided driver interfaces save
program development time. The sales pitch of National Instruments is, therefore, that even people with limited
coding experience can write programs and deploy test solutions in a reduced time frame when compared to
more conventional or competing systems. A new hardware driver topology (DAQmxBase), which consists
mainly of G-coded components with only a few register calls through NI Measurement Hardware DDK (Driver
Development Kit) functions, provides platform independent hardware access to numerous data acquisition and
instrumentation devices. The DAQmxBase driver is available for LabVIEW on Windows, Mac OS X and Linux
platforms.
This document introducing the following themes:
Start using LabVIEW
o The LabVIEW Environment
o Front Panel and Block Diagram
o Palettes: Control Palette, Functions Palette, Tools Palette
o Data Types
o Property Nodes
Sub VIs
Loops and Structures
Troubleshooting and Debugging
Working with Data
o Arrays
Array Functions
o Cluster
Working with Strings
Error Handling
Working with Projects using Project Explorer
Design Techniques
o Shift Register
o State Machine
o Multiple Loops
3 Introduction
Tutorial: An Introduction to LabVIEW
User Interface
Plotting Data
Deployment: Building Executable Applications (.exe)
Introduction to Add Ons and Toolkits
o Briefly explanations…
o More detail about Control and Simulation Toolkit in later chapter
Introduction to DAQ - Data Acquisition
o MAX – Measurement and Automation Explorer
o NI-DAQmx
Quick Reference with Keyboard Short-cuts
For more information about LabVIEW, visit my Blog: http://home.hit.no/~hansha/
http://home.hit.no/~hansha/
4
2 START USING LABVIEW
This chapter explains the basic concepts in LabVIEW.
Thetopics are as follows:
The LabVIEW Environment
Front Panel and Block Diagram
Palettes: Control Palette, Functions Palette, Tools Palette
Data Types
Property Nodes
2.1 THE LABVIEW ENVIRONMENT
LabVIEW programs are called Virtual Instruments, or VIs, because their appearance and operation imitate
physical instruments, such as oscilloscopes and multimeters. LabVIEW contains a comprehensive set of tools
for acquiring analyzing, displaying, and storing data, as well as tools to help you troubleshoot your code.
When opening LabVIEW, you first come to the “Getting Started” window.
5 Start using LabVIEW
Tutorial: An Introduction to LabVIEW
In order to create a new VI, select “Blank VI” or in order to create a new LabVIEW project, select “Empty
project”.
When you open a blank VI, an untitled front panel window appears. This window displays the front panel and is
one of the two LabVIEW windows you use to build a VI. The other window contains the block diagram. The
sections below describe the front panel and the block diagram.
2.2 FRONT PANEL
When you have created a new VI or selected an existing VI, the Front Panel and the Block Diagram for that
specific VI will appear.
In LabVIEW, you build a user interface, or front panel, with controls and indicators. Controls are knobs, push
buttons, dials, and other input devices. Indicators are graphs, LEDs, and other displays.
You build the front panel with controls and indicators, which are the interactive input and output terminals of
the VI, respectively. Controls are knobs, push buttons, dials, and other input devices. Indicators are graphs,
LEDs, and other displays. Controls simulate instrument input devices and supply data to the block diagram of
the VI. Indicators simulate instrument output devices and display data the block diagram acquires or generates.
E.g., a “Numeric” can either be a “Numeric Control” or a “Numeric Indicator”, as seen below.
6 Start using LabVIEW
Tutorial: An Introduction to LabVIEW
I you select a “Numeric Control”, it can easy be changed to an “Numeric Indicator” by right click on the object
an select “Change to Indicator”
Or opposite, I you select a “Numeric Indicator”, it can easy be changed to an “Numeric Control” by right click on
the object an select “Change to Control”
7 Start using LabVIEW
Tutorial: An Introduction to LabVIEW
The difference between a “Numeric Control” and a “Numeric Indicator” is that for a “Numeric Control” you
may enter a value, while the “Numeric Indicator” is read-only, i.e., you may only read the value, not change it.
The appearance is also slightly different, the “Numeric Control” has an increment and an decrement button in
front, while the “Numeric Indicator” has a darker background color in order to indicate that its read-only.
2.3 BLOCK DIAGRAM
After you build the user interface, you add code using VIs and structures to control the front panel objects. The
block diagram contains this code. In some ways, the block diagram resembles a flowchart.
After you build the front panel, you add code using graphical representations of functions to control the front
panel objects. The block diagram contains this graphical source code. Front panel objects appear as terminals,
8 Start using LabVIEW
Tutorial: An Introduction to LabVIEW
on the block diagram. Block diagram objects include terminals, subVIs, functions, constants, structures, and
wires, which transfer data among other block diagram objects.
The Figure below shows a front panel and its corresponding block diagram with front panel and block diagram
components.
The different components are as follows:
1. Toolbar
2. Owned Label
3. Numeric Control
4. Free Label
5. Numeric Control Terminal
6. Knob Terminal
7. Numeric Constant
8. Multiply Function
9 Start using LabVIEW
Tutorial: An Introduction to LabVIEW
9. Icon
10. Knob Control
11. Plot Legend
12. XY Graph
13. Wire Data Path
14. XY Graph Terminal
15. Bundle Function
16. SubVI
17. For Loop Structure
2.4 CONTROLS PALETTE
The Controls and Functions palettes contain sub palettes of objects you can use to create a VI. When you click a
sub palette icon, the entire palette changes to the sub palette you selected. To use an object on the palettes,
click the object and place it on the front panel or block diagram. The Controls palette is available only on the
front panel. The Controls palette contains the controls and indicators you use to build the front panel.
The most used Sub Palettes are the Numeric Sub Palette, the Boolean Sub Palette and the String & Path Sub
Palette.
You may change the appearance and the contents of the Controls palette:
10 Start using LabVIEW
Tutorial: An Introduction to LabVIEW
You may Pin the palette, so it is always visible, just click the little pin button in the upper left corner of the
palette:
If you want to change the content and appearance of the palette, click the “View” button.
Here you may change the way the palette should look.
If you click “Change Visible Categories…” you may change which Categories you want to have visible.
2.4.1 NUMERIC SUB PALETTE
“Numerical Control” and “Numerical Indicator” are the most used objects in the numeric sub palette.
11 Start using LabVIEW
Tutorial: An Introduction to LabVIEW
2.4.2 BOOLEAN SUB PALETTE
This palette has lots of different buttons you may use. OK, Cancel and Stop buttons are useful.
2.4.3 STRING & PATH SUB PALETTE
12 Start using LabVIEW
Tutorial: An Introduction to LabVIEW
In the String and Path palette we have String Controls, Combo Box, etc.
2.5 FUNCTION PALETTE
The Functions palette is available only on the block diagram. The Functions palette contains the VIs and
functions you use to build the block diagram.
13 Start using LabVIEW
Tutorial: An Introduction to LabVIEW
2.6 TOOLS PALETTE
You can create, modify, and debug VIs using the tools located on the floating Tools palette. The Tools palette is
available on both the front panel and the block diagram. A tool is a special operating mode of the mouse
cursor. The cursor corresponds to the icon of the tool selected in the Tools palette. Use the tools to operate
and modify front panel and block diagram objects.
14 Start using LabVIEW
Tutorial: An Introduction to LabVIEW
The Tools palette is available from the View menu:
If you make sure “Automatic wiring” is disabled (I recommend you do so!) you may use the Tab key on your
keyboard in order to switch between the most common tools.
The most used tools are:
Use the Operating tool, shown at left, to change the values of a control or select the text within a
control. The Operating tool changes to the icon shown at left when it moves over a text control, such as a
numeric or string control.
Use the Positioning tool, shown at left, to select, move, or resize objects. The Positioning tool changes to
resizing handles when it moves over the edge of a resizable object.
Use the Labeling tool, shown at left, to edit text and create free labels. The Labeling tool changes to
the following icon when you create free labels.
Use the Wiring tool, shown at left, to wire objects together on the block diagram.
15 Start using LabVIEW
Tutorial: An Introduction to LabVIEW
2.7 WIRING
In order to create the logical flow between the object on the Block Diagram, you need to use the Wiring tool in
order to connect the different objects together.
Use the Wiring tool to wire objects together on the block diagram.
Available Keyboard Shortcuts when dealing with Wiring:
Ctrl-B is very useful. This short-cut removes all broken wires on the Block Diagram.
2.8 TOOLBAR
Below we see the LabVIEW Toolbar:
The behaviors of the different buttons are as follows:Click the Run button to run a VI. LabVIEW compiles the VI, if necessary. You can run a VI if the Run button
appears as a solid white arrow. The solid white arrow, shown above, also indicates you can use the VI as a
subVI if you create a connector pane for the VI.
16 Start using LabVIEW
Tutorial: An Introduction to LabVIEW
While the VI runs, the Run button appears as shown at left if the VI is a top-level VI, meaning it has no
callers and therefore is not a subVI.
If the VI that is running is a subVI, the Run button appears as shown at left.
The Run button appears broken, shown at left, when the VI you are creating or editing contains errors. If
the Run button still appears broken after you nish wiring the block diagram, the VI is broken and cannot run.
Click this button to display the Error list window, which lists all errors and warnings.
Click the Run Continuously button, shown at left, to run the VI until you abort or pause execution. You
also can click the button again to disable continuous running.
While the VI runs, the Abort Execution button, shown at left, appears. Click this button to stop the VI
immediately if there is no other way to stop the VI. If more than one running top-level VI uses the VI, the
button is dimmed.
Note: Avoid using the Abort Execution button to stop a VI. Either let the VI complete its data ow or design a
method to stop the VI programmatically. By doing so, the VI is at a known state. For example, place a button on
the front panel that stops the VI when you click it.
Click the Pause button, shown at left, to pause a running VI. When you click the Pause button, LabVIEW
highlights on the block diagram the location where you paused execution, and the Pause button appears red.
Click the button again to continue running the VI.
2.9 EXECUTION
In addition to the Toolbar buttons above the following Keyboard Shortcuts are available when dealing with
Execution:
17 Start using LabVIEW
Tutorial: An Introduction to LabVIEW
2.10 THE OBJECTS SHORT-CUT MENU
The most often-used menu is the object shortcut menu. All LabVIEW objects and empty space on the front
panel and block diagram have associated shortcut menus. Use the shortcut menu items to change the look or
behavior of front panel and block diagram objects. To access the shortcut menu, right-click the object, front
panel, or block diagram.
The Numeric control has the following short-cut/right-click menu:
The short-cut menu will be different for the different controls or objects.
2.11 DATAFLOW PROGRAMMING
LabVIEW follows a dataflow model for running VIs. A block diagram node executes when all its inputs are
available. When a node completes execution, it supplies data to its output terminals and passes the output
data to the next node in the dataflow path.
Visual Basic, C++/C#, Java, and most other text-based programming languages follow a control flow model of
program execution. In control flow, the sequential order of program elements determines the execution order
of a program.
Example: Dataflow Programming
18 Start using LabVIEW
Tutorial: An Introduction to LabVIEW
The Example shows a block diagram that adds two numbers and then subtracts 50.00 from the result of the
addition. In this case, the block diagram executes from left to right, not because the objects are placed in that
order, but because the Subtract function cannot execute until the Add function finishes executing and passes
the data to the Subtract function. Remember that a node executes only when data are available at all of its
input terminals, and it supplies data to its output terminals only when it finishes execution.
Example: Dataflow Programming
In this example, consider which code segment would execute first-the Add, Random Number, or Divide
function. You cannot know because inputs to the Add and Divide functions are available at the same time, and
the Random Number function has no inputs. In a situation where one code segment must execute before
another and no data dependency exists between the functions, use other programming methods, such as error
clusters, to force the order of execution.
2.12 HELP
The Context Help window (Ctrl +H) displays basic information about LabVIEW objects when you move the
cursor over each object. The Context Help window is visible by default. To toggle display of the Context Help
window, select Help-Show Context Help, press the Ctrl-H keys, or click the Show Context Help Window button
on the toolbar.
When you move the cursor over front panel and block diagram objects, the Context Help window displays the
icon for subVIs, functions, constants, controls, and indicators, with wires attached to each terminal. When you
move the cursor over dialog box options, the Context Help window displays descriptions of those options. In
the window, required connections are bold, recommended connections are plain text, and optional
connections are dimmed or do not appear. The Figure below shows an example of the Context Help window.
19 Start using LabVIEW
Tutorial: An Introduction to LabVIEW
EXERCISES
Exercise: Create your first LabVIEW application (VI)
Create a simple LabVIEW application (VI) with a Front Panel with some Controls and Indicators. Create the logic
by connecting the Terminals on the Block Diagram
The Front Panel could look something like this:
The Block Diagram could look something like this:
20 Start using LabVIEW
Tutorial: An Introduction to LabVIEW
Start the program with the Run button.
Exercise: Create a simple Calculator
Create a simple calculator that Add and Subtract 2 numbers like this:
Start the program with the Run button.
Exercise: Write Data to File
Create a VI that writes data to a Text File.
Use Vis or functions from the File I/O palette
21 Start using LabVIEW
Tutorial: An Introduction to LabVIEW
The program could look something like this:
22 Start using LabVIEW
Tutorial: An Introduction to LabVIEW
Exercise: Read Data from File
Create another VI that read the text file you created in the previous VI.
23
3 SUB VIS
This chapter explains the basic concepts of creating and using Sub VIs in LabVIEW.
Topics:
Create New Sub VI from Scratch
Create Sub VI from existing code
Using Sub VIs
When you place a VI on the block diagram, LabVIEW considers the VI to be a subVI. When you double-click a
subVI, its front panel and block diagram appear, rather than a dialog box in which you can configure options.
The front panel includes controls and indicators. The block diagram includes wires, front panel icons, functions,
possibly subVIs, and other LabVIEW objects. The upper right corner of the front panel and block diagram
displays.
Below we see an example of a bad Block Diagram. This example does not make use of the SubVI functionality in
LabVIEW at all! This makes the Block diagram hard to read and understand. The size of the diagram is also too
large! The Block Diagram should always fit into the screen. Both the Front Panel and the Block Diagram should
fit into a screen resolution of 1024x768.
24 Sub VIs
Tutorial: An Introduction to LabVIEW
With use of SubVIs, the example above could turn into, e.g.:
As you can see, much of the code in the Main VI have been replaced and put into SubVIs. The program is now
more readable.
Another approach is to use a so-called State Machine principle (more about this in chapter 11 - Design
Techniques ).
Available Keyboard Shortcuts when dealing with Sub Vis:
3.1 CREATE NEW SUB VI FROM SCRATCH
25 Sub VIs
Tutorial: An Introduction to LabVIEW
Select “Blank VI” in the “Getting Started” window when opening LabVIEW, or when LabVIEW is already opened
select File → New V” or use the short-cut Ctrl+N.
3.1.1 INPUT AND OUTPUTSUBVI CONNECTORS
Most SubVIs will have input and output “connectors”. This is similar with functions or methods in other
programming language that have input arguments and an output/result.
In order to create connectors, Right-click on the icon in the upper right corner of the VI and select “Show
Connector”.
You may select different Patterns, i.e., how many input and output connectors you need.
26 Sub VIs
Tutorial: An Introduction to LabVIEW
Make sure you select a Pattern with enough connectors even if you don’t need all the connectors at the
moment. I recommend that you standardize on the pattern in the Figure above.
Select the Wire tool and click on the wanted connector, then click on the Control or Indicator on the
Front Panel you want to connect to this connector.
You should always follow these connector rules:
Upper left connector: “Reference” In
Upper right connector: “Reference” Out
Lower left connector: Error In Cluster
Lower right connector: Error Out Cluster
Example: SubVI Connectors
See example below about these connector rules:
27 Sub VIs
Tutorial: An Introduction to LabVIEW
Most common VIs that exits follow these rules, see example below.
If you follow these connector rules it’s much easier to create a clean and neat code like this:
By doing this it’s also clear how the Data flows in the program. It should always flow from left to right.
3.1.2 ICON EDITOR
You should also create a suitable icon for your SubVI.
In order to open the Icon Editor, double-click on the icon in the upper right corner of your VI.
28 Sub VIs
Tutorial: An Introduction to LabVIEW
Below we see a block diagram with SubVIs icon appearance created with the Icon Editor.
3.2 CREATE SUB VI FROM EXISTING CODE
If you find out that you code is getting messy, you could consider put some code into a SubVI.
The procedure is as follows:
1. Select the part of your code you want to turn into a SubVI
2. From the Edit menu, select “Create SubVI”
3. LabVIEW will automatically create a SubVI for the selected code.
4. Clean up automatically created wires, etc.
5. Create a suitable icon for your SubVI
29 Sub VIs
Tutorial: An Introduction to LabVIEW
Although this is quite easy to do this, I do not recommend that you use this functionality to much. This is
because you should create and use SubVIs from the first moment you start creating your application and not
afterwards when you find out that you have been creating a messy code.
So you should structure and design your code with the use of SubVIs from the beginning!
3.3 USING SUB VIS
Below we see an example of how to use SubVIs in a program (Top VI or SubVIs):
You may open a SubVI from the File menu, select a SubVI from the Functions palette or use drag and drop in
different ways, e.g., you may drag a VI from the File Explorer in Windows directly into an existing VI you have
already opened in LabVIEW
EXERCISES
Exercise: Convert C to F VI
Create a SubVI that convert a Temperature in Celsius to a Temperature in Fahrenheit
30 Sub VIs
Tutorial: An Introduction to LabVIEW
1. Create the SubVI
2. Create the Front Panel and the Block Diagram as shown above
3. Create necessary Connectors
4. Create a suitable icon, e.g.:
5. Use the SubVI in another VI
6. Run the program to see if it works
7. Expand the program so you can select if you want to convert from Celsius to Fahrenheit or from
Fahrenheit to Celsius
Exercise: Convert existing code into a SubVI
Convert a part of your application into a SubVI by using the Create SubVI function in LabVIEW.
31 Sub VIs
Tutorial: An Introduction to LabVIEW
32
4 CUSTOMIZE LABVIEW
LabVIEW has lots of possibilities for customizing the appearance and the use of the LabVIEW environment.
Select “Options…” from the Tools menu.
The default settings is not necessary the best, here are some recommendations for setting up the LabVIEW
environment.
Category: Block Diagram
33 Customize LabVIEW
Tutorial: An Introduction to LabVIEW
Disable “Enable auto wiring” option. This prevents LabVIEW from automatically connecting adjacent
blocks. Although it seems useful to have auto wiring enables, it is my experience that the auto wiring is
a little annoying since it tends to draw wires between blocks when you do not want any wire.
Disable “Place front panel elements as icons” option. This causes LabVIEW to use small terminal icons
on the block diagram. If you, instead, activate this option, the terminal icons are larger, with a mimic
of the element as it appears at the front panel.
Category: Controls/Functions Palettes
In the Format list: select “Category (Icons and Text)”
Category: Alignment Grid
Turn off “Show Front Panel Grid” and “Show Block Diagram Grid”
EXERCISES
Exercise: Customize LabVIEW
Try the different settings explained in this chapter. Turn them on and off and watch the different.
34
5 LOOPS AND STRUCTURES
This chapter explains the basic concepts of Loops and Structures in LabVIEW.
The topics are as follows:
For Loop
While Loop
Case Structure
Sequence Structure
Event Structure
The different Loops and Structures available is located in the “Structures” sub palette in the Functions palette
on the Block Diagram.
5.1 LOOPS
The most important loops are:
For Loop
While Loop
These loops will be explained in detail below.
35 Loops and Structures
Tutorial: An Introduction to LabVIEW
5.1.1 FOR LOOP
A For Loop executes a sub diagram a set number of times. The Figure below shows an empty For Loop in
LabVIEW.
A For loop executes its sub diagram n times, where n is the value wired to the count ( ) terminal. The
iteration ( ) terminal provides the current loop iteration count, which ranges from 0 to n-1.
After you create a For Loop, you can use shift registers to pass values from one iteration to the next. If you wire
an array to a For Loop, you can read and process every element in that array by enabling auto-indexing. You
also can enable auto-indexing by configuring a For Loop to return an array of every value generated by the
loop.
You can add a conditional terminal to configure a For Loop to stop when a Boolean condition or an error
occurs. A For Loop with a conditional terminal executes until the condition occurs or until all iterations
complete, whichever happens first. To add a conditional terminal to a For Loop, right-click the For Loop border
and select Conditional Terminal from the shortcut menu. You must wire the conditional terminal and either
wire the count terminal or auto-index an input array for the loop to execute and for the VI to run.
To convert a For Loop to a While Loop, right-click the For Loop and select Replace with While Loop from the
shortcut menu.
Example: For Loop
The following example uses a For Loop in order to create an array with 10 elements and fill it with random
numbers.
36 Loops and Structures
Tutorial: An Introduction to LabVIEW
5.1.2 WHILE LOOP
A While loop repeats the sub diagram inside it until the conditional terminal, an input terminal, receives a
particular Boolean value. The Boolean value depends on the continuation behavior of the While Loop.
Right-click the conditional terminal and select Stop if True or Continue if True from the shortcut menu. You
also can wire an error cluster to the conditional terminal, right-click the terminal, and select Stop on Error or
Continue while Error from the shortcut menu. The While Loop always executes at least once.
Below we see an empty While loop:
After you create a While Loop, you can use shift registers to pass values from one iteration to the next. If you
wire an array to a While Loop, you can read and process every element in that array by enabling auto-indexing.In order to convert a While Loop into a For Loop, right-click the While Loop and select “Replace with For Loop”
from the shortcut menu. To convert a While Loop into a Timed Loop, right-click the While Loop and select
“Replace with Timed Loop” from the shortcut menu.
Example: While Loop
This example run until either the user clicks the stop button or number of iterations is greater than 10.
37 Loops and Structures
Tutorial: An Introduction to LabVIEW
5.2 STRUCTURES
5.2.1 CASE STRUCTURE
The Case Structure has one or more sub diagrams, or cases, exactly one of which executes when the structure
executes. The value wired to the selector terminal determines which case to execute and can be Boolean,
string, integer, or enumerated type. You may right-click the structure border to add or delete cases. Use the
Labeling tool to enter value(s) in the case selector label and configure the value(s) handled by each case.
Below we see an empty Case structure:
Below we see an example of a Case structure with 2 cases, a “True” case and a “False” case. Depending of the
Boolean input value, the Numeric1 and Numeric2 is either Added or Subtracted.
38 Loops and Structures
Tutorial: An Introduction to LabVIEW
5.2.2 SEQUENCE STRUCTURE
A Sequence structure Consists of one or more sub diagrams, or frames, that execute sequentially. Right-click
the structure border to add and delete frames or to create sequence locals to pass data between frames. Use
the Stacked Sequence structure to ensure a sub diagram executes before or after another sub diagram.
Below we see an empty Sequence structure.
39 Loops and Structures
Tutorial: An Introduction to LabVIEW
Below we see an example where we use “Sequence Local”, i.e., we pass a value from one sequence to the next
Note! To take advantage of the inherent parallelism in LabVIEW, avoid overusing Sequence structures.
Sequence structures guarantee the order of execution, but prohibit parallel operations. Another negative to
using Sequence structures is that you cannot stop the execution part way through the sequence.
5.2.3 EVENT STRUCTURE
An Event structure has one or more sub diagrams, or event cases, exactly one of which executes when the
structure executes. The Event structure waits until an event happens, then executes the appropriate case to
handle that event. Right-click the structure border to add new event cases and configure which events to
handle. Wire a value to the Timeout terminal at the top left of the Event structure to specify the number of
milliseconds the Event structure should wait for an event to occur. The default is –1, indicating never to time
out.
Below we see an example:
40 Loops and Structures
Tutorial: An Introduction to LabVIEW
Right-click on the border in order to Add/Edit Event Cases, see the dialog box below.
41 Loops and Structures
Tutorial: An Introduction to LabVIEW
EXERCISES
Exercise: For Loop
Create a VI with a For Loop. Create the logic to find out if a number in an array is greater than 10. See Front
Panel below:
42 Loops and Structures
Tutorial: An Introduction to LabVIEW
Exercise: While Loop
Create a VI with a While Loop. Create the logic to find out which (the first) index in the array that have a
number greater than 30. See Front Panel below:
Exercise: Case Structure
Create a VI with a Case Structure.
Use a Case structure inside a For Loop to write the text “The Number is greater than 10” if value is greater than
10. See Front Panel below:
43 Loops and Structures
Tutorial: An Introduction to LabVIEW
Exercise: Sequence Structure
Create a VI with a Sequence Structure. See Front Panel below:
Exercise: Event Structure
Create a VI with an Event Structure. See Front Panel below:
44
6 TROUBLESHOOTING AND DEBUGGING
This chapter explains the basic concepts of troubleshooting and debugging in LabVIEW.
Topics:
How to find errors
Highlight Execution
Probes
Breakpoints
Step into/over/out debugging
6.1 HOW TO FIND ERRORS
If a VI does not run, it is a broken, or “nonexecutable”, VI. The Run button often appears broken, shown
at left, when you create or edit a VI. If it is still broken when you finish wiring the block diagram, the VI is
broken and will not run. Generally, this means that a required input is not wired, or a wire is broken.
Click the broken Run button to display the Error list window, which lists all the errors. Double-click an error
description to display the relevant block diagram or front panel and highlight the object that contains the error.
6.2 HIGHLIGHT EXECUTION
View an animation of the execution of the block diagram by clicking the Highlight Execution button.
Execution highlighting shows the flow of data on the block diagram from one node to another using bubbles
that move along the wires. Note! Execution highlighting greatly reduces the speed at which the VI runs.
6.3 PROBES
Use the Probe tool to check intermediate values on a wire as a VI runs.
45 Troubleshooting and Debugging
Tutorial: An Introduction to LabVIEW
When execution pauses at a node because of single-stepping or a breakpoint, you also can probe the wire that
just executed to see the value that flowed through that wire. You also can create a custom probe to specify
which indicator you use to view the probed data. For example, if you are viewing numeric data, you can choose
to see that data in a chart within the probe. To create a custom probe, right-click a wire and select Custom
Probe-New from the shortcut menu.
6.4 BREAKPOINTS
Use the Breakpoint tool to place a breakpoint on a VI, node, or wire on the block diagram and pause
execution at that location. When you set a breakpoint on a wire, execution pauses after data pass through the
wire. Place a breakpoint on the block diagram workspace to pause execution after all nodes on the block
diagram execute. When a VI pauses at a breakpoint, LabVIEW brings the block diagram to the front and uses a
marquee to highlight the node or wire that contains the breakpoint. LabVIEW highlights breakpoints with red
borders for nodes and block diagrams and red bullets for wires. When you move the cursor over an existing
breakpoint, the black area of the Breakpoint tool cursor appears white. Use the Breakpoint tool to click an
existing breakpoint to remove it.
You may also right-click on the wire in order to set a breakpoint or open the Breakpoint Manager.
46 Troubleshooting and Debugging
Tutorial: An Introduction to LabVIEW
Breakpoint Manager is a tool for enable, disable and delete breakpoints.
6.5 STEP INTO/OVER/OUT DEBUGGING
Available Keyboard Shortcuts when Debugging:
EXERCISES
47 Troubleshooting and Debugging
Tutorial: An Introduction to LabVIEW
Exercise: Highlight Execution
Enable “Highlight Execution” in one of your programs, and see how it works.
Exercise: Probes
Set Several Probes around in your application and watch how it works. Use the Probe watch Window and check
out the functionality this tool offers.
Also check out the “Custom Probe” and the “Find Probe” functionality.
Exercise: Breakpoints
Set some Breakpoint around in your code and check out how it works. Use the Breakpoint Manager tool.
Example:
Exercise: Step into/over/out debugging
Use the Step into/over/out functionality together with your Breakpoints and learn how you can use them and
see what the difference between them is.
48
7 WORKING WITH DATA
This chapter explains the basic concepts of creating and using Sub Vis in LabVIEW.
Topics:
Arrays
Array Functions
Cluster
7.1 ARRAYS
Arrays are very powerful to use in LabVIEW. In all your applications you would probably use both
One-Dimensional Arrays and Two-Dimensional Arrays.
7.1.1 AUTO-INDEXINGLabVIEW uses a powerful mechanism called “Auto-indexing”.
For Example you may use a For loop to create Array data like this:
Or you may use an Array like this in order to automatically specify number of iterations:
7.1.2 ARRAY FUNCTIONS
LabVIEW has lots of built-in functions for manipulating arrays.
49 Working with Data
Tutorial: An Introduction to LabVIEW
The most useful Array functions are:
Array Size
Index Array
Delete from Array
Search 1D Array
Initialize Array
Build Array
Array Subset
Array Constant
All these functions are basic (but very useful) array functions you will probably be using in all your applications
and VIs.
50 Working with Data
Tutorial: An Introduction to LabVIEW
Example: Array functions
In this example we see how we can use these Array functions and what they do.
The resulting Front Panel is as follows:
51 Working with Data
Tutorial: An Introduction to LabVIEW
7.2 CLUSTER
Clusters group data elements of mixed types, such as a bundle of wires, as in a telephone cable, where each
wire in the cable represents a different element of the cluster. A cluster is similar to a record or a struct in
text-based programming languages. Bundling several data elements into clusters eliminates wire clutter on the
block diagram and reduces the number of connector pane terminals that subVIs need. The connector pane has,
at most, 28 terminals. If a front panel contains more than 28 controls and indicators that you want to use
programmatically, group some of them into a cluster and assign the cluster to a terminal on the connector
pane. Like an array, a cluster is either a control or an indicator. A cluster cannot contain a mixture of controls
and indicators.
Although cluster and array elements are both ordered, you must unbundle all cluster elements at once rather
than index one element at a time. You also can use the “Unbundle By Name” function to access specific cluster
elements.
Example of a Cluster in LabVIEW:
7.2.1 CLUSTER ORDER
You may sort the different elements in the cluster by right-click on the cluster border and select “Reorder
Controls in Cluster…”
52 Working with Data
Tutorial: An Introduction to LabVIEW
7.2.2 CLUSTER ELEMENTS
In order to manipulate and work with cluster LabVIEW offers lots of functions, such as the “Bundle” and
“Unbundle” functions.
In order to write to a cluster from the code, you may use the “Bundle” function or the “Bundle By Name”
function. See example below:
Example: Clusters
53 Working with Data
Tutorial: An Introduction to LabVIEW
In order to get access to the different elements in the cluster, you need to “Unbundle” by using the “Unbundle”
function or the “Unbundle By Name”. See example below:
EXERCISES
Exercise: Arrays
Create some simple VIs where you use these array functions to manipulate array data:
Array Size
Index Array
Delete from Array
Search 1D Array
Initialize Array
Build Array
Array Subset
Exercise: Arrays
Create a SubVI that find the “peaks” in the input array regarding to an input peak level.
54 Working with Data
Tutorial: An Introduction to LabVIEW
Exercise: Clusters
Create a Cluster and get the different values from the controls in the Cluster. See Front Panel below:
55
8 WORKING WITH STRINGS
Working and manipulating with strings is an important part in LabVIEW development.
On the Front panel we have the following String controls and indicators available from the Control palette:
On the Block Diagram we have the following String functions available from the Functions palette:
Some of the most important String functions are:
Concatenate Strings
56 Working with Strings
Tutorial: An Introduction to LabVIEW
This function concatenates several strings into on string:
Search and Replace String
Use this when you want to replace or remove a certain text in a string.
Match Pattern
57 Working with Strings
Tutorial: An Introduction to LabVIEW
This is the most useful function when it comes to string manipulation.
Format Into String
Example:
EXERCISES
Here are some exercises using some of the String functions that is available in LabVIEW.
Exercise: SubVI: Remove leading zeros in string.vi
Create a SubVI which removes leading zeros in a string. Create a Test VI that uses the SubVI.
58 Working with Strings
Tutorial: An Introduction to LabVIEW
Exercise: SubVI: Remove space from end of string.vi
Create a SubVI which removes all spaces from the end of the string. Create a Test VI that uses the SubVI.
Exercise: SubVI: Add 2 String.vi
Create a SubVI which adds 2 strings into one. Create a Test VI that uses the SubVI.
59
9 ERROR HANDLING
This chapter explains the basic concepts of handle errors in your code.
Topics:
Finding Errors
Error Wiring
Error Handling
9.1 FINDING ERROR
If a VI does not run, it is a broken, or “nonexecutable”, VI. The Run button often appears broken, shown at
left, when you create or edit a VI. If it is still broken when you finish wiring the block diagram, the VI is broken
and will not run. Generally, this means that a required input is not wired, or a wire is broken. Click the broken
Run button to display the Error list window, which lists all the errors. Double-click an error description to
display the relevant block diagram or front panel and highlight the object that contains the error.
9.2 ERROR WIRING
Error handling is important in all programming languages. LabVIEW has powerful mechanism for handling
errors and error wiring.
You should always wire the Error cluster between all SubVIs, nodes, etc. that support this, see example below.
The Error cluster is located in the Controls palette here:
60 Error Handling
Tutorial: An Introduction to LabVIEW
The Error Cluster:
The Error cluster contains of the following parts:
Status – True/False. False: No Error, True: Error
Code – Error Code
Source – Textual Error message
9.3 ERROR HANDLING IN SUBVIS
When creating SubVIs you should always create an Error In and an Error Out. In the SubVI code you should also
use a Case structure and wire the Error in cluster to the Case Selector as shown below.
61 Error Handling
Tutorial: An Introduction to LabVIEW
9.4 ERROR HANDLING
LabVIEW has several useful SubVIs, etc for Error Handling:
These are:
In general you should always show the error to the user. See LabVIEW Help for more details of how to use
these SubVIs.
EXERCISES
Exercise: Error Handling
Check out the different Error Vis in LabVIEW. Use them in some of your previous Vis.
62
10 WORKING WITH PROJECTS
This chapter explains the basic concepts of the project Explorer in LabVIEW.
Topics:
Project Explorer
Building .exe (executable) applications
Deployment: Create an Installer
10.1 PROJECT EXPLORER
It is not necessary to use the Project Explorer when developing your LabVIEW code, but it is an easy way to
structure your code, especially for larger projects.
The project Explorer is necessary when you want to deploy your code into, e.g., an executable (.exe)
application, build a setup, etc.
The Project Explorer is also very useful when you integrate a source control tool, such as Team Foundation
Server, Visual Source Safe, etc. Then you may easily check files in and out of the source code system.
In order to create a new Project in LabVIEW, simply select “Empty Project” from the Getting Started window
when you open LabVIEW.
63 Working with Projects
Tutorial: An Introduction to LabVIEW
10.2 DEPLOYMENT
When your application is finished, you may want to distribute or deploy your application and share it with
others.
The Project Explorergives you several choices when it comes to distribute and deploy your application. Some
of the options are:
Create an executable application (.exe) – this means that the target doesn’t need to have LabVIEW
installed on their computer. All the target need is LabVIEW Run-Rime, which is a small installation
package.
You may create your own installer, so all the target need is to run a setup.exe in order to use your
application
Other possibilities is to create a Web Service or a Shared Library (DLL) of your application
All these options are available from the Project Explorer, just right-click on your “Build Specifications” node.
64 Working with Projects
Tutorial: An Introduction to LabVIEW
We will go through how we create an executable application. Click Build Specifications→New→Application
(EXE).
In the Properties window fill in your name of the application.
Make sure you select a Startup VI.
65 Working with Projects
Tutorial: An Introduction to LabVIEW
There are lots of properties and setting you may use in order to create your application, go through all the
Categories in the Properties window.
When you have finished all the steps, just select “Build” in order to create your application.
When you make changes in your application, it is easy to rebuild your application:
EXERCISES
Exercise: Project Explorer
Create a new Project and put on of your existing application into the project
Exercise: Deployment
Create an executable application
66
11 DESIGN TECHNIQUES
This chapter explains some useful techniques to use when creating your application.
Topics:
Force the Program Flow using an Error cluster
Shift Register
State Machine
Multiple Loops
Templates
11.1 FORCE PROGRAM FLOW
As mentioned earlier, LabVIEW follows a dataflow model for running VIs. A block diagram node executes when
all its inputs are available. When a node completes execution, it supplies data to its output terminals and
passes the output data to the next node in the dataflow path.
In the example below we cannot be sure that the DAQmx Write.vi executes before the DAQmx Stop Task.vi
executes. LabVIEW will in this case randomly execute one of these first. If the Stop VI happens to execute first
then the Write VI will failed because task has been stopped.
In the example below we wire the Error cluster through all the VIs, and there will be no doubt that the Write VI
will execute before the Stop VI.
This approach will also take care of the error handling in your program, which is very important in real-world
applications.
67 Design Techniques
Tutorial: An Introduction to LabVIEW
11.2 SHIFT REGISTER
Use shift registers on For Loops and While Loops to transfer values from one loop iteration to the next. Shift
registers are similar to static variables in text-based programming languages. A shift register appears as a pair
of terminals, directly opposite each other on the vertical sides of the loop border. The right terminal contains
an up arrow and stores data on the completion of an iteration. LabVIEW transfers the data connected to the
right side of the register to the next iteration. Create a shift register by right-clicking the left or right border of a
loop and selecting Add Shift Register from the shortcut menu.
A shift register transfers any data type and automatically changes to the data type of the first object wired to
the shift register. The data you wire to the terminals of each shift register must be the same type.
To initialize a shift register, wire any value from outside the loop to the left terminal. If you do not initialize the
shift register, the loop uses the value written to the shift register when the loop last executed or the default
value for the data type if the loop has never executed.
Use a loop with an uninitialized shift register to run a VI repeatedly so that each time the VI runs, the initial
output of the shift register is the last value from the previous execution. Use an uninitialized shift register to
preserve state information between subsequent executions of a VI. After the loop executes, the last value
stored in the shift register remains at the right terminal. If you wire the right terminal outside the loop, the
wire transfers the last value stored in the shift register. You can add more than one shift register to a loop. If
you have multiple operations within a loop, use multiple shift registers to store the data values from those
different processes in the structure.
11.3 STATE PROGRAMMING ARCHITECTURE
Creating VIs using the State Machine approach is very useful when creating (large) applications.
In general, a state machine is a model of behavior composed of a finite number of states, transitions between
those states, and actions. It is similar to a "flow graph" where we can inspect the way in which the logic runs
when certain conditions are met.
68 Design Techniques
Tutorial: An Introduction to LabVIEW
Sometimes, you may want to change the order of the sequence, repeat one item in the sequence more often
than the other items, stop a sequence immediately, or have items in the sequence that may execute only when
certain conditions are met. Although your program may not have any such requirements, there is always the
possibility that the program must be modified in the future. Therefore, a state programming architecture is a
good choice, even if a sequential programming structure is sufficient. The following list describes more complex
programming requirements that justify the use of a state programming architecture for an application.
You need to change the order of the sequence
You must repeat an item in the sequence more often than other items
You want some items in the sequence to execute only when certain conditions are met
The State Machine approach in LabVIEW uses a Case structure inside a While loop to handle the different
states in the program, and the transitions between them. The Shift Register is used to save data from and
between the different states.
69 Design Techniques
Tutorial: An Introduction to LabVIEW
Below we see examples of a state machine principle implemented in LabVIEW.
Simple State Machine principle
State Machine with multiple transitions depending on the State:
More advanced State Machine using Shift Registers:
70 Design Techniques
Tutorial: An Introduction to LabVIEW
11.4 MULTIPLE LOOPS/PARALLELL PROGRAMMING
Often, you need to program multiple tasks so that they execute at the same time. In LabVIEW tasks can run in
parallel if they do not have a data dependency between them, and if they are not using the same shared
resource. An example of a shared resource is a file, or an instrument.
Using multiple While loops is sometimes useful in applications that need to handle User interactions in parallel
with, e.g., DAQ operations, etc.
Below we see an example of how this structure could look like. The upper loop could handle interaction with
the user, while the lower loop could handle DAQ operations, such as reading and writing to some I/O
equipments.
71 Design Techniques
Tutorial: An Introduction to LabVIEW
In order to pass data between the loops, you may e.g. use local variables. The loop may have different time
cycles. The I/O may require faster cycles than the User interaction loop.
11.5 TEMPLATES
You should create your own templates for such VI you use a lot. It is easy to create your own templates for
scratch, just create a VI as you normally do and then save it as a template with the ending “.vit”. You may also
convert a VI you already made just by changing the extension to “.vit”.
You should copy your templates to the LabVIEW template folder which is default located in “C:\Program
Files\National Instruments\LabVIEW X.X\Templates\”.72 Design Techniques
Tutorial: An Introduction to LabVIEW
The Templates will then be available from the Getting Started Window or File→New… in LabVIEW.
I may case I have created a sub folder called “My Templates” where I place all my templates.
73 Design Techniques
Tutorial: An Introduction to LabVIEW
EXERCISES
Here are some exercises about shift-registers, State Machines and parallel programming.
Exercise: Shift-register
Create a VI (see example below) where you have the following states:
Initialize
Write
Read
Close
In the VI you will use a shift-register as a temporary storage. In the Write state you Write Data to the storage
(shift-register) while you in the Read state will read the Data from the Storage.
See Example below:
74 Design Techniques
Tutorial: An Introduction to LabVIEW
Write a Test program that test the SubVI, e.g.,
This example shows how you can use a shift-register as a temporary storage, which is very useful in many
situations.
Exercise: State Machine
Use the State Machine principle on one of your previous exercises.
Exercise: Parallel Programming
Create a VI that consists of 2 parallel loops. Use local variables and other mechanisms in order to share data
between the 2 loops.
Exercise: Templates
Strip some of yours previous Vis and save them as reusable Templates.
75
12 USER INTERFACE
This chapter explains the basic concepts of creating user-friendly Graphical User Interfaces (GUI) in LabVIEW.
Topics:
Decorations
Tab Control
Splitter
Sub Panel
Etc.
Below we see a Front Panel (GUI) with a “poor” design.
The information (Controls and Indicators) on the Front Panel is not structured. You should group elements that
naturally belong together and use different colors with care.
When creating Graphical User Interfaces (GUI) you should use the controls from the System palette and not
from the Modern or Classic palettes. Modern Controls may be used in Sub Vis with no visible User Interface (for
the user).
The appearance of the controls in the System palette is standard MS Windows look and feeling and this look is
familiar for most users. These controls also change appearance due to changes in the appearance in the
operation system.
76 User Interface
Tutorial: An Introduction to LabVIEW
12.1 VI PROPERTIES
In order to make the appearance of the Window that hosts your application, you should always make some
changes in the “VI Properties”.
You find the “VI Properties” by right-click on the icon in the upper right corner of your VI.
77 User Interface
Tutorial: An Introduction to LabVIEW
The first thing you should change is the “Window title”. Here you may type appropriate name of your
application or SubVI.
The next you should do is to the “Customize” button in order to customize the Window appearance.
Below we see an application with a simple and neat User Interface and with a Customized Windows
appearance.
78 User Interface
Tutorial: An Introduction to LabVIEW
Below we see a professional application created in LabVIEW that implement common GUI objects such as a
Toolbar, a Tree view and a List view.
79 User Interface
Tutorial: An Introduction to LabVIEW
EXERCISES
Exercise: User Interface
Create a Dialog Box where you use some of the Controls from the System palette. Make the necessary settings
in VI Properties in order to hide menus, buttons, create a Title, etc.
Create a Test VI from where you open this Dialog Box, enter some data in the Dialog Box, and then retrieve
these data in the calling VI.
Example:
80
13 PLOTTING DATA
This chapter explains the basic concepts when plotting data in LabVIEW.
LabVIEW offers powerful functionality for plotting data. In the Graph palette we have lots of useful controls for
plotting and visualization of data.
The most useful are:
Waveform Chart
Waveform Graph
XY Graph
Example:
This simple example creates a graph with some random values.
81 Plotting Data
Tutorial: An Introduction to LabVIEW
The example below show the basic difference between a “Chart” and a “Graph”.
You use the “Graph” if you want to plot a set of data, e.g., an array with data, plot data from a file, etc. Use the
“Chart” if you want to plot one data point at a time, e.g., inside a loop, etc.
13.1 CUSTOMIZING
The different Chart components in LabVIEW offer a great deal of customizing.
82 Plotting Data
Tutorial: An Introduction to LabVIEW
You may click on the “Plot Legend” in order to set colors, different line styles, etc.
If you right-click on the Graph/Chart, you may set properties such as auto-scaling, etc.
If you select Properties, you get the following dialog:
83 Plotting Data
Tutorial: An Introduction to LabVIEW
You may also select which items that should be visible or not.
The “Graph Palette” lets you zoom in and out on the Graph, etc.
EXERCISES
Exercise: Graph
84 Plotting Data
Tutorial: An Introduction to LabVIEW
Create a VI that reads data from a file and plot the data in a Graph component.
Exercise: Chart
Create a VI where you use Data Binding in order to retrieve data from an OPC demo.
Data Binding is set in the Properties → Data Binding tab:
Exercise: Customizing
Customize the Graph and the Chart in the examples above in order to set colors, line thickness, etc.
85
14 TIPS & TRICKS
This chapter give you some useful Tips & Tricks
14.1 10 FUNCTIONS YOU NEED TO KNOW ABOUT
These are the 10 most useful functions in LabVIEW, so you could already now learn how to use them and
where to find them!
Build Array
This example using the Build Array function inside a For loop in order build an array with 10 elements.
Index Array
It is always useful to find a specific value in an array:
86 Tips & Tricks
Tutorial: An Introduction to LabVIEW
The Index Array is extendible, so you can drag it out to find more than one elements:
Array Size
Find the size of an arbitrary array:
Select
Depending on the input data, go to the Alarm case or the Write Data case.
87 Tips & Tricks
Tutorial: An Introduction to LabVIEW
Concatenate Strings
This function concatenate several strings into on string:
Search and Replace String
Use this when you want to replace or remove a certain text in a string.
88 Tips & Tricks
Tutorial: An Introduction to LabVIEW
Match Pattern
This is the most useful function when it comes to string manipulation.
Format Into String
Example:
89 Tips & Tricks
Tutorial: An Introduction to LabVIEW
Fract/Exp String to Number
This function converts a string into a number:
Example: Number To Fractional String
Example:
14.2 THE 10 MOST USEFUL SHORT-CUTS
These are the 10 most useful short-cuts in LabVIEW, so you could already now learn how to use them!
Short-Cut Description
Ctrl + B Deletes all broken wires in a VI
Ctrl + . Stops the Running VI
Ctrl + E Toggle between the Front Panel and Block Diagram
Tab Cycles through the most common Tools (Automatic Tool Selection should be
90 Tips & Tricks
Tutorial: An Introduction to LabVIEW
disabled!)
Ctrl + Mouse wheel Scrolls through subdiagrams in Case, Event or Sequence structures
Ctrl + H Displays the Context Help window
Ctrl + Mouse
Double-click on a
SubVI
Opens the Block Diagram directly
Ctrl + Arrows
(→←←↓ )
Move faster. You first have to select a SubVI, a Function, Object, etc
Ctrl + W Close the SubVI
Double-click on a
wire
Selects the hole wire
91
15 ADDITIONAL EXERCISES
This chapter lists lots of additional exercises you could try out in order to improve your LabVIEWskills.
Exercise: vCard Reader
Create an application that reads information from a vCard.
vCard is a file format standard for electronic business cards. vCards are often attached to e-mail messages, but
can be exchanged in other ways, such as on the World Wide Web. They can contain name and address
information, phone numbers, URLs, logos, photographs, and even audio clips.
Example:
BEGIN:VCARD
VERSION:2.1
N:Gump;Forrest
FN:Forrest Gump
ORG:Bubba Gump Shrimp Co.
TITLE:Shrimp Man
TEL;WORK;VOICE:(111) 555-1212
TEL;HOME;VOICE:(404) 555-1212
ADR;WORK:;;100 Waters Edge;Baytown;LA;30314;United States of America
LABEL;WORK;ENCODING=QUOTED-PRINTABLE:100 Waters Edge=0D=0ABaytown, LA 30314=0D=0AUSA
ADR;HOME:;;42 Plantation St.;Baytown;LA;30314;United States of America
LABEL;HOME;ENCODING=QUOTED-PRINTABLE:42 Plantation St.=0D=0ABaytown, LA 30314=0D=0AUSA
EMAIL;PREF;INTERNET:forrestgump@example.com
REV:20080424T195243Z
END:VCARD
For more information about the vCard format, see http://en.wikipedia.org/wiki/VCard.
The application should look something like this:
When the user click Open, then a dialog box like this should appear:
http://en.wikipedia.org/wiki/VCard
92 Additional Exercises
Tutorial: An Introduction to LabVIEW
Requirements:
Use the Project Explorer
Use the State Machine principle
Use the Event Structure
Use System Controls
Set the appropriate settings in the VI Properties.
Create a executable application (vCard.exe)
Exercise: vCard Write & Read
Extend the application in the previous example. You should now be able to both write and read vCard files. The
application could look something like this:
93 Additional Exercises
Tutorial: An Introduction to LabVIEW
When the user clicks New, the dialog box in the previous exercise appears. The user may enter a new vCard. If
the user clicks Edit, a dialog box with the selected contact should appear.
Exercise: Read/Write from .ini files
Read/Write from .ini files. Use the Configuration File VIs:
Exercise: ActiveX
Create a simple Web Browser using ActiveX and the Internet Explorer ActiveX control (Microsoft Web Browser)
Use the ActiveX Container from the Containers control palette:
94 Additional Exercises
Tutorial: An Introduction to LabVIEW
Use the ActiveX function palette:
The application could look something like this:
95 Additional Exercises
Tutorial: An Introduction to LabVIEW
Exercise: Themes
In e.g., ASP.NET we have something called Themes. Themes are used to change the appearance of your whole
application regarding to color, font, pictures, etc.
LabVIEW do not offer such a functionality , but try to create your own Theme Configurator, so you can change
the appearance of your VI instantly.
Here is an example of how Windows XP handles different Themes:
Create a similar Theme Configurator so you may easily change the appearance of your Vis.
96
16 WHATS NEXT?
16.1 MY BLOG
For more information about LabVIEW, visit my Blog: http://home.hit.no/~hansha/
16.2 TRAINING
This Training is a part of a series with other Training Kits I have made, such as:
Introduction to LabVIEW
Data Acquisition in LabVIEW
Control and Simulation in LabVIEW
LabVIEW MathScript
Linear Algebra in LabVIEW
Datalogging and Supervisory Control in LabVIEW
Wireless Data Acquisition in LabVIEW
Intermediate Topics in LabVIEW
Advanced Topics in LabVIEW
These Training Kits are available for download from my blog: http://home.hit.no/~hansha
16.3 ADDITIONAL RESOURCES
www.ni.com
16.4 EXAMPLES
In the NI example Finder (Help→Find Examples…) you find lots of useful examples that you can play with or use
as a start when creating your own applications.
http://home.hit.no/~hansha/
http://home.hit.no/~hansha
http://www.ni.com/
97 Whats Next?
Tutorial: An Introduction to LabVIEW
16.5 DOCUMENTATION
As part of the LabVIEW installation there comes a lots of useful documentation.
16.6 LABVIEW WIKI
LabVIEW Wiki is the free LabVIEW information resource that anyone can edit.
http://labviewwiki.org/Home
http://labviewwiki.org/Home
98 Whats Next?
Tutorial: An Introduction to LabVIEW
16.7 LABVIEW ON YOUTUBE
There are lots of LabVIEW videos available at YouTube:
http://www.youtube.com/results?search_query=labview&search=Search
http://www.youtube.com/results?search_query=labview&search=Search
99
QUICK REFERENCE
Quick Reference
Tutorial: An Introduction to LabVIEW
Telemark University College
Faculty of Technology
Kjølnes Ring 56
N-3914 Porsgrunn, Norway
www.hit.no
Hans-Petter Halvorsen, M.Sc.
Telemark University College
Department of Electrical Engineering, Information Technology and Cybernetics
Phone: +47 3557 5158
E-mail: hans.p.halvorsen@hit.no
Blog: http://home.hit.no/~hansha/
Room: B-237a
http://www.hit.no/
mailto:hans.p.halvorsen@hit.no
http://home.hit.no/~hansha/
Telemark University College
Department of Electrical Engineering, Information Technology and Cybernetics
Faculty of Technology, Postboks 203, Kjølnes ring 56, N-3901 Porsgrunn, Norway. Tel: +47 35 57 50 00 Fax: +47 35 57 54 01
LABVIEW MATHSCRIPT
HANS-PETTER HALVORSEN, 2010.03.09
i
PREFACE
This document explains the basic concepts of using LabVIEW MathScript.
For more information about LabVIEW, visit my Blog: http://home.hit.no/~hansha/
What is LabVIEW?
LabVIEW (short for Laboratory Virtual Instrumentation Engineering Workbench) is a platform and development
environment for a visual programming language from National Instruments. The graphical language is named
"G".
What is MATLAB?
MATLAB is a tool for technical computing, computation and visualization in an integrated environment.
MATLAB is an abbreviation for MATrix LABoratory, so it is well suited for matrix manipulation and problem
solving related to Linear Algebra.
MATLAB offers lots of additional Toolboxes for different areas such as Control Design, Image Processing, Digital
Signal Processing, etc.
What is MathScript?
MathScript is a high-level, text- based programming language. MathScript includes more than 800 built-in
functions and the syntax is similar to MATLAB. You may also create custom-made m-file like you do in MATLAB.
MathScript is an add-on module to LabVIEW but you don’t need to know LabVIEW programming in order to use
MathScript. If you want to integrate MathScript functions (built-in or custom-made m-files) as part of a
LabVIEW application and combine graphical and textual programming, you can work with the MathScript
Node.
In addition to the MathScript built-in functions, different add-on modules and toolkits installs additional
functions. The LabVIEW Control Design and Simulation Module and LabVIEW Digital Filter Design Toolkit
install lots of additional functions.
You can more information about MathScript here: http://www.ni.com/labview/mathscript.htm
How do you start using MathScript?
You need to install LabVIEW and the LabVIEW MathScript RT Module. When necessary software is installed,
start MathScript by open LabVIEW:
http://home.hit.no/~hansha/
http://www.ni.com/labview/mathscript.htm
ii Preface
Tutorial: LabVIEW MathScript
In the Getting Started window, select Tools -> MathScript Window...:
iii
INSTALLATION REQUIREMENTS
NI LabVIEW
Name Required
LabVIEW Professional Development System Yes
NI LabVIEW Core Components
Name Required
LabVIEW Control Design and Simulation Module
LabVIEW MathScript RT Module Yes
NI Vision Development Module
Vision Builder for Automated Inspection
LabVIEW Digital Filter Design Toolkit
LabVIEW Modulation Toolkit
LabVIEW System Identification Toolkit
LabVIEW Desktop Execution TraceToolkit
LabVIEW Report Generation for Microsoft Office Toolkit
LabVIEW Database Connectivity Toolkit
LabVIEW Internet Toolkit
NI LabVIEW SignalExpress
LabVIEW Basics 1 and 2 Computer Based Training
Extended Development Suite Components
Name Required
LabWindows/CVI Full Development System
LabWindows/CVI Real-Time Module
LabWindows/CVI PID Control Toolkit
LabWindows/CVI Signal Processing Toolkit
LabWindows/CVI Spectral Measurements Toolkit and Run-time Engine
LabWindows/CVI SQL Toolkit
Measurement Studio Enterprise Edition
DIAdem Professional
Control and Embedded Systems Option Components
Name Required
LabVIEW FPGA Module
LabVIEW Real-Time Module
LabVIEW Statechart Module
LabVIEW Mobile Module
LabVIEW Datalogging and Supervisory Control Module
LabVIEW PID and Fuzzy Logic Toolkit
NI Real-Time Execution Trace Toolkit
LabVIEW Simulation Interface Toolkit
NI Motion Assistant
NI-DAQ Base
Signal processing and Communications Option Components
Name Required
LabVIEW FPGA Module
LabVIEW Sound and Vibration Measurement Suite
LabVIEW Spectral Measurement Toolkit
LabVIEW Advanced Signal Processing Toolkit
LabVIEW Adaptive Filter Toolkit
NI Device Drivers
Name Required
FieldPoint
NI-DAQmx
NI LabVIEW SignalExpress
NI Instrument I/O Assistant
NI-IMAQ
NI Measurement & Automation Explorer
NI PXI
NI-VISA
vi
TABLE OF CONTENTS
Preface ......................................................................................................................................................................i
Installation Requirements ....................................................................................................................................... iii
Table of Contents .................................................................................................................................................... vi
1 Introduction to LabVIEW ............................................................................................................................... 1
1.1 Dataflow programming.......................................................................................................................... 1
1.2 Graphical programming ......................................................................................................................... 1
1.3 Benefits .................................................................................................................................................. 2
1.4 LabVIEW MathScript RT Module ........................................................................................................... 2
2 LabVIEW MathScript RT Module ................................................................................................................... 3
3 LabVIEW MathScript ...................................................................................................................................... 4
3.1 Help........................................................................................................................................................ 6
3.2 Examples ................................................................................................................................................ 6
3.3 Useful commands .................................................................................................................................. 8
3.4 Flow Control .......................................................................................................................................... 9
3.4.1 If-else Statement ........................................................................................................................... 9
3.4.2 Switch and Case Statement .......................................................................................................... 9
3.4.3 For loop ....................................................................................................................................... 10
3.4.4 While loop ................................................................................................................................... 10
3.5 Plotting ................................................................................................................................................ 11
4 Linear Algebra Examples.............................................................................................................................. 13
4.1 Vectors ................................................................................................................................................. 13
4.2 Matrices ............................................................................................................................................... 14
4.2.1 Transpose .................................................................................................................................... 14
4.2.2 Diagonal ...................................................................................................................................... 14
4.2.3 Triangular .................................................................................................................................... 15
4.2.4 Matrix Multiplication .................................................................................................................. 15
vii Table of Contents
Tutorial: LabVIEW MathScript
4.2.5 Matrix Addition ........................................................................................................................... 16
4.2.6 Determinant ................................................................................................................................ 17
4.2.7 Inverse Matrices ......................................................................................................................... 18
4.3 Eigenvalues .......................................................................................................................................... 19
4.4 Solving Linear Equations ...................................................................................................................... 19
4.5 LU factorization ................................................................................................................................... 20
4.6 The Singular Value Decomposition (SVD) ............................................................................................ 22
4.7 Commands ........................................................................................................................................... 22
5 Control Design and Simulation .................................................................................................................... 24
5.1 State-space models and Transfer functions ........................................................................................ 24
5.1.1 PID ............................................................................................................................................... 25
5.1.2 State-space model ...................................................................................................................... 26
5.1.3 Transfer function ........................................................................................................................ 27
5.1.4 First Order Systems ..................................................................................................................... 27
5.1.5 Second Order Systems ................................................................................................................ 28
5.1.6 Padé-approximation ...................................................................................................................30
5.2 Frequency Response Analysis .............................................................................................................. 31
5.2.1 Bode Diagram ............................................................................................................................. 31
Time Response ................................................................................................................................................. 35
6 MathScript Node ......................................................................................................................................... 37
6.1 Transferring MathScript Nodes between Computers ......................................................................... 38
6.2 Examples .............................................................................................................................................. 39
6.3 Exercises .............................................................................................................................................. 42
7 MATLAB Script ............................................................................................................................................. 43
8 Whats Next? ................................................................................................................................................ 44
8.1 My Blog ................................................................................................................................................ 44
8.2 Training ................................................................................................................................................ 44
8.3 MathScript Functions .......................................................................................................................... 44
viii Table of Contents
Tutorial: LabVIEW MathScript
Quick Reference .................................................................................................................................................... 46
1
1 INTRODUCTION TO LABVIEW
LabVIEW (short for Laboratory Virtual Instrumentation Engineering Workbench) is a platform and development
environment for a visual programming language from National Instruments. The graphical language is named
"G". Originally released for the Apple Macintosh in 1986, LabVIEW is commonly used for data acquisition,
instrument control, and industrial automation on a variety of platforms including Microsoft Windows, various
flavors of UNIX, Linux, and Mac OS X. The latest version of LabVIEW is version LabVIEW 2009, released in
August 2009. Visit National Instruments at www.ni.com.
The code files have the extension “.vi”, which is an abbreviation for “Virtual Instrument”. LabVIEW offers lots of
additional Add-Ons and Toolkits.
This paper is part of a series with LabVIEW papers:
Introduction to LabVIEW
Data Acquisition in LabVIEW
Control and Simulation in LabVIEW
Linear Algebra in LabVIEW
Database Communication in LabVIEW
Datalogging and Supervisory Control in LabVIEW
Intermediate Topics in LabVIEW
Advanced Topics in LabVIEW
Etc.
Each paper may be used independently of each other.
1.1 DATAFLOW PROGRAMMING
The programming language used in LabVIEW, also referred to as G, is a dataflow programming language.
Execution is determined by the structure of a graphical block diagram (the LV-source code) on which the
programmer connects different function-nodes by drawing wires. These wires propagate variables and any
node can execute as soon as all its input data become available. Since this might be the case for multiple nodes
simultaneously, G is inherently capable of parallel execution. Multi-processing and multi-threading hardware is
automatically exploited by the built-in scheduler, which multiplexes multiple OS threads over the nodes ready
for execution.
1.2 GRAPHICAL PROGRAMMING
LabVIEW ties the creation of user interfaces (called front panels) into the development cycle. LabVIEW
programs/subroutines are called virtual instruments (VIs). Each VI has three components: a block diagram, a
front panel, and a connector panel. The last is used to represent the VI in the block diagrams of other, calling
VIs. Controls and indicators on the front panel allow an operator to input data into or extract data from a
running virtual instrument. However, the front panel can also serve as a programmatic interface. Thus a virtual
instrument can either be run as a program, with the front panel serving as a user interface, or, when dropped
as a node onto the block diagram, the front panel defines the inputs and outputs for the given node through
the connector pane. This implies each VI can be easily tested before being embedded as a subroutine into a
larger program.
http://www.ni.com/
2 Introduction to LabVIEW
Tutorial: LabVIEW MathScript
The graphical approach also allows non-programmers to build programs simply by dragging and dropping
virtual representations of lab equipment with which they are already familiar. The LabVIEW programming
environment, with the included examples and the documentation, makes it simple to create small applications.
This is a benefit on one side, but there is also a certain danger of underestimating the expertise needed for
good quality "G" programming. For complex algorithms or large-scale code, it is important that the
programmer possess an extensive knowledge of the special LabVIEW syntax and the topology of its memory
management. The most advanced LabVIEW development systems offer the possibility of building stand-alone
applications. Furthermore, it is possible to create distributed applications, which communicate by a
client/server scheme, and are therefore easier to implement due to the inherently parallel nature of G-code.
1.3 BENEFITS
One benefit of LabVIEW over other development environments is the extensive support for accessing
instrumentation hardware. Drivers and abstraction layers for many different types of instruments and buses
are included or are available for inclusion. These present themselves as graphical nodes. The abstraction layers
offer standard software interfaces to communicate with hardware devices. The provided driver interfaces save
program development time. The sales pitch of National Instruments is, therefore, that even people with limited
coding experience can write programs and deploy test solutions in a reduced time frame when compared to
more conventional or competing systems. A new hardware driver topology (DAQmxBase), which consists
mainly of G-coded components with only a few register calls through NI Measurement Hardware DDK (Driver
Development Kit) functions, provides platform independent hardware access to numerous data acquisition and
instrumentation devices. The DAQmxBase driver is available for LabVIEW on Windows, Mac OS X and Linux
platforms.
For more information about LabVIEW, visit my Blog: http://home.hit.no/~hansha/
1.4 LABVIEW MATHSCRIPT RT MODULE
The LabVIEW MathScript RT Module is an add-on module to LabVIEW. With LabVIEW MathScript RT Module
you can:
Deploy your custom .m files to NI real-time hardware
Reuse many of your scripts created with The MathWorks, Inc. MATLAB® software and others
Develop your .m files with an interactive command-line interface
Embed your scripts into your LabVIEW applications using the MathScript Node
http://home.hit.no/~hansha/
3
2 LABVIEW MATHSCRIPT RT MODULE
You can work with LabVIEW MathScript through either of two interfaces: the “LabVIEW MathScript Interactive
Window” or the “MathScript Node”.
You can work with LabVIEW MathScript RT Module through both interactive and programmatic interfaces. For
an interactive interface in which you can load, save, design, and execute your .m file scripts, you can workwith
the “MathScript Interactive Window”. To deploy your .m file scripts as part of a LabVIEW application and
combine graphical and textual programming, you can work with the “MathScript Node”.
The LabVIEW MathScript RT Module complements traditional LabVIEW graphical programming for such tasks
as algorithm development, signal processing, and analysis. The LabVIEW MathScript RT Module speeds up
these and other tasks by giving users a single environment in which they can choose the most effective syntax,
whether textual, graphical, or a combination of the two. In addition, you can exploit the best of LabVIEW and
thousands of publicly available .m file scripts from the web, textbooks, or your own existing m-script
applications. LabVIEW MathScript RT Module is able to process your files created using the current MathScript
syntax and, for backwards compatibility, files created using legacy MathScript syntaxes. LabVIEW MathScript RT
Module can also process certain of your files utilizing other text-based syntaxes, such as files you created using
MATLAB software. Because the MathScript RT engine is used to process scripts contained in a MathScript
Windows or MathScript Node, and because the MathScript RT engine does not support all syntaxes, not all
existing text-based scripts are supported.
LabVIEW MathScript RT Module supports most of the functionality available in MATLAB, the syntax is also
similar.
For more details, see http://zone.ni.com/devzone/cda/tut/p/id/3257
http://zone.ni.com/devzone/cda/tut/p/id/3257
4
3 LABVIEW MATHSCRIPT
Requires: MathScript RT Module
How do you start using MathScript? You need to install LabVIEW and the LabVIEW MathScript RT Module.
When necessary software is installed, start MathScript by open LabVIEW:
In the Getting Started window, select Tools -> MathScript Window...:
The “LabVIEW MathScript Window” is an interactive interface in which you can enter .m file script commands
and see immediate results, variables and commands history. The window includes a command-line interface
where you can enter commands one-by-one for quick calculations, script debugging or learning. Alternatively,
you can enter and execute groups of commands through a script editor window.
As you work, a variable display updates to show the graphical / textual results and a history window tracks your
commands. The history view facilitates algorithm development by allowing you to use the clipboard to reuse
your previously executed commands.
5 LabVIEW MathScript
Tutorial: LabVIEW MathScript
You can use the “LabVIEW MathScript Window” to enter commands one at time. You also can enter batch
scripts in a simple text editor window, loaded from a text file, or imported from a separate text editor. The
“LabVIEW MathScript Window” provides immediate feedback in a variety of forms, such as graphs and text.
Example:
6 LabVIEW MathScript
Tutorial: LabVIEW MathScript
3.1 HELP
You may also type help in your command window
>>help
Or more specific, e.g.,
>>help plot
3.2 EXAMPLES
I advise you to test all the examples in this text in LabVIEW MathScript in order to get familiar with the program
and its syntax. All examples in the text are outlined in a frame like this:
>>
…
This is commands you should write in the Command Window.
You type all your commands in the Command Window. I will use the symbol “>>” to illustrate that the
commands should be written in the Command Window.
Example: Matrices
Defining the following matrix
The syntax is as follows:
>> A = [1 2;0 3]
Or
>> A = [1,2;0,3]
If you, for an example, want to find the answer to
>>a=4
>>b=3
>>a+b
MathScript then responds:
ans =
7
7 LabVIEW MathScript
Tutorial: LabVIEW MathScript
MathScript provides a simple way to define simple arrays using the syntax: “init:increment:terminator”. For
instance:
>> array = 1:2:9
array =
1 3 5 7 9
The code defines a variable named array (or assigns a new value to an existing variable with the name array)
which is an array consisting of the values 1, 3, 5, 7, and 9. That is, the array starts at 1 (the init value),
increments with each step from the previous value by 2 (the increment value), and stops once it reaches (or to
avoid exceeding) 9 (the terminator value).
The increment value can actually be left out of this syntax (along with one of the colons), to use a default value
of 1.
>> ari = 1:5
ari =
1 2 3 4 5
The code assigns to the variable named ari an array with the values 1, 2, 3, 4, and 5, since the default value of 1
is used as the incrementer.
Note that the indexing is one-based, which is the usual convention for matrices in mathematics. This is atypical
for programming languages, whose arrays more often start with zero.
Matrices can be defined by separating the elements of a row with blank space or comma and using a semicolon
to terminate each row. The list of elements should be surrounded by square brackets: []. Parentheses: () are
used to access elements and subarrays (they are also used to denote a function argument list).
>> A = [16 3 2 13; 5 10 11 8; 9 6 7 12; 4 15 14 1]
A =
16 3 2 13
5 10 11 8
9 6 7 12
4 15 14 1
>> A(2,3)
ans =
11
8 LabVIEW MathScript
Tutorial: LabVIEW MathScript
Sets of indices can be specified by expressions such as "2:4", which evaluates to [2, 3, 4]. For example, a
submatrix taken from rows 2 through 4 and columns 3 through 4 can be written as:
>> A(2:4,3:4)
ans =
11 8
7 12
14 1
A square identity matrix of size n can be generated using the function eye, and matrices of any size with zeros
or ones can be generated with the functions zeros and ones, respectively.
>> eye(3)
ans =
1 0 0
0 1 0
0 0 1
>> zeros(2,3)
ans =
0 0 0
0 0 0
>> ones(2,3)
ans =
1 1 1
1 1 1
3.3 USEFUL COMMANDS
Here are some useful commands:
Command Description
eye(x), eye(x,y) Identity matrix of order x
ones(x), ones(x,y) A matrix with only ones
9 LabVIEW MathScript
Tutorial: LabVIEW MathScript
zeros(x), zeros(x,y) A matrix with only zeros
diag([x y z]) Diagonal matrix
size(A) Dimension of matrix A
A’ Inverse of matrix A
3.4 FLOW CONTROL
This chapter explains the basic concepts of flow control in MathScript.
The topics are as follows:
If-else statement
Switch and case statement
For loop
While loop
3.4.1 IF-ELSE STATEMENT
The if statement evaluates a logical expression and executes a group of statements when the expression is
true. The optional elseif and else keywords provide for the execution of alternate groups of statements. An end
keyword, which matches the if, terminates the last group of statements. The groups of statements are
delineated by the four keywords—no braces or brackets are involved.
Example: If-Else Statement
Test the following code:
n=5
if n > 2
M = eye(n)
elseif n < 2
M = zeros(n)
else
M = ones(n)
end
3.4.2 SWITCH AND CASE STATEMENT
The switch statement executes groups of statements based on the value of a variable or expression. The
keywords case and otherwise delineate the groups. Only the first matching case is executed. There must always
be an end to match the switch.
Example: Switch and Case Statement
Test the following code:
10 LabVIEW MathScript
Tutorial: LabVIEW MathScript
n=2
switch(n)
case 1
M = eye(n)
case 2
M = zeros(n)
case 3
M = ones(n)
end
3.4.3 FOR LOOP
The for loop repeats a group of statements a fixed, predetermined number of times. A matching end delineates
the statements.
Example: For Loop
Test the following code:
m=5
for n = 1:m
r(n) = rank(magic(n));
end
r
3.4.4 WHILE LOOP
The while loop repeats a group of statements an indefinite numberof times under control of a logical
condition. A matching end delineates the statements.
Example: While Loop
Test the following code:
m=5;
while m > 1
m = m - 1;
zeros(m)
end
11 LabVIEW MathScript
Tutorial: LabVIEW MathScript
3.5 PLOTTING
This chapter explains the basic concepts of creating plots in MathScript.
Topics:
Basic Plot commands
Example: Plotting
Function plot can be used to produce a graph from two vectors x and y. The code:
x = 0:pi/100:2*pi;
y = sin(x);
plot(x,y)
produces the following figure of the sine function:
Example: Plotting
Three-dimensional graphics can be produced using the functions surf, plot3 or mesh.
[X,Y] = meshgrid(-10:0.25:10,-10:0.25:10);
f = sinc(sqrt((X/pi).^2+(Y/pi).^2));
mesh(X,Y,f);
axis([-10 10 -10 10 -0.3 1])
12 LabVIEW MathScript
Tutorial: LabVIEW MathScript
xlabel('{\bfx}')
ylabel('{\bfy}')
zlabel('{\bfsinc} ({\bfR})')
hidden off
This code produces the following 3D plot:
13
4 LINEAR ALGEBRA EXAMPLES
Requires: MathScript RT Module
Linear algebra is a branch of mathematics concerned with the study of matrices, vectors, vector spaces (also
called linear spaces), linear maps (also called linear transformations), and systems of linear equations.
MathScript are well suited for Linear Algebra.
4.1 VECTORS
Given a vector x
Example: Vectors
Given the following vector
>> x=[1; 2; 3]
x =
1
2
3
The Transpose of vector x:
>> x'
ans =
1 2 3
The Length of vector x:
Orthogonality:
14 Linear Algebra Examples
Tutorial: LabVIEW MathScript
4.2 MATRICES
Given a matrix A:
Example: Matrices
Given the following matrix:
>> A=[0 1;-2 -3]
A =
0 1
-2 -3
4.2.1 TRANSPOSE
The Transpose of matrix A:
Example: Transpose
Given the matrix:
>> A'
ans =
0 -2
1 -3
4.2.2 DIAGONAL
The Diagonal elements of matrix A is the vector
Example: Diagonal
15 Linear Algebra Examples
Tutorial: LabVIEW MathScript
Find the diagonal elements of matrix A:
>> diag(A)
ans =
0
-3
The Diagonal matrix Λ is given by:
Given the Identity matrix I:
Example: Identity Matrix
Get the 3x3 Identity matrix:
>> eye(3)
ans =
1 0 0
0 1 0
0 0 1
4.2.3 TRIANGULAR
Lower Triangular matrix L:
Upper Triangular matrix U:
4.2.4 MATRIX MULTIPLICATION
Given the matrices and , then
16 Linear Algebra Examples
Tutorial: LabVIEW MathScript
where
Example: Matrix Multiplication
Matrix multiplication:
>> A=[0 1;-2 -3]
A =
0 1
-2 -3
>> B=[1 0;3 -2]
B =
1 0
3 -2
>> A*B
ans =
3 -2
-11 6
Note!
4.2.5 MATRIX ADDITION
Given the matrices and , then
Example: Matrix Addition
Matrix addition:
>> A=[0 1;-2 -3]
>> B=[1 0;3 -2]
>> A+B
17 Linear Algebra Examples
Tutorial: LabVIEW MathScript
ans =
1 1
1 -5
4.2.6 DETERMINANT
Given a matrix , then the Determinant is given:
Given a 2x2 matrix
Then
Example: Determinant
Find the determinant:
A =
0 1
-2 -3
>> det(A)
ans =
2
Notice that
and
Example: Determinant
Determinants:
>> det(A*B)
ans =
18 Linear Algebra Examples
Tutorial: LabVIEW MathScript
-4
>> det(A)*det(B)
ans =
-4
>> det(A')
ans =
2
>> det(A)
ans =
2
4.2.7 INVERSE MATRICES
The inverse of a quadratic matrix is defined by:
if
For a 2x2 matrix we have:
The inverse is given by
Example: Inverse Matrices
Inverse matrix:
A =
0 1
-2 -3
>> inv(A)
ans =
-1.5000 -0.5000
1.0000 0
Notice that:
→ Prove this in MathScript
19 Linear Algebra Examples
Tutorial: LabVIEW MathScript
4.3 EIGENVALUES
Given , then the Eigenvalues is defined as:
Example: Eigenvalues
Find the Eigenvalues:
A =
0 1
-2 -3
>> eig(A)
ans =
-1
-2
4.4 SOLVING LINEAR EQUATIONS
Given the linear equation
with the solution:
(Assuming that the inverse of A exists)
Example: Solving Linear Equations
Solving the following equation:
The equations
may be written
where
20 Linear Algebra Examples
Tutorial: LabVIEW MathScript
The solution is:
A =
1 2
3 4
>> b=[5;6]
b =
5
6
>> x=inv(A)*b
x =
-4.0000
4.5000
In MathScript you could also write “x=A\b”, which should give the same answer. This syntax can also be used
when the inverse of A don’t exists.
Example: Solving Linear Equations
Illegal operation:
>> A=[1 2;3 4;7 8]
>> x=inv(A)*b
??? Error using ==> inv
Matrix must be square.
>> x=A\b
x =
-3.5000
4.1786
4.5 LU FACTORIZATION
LU factorization of is given by
where
L is a lower triangular matrix
21 Linear Algebra Examples
Tutorial: LabVIEW MathScript
U is a upper triangular matrix
The MathScript syntax is [L,U]=lu(A)
Example: LU Factorization
Find L and U:
>> A=[1 2;3 4]
>> [L,U]=lu(A)
L =
0.3333 1.0000
1.0000 0
U =
3.0000 4.0000
0 0.6667
Or sometimes LU factorization of is given by
where
D is a diagonal matrix
The MathScript syntax is [L,U,P]=lu(A)
Example: LU Factorization
Find L, U and P:
>> A=[1 2;3 4]
A =
1 2
3 4
>> [L,U,P]=lu(A)
L =
1.0000 0
0.3333 1.0000
U =
3.0000 4.0000
22 Linear Algebra Examples
Tutorial: LabVIEW MathScript
0 0.6667
P =
0 1
1 0
4.6 THE SINGULAR VALUE DECOMPOSITION (SVD)
The Singular value Decomposition (SVD) of the matrix is given by
where
U is a orthogonal matrix
V is a orthogonal matrix
S is a diagonal singular matrix
Example: SVD Decomposition
Find S, V and D:
>> A=[1 2;3 4];
>> [U,S,V] = svd(A)
U =
-0.4046 -0.9145
-0.9145 0.4046
S =
5.4650 0
0 0.3660
V =
-0.5760 0.8174
-0.8174 -0.5760
4.7 COMMANDS
23 Linear Algebra Examples
Tutorial: LabVIEW MathScript
Command Description
[L,U]=lu(A)
[L,U,P]=lu(A)
LU Factorization
[U,S,V] = svd(A) Singular Value Decomposition (SVD )
24
5 CONTROL DESIGN AND SIMULATION
Using LabVIEW MathScript for Control Design purposes you need to install the “Control Design and Simulation
Module” in addition to the “MathScript RT Module” itself.
Use the Control Design MathScript RT Module functions to design, analyze, and simulate linear controller
models using a text-based language. The following is a list of Control Design MathScript RT Module classes of
functions and commands that LabVIEW MathScript supports.
Getting help about MathScript functions regarding the Control Design Toolkit (CDT), type “help cdt” in the
Command Window in the MathScript environment.
The following function classes exist:
We will go through some of the classes and function in detail below:
5.1 STATE-SPACE MODELS AND TRANSFER FUNCTIONS
MathScript offers lots of functions for defining and manipulate state-space models and transfer functions.
Class: contruct
Description:
Use functions in the construct class to construct linear time-invariant system models and to convert between
model forms.
Below we see the different functions available in the construct class:
25 Control Design and Simulation
Tutorial: LabVIEW MathScript
Below we will give some examples of how to use the most import functions in this class.
5.1.1 PID
Currently, the Proportional-Integral-Derivative (PID) algorithm is the most common controlalgorithm used in
industry.
In PID control, you must specify a process variable and a setpoint. The process variable is the system parameter
you want to control, such as temperature, pressure, or flow rate, and the setpoint is the desired value for the
parameter you are controlling.
A PID controller determines a controller output value, such as the heater power or valve position. The
controller applies the controller output value to the system, which in turn drives the process variable toward
the setpoint value.
Then the PID controller calculates the controller action, u(t):
Where
Controller gain
Integral time
Derivative time
And is the error
SP – Setpoint
PV – Process Variable
26 Control Design and Simulation
Tutorial: LabVIEW MathScript
Function: pid
Description:
Constructs a proportional-integral-derivative (PID) controller model in either parallel, series, or academic form.
Examples:
Kc = 0.5;
Ti = 0.25;
SysOutTF = pid(Kc, Ti, 'academic');
5.1.2 STATE-SPACE MODEL
A state-space model is just a structured form or representation of the differential equations for a system.
A linear State-space model:
where x is the state vector and u is the input vector. A is called the system-matrix, and is square in all cases.
Example:
The differential equations:
May be written on state-space form:
Function: ss
Description:
This function constructs a continuous or discrete linear system model in state-space form. You also can use this
function to convert transfer function and zero-pole-gain models to state-space form.
Examples:
% Creates a state-space model
A = eye(2)
B = [0; 1]
C = B'
SysOutSS = ss(A, B, C)
27 Control Design and Simulation
Tutorial: LabVIEW MathScript
% Converts a zero-pole-gain model to state-space form
z = 1
p = [1, -1]
k = 1
SysIn = zpk(z, p, k)
SysOutSS = ss(SysIn)
5.1.3 TRANSFER FUNCTION
The transfer function of a linear system is defined as the ratio of the Laplace transform of the output variable
to the Laplace transform of the input variable.
Function tf
Description:
This function creates a continuous or discrete linear system model in transfer function form. You also can use
this function to convert zero-pole-gain and state-space models to transfer function form.
Examples:
>>s = tf('s')
This specifies that you want to create the continuous transfer function s / 1. After you enter this command, you
can use LabVIEW MathScript operands on this transfer function to define a zero-pole-gain or transfer function
model.
SysOutZPK = 4*(s + 2) / (s + 1)
This example constructs a zero-pole-gain model with a gain of 4, a zero at -2, and a pole at -1.
SysOutTF = (3*(s*s*s) + 2) / (4*(s*s*s*s) + 8)
This example constructs the transfer function model 3s^3 + 2 / 4s^4 + 8.
5.1.4 FIRST ORDER SYSTEMS
The following transfer function defines a first order system:
Where
28 Control Design and Simulation
Tutorial: LabVIEW MathScript
is the gain
is the Time constant
Function sys_order1
Description:
This function constructs the components of a first-order system model based on a gain, time constant, and
delay that you specify. You can use this function to create either a state-space model or a transfer function
model, depending on the output parameters you specify.
Inputs:
K Specifies the gain matrix. K is a real matrix.
tau Specifies the time constant, in seconds, which is the time required for the model output to reach 63% of its
final value. The default value is 0.
delay Specifies the response delay of the model, in seconds. The default value is 0.
Examples:
K = 0.5;
tau = 1.5;
SysOutTF = sys_order1(K, tau);
…
5.1.5 SECOND ORDER SYSTEMS
A standard second order transfer function model may be written like this:
Where
is the gain
(zetais the relative damping factor
[rad/s] is the undamped resonance frequency.
Function sys_order2
Description:
This function constructs the components of a second-order system model based on a damping ratio and
natural frequency you specify. You can use this function to create either a state-space model or a transfer
function model, depending on the output parameters you specify.
29 Control Design and Simulation
Tutorial: LabVIEW MathScript
Example:
Examples of how to use the sys_order2 function:
dr = 0.5
wn = 20
[num, den] = sys_order2(wn, dr)
SysTF = tf(num, den)
[A, B, C, D] = sys_order2(wn, dr)
SysSS = ss(A, B, C, D)
Class: connect
Description:
Use members of the connect class to connect systems models together in various configurations.
Below we see the different functions available in the connect class:
Function series
Description:
This function connects two system models in series to produce a model SysSer with input and output
connections you specify. The input models must be either continuous models or discrete models with identical
sampling times.
Example:
Here is an example of how to use the series function.
SysIn_1 = tf([1, 1], [1 -1, 3])
SysIn_2 = zpk([1], [1, -1], 1)
SysSer = series(SysIn_1, SysIn_2)
Class: convert
30 Control Design and Simulation
Tutorial: LabVIEW MathScript
Description:
Use members of the convert class to convert a continuous system model to a discrete model, convert a discrete
model to a continuous model, and resample a discrete model. You also can use members of this class to
incorporate delays into a system model.
Below we see the different functions available in the convert class:
5.1.6 PADÉ-APPROXIMATION
The Transfer function of a time-delay is:
In some situations it is necessary to substitute with an approximation, e.g., the Padé-approximation:
Function: pade
Description:
This function incorporates time delays into a system model using the Pade approximation method, which
converts all residuals. You must specify the delay using the set function. You also can use this function to
calculate coefficients of numerator and denominator polynomial functions with a specified delay.
Example:
Examples of how to use the pade function:
SysCon = zpk(1, 3.2, 6)
SysCon = set(SysCon, 'inputdelay', 6, 'outputdelay', 1.1)
SysDel = pade(SysCon, 2)
delay = 1.2
order = 3
[num, den] = pade(delay, order)
31 Control Design and Simulation
Tutorial: LabVIEW MathScript
5.2 FREQUENCY RESPONSE ANALYSIS
The frequency response of a system is a frequency dependent function which expresses how a sinusoidal signal
of a given frequency on the system input is transferred through the system. Each frequency component is a
sinusoidal signal having a certain amplitude and a certain frequency.
The frequency response is an important tool for analysis and design of signal filters and for analysis and design
of control systems.
The frequency response can found experimentally or from a transfer function model.
The frequency response of a system is defined as the steady-state response of the system to a sinusoidal input
signal. When the system is in steady-state it differs from the input signal only in amplitude (A) and phase angle
(ω).
If we have the input signal:
The steady-state output signal will be:
A and is a function of the frequency ω so we may write
For a transfer function
We have:
Where is the frequency response of the system, i.e., we may find the frequency response by setting
in the transfer function.
5.2.1 BODE DIAGRAM
Bode diagrams are useful in frequency response analysis. The Bode diagram consists of 2 diagrams, the Bode
magnitude diagram, and the Bode phase diagram, .
The -axis is in decibel (dB)
Where the decibel value of x is calculated as:
The -axis is in degrees (not radians)
32 Control Design and Simulation
Tutorial: LabVIEW MathScript
Function: bode
Description:This function creates the Bode magnitude and Bode phase plots of a system model. You also can use this
function to return the magnitude and phase values of a model at frequencies you specify. If you do not specify
an output, this function creates a plot.
Examples:
We have the following transfer function
We want to plot the Bode diagram for this transfer function:
In MathScript we could write:
num=[1];
den=[1,1];
H1=tf(num,den)
bode(H1)
Function: margin
Description:
33 Control Design and Simulation
Tutorial: LabVIEW MathScript
This function calculates and/or plots the smallest gain and phase margins of a single-input single-output (SISO)
system model.
The gain margin indicates where the frequency response crosses at 0 decibels (“crossover frequency”, ).
is also the bandwidth of the system
The phase margin indicates where the frequency response crosses -180 degrees (“crossover frequency”, ).
Examples:
The following example illustrates the use of the margin function.
num = [1]
den = [1, 5, 6]
H = tf(num, den)
margin(H)
Example:
Given the following system:
We want to plot the Bode diagram and find the crossover-frequencies for the system using MathScript.
The code is as follows:
H = tf([1, 1], [1, -1, 3])
bode(H)
[gmf, gm, pmf, pm] = margins(H)
margin(H)
We use the following functions: tf, bode, margins and margin.
gmf is the gain margin frequencies, in radians/second. A gain margin frequency indicates where the
model phase crosses -180 degrees.
gm Returns the gain margins of the system.
pmf Returns the phase margin frequencies, in radians/second. A phase margin frequency indicates
where the model magnitude crosses 0 decibels.
34 Control Design and Simulation
Tutorial: LabVIEW MathScript
pm Returns the phase margins of the system.
We get the following results:
Bode Plot:
Cross-frequencies:
We get the following values:
35 Control Design and Simulation
Tutorial: LabVIEW MathScript
gmf = 1
gm = 2
pmf = -70.379 2.2333e-010
pm = 1.4155 2
TIME RESPONSE
Class: timeresp
Description:
Use members of the timeresp class to create generic linear simulations and time domain plots for step inputs,
impulse inputs, and initial condition responses.
Below we see the different functions available in the timeresp class:
Function: step
Description:
This function creates a step response plot of the system model. You also can use this function to return the
step response of the model outputs. If the model is in state-space form, you also can use this function to return
the step response of the model states. This function assumes the initial model states are zero. If you do not
specify an output, this function creates a plot.
Example:
Given the following system:
We will plot the time response for the transfer function using the step function
The result is as follows:
36 Control Design and Simulation
Tutorial: LabVIEW MathScript
The MathScript code:
H = tf([1, 1], [1, -1, 3])
step(H)
37
6 MATHSCRIPT NODE
The “MathScript Node” offers an intuitive means of combining graphical and textual code within LabVIEW. The
figure below shows the “MathScript Node” on the block diagram, represented by the blue rectangle. Using
“MathScript Nodes”, you can enter .m file script text directly or import it from a text file.
You can define named inputs and outputs on the MathScript Node border to specify the data to transfer
between the graphical LabVIEW environment and the textual MathScript code.
You can associate .m file script variables with LabVIEW graphical programming, by wiring Node inputs and
outputs. Then you can transfer data between .m file scripts with your graphical LabVIEW programming. The
textual .m file scripts can now access features from traditional LabVIEW graphical programming.
The MathScript Node is available from LabVIEW from the Functions Palette: Mathematics → Scripts & Formulas
38 MathScript Node
Tutorial: LabVIEW MathScript
If you click Ctrl+H you get help about the MathScript Node:
Click “Detailed help” in order to get more information about the MathScript Node.
Use the NI Example Finder in order to find examples:
6.1 TRANSFERRING MATHSCRIPT NODES BETWEEN COMPUTERS
If a script in a MathScript Node calls a user-defined function, LabVIEW uses the default search path list to link
the function call to the specified .m file. After you configure the default search path list and save the VI that
contains the MathScript Node, you do not need to reconfigure the MathScript search path list when you open
the VI on a different computer because LabVIEW looks for the .m file in the directory where the .m file was
39 MathScript Node
Tutorial: LabVIEW MathScript
located when you last saved the VI. However, you must maintain the same relative path between the VI and
the .m file.
6.2 EXAMPLES
Example: Using the MathScript Node
Here is an example of how you use the MathScript Node. On the left border you connect input variables to the
script, on the right border you have output variables. Right-click on the border and select “Add Input” or “Add
Output”.
Example: Calling a Windows DLL:
Example: Using m-files in the MathScript Node:
Use the LabVIEW MathScript to create a m-file script (or you may use MATLAB to create the same script):
40 MathScript Node
Tutorial: LabVIEW MathScript
Right-click on the border of the MathScript Node and select “Import”, and then select the m-file you want to
import into the Node.
41 MathScript Node
Tutorial: LabVIEW MathScript
Right-click on the right border and select “Add Output”. Then right-click on the output variable and select
“Create Indicator”.
Block Diagram:
The result is as follows (click the Run button):
If you, e.g., add the following command in the MathScript Node: plot(x), the following window appears:
42 MathScript Node
Tutorial: LabVIEW MathScript
6.3 EXERCISES
Use the MathScript Node and test the same examples you did in the previous chapter (Chapter 4 - “Linear
Algebra Examples”)
43
7 MATLAB SCRIPT
The MATLAB Script calls the MATLAB software to execute scripts. You must have a licensed copy of the
MATLAB software version 6.5 or later installed on your computer to use MATLAB script nodes because the
script nodes invoke the MATLAB software script server to execute scripts written in the MATLAB language
syntax. Because LabVIEW uses ActiveX technology to implement MATLAB script nodes, they are available only
on Windows.
44
8 WHATS NEXT?
8.1 MY BLOG
For more information about LabVIEW, visit my Blog: http://home.hit.no/~hansha/
8.2 TRAINING
This Training is a part of a series with other Training Kits I have made, such as:
Introduction to LabVIEW
Data Acquisition in LabVIEW
Control and Simulation in LabVIEW
LabVIEW MathScript
Linear Algebra in LabVIEW
Datalogging and Supervisory Control in LabVIEW
Wireless Data Acquisition in LabVIEW
Intermediate Topics in LabVIEW
Advanced Topics in LabVIEW
These Training Kits are available for download from my blog: http://home.hit.no/~hansha
8.3 MATHSCRIPT FUNCTIONS
In the Help system there is detailed information about all the MathScript functions available. In addition to the
MathScript RT Module functions, different add-on modules and toolkits installs additional functions. The
LabVIEW Control Design and Simulation Module and LabVIEW Digital Filter Design Toolkit install lots of
additional functions.
http://home.hit.no/~hansha/
http://home.hit.no/~hansha
45 MathScript Node
Tutorial: LabVIEW MathScript
46
QUICK REFERENCE
47 Quick Reference
Tutorial: LabVIEW MathScriptTelemark University College
Faculty of Technology
Kjølnes Ring 56
N-3914 Porsgrunn, Norway
www.hit.no
Hans-Petter Halvorsen, M.Sc.
Telemark University College
Department of Electrical Engineering, Information Technology and Cybernetics
Phone: +47 3557 5158
E-mail: hans.p.halvorsen@hit.no
Blog: http://home.hit.no/~hansha/
Room: B-237a
http://www.hit.no/
mailto:hans.p.halvorsen@hit.no
http://home.hit.no/~hansha/
Telemark University College
Department of Electrical Engineering, Information Technology and Cybernetics
Faculty of Technology, Postboks 203, Kjølnes ring 56, N-3901 Porsgrunn, Norway. Tel: +47 35 57 50 00 Fax: +47 35 57 54 01
DATA ACQUISITION IN LABVIEW
HANS-PETTER HALVORSEN, 2010.02.09
PREFACE
This tutorial explains the basic concepts of a Data Acquisition in LabVIEW.
You should have some basic knowledge about LabVIEW, e.g., the “Introduction to LabVIEW” tutorial. This
document is available for download at http://home.hit.no/~hansha/.
For more information about LabVIEW, visit: http://home.hit.no/~hansha/?page=labview.
http://home.hit.no/~hansha/
http://home.hit.no/~hansha/?page=labview
3
INSTALLATION REQUIREMENTS
NI LabVIEW
Name Required
LabVIEW Professional Development System Yes
NI LabVIEW Core Components
Name Required
LabVIEW Control Design and Simulation Module
LabVIEW MathScript RT Module
NI Vision Development Module
Vision Builder for Automated Inspection
LabVIEW Digital Filter Design Toolkit
LabVIEW Modulation Toolkit
LabVIEW System Identification Toolkit
LabVIEW Desktop Execution Trace Toolkit
LabVIEW Report Generation for Microsoft Office Toolkit
LabVIEW Database Connectivity Toolkit
LabVIEW Internet Toolkit
NI LabVIEW SignalExpress
LabVIEW Basics 1 and 2 Computer Based Training
Extended Development Suite Components
Name Required
LabWindows/CVI Full Development System
LabWindows/CVI Real-Time Module
LabWindows/CVI PID Control Toolkit
LabWindows/CVI Signal Processing Toolkit
LabWindows/CVI Spectral Measurements Toolkit and Run-time Engine
LabWindows/CVI SQL Toolkit
Measurement Studio Enterprise Edition
DIAdem Professional
Control and Embedded Systems Option Components
Name Required
LabVIEW FPGA Module
LabVIEW Real-Time Module
LabVIEW Statechart Module
LabVIEW Mobile Module
LabVIEW Datalogging and Supervisory Control Module
LabVIEW PID and Fuzzy Logic Toolkit
NI Real-Time Execution Trace Toolkit
LabVIEW Simulation Interface Toolkit
NI Motion Assistant
NI-DAQ Base
Signal processing and Communications Option Components
Name Required
LabVIEW FPGA Module
LabVIEW Sound and Vibration Measurement Suite
LabVIEW Spectral Measurement Toolkit
LabVIEW Advanced Signal Processing Toolkit
LabVIEW Adaptive Filter Toolkit
NI Device Drivers
Name Required
FieldPoint
NI-DAQmx Yes
NI LabVIEW SignalExpress
NI Instrument I/O Assistant
NI-IMAQ
NI Measurement & Automation Explorer Yes
NI PXI
NI-VISA Yes
vi
TABLE OF CONTENTS
Preface .................................................................................................................................................................... 2
Installation Requirements ....................................................................................................................................... 3
Table of Contents .................................................................................................................................................... vi
1 Introduction to LabVIEW ............................................................................................................................... 1
1.1 Dataflow programming.......................................................................................................................... 1
1.2 Graphical programming ......................................................................................................................... 1
1.3 Benefits .................................................................................................................................................. 2
2 Introduction to Data Acquisition ................................................................................................................... 3
2.1 Introduction to DAQ - Data Acquisition ................................................................................................. 3
2.1.1 Physical input/output signals ........................................................................................................ 4
2.1.2 DAQ device/hardware .................................................................................................................. 4
2.1.3 Driver software ............................................................................................................................. 5
2.1.4 Your software application (Application software) ........................................................................ 5
2.2 MAX – Measurement and Automation Explorer ................................................................................... 6
2.3 NI-DAQmx .............................................................................................................................................. 7
2.3.1 DAQ Assistant ............................................................................................................................... 7
2.4 NI USB-6008 ........................................................................................................................................... 8
3 Physical input/output signals ........................................................................................................................ 9
3.1 Transducers ........................................................................................................................................... 9
3.2 Signals .................................................................................................................................................. 10
3.2.1 Analog Signals ............................................................................................................................ 10
3.3 Digital Signals ....................................................................................................................................... 11
4 MAX ............................................................................................................................................................. 13
5 NI-DAQmx .................................................................................................................................................... 15
5.1.1 DAQ Assistant ............................................................................................................................. 16
5.2 Simulating a DAQ Device ..................................................................................................................... 16
vii Table of Contents
Tutorial: Data Acquisition in LabVIEW
6 DAQ Devices ................................................................................................................................................ 18
6.1 Performing Analog-to-Digital Conversion ............................................................................................ 19
6.2 Performing Digital-to-Analog Conversion ............................................................................................ 19
6.3 Using Counters .................................................................................................................................... 19
6.4 Using Digital I/O ...................................................................................................................................19
7 NI USB 6008 ................................................................................................................................................. 20
7.1 Connect NI USB-6008 to the PC ........................................................................................................... 20
7.1.1 Testing the USB-6008 in MAX ..................................................................................................... 20
7.2 Using NI USB-6008 in LabVIEW ............................................................................................................ 26
7.3 DAQ Assistant ...................................................................................................................................... 27
7.3.1 Analog Input ................................................................................................................................ 27
7.3.2 Analog Output ............................................................................................................................. 34
8 Whats Next? ................................................................................................................................................ 37
8.1 My Blog ................................................................................................................................................ 37
8.2 Training ................................................................................................................................................ 37
8.3 Additional Resources ........................................................................................................................... 37
8.4 Examples .............................................................................................................................................. 37
8.5 Documentation .................................................................................................................................... 38
8.6 LabVIEW Wiki....................................................................................................................................... 38
8.7 lABview ON yOUtUBE .......................................................................................................................... 39
Quick Reference .................................................................................................................................................... 40
1
1 INTRODUCTION TO LABVIEW
LabVIEW (short for Laboratory Virtual Instrumentation Engineering Workbench) is a platform and development
environment for a visual programming language from National Instruments. The graphical language is named
"G". Originally released for the Apple Macintosh in 1986, LabVIEW is commonly used for data acquisition,
instrument control, and industrial automation on a variety of platforms including Microsoft Windows, various
flavors of UNIX, Linux, and Mac OS X. The latest version of LabVIEW is version LabVIEW 2009, released in
August 2009. Visit National Instruments at www.ni.com.
The code files have the extension “.vi”, which is a abbreviation for “Virtual Instrument”. LabVIEW offers lots of
additional Add-Ons and Toolkits.
This paper is part of a series with LabVIEW Tutorials:
Introduction to LabVIEW
Data Acquisition in LabVIEW
Control and Simulation in LabVIEW
LabVIEW MathScript
Linear Algebra in LabVIEW
Datalogging and Supervisory Control in LabVIEW
Wireless Data Acquisition in LabVIEW
Intermediate Topics in LabVIEW
Advanced Topics in LabVIEW
Etc.
Each tutorial may be used independently of each other.
1.1 DATAFLOW PROGRAMMING
The programming language used in LabVIEW, also referred to as G, is a dataflow programming language.
Execution is determined by the structure of a graphical block diagram (the LV-source code) on which the
programmer connects different function-nodes by drawing wires. These wires propagate variables and any
node can execute as soon as all its input data become available. Since this might be the case for multiple nodes
simultaneously, G is inherently capable of parallel execution. Multi-processing and multi-threading hardware is
automatically exploited by the built-in scheduler, which multiplexes multiple OS threads over the nodes ready
for execution.
1.2 GRAPHICAL PROGRAMMING
LabVIEW ties the creation of user interfaces (called front panels) into the development cycle. LabVIEW
programs/subroutines are called virtual instruments (VIs). Each VI has three components: a block diagram, a
front panel, and a connector panel. The last is used to represent the VI in the block diagrams of other, calling
VIs. Controls and indicators on the front panel allow an operator to input data into or extract data from a
running virtual instrument. However, the front panel can also serve as a programmatic interface. Thus a virtual
instrument can either be run as a program, with the front panel serving as a user interface, or, when dropped
as a node onto the block diagram, the front panel defines the inputs and outputs for the given node through
the connector pane. This implies each VI can be easily tested before being embedded as a subroutine into a
larger program.
http://www.ni.com/
2 Introduction to LabVIEW
Tutorial: Data Acquisition in LabVIEW
The graphical approach also allows non-programmers to build programs simply by dragging and dropping
virtual representations of lab equipment with which they are already familiar. The LabVIEW programming
environment, with the included examples and the documentation, makes it simple to create small applications.
This is a benefit on one side, but there is also a certain danger of underestimating the expertise needed for
good quality "G" programming. For complex algorithms or large-scale code, it is important that the
programmer possess an extensive knowledge of the special LabVIEW syntax and the topology of its memory
management. The most advanced LabVIEW development systems offer the possibility of building stand-alone
applications. Furthermore, it is possible to create distributed applications, which communicate by a
client/server scheme, and are therefore easier to implement due to the inherently parallel nature of G-code.
1.3 BENEFITS
One benefit of LabVIEW over other development environments is the extensive support for accessing
instrumentation hardware. Drivers and abstraction layers for many different types of instruments and buses
are included or are available for inclusion. These present themselves as graphical nodes. The abstraction layers
offer standard software interfaces to communicate with hardware devices. The provided driver interfaces save
program development time. The sales pitch of National Instruments is, therefore, that even people with limited
coding experience can write programs and deploy test solutions in a reduced time frame when compared to
more conventional or competing systems. A new hardware driver topology (DAQmxBase), which consists
mainly of G-coded components with only a few register calls through NI Measurement Hardware DDK (Driver
Development Kit) functions, provides platform independent hardware access to numerous data acquisition and
instrumentation devices. The DAQmxBase driver is available for LabVIEW on Windows, Mac OS X and Linux
platforms.
3
2 INTRODUCTION TO DATA ACQUISITION
This chapter explains the basic concepts of using DAQ in LabVIEW.
Topics:
Introduction to DAQ - Data Acquisition
MAX – Measurement and Automation Explorer
NI-DAQmx
LabVIEW is very powerful when it comes to creating DAQ applications. LabVIEW includes a set of VIs that let
you configure, acquire data from, and send data to DAQ devices. Often, one device can perform a variety of
functions, such as analog-to-digital (A/D) conversion, digital-to-analog (D/A) conversion, digitalI/O, and
counter/timer operations. Each device supports different DAQ and signal generation speeds. Also, each DAQ
device is designed for specific hardware, platforms and operating systems.
National Instruments, the inventor of LabVIEW, also make DAQ devices, so the integration with the DAQ
devices from NI and the LabVIEW software is seamless and makes it easy to do I/O operations from the
LabVIEW environment.
2.1 INTRODUCTION TO DAQ - DATA ACQUISITION
The purpose of data acquisition is to measure an electrical or physical phenomenon such as voltage, current,
temperature, pressure, or sound. PC-based data acquisition uses a combination of modular hardware,
application software, and a computer to take measurements. While each data acquisition system is defined by
its application requirements, every system shares a common goal of acquiring, analyzing, and presenting
information. Data acquisition systems incorporate signals, sensors, actuators, signal conditioning, data
acquisition devices, and application software.
So summing up, Data Acquisition is the process of:
Acquiring signals from real-world phenomena
Digitizing the signals
Analyzing, presenting and saving the data
The DAQ system has the following parts involved, see Figure:
4 Introduction to Data Acquisition
Tutorial: Data Acquisition in LabVIEW
The parts are:
Physical input/output signals
DAQ device/hardware
Driver software
Your software application (Application software)
For an Introduction to Data Acquisition, see this webcast: http://zone.ni.com/wv/app/doc/p/id/wv-169
2.1.1 PHYSICAL INPUT/OUTPUT SIGNALS
A physical input/output signal is typically a voltage or current signal.
2.1.2 DAQ DEVICE/HARDWARE
DAQ hardware acts as the interface between the computer and the outside world. It primarily functions as a
device that digitizes incoming analog signals so that the computer can interpret them
A DAQ device (Data Acquisition Hardware) usually has these functions:
Analog input
Analog output
Digital I/O
Counter/timers
We have different DAQ devices, such as:
“Desktop DAQ devices” where you need to plug a PCI DAQ board into your computer. The software is
running on a computer.
“Portable DAQ devices” for connection to the USB port, Wi-Fi connections, etc. The software is
running on a computer
“Distributed DAQ devices” where the software is developed on your computer and then later
downloaded to the distributed DAQ device.
http://zone.ni.com/wv/app/doc/p/id/wv-169
5 Introduction to Data Acquisition
Tutorial: Data Acquisition in LabVIEW
2.1.3 DRIVER SOFTWARE
Driver software is the layer of software for easily communicating with the hardware. It forms the middle layer
between the application software and the hardware. Driver software also prevents a programmer from having
to do register-level programming or complicated commands in order to access the hardware functions.
Driver software from National Instruments:
NI-DAQmx
NI-DAQmx Base
The DAQ Assistant, included with NI-DAQmx, is a graphical, interactive guide for configuring, testing, and
acquiring measurement data. With a single click, you can even generate code based on your configuration,
making it easier and faster to develop complex operations. Because DAQ Assistant is completely menu-driven,
you will make fewer programming errors and drastically decrease the time from setting up your DAQ system to
taking your first measurement.
NI-DAQmx Base offers a subset of NI-DAQmx functionality on Windows and Linux, Mac OS X, Windows Mobile
and Windows CE.
2.1.4 YOUR SOFTWARE APPLICATION (APPLICATION SOFTWARE)
Application software adds analysis and presentation capabilities to the driver software. Your software
application normally does such tasks as:
Real-time monitoring
Data analysis
Data logging
Control algorithms
Human machine interface (HMI)
6 Introduction to Data Acquisition
Tutorial: Data Acquisition in LabVIEW
In order to create your DAQ application you need a programming development tool, such as LabVIEW.
2.2 MAX – MEASUREMENT AND AUTOMATION EXPLORER
Measurement & Automation Explorer (MAX) provides access to your National Instruments devices and
systems.
With MAX, you can:
Configure your National Instruments hardware and software
Create and edit channels, tasks, interfaces, scales, and virtual instruments
Execute system diagnostics
View devices and instruments connected to your system
Update your National Instruments software
In addition to the standard tools, MAX can expose item-specific tools you can use to configure, diagnose, or
test your system, depending on which NI products you install. As you navigate through MAX, the contents of
the application menu and toolbar change to reflect these new tools.
7 Introduction to Data Acquisition
Tutorial: Data Acquisition in LabVIEW
2.3 NI-DAQMX
The NI-DAQmx Driver software is the layer of software for easily communicating with the hardware. It forms
the middle layer between the application software and the hardware. Driver software also prevents a
programmer from having to do register-level programming or complicated commands in order to access the
hardware functions.
The DAQmx palette in LabVIEW:
2.3.1 DAQ ASSISTANT
The DAQ Assistant, included with NI-DAQmx, is a graphical, interactive guide for configuring, testing, and
acquiring measurement data. With a single click, you can even generate code based on your configuration,
making it easier and faster to develop complex operations. Because DAQ Assistant is completely menu-driven,
8 Introduction to Data Acquisition
Tutorial: Data Acquisition in LabVIEW
you will make fewer programming errors and drastically decrease the time from setting up your DAQ system to
taking your first measurement.
2.4 NI USB-6008
NI USB-6008 is a simple and low-cost multifunction I/O device from National Instruments.
The device has the following specifications:
8 analog inputs (12-bit, 10 kS/s)
2 analog outputs (12-bit, 150 S/s)
12 digital I/O
USB connection, No extra power-supply neeeded
Compatible with LabVIEW, LabWindows/CVI, and Measurement Studio for Visual Studio .NET
NI-DAQmx driver software
The NI USB-6008 is well suited for education purposes due to its small size and easy USB connection.
9
3 PHYSICAL INPUT/OUTPUT SIGNALS
Data acquisition involves gathering signals from measurement sources and digitizing the signal for storage,
analysis, and presentation on a PC. Data acquisition (DAQ) systems come in many different PC technology
forms for great flexibility when choosing your system. Scientists and engineers can choose from PCI, PXI, PCI
Express, PXI Express, PCMCIA, USB, Wireless and Ethernet data acquisition for test, measurement, and
automation applications. There are five components to be considered when building a basic DAQ system
Transducers and sensors
Signals
Signal conditioning
DAQ hardware
Driver and application software
In this chapter we focus on Transducers, sensors and Signals.
3.1 TRANSDUCERS
Data acquisition begins with the physical phenomenon to be measured. This physical phenomenon could be he
temperature of a room, the intensity of a light source, the pressure inside a chamber, the force applied to an
object, or many other things. An effective DAQ system can measure all of these different phenomena.
A transducer is a device that converts a physical phenomenon into a measurable electrical signal, such as
voltage or current. The ability of a DAQ system to measure different phenomena depends on the transducers
to convert the physical phenomena into signals measurable by the DAQ hardware. Transducers are
synonymous with sensors in DAQ systems. There are specific transducers for many different applications, such
as measuring temperature,pressure, or fluid flow. Below we see some common phenomena and the
transducers used to measure them.
Phenomenon Transducer
Temperature Thermocouple, RTD, Thermistor
Light Photo Sensor
Sound Microphone
Force and Pressure Strain Gage, Piezoelectric Transducer
Position and Displacement Potentiometer, LVDT, Optical Encoder
Acceleration Accelerometer
pH pH Electrode
Different transducers have different requirements for converting phenomena into a measurable signal. Some
transducers may require excitation in the form of voltage or current. Other transducers may require additional
components and even resistive networks to produce a signal.
10 Physical input/output signals
Tutorial: Data Acquisition in LabVIEW
Refer to ni.com/sensors for more information on transducers.
3.2 SIGNALS
The appropriate transducers convert physical phenomena into measurable signals. However, different signals
need to be measured in different ways. For this reason, it is important to understand the different types of
signals and their corresponding attributes. Signals can be categorized into two groups:
Analog
Digital
3.2.1 ANALOG SIGNALS
Analog input is the process of measuring an analog signal and transferring the measurement to a computer for
analysis, display, or storage. An analog signal is a signal that varies continuously. Analog input is most
commonly used to measure voltage or current. You can use many types of devices to perform analog input,
such as multifunction DAQ (MIO) devices, high-speed digitizers, digital multimeters, and Dynamic Signal
Acquisition (DSA) devices.
An analog signal can be at any value with respect to time. A few examples of analog signals include voltage,
temperature, pressure, sound, and load. The three primary characteristics of an analog signal is:
Level
Shape
Frequency
http://www.ni.com/sensors
11 Physical input/output signals
Tutorial: Data Acquisition in LabVIEW
Level
Because analog signals can take on any value, the level gives vital information about the measured analog
signal. The intensity of a light source, the temperature in a room, and the pressure inside a chamber are all
examples that demonstrate the importance of the level of a signal. When measuring the level of a signal, the
signal generally does not change quickly with respect to time. The accuracy of the measurement, however, is
very important. A DAQ system that yields maximum accuracy should be chosen to aid in analog level
measurements.
Shape
Some signals are named after their specific shape - sine, square, sawtooth, and triangle. The shape of an analog
signal can be as important as the level, because by measuring the shape of an analog signal, you can further
analyze the signal, including peak values, DC values, and slope. Signals where shape is of interest generally
change rapidly with respect to time, but system accuracy is still important. The analysis of heartbeats, video
signals, sounds, vibrations, and circuit responses are some applications involving shape measurements.
Frequency
All analog signals can be categorized by their frequency. Unlike the level or shape of the signal, frequency
cannot be directly measured. The signal must be analyzed using software to determine the frequency
information. This analysis is usually done using an algorithm known as the Fourier transform.
When frequency is the most important piece of information, it is important to consider including both accuracy
and acquisition speed. Although the acquisition speed for acquiring the frequency of a signal is less than the
speed required for obtaining the shape of a signal, the signal must still be acquired fast enough that the
pertinent information is not lost while the analog signal is being acquired. The condition that stipulates this
speed is known as the Nyquist Sampling Theorem. Speech analysis, telecommunication, and earthquake
analysis are some examples of common applications where the frequency of the signal must be known.
3.3 DIGITAL SIGNALS
A digital signal cannot take on any value with respect to time. Instead, a digital signal has two possible levels:
high and low. Digital signals generally conform to certain specifications that define characteristics of the signal.
Digital signals are commonly referred to as transistor-to-transistor logic (TTL). TTL specifications indicate a
12 Physical input/output signals
Tutorial: Data Acquisition in LabVIEW
digital signal to be low when the level falls within 0 to 0.8 V, and the signal is high between 2 to 5 V. The useful
information that can be measured from a digital signal includes the state and the rate.
State
Digital signals cannot take on any value with respect to time. The state of a digital signal is essentially the level
of the signal - on or off, high or low. Monitoring the state of a switch - open or closed - is a common application
showing the importance of knowing the state of a digital signal.
Rate
The rate of a digital signal defines how the digital signal changes state with respect to time. An example of
measuring the rate of a digital signal includes determining how fast a motor shaft spins. Unlike frequency, the
rate of a digital signal measures how often a portion of a signal occurs. A software algorithm is not required to
determine the rate of a signal
13
4 MAX
Measurement & Automation Explorer (MAX) provides access to your National Instruments devices and
systems.
With MAX, you can:
Configure your National Instruments hardware and software
Create and edit channels, tasks, interfaces, scales, and virtual instruments
Execute system diagnostics
View devices and instruments connected to your system
Update your National Instruments software
In addition to the standard tools, MAX can expose item-specific tools you can use to configure, diagnose, or
test your system, depending on which NI products you install. As you navigate through MAX, the contents of
the application menu and toolbar change to reflect these new tools.
LabVIEW installs MAX to establish all devices and channel configuration parameters. MAX reads the
information the Device Manager records in the Windows Registry and assigns a logical device number to each
DAQ device.
You use the device number to refer to the device in LabVIEW. You can access MAX by selecting
Tools»Measurement & Automation Explorer in LabVIEW. This displays the primary MAX window.
14 MAX
Tutorial: Data Acquisition in LabVIEW
Before using a data acquisition board, you must confirm that the software can communicate with the board by
configuring the devices. For Windows, the Windows Configuration Manager keeps track of all the hardware
installed in the computer, including National Instruments DAQ devices. The Windows Configuration Manager
automatically detects and configures Plug & Play (PnP) devices.
Windows Configuration Manager
If you have a PnP device, such as an E Series MIO device, the Windows Configuration Manager automatically
detects and configures the device. If you have a non-PnP device, or legacy device, you must configure the
device manually using the Add New Hardware option in the Control Panel. You can verify the Windows
Configuration by accessing the Device Manager.
15
5 NI-DAQMX
Driver software is the layer of software for easily communicating with the hardware. It forms the middle layer
between the application software and the hardware. Driver software also prevents a programmer from having
to do register-level programming or complicated commands in order to access the hardware functions.
Driver software from National Instruments:
NI-DAQmx
NI-DAQmx Base
The DAQ Assistant, included with NI-DAQmx, is a graphical, interactive guide for configuring, testing, and
acquiring measurementdata. With a single click, you can even generate code based on your configuration,
making it easier and faster to develop complex operations. Because DAQ Assistant is completely menu-driven,
you will make fewer programming errors and drastically decrease the time from setting up your DAQ system to
taking your first measurement.
NI-DAQmx Base offers a subset of NI-DAQmx functionality on Windows and Linux, Mac OS X, Windows Mobile
and Windows CE.
National Instruments DAQ boards have a driver engine that communicates between the board and the
application software. There are two driver engines, NI-DAQmx and Traditional NI-DAQ. You can also use the
DAQ Assistant, an Express VI that communicates with NI-DAQmx, in LabVIEW to communicate with the DAQ
board. In addition, National Instruments provides Measurement & Automation Explorer (MAX) for configuring
DAQ boards.
The NI-DAQmx Driver software is the layer of software for easily communicating with the hardware. It forms
the middle layer between the application software and the hardware. Driver software also prevents a
programmer from having to do register-level programming or complicated commands in order to access the
hardware functions.
The DAQmx palette in LabVIEW:
16 NI-DAQmx
Tutorial: Data Acquisition in LabVIEW
5.1.1 DAQ ASSISTANT
The DAQ Assistant, included with NI-DAQmx, is a graphical, interactive guide for configuring, testing, and
acquiring measurement data. With a single click, you can even generate code based on your configuration,
making it easier and faster to develop complex operations. Because DAQ Assistant is completely menu-driven,
you will make fewer programming errors and drastically decrease the time from setting up your DAQ system to
taking your first measurement.
Scales
You can configure custom scales for your measurements using MAX. This is very useful when working with
sensors. It allows you to bring a scaled value into your application without having to work directly with the raw
values. For example, you can use a temperature sensor that represents temperature with a voltage. The
conversion equation for the temperature is, Voltage x 100 = Celsius. After a scale is set, you can use it in your
application program, providing the temperature value, rather than the voltage.
Using Task Timing
When performing analog input, the task can be timed to:
Acquire 1 Sample
Acquire n Samples
Acquire Continuosly
Performing Task Triggering
When a device controlled by NI-DAQmx does something, it performs an action. Two very common actions are
producing a sample and starting a generation. Every NI-DAQmx action needs a stimulus or cause. When the
stimulus occurs, the action is performed. Causes for actions are called triggers. A start trigger starts the
generation.
5.2 SIMULATING A DAQ DEVICE
You can create NI-DAQmx simulated devices in NI-DAQmx 7.4 or later. Using NI-DAQmx simulated devices:
17 NI-DAQmx
Tutorial: Data Acquisition in LabVIEW
You can try NI products in your application without the hardware.
Later, when you acquire the hardware, you can import the NI-DAQmx simulated device configuration to the
physical device using the MAX Portable Configuration Wizard.
You can work on your applications on a portable system and upon returning to the original system, you can
easily import your application work.
Creating NI-DAQmx Simulated Devices
To create an NI-DAQmx simulated device, right-click Devices and Interfaces and select Create New. The Create
New dialog box prompts you to select a device to add. Select NI-DAQmx Simulated Device and click Finish. In
the Choose Device dialog box, select the family of devices for the device you want to simulate. Select the
device and click OK. If you select a PXI device, you are prompted to select a chassis number and PXI slot
number. If you select an SCXI chassis, the SCXI configuration panels open.
18
6 DAQ DEVICES
DAQ hardware acts as the interface between the computer and the outside world. It primarily functions as a
device that digitizes incoming analog signals so that the computer can interpret them
A DAQ device (Data Acquisition Hardware) usually has these functions:
Analog input
Analog output
Digital I/O
Counter/timers
We have different DAQ devices, such as:
“Desktop DAQ devices” where you need to plug a PCI DAQ board into your computer. The software is
running on a computer.
“Portable DAQ devices” for connection to the USB port, Wi-Fi connections, etc. The software is
running on a computer
“Distributed DAQ devices” where the software is developed on your computer and then later
downloaded to the distributed DAQ device.
Most DAQ devices have four standard elements: analog input, analog output, digital I/O, and counters. The
DAQ device transfers the measured signals to a computer through different bus structures. For example, you
can plug a DAQ device into the PCI bus or the USB port of a computer or the Personal Computer Memory Card
International Association (PCMCIA) socket of a laptop. You also can use PXI/CompactPCI to create a portable,
versatile, and rugged measurement system.
19 DAQ Devices
Tutorial: Data Acquisition in LabVIEW
6.1 PERFORMING ANALOG-TO-DIGITAL CONVERSION
Analog-to-digital conversion is a process of acquiring and translating signals into digital data so that a computer
can process it. Analog-to-digital converters (ADCs) are circuit components that convert a voltage level into a
series of ones and zeroes. ADCs sample the analog signal on each rising or falling edge of a sample clock. In
each cycle, the ADC takes a snapshot of the analog signal, measures and converts it into a digital value. The
ADC obtains and approximates the signal with fixed precision and converts it into a series of digital values.
6.2 PERFORMING DIGITAL-TO-ANALOG CONVERSION
Digital-to-analog conversion is the opposite of analog-to-digital conversion. In digital-to-analog conversion, the
computer generates the data.
6.3 USING COUNTERS
A counter is a digital timing device. You typically use counters for event counting, frequency measurement,
period measurement, position measurement, and pulse generation.
6.4 USING DIGITAL I/O
Digital signals are electrical signals that transfer digital data over a wire. These signals typically have only two
states: on and off, also known as high and low, or 1 and 0. When sending a digital signal across a wire, the
sender applies a voltage to the wire and the receiver uses the voltage level to determine the value being sent.
The voltage ranges for each digital value depend on the voltage level standard being used.
Digital signals have many users:
Digital signals control or measure digital devices such as switches or LEDs
20
7 NI USB 6008
NI USB-6008 is a simple and low-cost multifunction I/O device from National Instruments.
The device has the following specifications:
8 analog inputs (12-bit, 10 kS/s)
2 analog outputs (12-bit, 150 S/s)
12 digital I/O
USB connection, No extra power-supply neeeded
Compatible with LabVIEW, LabWindows/CVI, and Measurement Studio for Visual Studio .NET
NI-DAQmx driver software
The NI USB-6008 is well suited for education purposes due to its small size and easy USB connection.
7.1 CONNECT NI USB-6008 TO THE PC
Configuring and testing: USB-6008 can be configured and tested using MAX (Measurement and Automation
Explorer), which is installed with the NI-DAQmx Driver Software.
The first time you connect the USB-6008 to the PC, the Windows Hardware Installer Wizard will open.
The wizard searches the PC for the necessary driver software for the USB-6008. This driver software was
installed along with the installation of the NI-DAQ software. When the wizard has finished the installation of
the driver software, the USB-6008 is ready foruse.
7.1.1 TESTING THE USB-6008 IN MAX
Before you start to use the USB-6008 in an application, you should test the device in the Measurement and
Automation Explorer (MAX).
21 NI USB 6008
Tutorial: Data Acquisition in LabVIEW
In the MAX window, expand the “Devices and Interfaces” node and then “NI DAQmx Devices”. Right-click on
the NI USB-6008 device and select “Self-Test”.
Hopefully the self-test passes without errors. Then, you should test the individual channels of the USB-6008 to
check that the input signals are detected correctly by the USB-6008, and that the output signals generated by
the USB-6009 have correct values. This I/O can be tested in several ways, depending on which channels you
actually want to test.
22 NI USB 6008
Tutorial: Data Acquisition in LabVIEW
We will perform a simple loopback test:
Here, let us test analog output channel 0 (AO0) and the analog input channel 0 (AI0) to see if they work
correctly. We will perform a very simple test, which is sufficient if we are to check that both AO0 and AI0 work
correctly. The test procedure, which is denoted loopback, is to connect the AI0 channel to the AO0 channel.
Then we generate some legal voltage at AO0. If AI0 detects the same voltage, we know that both AO0 and AI0
work. (We may then repeat this procedure for other channels.) If for some reason AI0 detects some other
voltage than the value we set for AO0, then there is an error in either the AI0 channel or in the the AO0
channel, and further investigations are necessary.
To prepare for the loopback test, we wire together AI0 and AO0. To see the terminals of the USB-6000, select
“Device Pinouts” from the right-click menu.
The Figure shows the AI0 and AO0 channels wired together.
23 NI USB 6008
Tutorial: Data Acquisition in LabVIEW
To actually perform the loopback test, right-click on the NI USB-6008 device in MAX, and then select “Test
Panels..” in order to open the Test Panels. In the Test Panels window, select the Analog Output tab.
24 NI USB 6008
Tutorial: Data Acquisition in LabVIEW
Figure 11: The Voltage Output dialog window in the Test Panels window
In the Analog Output tab, select any voltage between 0V and 5V.
Next, click the Analog Input tab in the Test Panels window.
25 NI USB 6008
Tutorial: Data Acquisition in LabVIEW
The Analog Input tab should indicate the same (or almost the same) voltage as is set out on AO0. There may be
a small difference between the values due to the limited resolution in the DA-converter (digital-to-analog) and
in the AD-converter (analog-to-digital).
26 NI USB 6008
Tutorial: Data Acquisition in LabVIEW
7.2 USING NI USB-6008 IN LABVIEW
In order to use the NI USB-6008 in LabVIEW you need to use the DAQmx functions, see Figure below.
DAQmx – Data Acquisition palette:
27 NI USB 6008
Tutorial: Data Acquisition in LabVIEW
7.3 DAQ ASSISTANT
The easiest ways is to use the DAQ Assistant.
7.3.1 ANALOG INPUT
When you drag the DAQ Assistant icon on your Block Diagram, the following window appears:
28 NI USB 6008
Tutorial: Data Acquisition in LabVIEW
In this window you need to select either “Acquire Signals” (i.e., Input Signals) or “Generate Signals” (i.e., Output
Signals).
Select Acquire Signals → Analog Input → Voltage.
In the next window you select which Analog Input you want to use. Select ai0 (Analog Input channel 0) and click
Finish.
29 NI USB 6008
Tutorial: Data Acquisition in LabVIEW
The following window appears:
30 NI USB 6008
Tutorial: Data Acquisition in LabVIEW
In the Timing Settings Select “1 Sample (On Demand)”.
31 NI USB 6008
Tutorial: Data Acquisition in LabVIEW
The next step is to select the Signal Input Range. A common signal is 0-5V.
You may also rename the name of the channel (right-click on the name):
32 NI USB 6008
Tutorial: Data Acquisition in LabVIEW
You are now finished with the configuration. Click OK in the DAQ Assistant window The DAQ Assistant icon
appears on the Block Diagram:
Example:
33 NI USB 6008
Tutorial: Data Acquisition in LabVIEW
Wire the data output to a numeric indicator like this (and hit the Run button):
Then numeric indicator will show, e.g., the following value:
Example:
If you want a continuous acquisition, put a While loop around the DAQ Assistant like this:
However you should not use the DAQ Assistant inside a loop because of the lack of performance. The following
is therefore better:
34 NI USB 6008
Tutorial: Data Acquisition in LabVIEW
In this example we have put the DAQ Assistant outside the While loop. Inside the loop we have used the
DAQmx Read.vi in order to read the value from the ai0 channel.
You should also use the “DAQmx Start Task.vi” and the “DAQmx Clear Task.vi”.
7.3.2 ANALOG OUTPUT
Analog Output is similar.
35 NI USB 6008
Tutorial: Data Acquisition in LabVIEW
36 NI USB 6008
Tutorial: Data Acquisition in LabVIEW
Example:
Or inside a loop:
Or better, put the DAQ Assistant outside the While loop:
37
8 WHATS NEXT?
8.1 MY BLOG
For more information about LabVIEW, visit my Blog: http://home.hit.no/~hansha/
8.2 TRAINING
This Training is a part of a series with other Training Kits I have made, such as:
Introduction to LabVIEW
Data Acquisition in LabVIEW
Control and Simulation in LabVIEW
LabVIEW MathScript
Linear Algebra in LabVIEW
Datalogging and Supervisory Control in LabVIEW
Wireless Data Acquisition in LabVIEW
Intermediate Topics in LabVIEW
Advanced Topics in LabVIEW
These Training Kits are available for download from my blog: http://home.hit.no/~hansha
8.3 ADDITIONAL RESOURCES
www.ni.com
8.4 EXAMPLES
In the NI example Finder (Help→Find Examples…) you find lots of useful examples that you can play with or use
as a start when creating your own applications.
http://home.hit.no/~hansha/
http://home.hit.no/~hansha
http://www.ni.com/
38 Whats Next?
Tutorial: Data Acquisition in LabVIEW
8.5 DOCUMENTATION
As part of the LabVIEW installation there comes a lots of useful documentation.
8.6 LABVIEW WIKI
LabVIEW Wiki is the free LabVIEW information resource that anyone can edit.
http://labviewwiki.org/Home
http://labviewwiki.org/Home
39 Whats Next?
Tutorial: Data Acquisition in LabVIEW
8.7 LABVIEW ON YOUTUBE
There are lots of LabVIEW videos available at YouTube:
http://www.youtube.com/results?search_query=labview&search=Search
http://www.youtube.com/results?search_query=labview&search=Search
40
QUICK REFERENCE
41 Quick Reference
Tutorial: Data Acquisition in LabVIEW
Telemark University College
Faculty of Technology
Kjølnes Ring 56
N-3914 Porsgrunn, Norway
www.hit.no
Hans-Petter Halvorsen, M.Sc.
Telemark University College
Department of Electrical Engineering, Information Technology and Cybernetics
Phone: +47 3557 5158
E-mail: hans.p.halvorsen@hit.no
Blog: http://home.hit.no/~hansha/
Room: B-237a
http://www.hit.no/
mailto:hans.p.halvorsen@hit.no
http://home.hit.no/~hansha/
Telemark University College
Department of Electrical Engineering, Information Technology and Cybernetics
Faculty of Technology, Postboks 203, Kjølnes ring 56, N-3901 Porsgrunn, Norway. Tel: +47 35 57 50 00 Fax: +47 35 57 54 01
CONTROL AND SIMULATION IN
LABVIEW
HANS-PETTER HALVORSEN, 2010.02.09
PREFACE
This document explains the basic concepts of using LabVIEW for Control and Simulation purposes.
You should have some basic knowledge about LabVIEW, e.g., the training: “An Introduction to LabVIEW”. This
document is availablefor download at http://home.hit.no/~hansha/.
For more information about LabVIEW, visit my Blog: http://home.hit.no/~hansha/.
http://home.hit.no/~hansha/
http://home.hit.no/~hansha/
iii
INSTALLATION REQUIREMENTS
NI LabVIEW
Name Required
LabVIEW Professional Development System Yes
NI LabVIEW Core Components
Name Required
LabVIEW Control Design and Simulation Module Yes
LabVIEW MathScript RT Module Yes
NI Vision Development Module
Vision Builder for Automated Inspection
LabVIEW Digital Filter Design Toolkit
LabVIEW Modulation Toolkit
LabVIEW System Identification Toolkit Yes
LabVIEW Desktop Execution Trace Toolkit
LabVIEW Report Generation for Microsoft Office Toolkit
LabVIEW Database Connectivity Toolkit
LabVIEW Internet Toolkit
NI LabVIEW SignalExpress
LabVIEW Basics 1 and 2 Computer Based Training
Extended Development Suite Components
Name Required
LabWindows/CVI Full Development System
LabWindows/CVI Real-Time Module
LabWindows/CVI PID Control Toolkit
LabWindows/CVI Signal Processing Toolkit
LabWindows/CVI Spectral Measurements Toolkit and Run-time Engine
LabWindows/CVI SQL Toolkit
Measurement Studio Enterprise Edition
DIAdem Professional
Control and Embedded Systems Option Components
Name Required
LabVIEW FPGA Module
LabVIEW Real-Time Module
LabVIEW Statechart Module
LabVIEW Mobile Module
LabVIEW Datalogging and Supervisory Control Module
LabVIEW PID and Fuzzy Logic Toolkit Yes
NI Real-Time Execution Trace Toolkit
LabVIEW Simulation Interface Toolkit (Yes)
NI Motion Assistant
NI-DAQ Base
Signal processing and Communications Option Components
Name Required
LabVIEW FPGA Module
LabVIEW Sound and Vibration Measurement Suite
LabVIEW Spectral Measurement Toolkit
LabVIEW Advanced Signal Processing Toolkit
LabVIEW Adaptive Filter Toolkit
NI Device Drivers
Name Required
FieldPoint
NI-DAQmx Yes
NI LabVIEW SignalExpress
NI Instrument I/O Assistant
NI-IMAQ
NI Measurement & Automation Explorer Yes
NI PXI
NI-VISA Yes
vi
TABLE OF CONTENTS
Preface .................................................................................................................................................................... 2
Installation Requirements ....................................................................................................................................... iii
Table of Contents .................................................................................................................................................... vi
1 Introduction to LabVIEW ............................................................................................................................... 1
1.1 Dataflow programming.......................................................................................................................... 1
1.2 Graphical programming ......................................................................................................................... 1
1.3 Benefits .................................................................................................................................................. 2
2 Introduction to Control and Simulation ........................................................................................................ 3
3 Introduction to Control and Simulation in LabVIEW ..................................................................................... 4
3.1 LabVIEW Control Design and Simulation Module ................................................................................. 4
3.1.1 Simulation ..................................................................................................................................... 4
3.1.2 Control Design .............................................................................................................................. 5
3.2 LabVIEW PID and Fuzzy Logic Toolkit .................................................................................................... 6
3.2.1 PID Control .................................................................................................................................... 6
3.2.2 Fuzzy Logic .................................................................................................................................... 6
3.3 LabVIEW System Identification Toolkit .................................................................................................. 6
3.4 LabVIEW Simulation Interface Toolkit ................................................................................................... 7
4 Simulation ...................................................................................................................................................... 8
4.1 Simulation in LabvIEW ........................................................................................................................... 8
4.2 Simulation Subsystem ......................................................................................................................... 12
4.3 Continuous Linear Systems .................................................................................................................. 13
Exercises ........................................................................................................................................................... 18
5 PID Control................................................................................................................................................... 29
5.1 PID Control in LabVIEW ....................................................................................................................... 30
5.2 Auto-tuning .......................................................................................................................................... 30
6 Control Design ............................................................................................................................................. 32
vii Table of Contents
Tutorial: Control and Simulation in LabVIEW
6.1 Control Design in LabVIEW .................................................................................................................. 32
7 System Identification ................................................................................................................................... 33
7.1 System Identification in LabVIEW ........................................................................................................ 33
8 Fuzzy Logic ................................................................................................................................................... 34
8.1 Fuzzy Logic in LabVIEW ........................................................................................................................ 34
9 LabVIEW MathScript .................................................................................................................................... 35
9.1 Help...................................................................................................................................................... 36
9.2 Examples .............................................................................................................................................. 36
9.3 Useful commands ................................................................................................................................ 39
9.4 Plotting ................................................................................................................................................ 39
10 Whats next? ................................................................................................................................................. 41
10.1 My Blog................................................................................................................................................ 41
10.2 Training ................................................................................................................................................ 41
10.3 Additional Resources ........................................................................................................................... 41
10.4 Examples .............................................................................................................................................. 41
10.5 Documentation .................................................................................................................................... 42
10.6 LabVIEW Wiki....................................................................................................................................... 42
10.7 lABview ON yOUtUBE .......................................................................................................................... 43
Quick Reference .................................................................................................................................................... 44
1
1 INTRODUCTION TO LABVIEW
LabVIEW (short for Laboratory Virtual Instrumentation Engineering Workbench) is a platform and development
environment for a visual programming language from National Instruments. The graphical language is named
"G". Originally released for the Apple Macintosh in 1986, LabVIEW is commonly used for data acquisition,
instrument control, and industrial automation on a variety of platforms including Microsoft Windows, various
flavors of UNIX, Linux, and Mac OS X. The latest version of LabVIEW is version LabVIEW 2009, released in
August 2009. Visit National Instruments at www.ni.com.
The code files have the extension “.vi”, which is a abbreviation for “Virtual Instrument”. LabVIEW offers lots of
additional Add-Ons and Toolkits.
This paper is part of a series with LabVIEW Tutorials:
Introduction to LabVIEW
Linear Algebra in LabVIEW
Data Acquisition and Instrument Control in LabVIEW
Control Design and Simulation in LabVIEW
Signal Processing in LabVIEW
Datalogging and Supervisory Control in LabVIEW
System identification in LabVIEW
Model based Control in LabVIEW
Advanced Topics in LabVIEW
Etc.
Each tutorial may be used independently of each other.
1.1 DATAFLOW PROGRAMMING
The programming language used in LabVIEW, also referred to as G, is a dataflow programming language.
Execution is determined by the structure of a graphical block diagram (the LV-source code) on which the
programmer connects different function-nodes by drawing wires. These wires propagate variables and any
node can execute as soon as all its input data become available. Since this might be the case for multiple nodes
simultaneously, G is inherently capable of parallel execution. Multi-processing and multi-threading hardware is
automatically exploited by the built-in scheduler, which multiplexes multiple OS threads over the nodes ready
for execution.
1.2 GRAPHICAL PROGRAMMING
LabVIEW ties the creation of user interfaces (called front panels) into the development cycle. LabVIEW
programs/subroutines are called virtual instruments (VIs). Each VI has three components: a block diagram, a
front panel, and a connector panel. The last is used to represent the VI in the block diagrams of other, calling
VIs. Controls and indicators on the front panel allow an operator to input data into or extract data from a
running virtual instrument. However, the front panel can also serve as a programmatic interface. Thus a virtual
instrument can either be run as a program, with the front panel serving as a user interface, or, when dropped
as a node onto the block diagram, the front panel defines the inputs and outputs for the given node through
the connector pane. This implies each VI can be easily tested before being embedded as a subroutine into a
larger program.
http://www.ni.com/
2 Introduction to LabVIEW
Tutorial: Control and Simulation in LabVIEW
The graphical approach also allows non-programmers to build programs simply by dragging and dropping
virtual representations of lab equipment with which they are already familiar. The LabVIEW programming
environment, with the included examples and the documentation, makes it simple to create small applications.
This is a benefit on one side, but there is also a certain danger of underestimating the expertise needed for
good quality "G" programming. For complex algorithms or large-scale code, it is important that the
programmer possess an extensive knowledge of the special LabVIEW syntax and the topology of its memory
management. The most advanced LabVIEW development systems offer the possibility of building stand-alone
applications. Furthermore, it is possible to create distributed applications, which communicate by a
client/server scheme, and are therefore easier to implement due to the inherently parallel nature of G-code.
1.3 BENEFITS
One benefit of LabVIEW over other development environments is the extensive support for accessing
instrumentation hardware. Drivers and abstraction layers for many different types of instruments and buses
are included or are available for inclusion. These present themselves as graphical nodes. The abstraction layers
offer standard software interfaces to communicate with hardware devices. The provided driver interfaces save
program development time. The sales pitch of National Instruments is, therefore, that even people with limited
coding experience can write programs and deploy test solutions in a reduced time frame when compared to
more conventional or competing systems. A new hardware driver topology (DAQmxBase), which consists
mainly of G-coded components with only a few register calls through NI Measurement Hardware DDK (Driver
Development Kit) functions, provides platform independent hardware access to numerous data acquisition and
instrumentation devices. The DAQmxBase driver is available for LabVIEW on Windows, Mac OS X and Linux
platforms.
3
2 INTRODUCTION TO CONTROL AND SIMULATION
Control design is a process that involves developing mathematical models that describe a physical system,
analyzing the models to learn about their dynamic characteristics, and creating a controller to achieve certain
dynamic characteristics.
Simulation is a process that involves using software to recreate and analyze the behavior of dynamic systems.
You use the simulation process to lower product development costs by accelerating product development. You
also use the simulation process to provide insight into the behavior of dynamic systems you cannot replicate
conveniently in the laboratory.
Below we see a closed-loop feedback control system:
4
3 INTRODUCTION TO CONTROL AND SIMULATION IN LABVIEW
LabVIEW has several additional modules and Toolkits for Control and Simulation purposes, e.g., “LabVIEW
Control Design and Simulation Module”, “LabVIEW PID and Fuzzy Logic Toolkit”, “LabVIEW System
Identification Toolkit” and “LabVIEW Simulation Interface Toolkit”. LabVIEW MathScript is also useful for
Control Design and Simulation.
LabVIEW Control Design and Simulation Module
LabVIEW PID and Fuzzy Logic Toolkit
LabVIEW System Identification Toolkit
LabVIEW Simulation Interface Toolkit
This tutorial will focus on the main aspects in these modules and toolkits.
All VIs related to these modules and toolkits are placed in the Control Design and Simulation Toolkit:
3.1 LABVIEW CONTROL DESIGN AND SIMULATION MODULE
With LabVIEW Control Design and Simulation Module you can construct plant and control models using
transfer function, state-space, or zero-pole-gain. Analyze system performance with tools such as stepresponse,
pole-zero maps, and Bode plots. Simulate linear, nonlinear, and discrete systems with a wide option of solvers.
With the NI LabVIEW Control Design and Simulation Module, you can analyze open-loop model behavior,
design closed-loop controllers, simulate online and offline systems, and conduct physical implementations.
3.1.1 SIMULATION
The Simulation palette in LabVIEW:
5 Introduction to Control and Simulation in LabVIEW
Tutorial: Control and Simulation in LabVIEW
The main features in the Simulation palette are:
Control and Simulation Loop - You must place all Simulation functions within a Control & Simulation
Loop or in a simulation subsystem.
Continuous Linear Systems Functions - Use the Continuous Linear Systems functions to represent
continuous linear systems of differential equations on the simulation diagram.
Signal Arithmetic Functions - Use the Signal Arithmetic functions to perform basic arithmetic
operations on signals in a simulation system.
3.1.2 CONTROL DESIGN
The Control Design palette in LabVIEW:
6 Introduction to Control and Simulation in LabVIEW
Tutorial: Control and Simulation in LabVIEW
3.2 LABVIEW PID AND FUZZY LOGIC TOOLKIT
The NI LabVIEW PID and Fuzzy Logic Toolkit add control algorithms to LabVIEW. By combining the PID and fuzzy
logic control functions in this toolkit with the math and logic functions in LabVIEW software, you can quickly
develop programs for automated control. You may integrate these control tools with the power of data
acquisition.
3.2.1 PID CONTROL
The PID palette in LabVIEW:
3.2.2 FUZZY LOGIC
The Fuzzy Logic palette in LabVIEW:
3.3 LABVIEW SYSTEM IDENTIFICATION TOOLKIT
The “LabVIEW System Identification Toolkit” combines data acquisition tools with system identification
algorithms for plant modeling. You can use the LabVIEW System Identification Toolkit to find empirical models
from real plant stimulus-response information.
The System Identification palette in LabVIEW:
7 Introduction to Control and Simulation in LabVIEW
Tutorial: Control and Simulation in LabVIEW
3.4 LABVIEW SIMULATION INTERFACE TOOLKIT
The “LabVIEW Simulation Interface Toolkit” gives control system design and test engineers a link between the
LabVIEW graphical development environment and Simulink software from The MathWorks. With the LabVIEW
Simulation Interface Toolkit, you can easily build custom LabVIEW user interfaces to view and control your
simulation model during run time.
The “LabVIEW Simulation Interface Toolkit” will not be further investigated in this training.
8
4 SIMULATION
Simulation is a process that involves using software to recreate and analyze the behavior of dynamic systems.
You use the simulation process to lower product development costs by accelerating product development. You
also use the simulation process to provide insight into the behavior of dynamic systems you cannot replicate
conveniently in the laboratory. For example, simulating a jet engine saves time, labor, and money compared to
building, testing, and rebuilding an actual jet engine. You can use the LabVIEW Control Design and Simulation
Module to simulate a dynamic system or a component of a dynamic system. For example, you can simulate
only the plant while using hardware for the controller, actuators, and sensors (Hardware-in-the-loop
Simulation).
A dynamic system model is a differential or difference equation that describes the behavior of the dynamic
system.
4.1 SIMULATION IN LABVIEW
Use the Simulation VIs and functions to create simulation applications in LabVIEW. In the Control Design &
Simulation palette we have the Simulation Sub palette:
Below we see the Simulation Sub palette:
9 Simulation
Tutorial: Control and Simulation in LabVIEW
Note! All the “Blocks” in the Simulation palette are not SubVIs, i.e., we cannot double-click on them and open
the Block Diagram because they have none. All the Blocks in the Simulation palette must be used inside the
Control and Simulation Loop (explained below).
Control and Simulation Loop:
In the “Simulation” Sub palette we have the “Control and Simulation Loop” which is very useful in simulations:
You must place all Simulation functions within a Control & Simulation Loop or in a simulation subsystem. You
also can place simulation subsystems within a Control & Simulation Loop or another simulation subsystem, or
you can place simulation subsystems on a block diagram outside a Control & Simulation Loop or run the
simulation subsystems as stand-alone VIs.
10 Simulation
Tutorial: Control and Simulation in LabVIEW
The Control & Simulation Loop has an Input Node (upper left corner) and an Output Node (upper right corner).
Use the Input Node to configure simulation parameters programmatically. You also can configure these
parameters interactively using the Configure Simulation Parameters dialog box. Access this dialog box by
double-clicking the Input Node or by right-clicking the border and selecting Configure Simulation Parameters
from the shortcut menu.
Configuration:
When you place these blocks on the diagram you may double-click or right-click and then select
“Configuration…”
Example: Configuration Dialog box
For the “Transfer Function” (Simulation → Continuous Linear Systems) block we have the following
Configuration window:
All the different blocks have their own different Configuration window.
In the Parameter source you may select between:
Configuration Dialog Box
Terminal
If you select “Configuration Dialog Box” you enter the configuration in the Configuration window like we see
above, while if you select “Terminal” that specific configuration is set from the Block Diagram like this:
11 Simulation
Tutorial: Control and Simulation in LabVIEW
Icon Style:
When you place the block on the block diagram you may select how that should appear. Right-click on the
block/icon and select “Icon Style”:
Example: Icon Style
For the “Transfer Function” (Simulation → Continuous Linear Systems) block we have the following
different icon styles:
Static:
Dynamic:
Text Only:
Express:
12 Simulation
Tutorial: Control and Simulation in LabVIEW
We see for the Dynamic and Express styles that the appearance changes according to configuration parameters
we set.
I personally prefer the “static” icon style because it does not require lots of space on the diagram.
4.2 SIMULATION SUBSYSTEM
You may create a Simulation Subsystem (File → New…):
The Simulation Subsystem is very useful when dealing with larger simulation systems in order to create a more
structured code. I recommend that you (always) use this feature.
The Simulation Subsystem is almost equal to a normal LabVIEW Block Diagram but notice the background color
is slightly darker.
Note! In order to open the Simulation Subsystem, right-click and select “Open Subsystem”.
The Simulation Subsystem may also be represented by different icons. If you select “dynamic” icon style, you
will see a “miniature” version of the subsystem like this:
13 Simulation
Tutorial: Control and Simulation in LabVIEW
You may drag in the corner in order to increase or decrease the dynamic icon.
If you select “static” icon style you see the icon you created with the Icon Editor.
Like this:
4.3 CONTINUOUS LINEAR SYSTEMS
In the “Continuous Linear Systems” Sub palette we want to create a simulation model:
The most used blocks probably are Integrator, Transport Delay, State-Space and Transfer Function.
When you place these blocks on the diagram you may double-click or right-click and then select
“Configuration…”
14 Simulation
Tutorial: Control and Simulation in LabVIEW
Integrator - Integrates a continuous input signal using the ordinary differential equation(ODE) solver
you specify for the simulation.
The Configuration window for the Integrator block looks like this:
Transport Delay - Delays the input signal by the amount of time you specify.
The Configuration window for the Transport Delay block looks like this:
Transfer Function - Implements a system model in transfer function form. You define the system model
by specifying the Numerator and Denominator of the transfer function equation.
The Configuration window for the Transfer Function block looks like this:
15 Simulation
Tutorial: Control and Simulation in LabVIEW
State-Space - Implements a system model in state-space form. You define the system model by
specifying the input, output, state, and direct transmission matrices.
The Configuration window for the State-Space block looks like this:
Signal Arithmetic:
The “Signal Arithmetic” Sub palette is also useful when creating a simulation model:
16 Simulation
Tutorial: Control and Simulation in LabVIEW
Example: Simulation Model
Below we see an example of a simulation model created in LabVIEW.
Example: Simulation
Below we see an example of a simulation model using the Control and Simulation Loop.
17 Simulation
Tutorial: Control and Simulation in LabVIEW
Notice the following:
Click on the border of the simulation loop and select “Configure Simulation Parameters…”
The following window appears (Configure Simulation Parameters):
In this window you set some Parameters regarding the simulation, some important are:
Final Time (s) – set how long the simulation should last. For an infinite time set “Inf”.
18 Simulation
Tutorial: Control and Simulation in LabVIEW
Enable Synchronized Timing - Specifies that you want to synchronize the timing of the Control &
Simulation Loop to a timing source. To enable synchronization, place a checkmark in this checkbox and
then choose a timing source from the Source type list box.
Click the Help button for more details.
You may also set some of these Parameters in the Block Diagram:
You may use the mouse to increase the numbers of Parameters and right-click and select “Select Input”.
EXERCISES
Exercise: Simulation of a spring-mass damper system
In this exercise you will construct a simulation diagram that represents the behavior of a dynamic system. You
will simulate a spring-mass damper system.
where t is the simulation time, F(t) is an external force applied to the system, c is the damping constant of the
spring, k is the stiffness of the spring, m is a mass, and x(t) is the position of the mass. is the first derivative
of the position, which equals the velocity of the mass. is the second derivative of the position, which equals
the acceleration of the mass.
The following figure shows this dynamic system.
The goal is to view the position x(t) of the mass m with respect to time t. You can calculate the position by
integrating the velocity of the mass. You can calculate the velocity by integrating the acceleration of the mass.
19 Simulation
Tutorial: Control and Simulation in LabVIEW
If you know the force and mass, you can calculate this acceleration by using Newton's Second Law of Motion,
given by the following equation:
Force = Mass × Acceleration
Therefore,
Acceleration = Force / Mass
Substituting terms from the differential equation above yields the following equation:
You will construct a simulation diagram that iterates the following steps over a period of time.
Creating the Simulation Diagram
You create a simulation diagram by placing a Control & Simulation Loop on the LabVIEW block diagram.
1. Launch LabVIEW and select File»New VI to create a new, blank VI.
2. Select Window»Show Block Diagram to view the block diagram. You also can press the <Ctrl-E> keys to
view the block diagram.
3. If you are not already viewing the Functions palette, select View»Functions Palette to display this
palette.
4. Select Control Design & Simulation»Simulation to view the Simulation palette.
5. Click the Control & Simulation Loop icon.
6. Move the cursor over the block diagram. Click to place the top left corner of the loop, drag the cursor
diagonally to establish the size of the loop, and click again to place the loop on the block diagram.
The simulation diagram is the area enclosed by the Control & Simulation Loop. Notice the simulation diagram
has a pale yellow background to distinguish it from the rest of the block diagram. You can resize the Control &
Simulation Loop by dragging its borders.
Configuring Simulation Parameters
The Control & Simulation Loop contains the parameters that define how the simulation executes. Complete the
following steps to view and configure these simulation parameters.
1. Double-click the Input Node, attached to the left side of the Control & Simulation Loop, to display the
Configure Simulation Parameters dialog box. You also can right-click the loop border and select
Configure Simulation Parameters from the shortcut menu.
2. Ensure the value of the Final Time (s) numeric control is 10, which specifies that this tutorial simulates
ten seconds of time.
3. Click the ODE Solver pull-down menu to view the list of ODE solvers the Control Design and Simulation
Module includes. If the term (variable) appears next to an ODE solver, that solver has a variable step
size. The other ODE solvers have a fixed step size. Ensure a checkmark is beside the default ODE solver
Runge-Kutta 23 (variable).
4. Because this ODE solver is a variable step-size solver, you can specify the Minimum Step Size (s) and
Maximum Step Size (s) this ODE solver can take. Enter 0.01 in the Maximum Step Size (s) numeric
control to limit the size of the time step this ODE solver can take.
5. Click the Timing Parameters tab to access parameters that control how often the simulation executes.
20 Simulation
Tutorial: Control and Simulation in LabVIEW
6. Ensure the Synchronize Loop to Timing Source checkbox does not contain a checkmark. This option
specifies that the simulation executes without any timing restrictions. Use this option when you want
the simulation to run as fast as possible. If you are running this simulation in real-time, you can place a
checkmark in this checkbox and configure how often the simulation executes.
7. Click the OK button to save changes and return to the simulation diagram.
Building the Simulation
The next step is to build the simulation by placing Simulation functions on the simulation diagram and wiring
these functions together. Note that you can place most Simulation functions only on the simulation diagram,
that is, you cannot place Simulation functions on a LabVIEW block diagram. Complete the following steps to
build the simulation of this dynamic system.
Placing Functions on the Simulation Diagram
1. Open the Simulation palette.
2. Select the Signal Arithmetic palette and place a Multiplication function on the simulation diagram.
You will use this function to divide the force by the mass to calculate the acceleration.
3. Double-click the Multiplication function to display the Multiplication Configuration dialog box. You can
double-click most Simulation functions to view and change the parameters of that function.
4. The function currently displays two × symbols on the left side of the dialog box. This setting specifies
that both incoming signals are multiplied together. Click the bottom × symbol to change it to a ÷
symbol. This Multiplication function now divides the top signal by the bottom signal.
5. Click the OK button to save changes and return to the simulation diagram.
6. Right-click the Multiplication function and select Visible Items»Label from the shortcut menu.
Double-click the Multiplication label and enter Calculate Acceleration as the new label.
7. Returnto the Simulation palette and select the Continuous Linear Systems palette.
8. Place an Integrator function on the simulation diagram. You will use this function to calculate velocity
by integrating acceleration.
9. Label this Integrator function Calculate Velocity.
10. Press the <Ctrl> key and click and drag the Integrator function to another location on the simulation
diagram. This action creates a copy of the Integrator function, which you will use to calculate position
by integrating velocity. Label this new Integrator function Calculate Position.
11. Select the Graph Utilities palette and place two SimTime Waveform functions on the simulation
diagram. You will use these functions to view the results of the simulation over time.
12. Each SimTime Waveform function has an associated Waveform Chart. Label the first waveform chart
Velocity and the second waveform chart Position.
13. Arrange the functions to look like the following simulation diagram.
14. Save this VI by selecting File»Save. Save this VI to a convenient location as “Spring-Mass Damper
Example.vi”.
The Block Diagram should now look like this:
21 Simulation
Tutorial: Control and Simulation in LabVIEW
Wiring the Simulation Functions Together
The next step is wiring the functions together to represent the flow of data from one function to another.
Note! Wires on the simulation diagram include arrows that show the direction of the dataflow, whereas wires
on a LabVIEW block diagram do not show these arrows.
Complete the following steps to wire these functions together.
1. Right-click the Operand1 input of the Calculate Acceleration function and select Create»Control from
the shortcut menu to add a numeric control to the front panel window.
2. Label this control Force.
3. Double-click this control on the simulation diagram. LabVIEW displays the front panel and highlights
the Force control.
4. Display the block diagram and create a control for the Operand2 input of the Calculate Acceleration
function. Label this new control Mass.
5. Wire the Result output of the Calculate Acceleration function to the input input of the Calculate
Velocity function.
6. Wire the output output of the Calculate Velocity function to the input input of the Calculate Position
function.
7. Right-click the wire you just created and select Create Wire Branch from the shortcut menu. Wire this
branch to the Value input of the SimTime Waveform function that has the Velocity waveform chart.
8. Wire the output output of the Calculate Position function to the Value input of the SimTime Waveform
function that has the Position waveform chart.
The Block Diagram should now look like this:
22 Simulation
Tutorial: Control and Simulation in LabVIEW
Running the Simulation
You now can run this simulation to test that the data is flowing properly through the Simulation functions.
Complete the following steps to run this simulation.
1. Select Window»Show Front Panel, or press <Ctrl-E>, to view the front panel of this simulation. The
front panel displays the following objects: a control labeled Force, a control labeled Mass, a waveform
chart labeled Velocity, and a waveform chart labeled Position.
2. If necessary, rearrange these controls and indicators so that all objects are visible.
3. Enter -9.8 in the Force numeric control. This value represents the force of gravity, 9.8 meters per
second squared, acting on the dynamic system.
4. Enter 1 in the Mass numeric control. This value represents a mass of one kilogram.
5. Click the Run button, or press the <Ctrl-R> keys, to run the VI.
The Front Panel should look like this:
23 Simulation
Tutorial: Control and Simulation in LabVIEW
In the Figure above notice that the force of gravity causes the mass position and velocity to constantly
decrease. However, in the real world, a mass attached to a spring oscillates up and down. This simulated spring
does not oscillate because the simulation diagram does not represent damping or stiffness. You must represent
these factors to have a complete simulation of the dynamic system.
Representing Damping and Stiffness
Representing damping and stiffness involves feeding back the velocity and position, each multiplied by a
different constant, to the input of the Calculate Acceleration function. Recall the following differential equation
this VI simulates.
In the previous equation, notice you multiply the damping constant c by the velocity of the mass . You
multiply the stiffness constant k by the mass position x(t). You then subtract these quantities from the external
force applied to the mass.
Complete the following steps to represent damping and stiffness in this dynamic system model.
1. View the simulation diagram.
2. Select the Signal Arithmetic palette and place a Summation function on the simulation diagram. Move
this function to the left of the Force and Mass controls.
24 Simulation
Tutorial: Control and Simulation in LabVIEW
3. Double-click the Summation function to configure its operation. By default, the Summation function
displays the following three input terminals: a Ø symbol, a + symbol, and a – symbol. This
configuration subtracts one input signal from another.
4. Click the Ø symbol twice to change this terminal to the – symbol. This Summation function now
subtracts the top and bottom input signals from the left input signal.
5. Click the OK button to save changes and return to the simulation diagram.
6. Select the Signal Arithmetic palette and place a Gain function on the simulation diagram. Move this
function above the existing simulation diagram code but still within the Control & Simulation Loop.
7. The input of the Gain function is on the left side of the function, and the output is on the right side.
You can reverse the direction of these terminals to indicate feedback better. Right-click the Gain
function and select Reverse Terminals from the shortcut menu. The Gain function now points toward
the left side of the simulation diagram.
8. Label this Gain function Damping.
9. Press the <Ctrl> key and drag the Gain function to create a separate copy. Move this copy below the
existing simulation diagram code but still within the Control & Simulation Loop. Label this function
Stiffness.
10. Right-click the wire connecting the Force control to the Calculate Acceleration function and select
Delete Wire Branch from the shortcut menu. Move the Force control to the left of the Summation
function, and wire this control to the Operand2 input of the Summation function.
11. Create wires 1–5 as indicated in the Figure below. The simulation diagram now fully represents the
equation that defines the behavior of the dynamic system.
12. Press <Ctrl-S> to save the VI.
The Block Diagram should now look like this:
Configuring the Stiffness of the Spring
Before you run the simulation again, you must configure the stiffness of the simulated spring. Complete the
following steps to configure this Simulation function.
25 Simulation
Tutorial: Control and Simulation in LabVIEW
1. Double-click the Stiffness function to display the Gain Configuration dialog box.
2. Enter 100 in the gain numeric control. This value represents a stiffness of 100 Newtons per meter.
3. Click OK to return to the simulation diagram. Notice that the Stiffness function displays 100.
4. Display the front panel and ensure the Force control is set to -9.8 and the Mass control is set to 1.
5. Run the simulation. The Velocity and Position charts display the behavior of the mass as the spring
oscillates. Notice the new behavior compared to the last time you ran the simulation. This time, the
velocity and position do not constantly decrease. Both values oscillate, which is how a spring behaves
in the real world.
6. Change the value of theMass control to 10 and run the simulation again. Notice the different behavior
in the Velocity and Position charts. The 10 kg mass forces the spring to oscillate less frequently and
within a smaller velocity/position range.
The Front Panel should look like this:
Configuring Simulation Functions Programmatically
The previous section provided information about configuring Simulation functions using the configuration
dialog box. Instead of using the configuration dialog box, you can improve the interactivity of a simulation by
creating front panel controls that configure a Simulation function programmatically. Complete the following
steps to configure the Stiffness function programmatically.
1. If you are not already viewing the Context Help window, press <Ctrl-H> to display this window.
2. Display the block diagram and move the cursor over the Stiffness function. Notice this function has
only one input terminal.
26 Simulation
Tutorial: Control and Simulation in LabVIEW
3. Display the Gain Configuration dialog box of the Stiffness function.
4. Select Terminal from the Parameter source pull-down menu. This action disables the gain numeric
control.
5. Click the OK button to save changes and return to the block diagram.
6. Move the cursor over the Stiffness function. Notice the Context Help window displays the Gain
function with the new gain input terminal.
7. Create a control for this input, and label the control gain (k).
8. View the front panel. Notice the new control gain (k). Enter a value of 100 for this control and run the
simulation. Notice the behavior is exactly the same as when you used the configuration dialog box to
configure the Stiffness function.
Modularizing Simulation Diagram Code
You can create simulation subsystems to divide simulation diagrams into components that are modular,
reusable, and independently verifiable. Complete the following steps to create a simulation subsystem from
this simulation diagram.
1. View the simulation diagram.
2. Select the Calculate Acceleration, Calculate Velocity, and Calculate Position functions by pressing the
<Shift> key and clicking each function.
3. Select Edit»Create Simulation Subsystem. LabVIEW replaces these three functions with a single
function that represents the simulation subsystem, which is circled in the Figure below. The inputs and
outputs of the simulation subsystem include the inputs and outputs of all the functions you selected.
Also, notice the amount of blank space on the simulation diagram. Because you combined three
functions into a subsystem, you can resize the Control & Simulation Loop and reposition the functions
to make the simulation diagram easier to view.
4. Press <Ctrl-S> to save the simulation diagram. LabVIEW prompts you to save the simulation subsystem
you just created. Click the Yes button and save this simulation subsystem as “Newton.vi”. You now
have a simulation subsystem that obtains the position of a mass by using Newton's Second Law of
Motion.
Note! You can resize the simulation subsystem to better display its simulation diagram. You also can
double-click the simulation subsystem to display the configuration dialog box of that simulation subsystem.
The simulation subsystem should look like this:
27 Simulation
Tutorial: Control and Simulation in LabVIEW
Editing the Simulation Subsystem
Edit the simulation subsystem “Newton.vi” by right-clicking this subsystem and selecting Open Subsystem from
the shortcut menu. View the simulation diagram.
Notice this simulation subsystem does not contain a Control & Simulation Loop, but the entire background is
pale yellow to indicate a simulation diagram. If you place this simulation subsystem in a Control & Simulation
Loop, the simulation subsystem inherits all simulation parameters from the Control & Simulation Loop.
If you run this subsystem as a stand-alone VI, you can configure the simulation parameters by selecting
Operate»Configure Simulation Parameters. Any parameters you configure using this method do not take effect
when the subsystem is within another Control & Simulation Loop. If you place this simulation subsystem on a
block diagram outside a Control & Simulation Loop, you can configure the simulation parameters by
double-clicking the simulation subsystem to display the configuration dialog box of that simulation subsystem.
Configuring Simulation Parameters Programmatically
Earlier in this exercise, you used the Configure Simulation Parameters dialog box to configure the parameters
of “Spring-Mass Damper Example.vi”. You also can configure simulation parameters programmatically by using
the Input Node of the Control & Simulation Loop. Complete the following steps to configure simulation
parameters programmatically.
1. View the simulation diagram of “Spring-Mass Damper Example.vi”.
2. Move the cursor over the Input Node to display resizing handles.
3. Drag the bottom handle down to display all available Node inputs. You use these inputs to configure
the simulation parameters without displaying the Configure Simulation Parameters dialog box. You
also can right-click the Input Node and select Show All Inputs from the shortcut menu.
Notice the gray boxes next to each input. These boxes display values you configure in the Configure
Simulation Parameters dialog box. For example, the third gray box from the top displays 10.0000,
which is the value of the Final Time numeric control that you configured. The fifth gray box from the
top displays RK 23. This box specifies the current ODE solver, which you configured as Runge-Kutta 23
(variable). Move the cursor over the left edge of each Node input to display the label of that input.
28 Simulation
Tutorial: Control and Simulation in LabVIEW
4. Right-click the input terminal of the ODE Solver input and select Create»Constant from the shortcut
menu. A block diagram constant appears outside the Control & Simulation Loop. The value of this
constant is Runge-Kutta 1 (Euler), which is different than what you configured in the Configure
Simulation Parameters dialog box. However, the gray box disappears from the Input Node, indicating
that the value of this parameter does not come from the Configure Simulation Parameters dialog box.
Values that you programmatically configure override any settings you made in the Configure
Simulation Parameters dialog box.
The Input Node should now looks like the following figure:
Summary
This exercise introduced you to the following concepts:
The simulation diagram reflects the dynamic system model you want to simulate. This dynamic system model is
a differential or difference equation that represents a dynamic system.
The Control & Simulation Loop contains the parameters that define the behavior of the simulation. The Control
& Simulation Loop also defines the visual boundary of the simulation diagram. Double-click the Input Node of
the Control & Simulation Loop to access configurable parameters. You also can expand the Input Node to
access these parameters.
The Simulation palette contains the VIs and functions you use to build a simulation. You can double-click most
Simulation functions to display a dialog box that configures that function. You also can create input terminals
for function inputs.
You can create simulation subsystems to modularize, encapsulate, validate, and re-use portions of the
simulation diagram.
29
5 PID CONTROL
Currently, the Proportional-Integral-Derivative (PID) algorithm is the most common control algorithm used in
industry. Often, people use PID to control processes that include heating and cooling systems, fluid level
monitoring, flow control, and pressure control. In PID control, you must specify a process variable and a
setpoint. The process variable is the system parameter you want to control, such astemperature, pressure, or
flow rate, and the setpoint is the desired value for the parameter you are controlling. A PID controller
determines a controller output value, such as the heater power or valve position. The controller applies the
controller output value to the system, which in turn drives the process variable toward the setpoint value.
The PID controller compares the setpoint (SP) to the process variable (PV) to obtain the error (e).
Then the PID controller calculates the controller action, u(t), where Kc is controller gain.
Ti is the integral time in minutes, also called the reset time, and Td is the derivative time in minutes, also called
the rate time.
The following formula represents the proportional action.
The following formula represents the integral action.
The following formula represents the derivative action.
http://en.wikipedia.org/wiki/File:Pid-feedback-nct-int-correct.png
30 PID Control
Tutorial: Control and Simulation in LabVIEW
5.1 PID CONTROL IN LABVIEW
In the “PID” Sub palette we have the functions/SubVIs for PID Control. I recommend that you use the “PID
Advanced.vi”.
Example: PID Control
Below we see how we can use the PID Advanvanced.vi in order to control a simulated Model.
5.2 AUTO-TUNING
The LabVIEW PID and Fuzzy Logic Toolkit include a VI for auto-tuning.
31 PID Control
Tutorial: Control and Simulation in LabVIEW
32
6 CONTROL DESIGN
Control design is a process that involves developing mathematical models that describe a physical system,
analyzing the models to learn about their dynamic characteristics, and creating a controller to achieve certain
dynamic characteristics.
6.1 CONTROL DESIGN IN LABVIEW
Control Design palette:
33
7 SYSTEM IDENTIFICATION
7.1 SYSTEM IDENTIFICATION IN LABVIEW
The “System Identification Toolkit” combines data acquisition tools with system identification algorithms for
accurate plant modeling. You can take advantage of LabVIEW intuitive data acquisition tools such as the DAQ
Assistant to stimulate and acquire data from the plant and then automatically identify a dynamic system
model. You can convert system identification models to state-space, transfer function, or pole-zero-gain form
for control system analysis and design. The toolkit includes built-in functions for common tasks such as data
preprocessing, model creation, and system analysis. Using other built-in utilities, you can plot the model with
intuitive graphical representation as well as store the model.
System Identification palette:
34
8 FUZZY LOGIC
Fuzzy logic is a method of rule-based decision making used for expert systems and process control. Fuzzy logic
differs from traditional Boolean logic in that fuzzy logic allows for partial membership in a set. You can use
fuzzy logic to control processes represented by subjective, linguistic descriptions.
A fuzzy system is a system of variables that are associated using fuzzy logic. A fuzzy controller uses defined
rules to control a fuzzy system based on the current values of input variables.
8.1 FUZZY LOGIC IN LABVIEW
The Fuzzy Logic palette in LabVIEW:
35
9 LABVIEW MATHSCRIPT
Requires: MathScript RT Module
The “LabVIEW MathScript Window” is an interactive interface in which you can enter .m file script commands
and see immediate results, variables and commands history. The window includes a command-line interface
where you can enter commands one-by-one for quick calculations, script debugging or learning. Alternatively,
you can enter and execute groups of commands through a script editor window.
As you work, a variable display updates to show the graphical / textual results and a history window tracks your
commands. The history view facilitates algorithm development by allowing you to use the clipboard to reuse
your previously executed commands.
You can use the “LabVIEW MathScript Window” to enter commands one at time. You also can enter batch
scripts in a simple text editor window, loaded from a text file, or imported from a separate text editor. The
“LabVIEW MathScript Window” provides immediate feedback in a variety of forms, such as graphs and text.
Example:
36 Error! Reference source not found.
Tutorial: Control and Simulation in LabVIEW
9.1 HELP
You may also type help in your command window
>>help
Or more specific, e.g.,
>>help plot
9.2 EXAMPLES
I advise you to test all the examples in this text in LabVIEW MathScript in order to get familiar with the program
and its syntax. All examples in the text are outlined in a frame like this:
>>
…
This is commands you should write in the Command Window.
You type all your commands in the Command Window. I will use the symbol “>>” to illustrate that the
commands should be written in the Command Window.
37 Error! Reference source not found.
Tutorial: Control and Simulation in LabVIEW
Example: Matrices
Defining the following matrix
The syntax is as follows:
>> A = [1 2;0 3]
Or
>> A = [1,2;0,3]
If you, for an example, want to find the answer to
>>a=4
>>b=3
>>a+b
MathScript then responds:
ans =
7
MathScript provides a simple way to define simple arrays using the syntax: “init:increment:terminator”. For
instance:
>> array = 1:2:9
array =
1 3 5 7 9
defines a variable named array (or assigns a new value to an existing variable with the name array) which is an
array consisting of the values 1, 3, 5, 7, and 9. That is, the array starts at 1 (the init value), increments with each
step from the previous value by 2 (the increment value), and stops once it reaches (or to avoid exceeding) 9
(the terminator value).
The increment value can actually be left out of this syntax (along with one of the colons), to use a default value
of 1.
>> ari = 1:5
ari =
1 2 3 4 5
38 Error! Reference source not found.
Tutorial: Control and Simulation in LabVIEW
assigns to the variable named ari an array with the values 1, 2, 3, 4, and 5, since the default value of 1 is used as
the incrementer.
Note that the indexing is one-based, which is the usual convention for matrices in mathematics. This is atypical
for programming languages, whose arrays more often start with zero.
Matrices can be defined by separating the elements of a row with blank space or comma and using a semicolon
to terminate each row. The list of elements should be surrounded by square brackets: []. Parentheses: () are
used to access elements and subarrays (they are also used to denote a function argument list).
>> A = [16 3 2 13; 5 10 11 8; 9 6 7 12; 4 15 14 1]
A =
16 3 2 13
5 10 11 8
9 6 7 12
4 15 14 1
>> A(2,3)
ans =
11
Sets of indices can be specified by expressions such as "2:4", which evaluates to [2, 3, 4]. For example, a
submatrix taken from rows 2 through 4 and columns 3 through 4 can be written as:
>> A(2:4,3:4)
ans =
11 8
7 12
14 1
A square identity matrix of size n can be generated using the function eye, and matrices of any size with zeros
or ones can be generated with the functions zeros and ones, respectively.
>> eye(3)
ans =
1 0 0
0 1 0
39 Error! Reference source not found.
Tutorial: Control and Simulation in LabVIEW
0 0 1
>> zeros(2,3)
ans =
0 0 0
0 0 0
>> ones(2,3)
ans =
1 1 1
1 1 1
9.3 USEFUL COMMANDS
Here are some useful commands:
Command Description
eye(x), eye(x,y) Identity matrix of order x
ones(x), ones(x,y) A matrix with only ones
zeros(x), zeros(x,y) A matrix with only zeros
diag([x y z]) Diagonal matrix
size(A) Dimension of matrix A
A’ Inverse of matrix A
9.4 PLOTTING
This chapter explains the basic concepts of creating plots in MathScript.
Topics:
Basic Plot commands
Example: PlottingFunction plot can be used to produce a graph from two vectors x and y. The code:
x = 0:pi/100:2*pi;
40 Error! Reference source not found.
Tutorial: Control and Simulation in LabVIEW
y = sin(x);
plot(x,y)
41
10 WHATS NEXT?
10.1 MY BLOG
For more information about LabVIEW, visit my Blog: http://home.hit.no/~hansha/
10.2 TRAINING
This Training is a part of a series with other Training Kits I have made, such as:
Introduction to LabVIEW
Data Acquisition in LabVIEW
Control and Simulation in LabVIEW
LabVIEW MathScript
Linear Algebra in LabVIEW
Datalogging and Supervisory Control in LabVIEW
Wireless Data Acquisition in LabVIEW
Intermediate Topics in LabVIEW
Advanced Topics in LabVIEW
These Training Kits are available for download from my blog: http://home.hit.no/~hansha
10.3 ADDITIONAL RESOURCES
www.ni.com
10.4 EXAMPLES
In the NI example Finder (Help→Find Examples…) you find lots of useful examples that you can play with or use
as a start when creating your own applications.
http://home.hit.no/~hansha/
http://home.hit.no/~hansha
http://www.ni.com/
42 Whats next?
Tutorial: Control and Simulation in LabVIEW
10.5 DOCUMENTATION
As part of the LabVIEW installation there comes a lots of useful documentation.
10.6 LABVIEW WIKI
LabVIEW Wiki is the free LabVIEW information resource that anyone can edit.
http://labviewwiki.org/Home
http://labviewwiki.org/Home
43 Whats next?
Tutorial: Control and Simulation in LabVIEW
10.7 LABVIEW ON YOUTUBE
There are lots of LabVIEW videos available at YouTube:
http://www.youtube.com/results?search_query=labview&search=Search
http://www.youtube.com/results?search_query=labview&search=Search
44
QUICK REFERENCE
45 Quick Reference
Tutorial: Control and Simulation in LabVIEW
Telemark University College
Faculty of Technology
Kjølnes Ring 56
N-3914 Porsgrunn, Norway
www.hit.no
Hans-Petter Halvorsen, M.Sc.
Telemark University College
Department of Electrical Engineering, Information Technology and Cybernetics
Phone: +47 3557 5158
E-mail: hans.p.halvorsen@hit.no
Blog: http://home.hit.no/~hansha/
Room: B-237a
http://www.hit.no/
mailto:hans.p.halvorsen@hit.no
http://home.hit.no/~hansha/
Telemark University College
Department of Electrical Engineering, Information Technology and Cybernetics
Faculty of Technology, Postboks 203, Kjølnes ring 56, N-3901 Porsgrunn, Norway. Tel: +47 35 57 50 00 Fax: +47 35 57 54 01
INTRODUCTION TO STATE-BASED
APPLICATIONS IN LABVIEW
HANS-PETTER HALVORSEN, 2010.01.15
PREFACE
Statecharts or State Diagrams are useful in simplifying the design of applications that use complex
decision-making algorithms. By constructing a statechart, you can visualize the flow of a complex
decision-making algorithm and achieve a high-level view of an application.
This document explains the basic concepts of creating state-based applications in LabVIEW.
You should have some basic knowledge about LabVIEW, e.g., the “An Introduction to LabVIEW” training. This
document is available for download at http://home.hit.no/~hansha/.
In addition to LabVIEW Professional Development System, you need to install the “LabVIEW Statechart
Module”.
http://home.hit.no/~hansha/
INSTALLATION REQUIREMENTS
NI LabVIEW
Name Required
LabVIEW Professional Development System Yes
NI LabVIEW Core Components
Name Required
LabVIEW Control Design and Simulation Module
LabVIEW MathScript RT Module
NI Vision Development Module
Vision Builder for Automated Inspection
LabVIEW Digital Filter Design Toolkit
LabVIEW Modulation Toolkit
LabVIEW System Identification Toolkit
LabVIEW Desktop Execution Trace Toolkit
LabVIEW Report Generation for Microsoft Office Toolkit
LabVIEW Database Connectivity Toolkit
LabVIEW Internet Toolkit
NI LabVIEW SignalExpress
LabVIEW Basics 1 and 2 Computer Based Training
Extended Development Suite Components
Name Required
LabWindows/CVI Full Development System
LabWindows/CVI Real-Time Module
LabWindows/CVI PID Control Toolkit
LabWindows/CVI Signal Processing Toolkit
LabWindows/CVI Spectral Measurements Toolkit and Run-time Engine
LabWindows/CVI SQL Toolkit
Measurement Studio Enterprise Edition
DIAdem Professional
Control and Embedded Systems Option Components
Name Required
LabVIEW FPGA Module
LabVIEW Real-Time Module
LabVIEW Statechart Module Yes
LabVIEW Mobile Module
LabVIEW Datalogging and Supervisory Control Module
LabVIEW PID and Fuzzy Logic Toolkit
NI Real-Time Execution Trace Toolkit
LabVIEW Simulation Interface Toolkit
NI Motion Assistant
NI-DAQ Base
Signal processing and Communications Option Components
Name Required
LabVIEW FPGA Module
LabVIEW Sound and Vibration Measurement Suite
LabVIEW Spectral Measurement Toolkit
LabVIEW Advanced Signal Processing Toolkit
LabVIEW Adaptive Filter Toolkit
NI Device Drivers
Name Required
FieldPoint
NI-DAQmx
NI LabVIEW SignalExpress
NI Instrument I/O Assistant
NI-IMAQ
NI Measurement & Automation Explorer
NI PXI
NI-VISA
TABLE OF CONTENTS
Preface .................................................................................................................................................................... 2
Installation Requirements ....................................................................................................................................... 3
Table of Contents .................................................................................................................................................... vi
1 Introduction to LabVIEW ............................................................................................................................... 1
1.1 Dataflow programming.......................................................................................................................... 1
1.2 Graphical programming ......................................................................................................................... 1
1.3 Benefits .................................................................................................................................................. 2
2 Introduction to Sequential Control................................................................................................................ 3
3 Introduction to State Diagrams ..................................................................................................................... 4
4 Introduction to Sequential Function Charts (SFC) ......................................................................................... 6
5 State-machine with LabVIEW ........................................................................................................................ 8
5.1 While Loop ............................................................................................................................................. 8
5.2 Case Structure ....................................................................................................................................... 9
5.3 Shift Register ........................................................................................................................................ 10
5.4 State Programming Architecture ......................................................................................................... 11
5.5 State-machine ...................................................................................................................................... 12
6 A Sequential Control example in LabVIEW ..................................................................................................15
7 Introduction to LabVIEW Statechart Module .............................................................................................. 17
7.1 Procedure for creating a Statechart application in LabVIEW .............................................................. 18
7.2 Statechart Editor .................................................................................................................................. 21
7.2.1 Statechart Development objects ................................................................................................ 23
7.3 Using a Caller VI to Execute a Statechart ............................................................................................. 25
8 Tutorial: Create a Statechart ....................................................................................................................... 28
9 Advanced Topics in LabVIEW Statechart Module ........................................................................................ 41
9.1 Using Regions and Substates ............................................................................................................... 41
9.2 Using Orthogonal Regions and State History....................................................................................... 41
vii Table of Contents
Tutorial: Introduction to State-based Applications in LabVIEW
9.3 Splitting and Merging Transition Segments ......................................................................................... 41
10 Whats Next? ................................................................................................................................................ 43
10.1 My Blog ................................................................................................................................................ 43
10.2 Training ................................................................................................................................................ 43
10.3 Additional Resources ........................................................................................................................... 43
10.4 Examples .............................................................................................................................................. 43
10.5 Documentation .................................................................................................................................... 44
10.6 LabVIEW Wiki....................................................................................................................................... 44
10.7 LabVIEW on YouTube .......................................................................................................................... 45
Quick Reference .................................................................................................................................................... 46
1
1 INTRODUCTION TO LABVIEW
LabVIEW (short for Laboratory Virtual Instrumentation Engineering Workbench) is a platform and development
environment for a visual programming language from National Instruments. The graphical language is named
"G". Originally released for the Apple Macintosh in 1986, LabVIEW is commonly used for data acquisition,
instrument control, and industrial automation on a variety of platforms including Microsoft Windows, various
flavors of UNIX, Linux, and Mac OS X. The latest version of LabVIEW is version LabVIEW 2009, released in
August 2009. Visit National Instruments at www.ni.com.
The code files have the extension “.vi”, which is an abbreviation for “Virtual Instrument”. LabVIEW offers lots of
additional Add-Ons and Toolkits.
This paper is part of a series with LabVIEW tutorials, such as:
Introduction to LabVIEW
Data Acquisition in LabVIEW
Control and Simulation in LabVIEW
LabVIEW MathScript
Linear Algebra in LabVIEW
Datalogging and Supervisory Control in LabVIEW
Wireless Data Acquisition in LabVIEW
Intermediate Topics in LabVIEW
Advanced Topics in LabVIEW
Each tutorial may be used independently of each other.
1.1 DATAFLOW PROGRAMMING
The programming language used in LabVIEW, also referred to as G, is a dataflow programming language.
Execution is determined by the structure of a graphical block diagram (the LV-source code) on which the
programmer connects different function-nodes by drawing wires. These wires propagate variables and any
node can execute as soon as all its input data become available. Since this might be the case for multiple nodes
simultaneously, G is inherently capable of parallel execution. Multi-processing and multi-threading hardware is
automatically exploited by the built-in scheduler, which multiplexes multiple OS threads over the nodes ready
for execution.
1.2 GRAPHICAL PROGRAMMING
LabVIEW ties the creation of user interfaces (called front panels) into the development cycle. LabVIEW
programs/subroutines are called virtual instruments (VIs). Each VI has three components: a block diagram, a
front panel, and a connector panel. The last is used to represent the VI in the block diagrams of other, calling
VIs. Controls and indicators on the front panel allow an operator to input data into or extract data from a
running virtual instrument. However, the front panel can also serve as a programmatic interface. Thus a virtual
instrument can either be run as a program, with the front panel serving as a user interface, or, when dropped
as a node onto the block diagram, the front panel defines the inputs and outputs for the given node through
the connector pane. This implies each VI can be easily tested before being embedded as a subroutine into a
larger program.
http://www.ni.com/
2 Introduction to LabVIEW
Tutorial: Introduction to State-based Applications in LabVIEW
The graphical approach also allows non-programmers to build programs simply by dragging and dropping
virtual representations of lab equipment with which they are already familiar. The LabVIEW programming
environment, with the included examples and the documentation, makes it simple to create small applications.
This is a benefit on one side, but there is also a certain danger of underestimating the expertise needed for
good quality "G" programming. For complex algorithms or large-scale code, it is important that the
programmer possess an extensive knowledge of the special LabVIEW syntax and the topology of its memory
management. The most advanced LabVIEW development systems offer the possibility of building stand-alone
applications. Furthermore, it is possible to create distributed applications, which communicate by a
client/server scheme, and are therefore easier to implement due to the inherently parallel nature of G-code.
1.3 BENEFITS
One benefit of LabVIEW over other development environments is the extensive support for accessing
instrumentation hardware. Drivers and abstraction layers for many different types of instruments and buses
are included or are available for inclusion. These present themselves as graphical nodes. The abstraction layers
offer standard software interfaces to communicate with hardware devices. The provided driver interfaces save
program development time. The sales pitch of National Instruments is, therefore, that even people with limited
coding experience can write programs and deploy test solutions in a reduced time frame when compared to
more conventional or competing systems. A new hardware driver topology (DAQmxBase), which consists
mainly of G-coded components with only a few register calls through NI Measurement Hardware DDK (Driver
Development Kit) functions, provides platform independent hardware access to numerous data acquisition and
instrumentation devices. The DAQmxBase driver is available for LabVIEW on Windows, Mac OS X and Linux
platforms.
3
2 INTRODUCTION TO SEQUENTIALCONTROL
Sequential control is crucial in many control applications, as in chemical batch processes. A sequential control
procedure can be represented graphically by e.g. one of the following two methods:
A State diagram, also denoted a State machine
A Sequential function chart (SFC)
State diagrams and SFC are quite similar, as they have the same basic elements:
States with actions to be executed when the state is active
Transitions from one active state to another
Sequential control can be implemented using graphical programming of state diagrams or SFCs in proper
programming tools. For example, state diagrams are supported by the LabVIEW Statechart Module. Different
PLC (Programmable Logic Controller) tools support SFC.
For more details about sequential control, se the article “Sequential Control” by Finn Haugen. A link to the
article is available from http://home.hit.no/~hansha.
http://home.hit.no/~hansha
4
3 INTRODUCTION TO STATE DIAGRAMS
State diagrams have states with actions to be executed when the state is active. They have transitions from
one active state to another taking place if the transition condition is logically true.
Below we see a typical state diagram:
A state diagram represents a state machine. States of a state machine are either active or passive. Only one
state is active at a time. The state machine always starts in a particular state defined as the initial state, and it
ends (stops) after the final state. Special symbols or colors may be used for the initial state and the final state.
See the Figure above.
Associated with a state are one or more actions. An action may be a control action executed by a controller.
Actions may be listed as indicated below:
State 1 actions:
o Action 1: Valve V1 is open;
o Action 2: Motor M1 runs;
State 2 actions:
o Action 1: Valve V1 is closed;
o Action 2: Heater H1 is on;
The actions for a given state can be listed in a box attached to the state symbol, see Figure below. However,
the diagram may then become overloaded by symbols. Therefore, in more comprehensive state diagrams, it
may be better to just list the actions in a separate document.
5 Introduction to State Diagrams
Tutorial: Introduction to State-based Applications in LabVIEW
Transitions bring the state machine from one state to another. A transition can go only from an active state
which is presently active. A transition takes place only if its transition condition is TRUE. Transition conditions
are in the form of logical expressions having value either TRUE or FALSE.
For more details about state diagrams, se the article “Sequential Control” by Finn Haugen. A link to the article is
available from http://home.hit.no/~hansha.
http://home.hit.no/~hansha
6
4 INTRODUCTION TO SEQUENTIAL FUNCTION CHARTS (SFC)
Sequential Function Charts describe control sequences in graphical form. State Diagrams and Sequential
function charts (SFC) techniques are very similar. They have states/steps (in SFC the term steps is used) with
actions to be executed when the state is active. They have transitions from one active state to another taking
place if the transition condition is logically true.
Sequential function chart (SFC) is a graphical programming language often used for PLCs (PLC - Programmable
Logic Controller).
Below we see a typical SFC chart:
The Sequential Function Charts break a sequential task down into Steps, Transitions and Actions. These are
drawn graphically to describe a sequence of interactions as seen above.
Steps:
Every step can execute one or more actions.
A step can be either active or inactive. When it becomes active, it's actions are executed
Transitions:
There are transitions between every step.
When a Step is active and the following transition become true the successor step becomes active and
the preceding step becomes inactive.
Each transition has associated events which are called transition conditions.
The transition conditions must combine to make a simple Boolean result, True or False.
Step Actions:
Every action is associated with a step. The step can have none or several actions associated.
If there is no associated action to the step, it will be considered as a WAIT function.
Each step/action association shall have an associated action qualifier.
7 Introduction to Sequential Function Charts (SFC)
Tutorial: Introduction to State-based Applications in LabVIEW
The Program Flow is as follows:
A step becomes active when its preceding transition activates (that is the transition is true, while the
step before that transition is active.)
A step becomes inactive when it's subsequent transition becomes true
In Parallel branches, all the initial steps become active when the preceding transition activates
A parallel branch end when all the steps before the branch end are be active, and the subsequent
transition becomes true
Many systems have sequential operation requirements and Sequential Function Charts (SFC’s) have become a
popular method of accurately specifying sequential control requirements. SFC’s have many advantages for
software development both in the design stage as well as the implementation and testing, maintaining and
fault finding stages, such as:
Design Stage
o Detailed clear graphical specification
o Non software people can specify / verify
Implementation
o Straight forward conversion from specification to code
o Structured testing / debugging
Maintenance of Software
o Readily understood by engineer modifying software
Machine Maintenance
o Allows quick accurate fault diagnosis
8
5 STATE-MACHINE WITH LABVIEW
The State Machine approach in LabVIEW uses a Case structure inside a While loop to handle the different
states in the program, and the transitions between them. The Shift Register is used to save data from and
between the different states.
Below we shortly repeat the While Loop, the Case structure and the Shift Register before we dig into the
principles of the state-machine.
For more details about basic LabVIEW programming techniques, refer to the tutorial “Introduction to
LabVIEW”. The tutorial is available for download from: http://home.hit.no/~hansha.
5.1 WHILE LOOP
A While loop repeats the sub diagram inside it until the conditional terminal, an input terminal, receives a
particular Boolean value. The Boolean value depends on the continuation behavior of the While Loop.
Right-click the conditional terminal and select Stop if True or Continue if True from the shortcut menu. You
also can wire an error cluster to the conditional terminal, right-click the terminal, and select Stop on Error or
Continue while Error from the shortcut menu. Note! The While Loop always executes at least once.
Below we see an empty While loop:
After you create a While Loop, you can use shift registers to pass values from one iteration to the next. If you
wire an array to a While Loop, you can read and process every element in that array by enabling auto-indexing.
Se example below.
http://home.hit.no/~hansha
9 State-machine with LabVIEW
Tutorial: Introduction to State-based Applications in LabVIEW
In order to convert a While Loop into a For Loop, right-click the While Loop and select “Replace with For Loop”
from the shortcut menu. To convert a While Loop into a Timed Loop, right-click the While Loop and select
“Replace with Timed Loop” from the shortcut menu.
5.2 CASE STRUCTURE
The Case Structure has one or more sub diagrams, or cases, exactly one of which executes when the structure
executes. The value wired to the selector terminal determines which case to execute and can be Boolean,
string, integer, or enumerated type. You may right-click the structure border to add or delete cases. Use the
Labeling tool to enter value(s) in the case selectorlabel and configure the value(s) handled by each case.
Below we see an empty Case structure:
Below we see an example of a Case structure with 2 cases, a “True” case and a “False” case. Depending of the
Boolean input value, the Numeric1 and Numeric2 is either Added or Subtracted.
10 State-machine with LabVIEW
Tutorial: Introduction to State-based Applications in LabVIEW
You may also connect an error cluster directly to a case structure, like this:
The case structure automatically switches to a “No Error” case and an “Error” case.
5.3 SHIFT REGISTER
Use shift registers on For Loops and While Loops to transfer values from one loop iteration to the next. Shift
registers are similar to static variables in text-based programming languages. A shift register appears as a pair
of terminals, directly opposite each other on the vertical sides of the loop border. The right terminal contains
an up arrow and stores data on the completion of an iteration. LabVIEW transfers the data connected to the
right side of the register to the next iteration. Create a shift register by right-clicking the left or right border of a
loop and selecting Add Shift Register from the shortcut menu.
11 State-machine with LabVIEW
Tutorial: Introduction to State-based Applications in LabVIEW
A shift register transfers any data type and automatically changes to the data type of the first object wired to
the shift register. The data you wire to the terminals of each shift register must be the same type.
To initialize a shift register, wire any value from outside the loop to the left terminal. If you do not initialize the
shift register, the loop uses the value written to the shift register when the loop last executed or the default
value for the data type if the loop has never executed.
Use a loop with an uninitialized shift register to run a VI repeatedly so that each time the VI runs, the initial
output of the shift register is the last value from the previous execution. Use an uninitialized shift register to
preserve state information between subsequent executions of a VI. After the loop executes, the last value
stored in the shift register remains at the right terminal. If you wire the right terminal outside the loop, the
wire transfers the last value stored in the shift register. You can add more than one shift register to a loop. If
you have multiple operations within a loop, use multiple shift registers to store the data values from those
different processes in the structure.
Shift Register Example:
Create and Run this example to see what happens.
5.4 STATE PROGRAMMING ARCHITECTURE
Creating VIs using the State Machine approach is very useful when creating (large) applications.
In general, a state machine is a model of behavior composed of a finite number of states, transitions between
those states, and actions. It is similar to a "flow graph" where we can inspect the way in which the logic runs
when certain conditions are met.
12 State-machine with LabVIEW
Tutorial: Introduction to State-based Applications in LabVIEW
Sometimes, you may want to change the order of the sequence, repeat one item in the sequence more often
than the other items, stop a sequence immediately, or have items in the sequence that may execute only when
certain conditions are met. Although your program may not have any such requirements, there is always the
possibility that the program must be modified in the future. Therefore, a state programming architecture is a
good choice, even if a sequential programming structure is sufficient. The following list describes more complex
programming requirements that justify the use of a state programming architecture for an application.
You need to change the order of the sequence
You must repeat an item in the sequence more often than other items
You want some items in the sequence to execute only when certain conditions are met
5.5 STATE-MACHINE
13 State-machine with LabVIEW
Tutorial: Introduction to State-based Applications in LabVIEW
The State Machine approach in LabVIEW uses a Case structure inside a While loop to handle the different
states in the program, and the transitions between them. The Shift Register is used to save data from and
between the different states.
Below we see examples of a state machine principle implemented in LabVIEW.
Simple State Machine principle
State Machine with multiple transitions depending on the State:
More advanced State Machine using Shift Registers:
14 State-machine with LabVIEW
Tutorial: Introduction to State-based Applications in LabVIEW
Templates for State-machines in LabVIEW are available for download at: http://home.hit.no/~hansha
http://home.hit.no/~hansha
15
6 A SEQUENTIAL CONTROL EXAMPLE IN LABVIEW
This example illustrates how we may use the state-machine principle in LabVIEW to create a sequential control
application.
This example uses a state machine for sequential control of the position of a bicycle.
The state-machine is implemented with:
An overall Case-structure which defines the states and contains the actions of each state
A Shift-register which remembers which state is the active state
An internal Case-structure inside each state (Case in the overall Case-structure) together with proper
Boolean comparison functions implementing the transition conditions.
The state-machine controls a simulated process (bicycle position) given by the following dynamic model:
Where x is position and v is speed. The speed is manipulated by the state-machine.
This model is implemented in a Simulation Loop which runs in parallel with the While loop. Data (variables) are
exchanged between these loops using local variables.
The arrow on a Vertical Pointer Slide is replaced with a picture of a bicycle. The procedure to substitute any
graphical part of an indicator or control on the Front panel is as follows: Right-click on the item (graphical part),
e.g. the arrow of a Vertical Pointer Slide. Select Advanced / Customize in the menu that is opened. Click the
Tool button in the toolbar of the new window that is opened. Right-click on the arrow on the slider, and select
the picture you want. Etc.
How to use it?
Use this VI as a template for your own state-machine controller for any simulated dynamic system. To control a
real (physical) process instead, just substitute the simulated process with read and/or write functions for
analog and/or digital I/O (input/output).
The Front Panel looks like this:
16 A Sequential Control example in LabVIEW
Tutorial: Introduction to State-based Applications in LabVIEW
The Block Diagram looks like this:
In order to get the feeling with state machines, while loops, case structures and shift registers, try to reproduce
the example.
The example is created by Finn Haugen, Telemark University College.
17
7 INTRODUCTION TO LABVIEW STATECHART MODULE
The NI LabVIEW Statechart Module provides a programming model that you can use to design applications at a
higher level than was previously possible. With the LabVIEW Statechart Module, you can develop statechart
diagrams, define behaviors with LabVIEW dataflow programming.
Statecharts expand the classic state diagram with the additional features of hierarchy, concurrency, and
comprehensive actions.
LabVIEW statecharts are especially useful for programming event-response applications such as intricate user
interfaces and advanced state machines used to implement dynamic system controllers, machine control logic,
and digital communication protocols.
Using the LabVIEW Statechart Module involves the following two steps:
Using the Statechart Editor window to build a statechart.
Creating a VI that executes the statechart. This VI also sends information to, and receives information
from, the statechart.Building a Statechart
Building a statechart involves defining the following items:
States
Actions and static reactions these states execute
Transitions between states
Actions these transitions execute
Triggers
When you build a statechart, you define unique states in which the statechart can be. You also define
transitions between these states, when the statechart can take these transitions, and what actions these
transitions can take. You then define triggers that cause the statechart to begin evaluating a certain transition.
For example, consider a statechart that you use to control a chemical process. You can specify that the
statechart moves from State 1 to State 2 after receiving the Valve Open trigger. States and transitions also have
associated actions, which you use to modify output and state data associated with the statechart.
Creating a VI that Executes the Statechart
After you define the valid triggers and configure the statechart to react to those triggers, you must send those
triggers to the statechart. You send triggers to the statechart by creating a VI, known as the Caller VI, to send
triggers at a specific time. For example, you can configure the caller VI to send the Stop trigger after you click
the Stop front panel button.
The caller VI also sends input data to the statechart so the statechart can act on that data. The caller VI receives
data that the statechart modifies as a result of a state or transition action. You then can use this data in other
parts of the caller VI or send this data to other VIs.
The following figure shows how a caller VI interacts with a statechart.
18 Introduction to LabVIEW Statechart Module
Tutorial: Introduction to State-based Applications in LabVIEW
The figure above shows how the caller VI sends data to the statechart, which returns output data to the caller
VI. If the statechart is asynchronous, the caller VI also might send a trigger to the statechart. Sending a trigger
to the statechart causes the statechart to begin executing.
7.1 PROCEDURE FOR CREATING A STATECHART APPLICATION IN LABVIEW
The procedure for creating a statechart application in LabVIEW with the LabVIEW Statechart Module is as
follows:
Step1: In the New dialog select “Statechart”.
Step 2: Name the Statechart
19 Introduction to LabVIEW Statechart Module
Tutorial: Introduction to State-based Applications in LabVIEW
Step3: The Project Explorer for the Statechart application appears:
As you see, the LabVIEW Statechart Module automatically generates a set of Vis and Controls.
LabVIEW Statechart Palette:
LabVIEW Statechart Module offers the following Functions and Objects in the Statechart palette:
20 Introduction to LabVIEW Statechart Module
Tutorial: Introduction to State-based Applications in LabVIEW
Statechart Communication Functions:
Use the Statechart Communication functions to execute a statechart, send triggers to a statechart, and
determine whether a particular state is active. You can place these functions on a block diagram.
Statechart Communication palette:
Run Statechart Executes an instance of the linked statechart. You typically place this function inside a
loop in the caller VI.
Example:
21 Introduction to LabVIEW Statechart Module
Tutorial: Introduction to State-based Applications in LabVIEW
Send External Trigger Sends a trigger to the external queue of an instance of the linked statechart. You
can use this function in the caller VI or in a VI that runs parallel to the caller VI. Se example above
IsIn Determines whether the specified state is active. An active state is one that a statechart is currently
in. You can use this function in a guard, an action, or a subVI that a guard or action calls.
Send Internal Trigger Sends a trigger to the internal queue of the statechart. You can use this function
within only an action or in a subVI that an action calls.
Statechart Development Objects:
Use the Statechart Development objects, consisting of states, regions, “pseudostates”, and connectors, to
construct statecharts. Note! You can place these objects only on a statechart diagram.
Statechart Development palette:
The different objects are explained below.
7.2 STATECHART EDITOR
22 Introduction to LabVIEW Statechart Module
Tutorial: Introduction to State-based Applications in LabVIEW
You use the Statechart Editor window to edit a statechart. You can display the Statechart Editor window in one
of the following ways:
Double-click the “Diagram.vi” item in the Project Explorer window of the statechart.
Right-click the “Diagram.vi” item and select Open from the shortcut menu.
Right-click a Run Statechart function that links to the statechart and select View»Statechart Diagram
from the shortcut menu.
Statechart Editor Window:
The Statechart Editor window, which displays a statechart diagram, is similar to the LabVIEW window that
displays a block diagram. In both of these windows, you can place objects from the Functions palette on the
diagram, use the LabVIEW tools to manipulate objects, and connect objects together. However, the Statechart
Editor window is different from the LabVIEW window in the following ways:
You can place only Statechart Development objects on a statechart diagram. You cannot place
LabVIEW VIs, functions, or structures directly on a statechart diagram.
23 Introduction to LabVIEW Statechart Module
Tutorial: Introduction to State-based Applications in LabVIEW
The LabVIEW block diagram window displays the Run button on the toolbar. The Statechart Editor
window displays the “Generate Code “button on the toolbar. Clicking this button generates
code for the statechart.
The LabVIEW block diagram has a front panel window. The Statechart Editor window does not have a
front panel window.
On the LabVIEW block diagram, you use the wiring tool to create wires between VIs and functions. In
the Statechart Editor window, you use the wiring tool to create transitions between states and other
objects.
The LabVIEW block diagram provides options for debugging VIs. The Statechart Editor window does
not provide any debugging options. You debug statecharts by using a separate window that you can
access while the statechart is running.
The Statechart Editor window disables many LabVIEW pull-down menu items that do not apply to
statecharts.
7.2.1 STATECHART DEVELOPMENT OBJECTS
Use the Statechart Development objects to construct statecharts. You can place these objects on a statechart
diagram.
The Statechart Development objects consist of states, regions, and connectors.
The Statechart Development palette:
The Statechart Development objects are as follows:
State Defines a state, which is a unique condition in which the statechart can be. You must place all
states within a region. Note! The top-level statechart diagram represents a region. All states must have at least
one incoming transition.
24 Introduction to LabVIEW Statechart Module
Tutorial: Introduction to State-based Applications in LabVIEW
Initial Specifies the first state that the enclosing region enters when the statechart enters that region.
To specify this state, create a transition from the Initial pseudostate to the state that you want to enter first.
You can place this pseudostate within only a region or at the top level of a statechart diagram. Each region
must have one and only one Initial pseudostate.
Terminal Specifies a state that can terminate the execution of the enclosing region. To specify this
state, create a transition from a state to a Terminal pseudostate. You can place this pseudostate within only a
region. You can place more than one Terminal pseudostate in a region.
Junction Connects common elements of multiple transitions together. For example, you canuse a
Junction connector to specify that multiple transitions use the same action, even though each transition might
have a different trigger. You can place this connector only in a region.
Region Defines the area in which you can place states and pseudostates. Each region must contain an
Initial pseudostate and at least one substate. Note! The top-level statechart diagram represents a region. You
can place regions within only a state.
Fork Splits one incoming transition segment into multiple outgoing segments. You can place this
connector within only a state.
25 Introduction to LabVIEW Statechart Module
Tutorial: Introduction to State-based Applications in LabVIEW
Join Merges multiple incoming transition segments into one outgoing segment. You can place this
connector within only a state.
Port Indicates where a transition leaves a state or connector. Ports also indicate where a transition
passes through a region. When you are editing a statechart, ports appear automatically as you create
transitions. You can place ports manually only when you are viewing a state as a subdiagram.
Shallow History Specifies that, when the statechart leaves and then returns to a region, the statechart
enters the highest-level substates that were active when the statechart left the region. To use the Shallow
History pseudostate, place this pseudostate in a region and then create a transition from a state to this
pseudostate.
Deep History Specifies that, when the statechart leaves and then returns to a region, the statechart
enters the lowest-level substates that were active when the statechart left the region. To use the Deep History
pseudostate, place this pseudostate in a region and then create a transition from a state to this pseudostate.
7.3 USING A CALLER VI TO EXECUTE A STATECHART
The caller VI is the VI you create that contains a “Run Statechart” function. This function creates and executes
an instance of a statechart. Executing a statechart means sending input data to a statechart. You also can use
the caller VI to send triggers to a statechart.
The caller VI has a different structure depending on whether the statechart is asynchronous or synchronous.
The following sections provide information about these differences.
Executing asynchronous statecharts involves the following two processes:
Executing the statechart by using the “Run Statechart” function.
Sending triggers to the external queue by using the “Send External Trigger” function.
In this situation, the VI that contains the “Run Statechart” function is the caller VI. You can send triggers to the
external queue from another VI or a parallel loop in the caller VI. The following figure shows a caller VI that
both executes an asynchronous statechart and sends triggers to the external queue.
26 Introduction to LabVIEW Statechart Module
Tutorial: Introduction to State-based Applications in LabVIEW
In the figure above, the Statechart Loop, which is a While Loop, executes the statechart. The Inputs control
contains any input data of the types that you defined. The Outputs indicator returns output data from the
statechart. The Instance Name constant specifies Statechart 1 as the name of the statechart instance.
The Trigger Loop, which can execute in parallel with the Statechart Loop, contains an Event structure. This
Event structure handles events that occur within the VI. In this case, an event occurs when you click the Button
front panel control. When you click this control, the Event structure detects this event and the Send External
Trigger function sends the Trigger1 trigger to the Statechart 1 statechart instance.
Note! This example uses the caller VI to send triggers to an external queue. However, as long as the caller VI is
running and the statechart is in memory, you can use any VI to send triggers to an external queue. This
behavior means that you can place the Trigger Loop and Statechart Loop in separate VIs.
Statechart Editor:
Open the Statechart Diagram (in the Statechart Editor) as follows:
Right-click on the “Run Statechart” VI and select View → Statechart Diagram.
27 Introduction to LabVIEW Statechart Module
Tutorial: Introduction to State-based Applications in LabVIEW
Project Explorer:
Open the Project Explorer as follows:
Right-click on the “Run Statechart” VI and select View → Statechart.
28
8 TUTORIAL: CREATE A STATECHART
In this Tutorial you will learn how to create a statechart from scratch. In this example we will create the
following application:
When you push the different buttons, the current state will be displayed in the “Current Activity” indicator
This Tutorial goes through the following steps:
Step 1: Creating and Configuring the Statechart
Step 2: Defining States
Step 3: Creating a Transition
Step 4: Creating a Trigger and Configuring a Transition
Step 5: Creating and Configuring the Terminal Transitions
Step 6: Creating and Configuring the Initial pseudostate and Transition
Step 7: Defining the Type of Output Data
Step 8: Defining the Type of State Data
Step 9: Configuring a State Entry Action
Step 10: Configuring the Action of a Transition
Step 11: Duplicating the Transition Node
Step 12: Generating Code for the Statechart
Step 13: Creating the Caller VI
Step 14: Debugging
Let’s start the Tutorial:
Step 1: Creating and Configuring the Statechart
Complete the following steps to create and configure the statechart.
1. Launch LabVIEW and display the Getting Started window.
29 Tutorial: Create a Statechart
Tutorial: Introduction to State-based Applications in LabVIEW
2. Select File»New to launch the New dialog box.
3. Select Other Files»Statechart from the Create New tree.
4. Click the OK button. LabVIEW prompts you to save the statechart.
5. Enter the name “Tutorial” as the name of your statechart (Note! It has the ending .lvsc) and save the
statechart in a convenient location on disk.
6. LabVIEW displays a Project Explorer window that contains the necessary support files. This project
item represents the “Tutorial.lvsc” file in which LabVIEW stores statechart information.
7. Right-click the “Tutorial.lvsc” item and select Properties. LabVIEW launches the Properties dialog box.
8. Select the “Statechart Code Generation” item from the Category list. LabVIEW displays options
relating to statechart code generation.
30 Tutorial: Create a Statechart
Tutorial: Introduction to State-based Applications in LabVIEW
9. Select Asynchronous from the Usage pull-down menu. This action specifies that the statechart is
asynchronous.
10. Click the OK button to save changes and return to the Project Explorer window.
Step 2: Defining States
The next step is creating the states that comprise the statechart. A state is a unique condition in which the
statechart can be.
This statechart consists of three states: Menu, Play, and Pause. Complete the following steps to create these
states.
1. In the Project Explorer window, double-click the Diagram.vi item to launch the Statechart Editor
window. This window displays the statechart diagram. You build a statechart by placing statechart
objects on the statechart diagram.
2. If you do not see the Functions palette, select View»Functions Palette to display this palette.
3. On this palette, select Statechart»Statechart Development to display the Statechart Development
palette.
31 Tutorial: Create a Statechart
Tutorial: Introduction to State-based Applications in LabVIEW
4. Click the State object.
5. Move the cursor over the statechart diagram. Click to place the top left corner of the state, drag the
cursor diagonally to establish the size of the state, and click again to place the state on the statechart
diagram.
6. Notice the state is labeled State. Double-clickthis label to enable text editing and enter “Menu” as the
new label.
7. Move the cursor over the black border of the Menu state until the cursor changes to the Positioning
tool.
8. Press the <Ctrl> key and click and drag the cursor to the right of the Menu state. This action creates
copy of the state.
9. Label this new state “Play”.
10. Create another new state labeled “Pause”. Place this state to the right of the Play state.
11. Return to the Statechart Development palette and place a “Terminal” pseudostate below the Play
state.
The diagram should look like this:
Step 3: Creating a Transition
The next step is defining the ways in which the statechart can move between states. To define this behavior,
you use transitions to connect one state to another visually. Complete the following steps to create transitions
between two states.
1. Move the cursor over the right border of the Menu state and change the cursor to the Wiring tool.
2. Click the state border. As you move the cursor across the statechart diagram, LabVIEW draws a dotted
line between the state and the Wiring tool.
3. Move the cursor over the left border of the Play state. A gray box appears under the cursor.
4. Click the border to finish the transition. LabVIEW creates a transition between the two states.
32 Tutorial: Create a Statechart
Tutorial: Introduction to State-based Applications in LabVIEW
The statechart diagram should look like this:
Step 4: Creating a Trigger and Configuring a Transition
The next step is specifying that the statechart takes the transition only after receiving a specific event, also
called a trigger. By default, transitions are configured to react to the NULL trigger. However, the caller VI that
executes this statechart does not send the NULL trigger. Therefore, you must configure this transition to react
to a different trigger.
Each statechart has a list of triggers from which you can choose when configuring a transition. Configuring a
transition involves creating a trigger and then associating that trigger with the transition. Complete the
following steps to configure the transition.
1. Double-click the transition node between the Menu and Play states. This action launches the
Configure Transition dialog box. You use this dialog box to configure transitions. The first tab in this
dialog box is the Triggers/Groups tab. Notice that the NULL trigger is selected by default in the Triggers
and Groups list. Every statechart has this trigger by default.
2. Click the “Edit Triggers and Groups” button to launch the Edit Triggers and Groups dialog box. You use
this dialog box to create and modify triggers.
33 Tutorial: Create a Statechart
Tutorial: Introduction to State-based Applications in LabVIEW
3. Click the Create Trigger button to create a new trigger, which appears in the Triggers and Groups list.
4. Enter “Play” as the new trigger name.
5. Click the OK button to save changes and return to the Configure Transition dialog box. Notice the new
trigger appears in the Triggers list.
6. In the Triggers/Groups list, place a checkmark in the Play checkbox to specify that this trigger causes
the statechart to take the transition.
7. Remove the checkmark from the NULL checkbox.
8. Click the OK button to save changes and return to the statechart diagram.
9. Save the statechart by selecting File»Save in the Statechart Editor window. You also can press the
<Ctrl-S> keys.
Notice the blue rectangle on the transition node. This rectangle indicates that you have specified a non-NULL
trigger for the transition. If you move the cursor over the transition node, the Context Help window displays
the properties of the transition, including the trigger. If you do not see the Context Help window, press the
<Ctrl-H> keys to display this window.
Create and configure the following transitions and triggers. Remember also to deselect the NULL trigger for
each transition.
From the “Play” state to the “Menu” state. Configure this transition to react to the “Menu” trigger.
From the “Pause” state to the “Play” state. Configure this transition to react to the “Play” trigger.
From the “Play” state to the “Pause” state. Configure this transition to react to the “Pause” trigger.
The statechart should look like this:
34 Tutorial: Create a Statechart
Tutorial: Introduction to State-based Applications in LabVIEW
Step 5: Creating and Configuring the Terminal Transitions
Create a transition from the “Menu” state to the “Terminal” pseudostate. Configure this transition to react only
to a new trigger, Stop. This transition specifies that if the statechart is in the Menu state and receives the Stop
trigger, the statechart terminates.
Tip! Right-click the transition node and select either Rotate or Reverse to ensure the node faces the proper
direction.
Then, save the statechart by pressing the <Ctrl-S> keys.
The statechart diagram should now look like this:
Step 6: Creating and Configuring the Initial pseudostate and Transition
Place an Initial pseudostate, located on the Statechart Development palette, to the left of the “Menu” state.
Create a transition between this pseudostate and the “Menu” state. Notice the Generate Code button no
longer is broken.
The statechart should look like this:
35 Tutorial: Create a Statechart
Tutorial: Introduction to State-based Applications in LabVIEW
Step 7: Defining the Type of Output Data
If you want the statechart to modify data, you first must define the type of data. This process involves creating
the controls and/or indicators that represent the statechart data.
Complete the following steps to define the statechart output data. Later in this part of the tutorial, you
configure the statechart to modify this data.
1. Double-click the Outputs.ctl item in the project Explorer. LabVIEW displays the Control Editor window
for this type definition.
2. Notice the numeric control Numeric inside the Outputs cluster. Right-click this control and select
Change to Indicator to change this control to a numeric indicator.
3. Right-click the Numeric indicator and select Replace»String Indicator. This action replaces the numeric
indicator with a string indicator.
4. Double-click the String label and enter Current Activity as the new label.
5. Press the <Ctrl-S> keys to save this type definition.
6. Close the Control Editor window to return to the Project Explorer window.
Step 8: Defining the Type of State Data
State data is different from output data. State data is accessible from only the statechart, whereas output data
also is accessible from a VI that calls the statechart. Use state data to define data types that other VIs do not
need to access.
Complete the following steps to define the statechart state data.
1. In the Project Explorer window, double-click the StateData.ctl item.
2. Right-click the Data control and select Change to Indicator. This action replaces the numeric control
with a numeric indicator.
3. Double-click the Data label and enter Counter as the new label.
4. Press the <Ctrl-S> keys to save this type definition.
5. Close the Control Editor window to return to the Project Explorer window.
36 Tutorial: Create a Statechart
Tutorial: Introduction to State-based Applications in LabVIEW
Step 9: Configuring a State Entry Action
The next step is configuring each state to modify the Current Activity indicator that you defined earlier. You
accomplish this task by defining an entry action for a state. An entry action is LabVIEW block diagram code that
the statechart executes immediately after entering a state.
Complete the following steps to configure the Menu state to update this indicator.
1. Double-click the Diagram.vi item to display the Statechart Editor window.
2. Double-click the border of theMenu state. This action launches the Configure State dialog box.
Note! When you configure a state, a wrench icon appears on the state () in the Statechart Editor
window. The state also changes color.
3. Notice the Outputs cluster element on the right side of this block diagram. Click this cluster element
and select Outputs»Current Activity. This element now displays Outputs.Current Activity, which
indicates you can write to the value of the type definition you defined.
4. Move the cursor over the input of this cluster element until the cursor changes to the Wiring tool.
5. Right-click the input and select Create»Constant. LabVIEW places a string constant on the block
diagram.
6. Enter Menu as the value of the constant.
37 Tutorial: Create a Statechart
Tutorial: Introduction to State-based Applications in LabVIEW
7. This entry action code means that, immediately after entering the Menu state, the statechart changes
the Current Activity indicator to read Menu. Later in this tutorial, you will display the value of this
indicator in the VI that calls the statechart.
8. Click the OK button to save changes and return to the statechart diagram.
9. The next step is defining the “Play” and “Pause” states to update the Current Activity indicator
appropriately. Configure the Entry Action for each state to update this indicator to “Playing” or
“Paused”, respectively.
10. Save the statechart.
Step 10: Configuring the Action of a Transition
The transition from the “Menu” state to the “Terminal” pseudostate also causes a change in the activity of the
statechart. Complete the following steps to configure this transition.
Double-click the transition node in between the “Menu” state and “Terminal” pseudostate. This action
launches the Configure Transition dialog box.
Click the Action tab.
Write the block diagram code that changes the value of the “Current Activity” indicator to “Stopped”.
Click the OK button to save changes and return to the statechart diagram.
Note! The transition node you just configured now displays two blue rectangles. The second blue rectangle
indicates the transition has a specified action.
Step 11: Duplicating the Transition Node
The next step is creating transitions from the Play and Pause states to the Terminal pseudostate. Instead of
configuring additional transition nodes, you can duplicate the transition node you configured already.
Complete the following steps to duplicate this transition node.
1. Press the <Ctrl> key and click and drag the transition node you just configured.
2. Move this node under the Play state.
3. Click the bottom border of the Play state to initiate a transition segment.
38 Tutorial: Create a Statechart
Tutorial: Introduction to State-based Applications in LabVIEW
4. Move the cursor over the incoming tunnel of the transition node until LabVIEW displays a tip strip that
reads Segment In.
5. Click again to complete the transition segment.
6. Create a transition segment from the other side of this node to the Terminal pseudostate.
7. Right-click the transition node and select either Rotate or Reverse to ensure the node faces the proper
direction.
Repeat steps 1–7 to create an additional transition node from the Pause state to the Terminal pseudostate. All
three states now have a transition to the Terminal pseudostate.
Save the statechart.
Step 12: Generating Code for the Statechart
The next step is generating code for the statechart. This code is contained in a single Run Statechart function
that you place on the block diagram of the caller VI. Complete the following steps to generate code for this
statechart.
1. Display the Statechart Editor window.
2. Click the “Generate Code” button , which is located on the toolbar of this window.
3. Close the Statechart Editor window.
Note! You also can generate code by right-clicking the .lvsc file in the Project Explorer window and selecting
Generate Code from the shortcut menu.
Step 13: Creating the Caller VI
The next step is to create the caller VI to execute and send triggers to the statechart. This VI contains two
functions, Run Statechart and Send External Trigger, that you must link to the statechart.
Run Statechart Executes an instance of the linked statechart. You typically place this function inside a
loop in the caller VI.
Send External Trigger Sends a trigger to the external queue of an instance of the linked statechart. You
can use this function in the caller VI or in a VI that runs parallel to the caller VI.
Complete the following steps.
1. Select File»New VI from the Project Explorer window
2. Create 2 While Loops called “Statechart Loop” and “Trigger Loop”
3. Add the “Run Statechart” VI in the “Statechart Loop”
4. Add “Send External Trigger” function in the “Trigger Loop”
39 Tutorial: Create a Statechart
Tutorial: Introduction to State-based Applications in LabVIEW
5. Link “Run Statechart” and “Send External Trigger” to the statechart. Right-click and select “Link to
statechart…”
6. Finish the Caller VI so it looks like this:
7. The Front Panel should look like this:
40 Tutorial: Create a Statechart
Tutorial: Introduction to State-based Applications in LabVIEW
8. Press the <Ctrl-R> keys to run the caller VI. Click the front panel buttons and notice how the Current
Activity indicators changes according to the state.
Step 14: Debugging
Right-click the Run Statechart function and select “Debug Statechart…”. This action displays the statechart in
the Statechart Debugging window.
Click the “Highlight Execution” button , located on the toolbar of the Statechart Debugging window, to
enable statechart execution highlighting.
Run the Caller VI and see how the debugging works.
41
9 ADVANCED TOPICS IN LABVIEW STATECHART MODULE
In this chapter we will mention some of the more advance features in the LabVIEW Statechart Module.
9.1 USING REGIONS AND SUBSTATES
We recall the following objects from the Statechart Development palette:
Region Defines the area in which you can place states and pseudostates. Each region must contain an
Initial pseudostate and at least one substate. The top-level statechart diagram represents a region. You can
place regions within only a state.
Port Indicates where a transition leaves a state or connector. Ports also indicate where a transition
passes through a region. When you are editing a statechart, ports appear automatically as you create
transitions. You can place ports manually only when you are viewing a state as a subdiagram.
9.2 USING ORTHOGONAL REGIONS AND STATE HISTORY
We recall the following objects from the Statechart Development palette:
Shallow History Specifies that, when the statechart leaves and then returns to a region, the statechart
enters the highest-level substates that were active when the statechart left the region. To use the Shallow
History pseudostate, place this pseudostate in a region and then create a transition from a state to this
pseudostate.
Deep History Specifies that, when the statechart leaves and then returns to a region, the statechart
enters the lowest-level substates that were active when the statechart left the region. To use the Deep History
pseudostate, place this pseudostate in a region and then create a transition from a state to this pseudostate.
9.3 SPLITTING AND MERGING TRANSITION SEGMENTS
We recall the following objects from the Statechart Development palette:
Fork Splits one incoming transition segment into multiple outgoing segments. You can place this
connector within only a state.
Join Merges multiple incoming transition segments into one outgoing segment. You can place this
connector within only a state.
42 Advanced Topics in LabVIEW Statechart Module
Tutorial: Introduction to State-based Applications in LabVIEW43
10 WHATS NEXT?
10.1 MY BLOG
For more information about LabVIEW, visit my Blog: http://home.hit.no/~hansha/
10.2 TRAINING
This Tutorial is a part of a series with other Tutorials I have made, such as:
Introduction to LabVIEW
Data Acquisition in LabVIEW
Control and Simulation in LabVIEW
LabVIEW MathScript
Linear Algebra in LabVIEW
Datalogging and Supervisory Control in LabVIEW
Wireless Data Acquisition in LabVIEW
Intermediate Topics in LabVIEW
Advanced Topics in LabVIEW
These Tutorials are available for download from my blog: http://home.hit.no/~hansha
10.3 ADDITIONAL RESOURCES
www.ni.com
10.4 EXAMPLES
In the NI example Finder (Help→Find Examples…) you find lots of useful examples that you can play with or use
as a start when creating your own applications.
http://home.hit.no/~hansha/
http://home.hit.no/~hansha
http://www.ni.com/
44 Whats Next?
Tutorial: Introduction to State-based Applications in LabVIEW
10.5 DOCUMENTATION
As part of the LabVIEW installation there is lots of useful documentation.
10.6 LABVIEW WIKI
LabVIEW Wiki is the free LabVIEW information resource that anyone can edit.
http://labviewwiki.org/Home
http://labviewwiki.org/Home
45 Whats Next?
Tutorial: Introduction to State-based Applications in LabVIEW
10.7 LABVIEW ON YOUTUBE
There are lots of LabVIEW videos available at YouTube:
http://www.youtube.com/results?search_query=labview&search=Search
http://www.youtube.com/results?search_query=labview&search=Search
46
QUICK REFERENCE
47 Quick Reference
Tutorial: Introduction to State-based Applications in LabVIEW
Telemark University College
Faculty of Technology
Kjølnes Ring 56
N-3914 Porsgrunn, Norway
www.hit.no
Hans-Petter Halvorsen, M.Sc.
Telemark University College
Department of Electrical Engineering, Information Technology and Cybernetics
Phone: +47 3557 5158
E-mail: hans.p.halvorsen@hit.no
Blog: http://home.hit.no/~hansha/
Room: B-237a
http://www.hit.no/
mailto:hans.p.halvorsen@hit.no
http://home.hit.no/~hansha/
Telemark University College
Department of Electrical Engineering, Information Technology and Cybernetics
Faculty of Technology, Postboks 203, Kjølnes ring 56, N-3901 Porsgrunn, Norway. Tel: +47 35 57 50 00 Fax: +47 35 57 54 01
DATABASE COMMUNICATION IN
LABVIEW
HANS-PETTER HALVORSEN, 2010.01.15
PREFACE
This document explains the basic concepts of a database system and how to communicate with a database
from LabVIEW.
You should have some basic knowledge about LabVIEW, e.g., the “An Introduction to LabVIEW” training. This
document is available for download at http://home.hit.no/~hansha/.
In addition to LabVIEW Professional Development System, you need to install the “LabVIEW Database
Connectivity Toolkit”.
For more information about LabVIEW and Databases, visit my Blog: http://home.hit.no/~hansha/
Some text in this document is based on text from www.wikipedia.org and “LabVIEW Database Connectivity
Toolkit User Manual”.
http://home.hit.no/~hansha/
http://home.hit.no/~hansha/
http://www.wikipedia.org/
3
INSTALLATION REQUIREMENTS
NI LabVIEW
Name Required
LabVIEW Professional Development System Yes
NI LabVIEW Core Components
Name Required
LabVIEW Control Design and Simulation Module
LabVIEW MathScript RT Module
NI Vision Development Module
Vision Builder for Automated Inspection
LabVIEW Digital Filter Design Toolkit
LabVIEW Modulation Toolkit
LabVIEW System Identification Toolkit
LabVIEW Desktop Execution Trace Toolkit
LabVIEW Report Generation for Microsoft Office Toolkit
LabVIEW Database Connectivity Toolkit Yes
LabVIEW Internet Toolkit
NI LabVIEW SignalExpress
LabVIEW Basics 1 and 2 Computer Based Training
Extended Development Suite Components
Name Required
LabWindows/CVI Full Development System
LabWindows/CVI Real-Time Module
LabWindows/CVI PID Control Toolkit
LabWindows/CVI Signal Processing Toolkit
LabWindows/CVI Spectral Measurements Toolkit and Run-time Engine
LabWindows/CVI SQL Toolkit
Measurement Studio Enterprise Edition
DIAdem Professional
Control and Embedded Systems Option Components
Name Required
LabVIEW FPGA Module
LabVIEW Real-Time Module
LabVIEW Statechart Module
LabVIEW Mobile Module
LabVIEW Datalogging and Supervisory Control Module
LabVIEW PID and Fuzzy Logic Toolkit
NI Real-Time Execution Trace Toolkit
LabVIEW Simulation Interface Toolkit
NI Motion Assistant
NI-DAQ Base
Signal processing and Communications Option Components
Name Required
LabVIEW FPGA Module
LabVIEW Sound and Vibration Measurement Suite
LabVIEW Spectral Measurement Toolkit
LabVIEW Advanced Signal Processing Toolkit
LabVIEW Adaptive Filter Toolkit
NI Device Drivers
Name Required
FieldPoint
NI-DAQmx
NI LabVIEW SignalExpress
NI Instrument I/O Assistant
NI-IMAQ
NI Measurement & Automation Explorer
NI PXI
NI-VISA
vi
TABLE OF CONTENTS
Preface .................................................................................................................................................................... 2
Installation Requirements ....................................................................................................................................... 3
Table of Contents .................................................................................................................................................... vi
1 Introduction to LabVIEW ............................................................................................................................... 1
1.1 Dataflow programming.......................................................................................................................... 1
1.2 Graphical programming ......................................................................................................................... 1
1.3 Benefits .................................................................................................................................................. 2
2 Database Systems .......................................................................................................................................... 3
2.1 RDBMS Components.............................................................................................................................. 3
2.2 Data warehouse ..................................................................................................................................... 3
2.3 Relational Database ............................................................................................................................... 3
2.4 Real-time databases .............................................................................................................................. 4
2.5 Database Management Systems ........................................................................................................... 4
2.6 MDAC ..................................................................................................................................................... 4
2.6.1 ODBC ............................................................................................................................................. 5
2.6.2 OLE DB........................................................................................................................................... 5
2.6.3 ADO (ActiveX Data Objects) .......................................................................................................... 5
3 Relational Databases .....................................................................................................................................6
3.1 Tables ..................................................................................................................................................... 6
3.2 Unique Keys and Primary Key ................................................................................................................ 6
3.3 Foreign Key ............................................................................................................................................ 8
3.4 Views ..................................................................................................................................................... 9
3.5 Functions ............................................................................................................................................... 9
3.6 Stored procedures ................................................................................................................................. 9
3.7 Triggers ................................................................................................................................................ 10
4 Structured Query Language (SQL) ............................................................................................................... 11
vii Table of Contents
Tutorial: Database Communication in LabVIEW
4.1 Queries ................................................................................................................................................ 11
4.2 Data manipulation ............................................................................................................................... 12
4.3 Data definition ..................................................................................................................................... 13
4.4 Data types ............................................................................................................................................ 13
4.4.1 Character strings ......................................................................................................................... 13
4.4.2 Bit strings .................................................................................................................................... 13
4.4.3 Numbers ..................................................................................................................................... 13
4.4.4 Date and Time ............................................................................................................................. 14
5 Database Modelling ..................................................................................................................................... 15
5.1 ER Diagram .......................................................................................................................................... 15
5.2 Microsoft Visio ..................................................................................................................................... 16
EXERCISES ......................................................................................................................................................... 17
6 Microsoft SQL Server ................................................................................................................................... 19
6.1 Introduction ......................................................................................................................................... 19
6.2 Requirements ...................................................................................................................................... 19
6.3 SQL Server Express .............................................................................................................................. 19
6.4 AdventureWorks .................................................................................................................................. 19
6.5 SQL Server Management Studio .......................................................................................................... 20
6.6 Create a new Database ........................................................................................................................ 20
6.7 Backup/Restore ................................................................................................................................... 22
6.8 Example Database ............................................................................................................................... 23
EXERCISES ......................................................................................................................................................... 25
7 Microsoft Office Access ............................................................................................................................... 26
7.1 Introduction ......................................................................................................................................... 26
7.2 Example Database ............................................................................................................................... 26
EXERCISES ......................................................................................................................................................... 28
8 LabVIEW Database Connectivity Toolkit ...................................................................................................... 30
8.1 Connect to the Database ..................................................................................................................... 30
viii Table of Contents
Tutorial: Database Communication in LabVIEW
8.1.1 DSN ............................................................................................................................................. 31
8.1.2 UDL .............................................................................................................................................. 33
8.1.3 Connection String ....................................................................................................................... 34
8.2 Reading Data from the Database ........................................................................................................ 34
8.3 Writing Data to the Database .............................................................................................................. 37
8.4 Using Stored Procedures ..................................................................................................................... 39
8.5 Creating and Droping Tables ............................................................................................................... 39
8.6 Using the Database Connectivity Toolkit Utility VIs ............................................................................ 40
8.7 Performing Advanced Database Operations ....................................................................................... 41
9 Creating and Using Tables ........................................................................................................................... 43
EXERCISES ......................................................................................................................................................... 45
10 Creating and Using Views ............................................................................................................................ 46
EXERCISES ......................................................................................................................................................... 46
11 Creating and using Stored Procedures ........................................................................................................ 47
Exercises ...........................................................................................................................................................48
12 Creating and Using Triggers ......................................................................................................................... 49
EXERCISES ......................................................................................................................................................... 49
13 cREATING AND USING fUNCTIONS .............................................................................................................. 50
EXERCISES ......................................................................................................................................................... 50
14 SQL Toolkit ................................................................................................................................................... 51
14.1 Installation ........................................................................................................................................... 51
15 Whats Next? ................................................................................................................................................ 54
15.1 My Blog ................................................................................................................................................ 54
15.2 Training ................................................................................................................................................ 54
15.3 Additional Resources ........................................................................................................................... 54
15.4 Examples .............................................................................................................................................. 54
15.5 Documentation .................................................................................................................................... 55
15.6 LabVIEW Wiki....................................................................................................................................... 55
ix Table of Contents
Tutorial: Database Communication in LabVIEW
15.7 LabVIEW on YouTube .......................................................................................................................... 56
Quick Reference .................................................................................................................................................... 57
1
1 INTRODUCTION TO LABVIEW
LabVIEW (short for Laboratory Virtual Instrumentation Engineering Workbench) is a platform and development
environment for a visual programming language from National Instruments. The graphical language is named
"G". Originally released for the Apple Macintosh in 1986, LabVIEW is commonly used for data acquisition,
instrument control, and industrial automation on a variety of platforms including Microsoft Windows, various
flavors of UNIX, Linux, and Mac OS X. The latest version of LabVIEW is version LabVIEW 2009, released in
August 2009. Visit National Instruments at www.ni.com.
The code files have the extension “.vi”, which is a abbreviation for “Virtual Instrument”. LabVIEW offers lots of
additional Add-Ons and Toolkits.
This paper is part of a series with LabVIEW papers:
Introduction to LabVIEW
Data Acquisition in LabVIEW
Control and Simulation in LabVIEW
LabVIEW MathScript
Linear Algebra in LabVIEW
Datalogging and Supervisory Control in LabVIEW
Wireless Data Acquisition in LabVIEW
Intermediate Topics in LabVIEW
Advanced Topics in LabVIEW
Each paper may be used independently of each other.
1.1 DATAFLOW PROGRAMMING
The programming language used in LabVIEW, also referred to as G, is a dataflow programming language.
Execution is determined by the structure of a graphical block diagram (the LV-source code) on which the
programmer connects different function-nodes by drawing wires. These wires propagate variables and any
node can execute as soon as all its input data become available. Since this might be the case for multiple nodes
simultaneously, G is inherently capable of parallel execution. Multi-processing and multi-threading hardware is
automatically exploited by the built-in scheduler, which multiplexes multiple OS threads over the nodes ready
for execution.
1.2 GRAPHICAL PROGRAMMING
LabVIEW ties the creation of user interfaces (called front panels) into the development cycle. LabVIEW
programs/subroutines are called virtual instruments (VIs). Each VI has three components: a block diagram, a
front panel, and a connector panel. The last is used to represent the VI in the block diagrams of other, calling
VIs. Controls and indicators on the front panel allow an operator to input data into or extract data from a
running virtual instrument. However, the front panel can also serve as a programmatic interface. Thus a virtual
instrument can either be run as a program, with the front panel serving as a user interface, or, when dropped
as a node onto the block diagram, the front panel defines the inputs and outputs for the given node through
the connector pane. This implies each VI can be easily tested before being embedded as a subroutine into a
larger program.
http://www.ni.com/
2 Introduction to LabVIEW
Tutorial: Database Communication in LabVIEW
The graphical approach also allows non-programmers to build programs simply by dragging and dropping
virtual representations of lab equipment with which they are already familiar. The LabVIEW programming
environment, with the included examples and the documentation, makes it simple to create small applications.
This is a benefit on one side, but there is also a certain danger of underestimating the expertise needed for
good quality "G" programming. For complex algorithms or large-scale code, it is important that the
programmer possess an extensive knowledge of the special LabVIEW syntax and the topology of its memory
management. The most advanced LabVIEW development systems offer the possibility of building stand-alone
applications. Furthermore, it is possible to create distributed applications, which communicate by a
client/server scheme, and are therefore easier to implement due to the inherently parallel nature of G-code.
1.3 BENEFITS
One benefit of LabVIEW over other development environments is the extensive support for accessing
instrumentation hardware. Drivers and abstraction layers for many different types of instruments and buses
are included or are available for inclusion. These present themselves as graphical nodes. The abstraction layers
offer standard software interfaces to communicate with hardware devices. The provided driver interfaces save
program development time. The sales pitch of National Instruments is, therefore, that even people with limited
coding experience can write programs and deploy test solutions in a reduced time frame when compared to
more conventional or competing systems. A new hardware driver topology (DAQmxBase), which consists
mainly of G-coded components with only a few register calls through NI Measurement Hardware DDK (Driver
Development Kit) functions, provides platform independent hardware access to numerous data acquisition and
instrumentation devices. The DAQmxBase driver is available for LabVIEW on Windows, Mac OS X and Linux
platforms.
3
2 DATABASE SYSTEMS
A database is an integrated collection of logically related records or files consolidated into a common pool that
provides data for one or more multiple uses.
One way of classifying databases involves the type of content, for example: bibliographic, full-text, numeric,
and image. Other classification methods start from examining database models or database architectures.
The data in a database is organized according to a database model. The relational model is the most common.
A Database Management System (DBMS)consists of software that organizes the storage of data. A DBMS
controls the creation, maintenance, and use of the database storage structures of organizations and of their
end users. It allows organizations to place control of organization-wide database development in the hands of
Database Administrators (DBAs) and other specialists. In large systems, a DBMS allows users and other
software to store and retrieve data in a structured way.
Database management systems are usually categorized according to the database model that they support,
such as the network, relational or object model. The model tends to determine the query languages that are
available to access the database. One commonly used query language for the relational database is SQL,
although SQL syntax and function can vary from one DBMS to another. A great deal of the internal engineering
of a DBMS is independent of the data model, and is concerned with managing factors such as performance,
concurrency, integrity, and recovery from hardware failures. In these areas there are large differences between
products.
2.1 RDBMS COMPONENTS
A Relational Database Management System (DBMS) consists of the following components:
Interface drivers - A user or application program initiates either schema modification or content
modification. These drivers are built on top of SQL. They provide methods to prepare statements,
execute statements, fetch results, etc. An important example is the ODBC driver.
SQL engine - This component interprets and executes the SQL query. It comprises three major
components (compiler, optimizer, and execution engine).
Transaction engine - Transactions are sequences of operations that read or write database elements,
which are grouped together.
Relational engine - Relational objects such as Table, Index, and Referential integrity constraints are
implemented in this component.
Storage engine - This component stores and retrieves data records. It also provides a mechanism to
store metadata and control information such as undo logs, redo logs, lock tables, etc.
2.2 DATA WAREHOUSE
A data warehouse stores data from current and previous years — data extracted from the various operational
databases of an organization. It becomes the central source of data that has been screened, edited,
standardized and integrated so that it can be used by managers and other end-user professionals throughout
an organization.
2.3 RELATIONAL DATABASE
4 2
Tutorial: Database Communication in LabVIEW
A relational database matches data using common characteristics found within the data set. The resulting
groups of data are organized and are much easier for people to understand.
For example, a data set containing all the real-estate transactions in a town can be grouped by the year the
transaction occurred; or it can be grouped by the sale price of the transaction; or it can be grouped by the
buyer's last name; and so on.
Such a grouping uses the relational model (a technical term for this is schema). Hence, such a database is called
a "relational database."
The software used to do this grouping is called a relational database management system. The term "relational
database" often refers to this type of software.
Relational databases are currently the predominant choice in storing financial records, manufacturing and
logistical information, personnel data and much more.
Strictly, a relational database is a collection of relations (frequently called tables).
2.4 REAL-TIME DATABASES
A real-time database is a processing system designed to handle workloads whose state may change constantly.
This differs from traditional databases containing persistent data, mostly unaffected by time. For example, a
stock market changes rapidly and dynamically. Real-time processing means that a transaction is processed fast
enough for the result to come back and be acted on right away. Real-time databases are useful for accounting,
banking, law, medical records, multi-media, process control, reservation systems, and scientific data analysis.
As computers increase in power and can store more data, real-time databases become integrated into society
and are employed in many applications
2.5 DATABASE MANAGEMENT SYSTEMS
There are Database Management Systems (DBMS), such as:
Microsoft SQL Server
Oracle
Sybase
dBase
Microsoft Access
MySQL from Sun Microsystems (Oracle)
DB2 from IBM
etc.
This document will focus on Microsoft Access and Microsoft SQL Server.
2.6 MDAC
The Microsoft Data Access Components (MDAC) is the framework that makes it possible to connect and
communicate with the database. MDAC includes the following components:
5 2
Tutorial: Database Communication in LabVIEW
ODBC (Open Database Connectivity)
OLE DB
ADO (ActiveX Data Objects)
MDAC also installs several data providers you can use to open a connection to a specific data source, such as an
MS Access database.
2.6.1 ODBC
Open Database Connectivity (ODBC) is a native interface that is accessed through a programming language
that can make calls into a native library. In MDAC this interface is defined as a DLL. A separate module or driver
is needed for each database that must be accessed.
2.6.2 OLE DB
OLE allows MDAC applications access to different types of data stores in a uniform manner. Microsoft has used
this technology to separate the application from the data store that it needs to access. This was done because
different applications need access to different types and sources of data, and do not necessarily need to know
how to access technology-specific functionality. The technology is conceptually divided into consumers and
providers. The consumers are the applications that need access to the data, and the provider is the software
component that exposes an OLE DB interface through the use of the Component Object Model (or COM).
2.6.3 ADO (ACTIVEX DATA OBJECTS)
ActiveX Data Objects (ADO) is a high level programming interface to OLE DB. It uses a hierarchical object model
to allow applications to programmatically create, retrieve, update and delete data from sources supported by
OLE DB. ADO consists of a series of hierarchical COM-based objects and collections, an object that acts as a
container of many other objects. A programmer can directly access ADO objects to manipulate data, or can
send an SQL query to the database via several ADO mechanisms.
6
3 RELATIONAL DATABASES
A relational database matches data using common characteristics found within the data set. The resulting
groups of data are organized and are much easier for people to understand.
For example, a data set containing all the real-estate transactions in a town can be grouped by the year the
transaction occurred; or it can be grouped by the sale price of the transaction; or it can be grouped by the
buyer's last name; and so on.
Such a grouping uses the relational model (a technical term for this is schema). Hence, such a database is called
a "relational database."
The software used to do this grouping is called a relational database management system. The term "relational
database" often refers to this type of software.
Relational databases are currently the predominant choice in storing financial records, manufacturing and
logistical information, personnel data and much more.
3.1 TABLES
The basic units in a database are tables and the relationship between them. Strictly, a relational database is a
collection of relations (frequently called tables).
3.2 UNIQUE KEYS AND PRIMARY KEY
In relational database design, a unique key or primary key is a candidate key to uniquely identify each row in a
table. A unique key or primary key comprises a single column or set of columns. No two distinct rows in a table
can have the same value (or combination of values) in those columns. Dependingon its design, a table may
have arbitrarily many unique keys but at most one primary key.
A unique key must uniquely identify all possible rows that exist in a table and not only the currently existing
rows. Examples of unique keys are Social Security numbers or ISBNs.
A primary key is a special case of unique keys. The major difference is that for unique keys the implicit NOT
NULL constraint is not automatically enforced, while for primary keys it is enforced. Thus, the values in unique
key columns may or may not be NULL. Another difference is that primary keys must be defined using another
syntax.
Primary keys are defined with the following syntax:
CREATE TABLE table_name (
7 Relational Databases
Tutorial: Database Communication in LabVIEW
id_col INT,
col2 CHARACTER VARYING(20),
...
CONSTRAINT tab_pk PRIMARY KEY(id_col),
...
)
If the primary key consists only of a single column, the column can be marked as such using the following
syntax:
CREATE TABLE table_name (
id_col INT PRIMARY KEY,
col2 CHARACTER VARYING(20),
...
)
The definition of unique keys is syntactically very similar to primary keys.
Likewise, unique keys can be defined as part of the CREATE TABLE SQL statement.
CREATE TABLE table_name (
id_col INT,
col2 CHARACTER VARYING(20),
key_col SMALLINT,
...
CONSTRAINT key_unique UNIQUE(key_col),
...
)
Or if the unique key consists only of a single column, the column can be marked as such using the following
syntax:
CREATE TABLE table_name (
id_col INT PRIMARY KEY,
col2 CHARACTER VARYING(20),
...
key_col SMALLINT UNIQUE,
8 Relational Databases
Tutorial: Database Communication in LabVIEW
...
)
3.3 FOREIGN KEY
In the context of relational databases, a foreign key is a referential constraint between two tables. The foreign
key identifies a column or a set of columns in one table that refers to a column or set of columns in another
table. The columns in the referencing table must be the primary key or other candidate key in the referenced
table. The values in one row of the referencing columns must occur in a single row in the referenced table.
Thus, a row in the referencing table cannot contain values that don't exist in the referenced table. This way
references can be made to link information together and it is an essential part of database normalization.
Multiple rows in the referencing table may refer to the same row in the referenced table. Most of the time, it
reflects the one (master table, or referenced table) to many (child table, or referencing table) relationship.
The referencing and referenced table may be the same table, i.e. the foreign key refers back to the same table.
Such a foreign key is known as self-referencing or recursive foreign key.
A table may have multiple foreign keys, and each foreign key can have a different referenced table. Each
foreign key is enforced independently by the database system. Therefore, cascading relationships between
tables can be established using foreign keys.
Improper foreign key/primary key relationships or not enforcing those relationships are often the source of
many database and data modeling problems.
Foreign keys can be defined as part of the CREATE TABLE SQL statement.
CREATE TABLE table_name (
id INTEGER PRIMARY KEY,
col2 CHARACTER VARYING(20),
col3 INTEGER,
...
CONSTRAINT col3_fk FOREIGN KEY(col3)
REFERENCES other_table(key_col),
... )
If the foreign key is a single column only, the column can be marked as such using the following syntax:
CREATE TABLE table_name (
id INTEGER PRIMARY KEY,
col2 CHARACTER VARYING(20),
col3 INTEGER REFERENCES other_table(column_name),
... )
9 Relational Databases
Tutorial: Database Communication in LabVIEW
3.4 VIEWS
In database theory, a view consists of a stored query accessible as a virtual table composed of the result set of
a query. Unlike ordinary tables in a relational database, a view does not form part of the physical schema: it is a
dynamic, virtual table computed or collated from data in the database. Changing the data in a table alters the
data shown in subsequent invocations of the view.
Views can provide advantages over tables:
Views can represent a subset of the data contained in a table
Views can join and simplify multiple tables into a single virtual table
Views can act as aggregated tables, where the database engine aggregates data (sum, average etc)
and presents the calculated results as part of the data
Views can hide the complexity of data; for example a view could appear as Sales2000 or Sales2001,
transparently partitioning the actual underlying table
Views take very little space to store; the database contains only the definition of a view, not a copy of
all the data it presents
Views can limit the degree of exposure of a table or tables to the outer world
Syntax:
CREATE VIEW <ViewName>
AS
…
3.5 FUNCTIONS
In SQL databases, a user-defined function provides a mechanism for extending the functionality of the
database server by adding a function that can be evaluated in SQL statements. The SQL standard distinguishes
between scalar and table functions. A scalar function returns only a single value (or NULL), whereas a table
function returns a (relational) table comprising zero or more rows, each row with one or more columns.
User-defined functions in SQL are declared using the CREATE FUNCTION statement.
Syntax:
CREATE FUNCTION <FunctionName>
(@Parameter1 <datatype>,
@ Parameter2 <datatype>,
…)
RETURNS <datatype>
AS
…
3.6 STORED PROCEDURES
10 Relational Databases
Tutorial: Database Communication in LabVIEW
A stored procedure is executable code that is associated with, and generally stored in, the database. Stored
procedures usually collect and customize common operations, like inserting a tuple into a relation, gathering
statistical information about usage patterns, or encapsulating complex business logic and calculations.
Frequently they are used as an application programming interface (API) for security or simplicity.
Stored procedures are not part of the relational database model, but all commercial implementations include
them.
Stored procedures are called or used with the following syntax:
CALL procedure(…)
or
EXECUTE procedure(…)
Stored procedures can return result sets, i.e. the results of a SELECT statement. Such result sets can be
processed using cursors by other stored procedures by associating a result set locator, or by applications.
Stored procedures may also contain declared variables for processing data and cursors that allow it to loop
through multiple rows in a table. The standard Structured Query Language provides IF, WHILE, LOOP, REPEAT,
CASE statements, and more. Stored procedures can receive variables, return results or modify variables and
return them, depending on how and where the variable is declared.
3.7 TRIGGERS
A database trigger is procedural code that is automatically executed in response to certain events on a
particular table or view in a database. The trigger is mostly used for keeping the integrity of the information on
the database. For example, when a new record (representing a new worker) added to the employees table,
new records should be created also in the tables of the taxes, vacations, and salaries.
The syntax is as follows:
CREATE TRIGGER <TriggerName> ON <TableName>
FOR INSERT, UPDATE, DELETE
AS
…
11
4 STRUCTURED QUERY LANGUAGE (SQL)
SQL (Structured Query Language) is a database computer language designed for managing data in relational
database management systems (RDBMS).
4.1 QUERIES
The most common operation in SQL is the query,which is performed with the declarative SELECT statement.
SELECT retrieves data from one or more tables, or expressions. Standard SELECT statements have no persistent
effects on the database.
Queries allow the user to describe desired data, leaving the database management system (DBMS) responsible
for planning, optimizing, and performing the physical operations necessary to produce that result as it chooses.
A query includes a list of columns to be included in the final result immediately following the SELECT keyword.
An asterisk ("*") can also be used to specify that the query should return all columns of the queried tables.
SELECT is the most complex statement in SQL, with optional keywords and clauses that include:
The FROM clause which indicates the table(s) from which data is to be retrieved. The FROM clause can
include optional JOIN subclauses to specify the rules for joining tables.
The WHERE clause includes a comparison predicate, which restricts the rows returned by the query.
The WHERE clause eliminates all rows from the result set for which the comparison predicate does not
evaluate to True.
The GROUP BY clause is used to project rows having common values into a smaller set of rows.
GROUP BY is often used in conjunction with SQL aggregation functions or to eliminate duplicate rows
from a result set. The WHERE clause is applied before the GROUP BY clause.
The HAVING clause includes a predicate used to filter rows resulting from the GROUP BY clause.
Because it acts on the results of the GROUP BY clause, aggregation functions can be used in the
HAVING clause predicate.
The ORDER BY clause identifies which columns are used to sort the resulting data, and in which
direction they should be sorted (options are ascending or descending). Without an ORDER BY clause,
the order of rows returned by an SQL query is undefined.
Example:
The following is an example of a SELECT query that returns a list of expensive books. The query retrieves all
rows from the Book table in which the price column contains a value greater than 100.00. The result is sorted
in ascending order by title. The asterisk (*) in the select list indicates that all columns of the Book table should
be included in the result set.
SELECT *
FROM Book
WHERE price > 100.00
ORDER BY title;
The example below demonstrates a query of multiple tables, grouping, and aggregation, by returning a list of
books and the number of authors associated with each book.
12 Structured Query Language (SQL)
Tutorial: Database Communication in LabVIEW
SELECT Book.title,count(*) AS Authors
FROM Book
JOIN Book_author ON Book.isbn = Book_author.isbn
GROUP BY Book.title
Example output might resemble the following:
Title Authors
-------------------------------
SQL Examples and Guide 4
The Joy of SQL 1
An Introduction to SQL 2
Pitfalls of SQL 1
4.2 DATA MANIPULATION
The Data Manipulation Language (DML) is the subset of SQL used to add, update and delete data.
The acronym CRUD refers to all of the major functions that need to be implemented in a relational database
application to consider it complete. Each letter in the acronym can be mapped to a standard SQL statement:
Operation SQL
Create INSERT
Read (Retrieve) SELECT
Update UPDATE
Delete (Destroy) DELETE
Example: INSERT
INSERT adds rows to an existing table, e.g.,:
INSERT INTO My_table field1, field2, field3)
VALUES ('test', 'N', NULL)
Example: UPDATE
UPDATE modifies a set of existing table rows, e.g.,:
UPDATE My_table
SET field1 = 'updated value'
WHERE field2 = 'N'
Example: DELETE
13 Structured Query Language (SQL)
Tutorial: Database Communication in LabVIEW
DELETE removes existing rows from a table, e.g.,:
DELETE FROM My_table
WHERE field2 = 'N'
4.3 DATA DEFINITION
The Data Definition Language (DDL) manages table and index structure. The most basic items of DDL are the
CREATE, ALTER, RENAME and DROP statements:
CREATE creates an object (a table, for example) in the database.
DROP deletes an object in the database, usually irretrievably.
ALTER modifies the structure an existing object in various ways—for example, adding a column to an
existing table.
Example: CREATE
Create a Database Table
CREATE TABLE My_table
(
my_field1 INT,
my_field2 VARCHAR(50),
my_field3 DATE NOT NULL,
PRIMARY KEY (my_field1)
)
4.4 DATA TYPES
Each column in an SQL table declares the type(s) that column may contain. ANSI SQL includes the following
datatypes.
4.4.1 CHARACTER STRINGS
CHARACTER(n) or CHAR(n) — fixed-width n-character string, padded with spaces as needed
CHARACTER VARYING(n) or VARCHAR(n) — variable-width string with a maximum size of n characters
NATIONAL CHARACTER(n) or NCHAR(n) — fixed width string supporting an international character set
NATIONAL CHARACTER VARYING(n) or NVARCHAR(n) — variable-width NCHAR string
4.4.2 BIT STRINGS
BIT(n) — an array of n bits
BIT VARYING(n) — an array of up to n bits
4.4.3 NUMBERS
14 Structured Query Language (SQL)
Tutorial: Database Communication in LabVIEW
INTEGER and SMALLINT
FLOAT, REAL and DOUBLE PRECISION
NUMERIC(precision, scale) or DECIMAL(precision, scale)
4.4.4 DATE AND TIME
DATE
TIME
TIMESTAMP
INTERVAL
15
5 DATABASE MODELLING
5.1 ER DIAGRAM
In software engineering, an Entity-Relationship Model (ERM) is an abstract and conceptual representation of
data. Entity-relationship modeling is a database modeling method, used to produce a type of conceptual
schema or semantic data model of a system, often a relational database, and its requirements in a top-down
fashion.
Diagrams created using this process are called entity-relationship diagrams, or ER diagrams or ERDs for short.
There are many ER diagramming tools. Some of the proprietary ER diagramming tools are ERwin, Enterprise
Architect and Microsoft Visio.
Microsoft SQL Server has also a built-in tool for creating Database Diagrams.
http://en.wikipedia.org/wiki/File:ER_Diagram_MMORPG.png
16 Database Modelling
Tutorial: Database Communication in LabVIEW
5.2 MICROSOFT VISIO
Microsoft Visio is a diagramming program for creating different kinds of diagrams. Visio have a template for
creating Database Model Diagrams.
In the Database menu Visio offers lots of functionality regarding your database model.
17 Database Modelling
Tutorial: Database Communication in LabVIEW
“Reverse Engineering” is the opposite procedure, i.e., extraction of a database schema from an existing
database into a database model in Microsoft Visio.
EXERCISES
Exercise: Database Diagram
Create the following tables in an ER Diagram using MS Visio.
CUSTOMER
o CustomerId (PK)
o FirstName
o LastName
o Address
o Phone
o PostCode
o PostAddress
PRODUCT
o ProductId (PK)
o ProductName
o ProductDescription
o Price
o ProductCode
ORDER
o OrderId (PK)
o OrderNumber
o OrderDescription
o CustomerId (FK)
ORDER_DETAIL
18 Database Modelling
Tutorial: Database Communication in LabVIEW
o OrderDetailId (PK)
o OrderId (FK)
o ProductId (FK)
Database Diagram:
19
6 MICROSOFT SQL SERVER
6.1 INTRODUCTION
Microsoft SQL Server is a relational model database server produced by Microsoft. Its primary query languages
are T-SQL and ANSI SQL.
The latest version is Microsoft SQL Server 2008.
Microsoft SQL Server homepage: www.microsoft.com/sqlserver
The Microsoft SQL Server comes in different versions, such as:
SQL Server Developer Edition
SQL Server Enterprise Edition
SQL Server Web Edition
SQL Server Express Edition
Etc.
The SQL Server Express Edition is a freely-downloadable and -distributable version.
6.2 REQUIREMENTSIn order to install SQL Server 2008, you need:
Microsoft .NET Framework 3.5 SP1
Windows Installer 4.5
Windows PowerShell 1.0
Note: You must have administrative rights on the computer to install Microsoft SQL Server 2008.
6.3 SQL SERVER EXPRESS
The SQL Server Express Edition is a freely-downloadable and -distributable version.
However, the Express edition has a number of technical restrictions which make it undesirable for large-scale
deployments, including:
Maximum database size of 4 GB per. The 4 GB limit applies per database (log files excluded); but in
some scenarios users can access more data through the use of multiple interconnected databases.
Single physical CPU, multiple cores
1 GB of RAM (runs on any size RAM system, but uses only 1 GB)
SQL Server Express offers a GUI tools for database management in a separate download and installation
package, called SQL Server Management Studio Express.
6.4 ADVENTUREWORKS
The AdventureWorks is a sample Database with lots of examples, etc.
http://www.microsoft.com/sqlserver
20 Microsoft SQL Server
Tutorial: Database Communication in LabVIEW
You should install this sample Database because some of the examples in this document will use the
AdventureWorks database.
6.5 SQL SERVER MANAGEMENT STUDIO
SQL Server Management Studio is a GUI tool included with SQL Server for configuring, managing, and
administering all components within Microsoft SQL Server. The tool includes both script editors and graphical
tools that work with objects and features of the server. As mentioned earlier, version of SQL Server
Management Studio is also available for SQL Server Express Edition, for which it is known as SQL Server
Management Studio Express.
A central feature of SQL Server Management Studio is the Object Explorer, which allows the user to browse,
select, and act upon any of the objects within the server. It can be used to visually observe and analyze query
plans and optimize the database performance, among others. SQL Server Management Studio can also be used
to create a new database, alter any existing database schema by adding or modifying tables and indexes, or
analyze performance. It includes the query windows which provide a GUI based interface to write and execute
queries.
6.6 CREATE A NEW DATABASE
It is quite simple to create a new database in Microsoft SQL Server. Just right-click on the “Databases” node and
select “New Database…”
21 Microsoft SQL Server
Tutorial: Database Communication in LabVIEW
There are lots of settings you may set regarding your database, but the only information you must fill in is the
name of your database:
22 Microsoft SQL Server
Tutorial: Database Communication in LabVIEW
6.7 BACKUP/RESTORE
An important task in database systems is to take backup of the database with regular intervals, e.g., during the
night when the system is not in use.
Database backup and Restore:
23 Microsoft SQL Server
Tutorial: Database Communication in LabVIEW
6.8 EXAMPLE DATABASE
Examples and exercises in this training are based on some basic tables. The Example Database consists of the
following Tables:
24 Microsoft SQL Server
Tutorial: Database Communication in LabVIEW
CUSTOMER
o CustomerId (PK)
o FirstName
o LastName
o Address
o Phone
o PostCode
o PostAddress
PRODUCT
o ProductId (PK)
o ProductName
o ProductDescription
o Price
o ProductCode
ORDER
o OrderId (PK)
o OrderNumber
o OrderDescription
o CustomerId (FK)
ORDER_DETAIL
o OrderDetailId (PK)
o OrderId (FK)
o ProductId (FK)
25 Microsoft SQL Server
Tutorial: Database Communication in LabVIEW
EXERCISES
Exercise: New Database
Create a new Database in MS SQL Server called TEST_SQLSERVER.
Exercise: Database Diagram
Create the tables in the Example Database using the Diagram Designer Tool in Microsoft SQL Server.
Exercise: Database Script
Create the tables in the Example Database Tables using SQL Code. Save the Tables as a SQL Script file (.sql). Use
The Query Tool in Microsoft SQL Server.
Exercise: ODBC
Create an ODBC connection for the Database.
26
7 MICROSOFT OFFICE ACCESS
7.1 INTRODUCTION
Microsoft Office Access, previously known as Microsoft Access, is a relational database management system
from Microsoft that combines the relational Microsoft Jet Database Engine with a graphical user interface and
software development tools. It is a member of the Microsoft Office suite of applications and is included in the
Professional and higher versions for Windows. Access stores data in its own format based on the Access Jet
Database Engine.
Microsoft Access is used by programmers and non-programmers to create their own simple database solutions.
Microsoft Access is a file server-based database. Unlike client-server relational database management systems
(RDBMS), e.g., Microsoft SQL Server, Microsoft Access does not implement database triggers, stored
procedures, or transaction logging. All database tables, queries, forms, reports, macros, and modules are
stored in the Access Jet database as a single file. This makes Microsoft Access useful in small applications,
teaching, etc. because it is easy to move from one computer to another.
7.2 EXAMPLE DATABASE
I will present an example database in Microsoft Access 2007 which will be used in some of the examples and
exercises in this document.
The database consists of the following tables:
CUSTOMER
o CustomerId (PK)
o FirstName
o LastName
o Address
o Phone
o PostCode
o PostAddress
PRODUCT
o ProductId (PK)
o ProductName
o ProductDescription
o Price
o ProductCode
ORDER
o OrderId (PK)
o OrderNumber
o OrderDescription
o CustomerId (FK)
ORDER_DETAIL
o OrderDetailId (PK)
o OrderId (FK)
o ProductId (FK)
27 Microsoft Office Access
Tutorial: Database Communication in LabVIEW
ODBC Connection:
Administrative Tools → Data Sources (ODBC)
28 Microsoft Office Access
Tutorial: Database Communication in LabVIEW
EXERCISES
Exercise: Database
Create a new Database in MS Access called TEST.
Exercise: Database Tables
29 Microsoft Office Access
Tutorial: Database Communication in LabVIEW
Create the tables in the Example Database Tables using the Diagram Designer Tool in Microsoft SQL Server.
Exercise: ODBC
Create an ODBC connection for the Database.
30
8 LABVIEW DATABASE CONNECTIVITY TOOLKIT
LabVIEW offers an additional Toolkit called “LabVIEW Database Connectivity Toolkit”. With this toolkit you can
communicate with different databases, such as SQL Server, Oracle, etc.
Functions Palette: Connectivity → Database
The following list describes the main features of the Database Connectivity Toolkit:
Works with any provider that adheres to the Microsoft ActiveX Data Object (ADO) standard.
Works with any database driver that complies with ODBC or OLE DB.
Maintains a high level of portability. In many cases, you can port an application to another database
by changing the connection information you pass to the DB Tools Open Connection VI.
Converts database column values from native data types to standard Database Connectivity Toolkit
data types, further enhancing portability.
Permits the use of SQL statements with all supported database systems, even non-SQL systems.
Includes VIs to retrieve the name and data type of a column returned by a SELECT statement.
Creates tables and selects, inserts, updates, and deletes records without using SQL statements.
Some of the text in this chapter is based on the “LabVIEW Database Connectivity Toolkit User Manual”.
8.1 CONNECT TO THE DATABASE
Before you can access data in a table or execute SQL statements, you must establish a connection to a
database. You may usedifferent methods in order to connect to the database:
ODBC Data Source Name (DSN)
Universal Data Link (UDL)
Connection String
These different methods are explained below.
For all of these methods, you will use the same VI:
31 LabVIEW Database Connectivity Toolkit
Tutorial: Database Communication in LabVIEW
Connecting to a database is where most errors occur because each database management system (DBMS) uses
different parameters for the connection and different levels of security. The different standards also use
different methods of connecting to databases. For example, ODBC uses Data Source Names (DSN) for the
connection, whereas the Microsoft ActiveX Data Object (ADO) standard uses Universal Data Links (UDL) for the
connection. The “DB Tools Open Connection.vi” VI supports all these methods for connecting to a database.
When you are finished with reading from the database and writing to the database, you should always close
the Connection. Use the “DB Tools Close Connection.vi”.
8.1.1 DSN
A DSN (ODBC Data Source Name (DSN)) is the name of the data source, or database, to which you are
connecting. The DSN also contains information about the ODBC driver and other connection attributes
including paths, security information, and read-only status of the database. Two main types of DSNs exist:
machine DSNs and file DSNs. Machine DSNs are in the system registry and apply to all users of the computer
system or to a single user. DSNs that apply to all users of a computer system are system DSNs. DSNs that apply
to single users are user DSNs. A file DSN is a text file with a .dsn extension and is accessible to anyone with
proper permissions. File DSNs are not restricted to a single user or computer system. Use the ODBC Data
Source Administrator to create and configure DSNs.
In the Control Panel, Administrative Tools, you find the ODBC Data Source Administrator tool.
32 LabVIEW Database Connectivity Toolkit
Tutorial: Database Communication in LabVIEW
Example: DSN
This Example specifies a DSN called MS Access to open a connection to that specific database.
Example: DSN from File
You can use a path to specify a file DSN. This example specifies a path to a file DSN called “access.dsn” to open
a connection to the database.
Example: DSN with UserId and Password
Most Database systems (DBMS – Database Management Systems) also require a UserId and a Password.
33 LabVIEW Database Connectivity Toolkit
Tutorial: Database Communication in LabVIEW
8.1.2 UDL
Whereas you must create a DSN to connect to a database using ODBC, you use UDL (Universal Data Link) to
connect to databases that use ADO and OLE DB.
A UDL is similar to a DSN in that it describes more than just the data source. A UDL specifies what OLE DB
provider is used, server information, the user ID and password, the default database, and other related
information.
In order to create a new UDL file, create an empty text file and change the file extension of this document from
.txt to .udl. You then can double-click the UDL file to display the Data Link Properties dialog box.
Example: UDL
Connect to a Database using UDL:
34 LabVIEW Database Connectivity Toolkit
Tutorial: Database Communication in LabVIEW
8.1.3 CONNECTION STRING
Rather than including an existing UDL in an application, you also can use an ODBC connection string with the
Microsoft ActiveX Data Object (ADO) standard.
A connection string is written like this:
PROVIDER=SQLOLEDB;DATA SOURCE=server_name;UID=user_name;PWD=password;DATABASE=database_name;
You could use more parameters, but the parameters used above are the most common ones.
8.2 READING DATA FROM THE DATABASE
Reading data from a database table is similar to writing data to the database. You open a connection to the
database, select the data from a table, and then close the connection.
The “DB Tools Select Data.vi" is used to read data from the Database:
Example: Select Data from MS Access
The following example gets data from the CUSTOMER table in MS Access.
The Front Panel looks like this:
35 LabVIEW Database Connectivity Toolkit
Tutorial: Database Communication in LabVIEW
Notice in Figures 5-4 and 5-5 that the database data is returned as a two-dimensional array of variants. As the
name implies, the Microsoft ActiveX Data Object (ADO) standard is based on ActiveX, which defines variants as
its data types. Variants work well in languages such as Visual Basic that are not strongly typed. Because
LabVIEW is strongly typed, you must use the Database Variant To Data function to convert the variant data to a
LabVIEW data type before you can display the data in standard indicators such as graphs, charts, and LEDs.
Example: Select Data from MS Access
The following example gets data from the CUSTOMER table in MS Access and converts the data to text.
The Front Panel looks like this:
36 LabVIEW Database Connectivity Toolkit
Tutorial: Database Communication in LabVIEW
You may read from more than one table if you use a comma-delimited string to specify multiple table names:
You may select which columns you want to read by using the “Columns” input:
You may also restrict which data to receive using the “optional Clause” input:
37 LabVIEW Database Connectivity Toolkit
Tutorial: Database Communication in LabVIEW
Example: Read Data
Using some VIs from the “Advanced” palette, create the following example:
8.3 WRITING DATA TO THE DATABASE
Writing data to a database with the LabVIEW Database Connectivity Toolkit is similar to reading data to a file.
You open a connection, insert the data, and close the connection when you are finished.
The “DB Tools Insert Data.vi" is used to write data to the Database:
38 LabVIEW Database Connectivity Toolkit
Tutorial: Database Communication in LabVIEW
Example: Write Data
Create the following block diagram:
Front Panel:
39 LabVIEW Database Connectivity Toolkit
Tutorial: Database Communication in LabVIEW
Example: Write Data
Create the following block diagram using some VIs from the “Advanced” palette.
8.4 USING STORED PROCEDURES
8.5 CREATING AND DROPING TABLES
You may use standard SQL syntax in order to create:
CREATE TABLE <TableName> (…)
Or you may use the “DB Tools Create Table.vi” in order to create a table.
You may use standard SQL syntax in order to drop tables (delete tables):
DROP TABLE <TableName>
Or you may use the “DB Tools Drop Table.vi” in order to drop/delete a table.
40 LabVIEW Database Connectivity Toolkit
Tutorial: Database Communication in LabVIEW
8.6 USING THE DATABASE CONNECTIVITY TOOLKIT UTILITY VIS
In the “Utility” palette there are several useful VIs for getting more information about tables, saving to text
files, etc.
Here is a short description of the VIs located in the “Utility” palette:
This VI lists the tables in the database identified by connection reference.
This VI lists the columns present in table. The column information includes the name,
the data type, and the defined size of the column.
This VI sets properties on the object as determined by the inputs.
This VI gets properties of the object as determined by the inputs.
41 LabVIEW Database Connectivity Toolkit
Tutorial: Database Communication in LabVIEW
This VI Returns a string containing the formatted date and time, and identifies
the string as a date/time string so other VIs can interpret it.
This VI begins, commits, or rolls back a transaction for any type of reference.
This VI saves the recordset identified by the recordset reference to either an
XML or ADTG file. The ADTG file format is a proprietary format that only the LabVIEW Database Connectivity
Toolkit can interpret. The ADTG format results in a smallerfile than the XML format.
This VI loads a recordset from a file and returns a recordset reference that
identifies this recordset. You can retrieve data from this recordset like any other recordset, but some
properties might not be available on this recordset.
8.7 PERFORMING ADVANCED DATABASE OPERATIONS
When creating real programs you will soon need some of the VIs in the “Advanced” palette.
Here is a short description of some of the VIs located in the “Advanced” palette:
This VI Executes an SQL query and returns a recordset reference that you must
eventually free with the DB Tools Free Object VI.
42 LabVIEW Database Connectivity Toolkit
Tutorial: Database Communication in LabVIEW
This VI retrieves the data in the recordset identified by the recordset reference
input. You can convert each element in the array to its native LabVIEW data type using the “Database Variant
To Data function”.
This VI frees an object by destroying its associated reference and returns a different
reference object.
43
9 CREATING AND USING TABLES
The SQL syntax for creating a Table is as follows:
CREATE TABLE <TableName>
(
<ColumnName> <datatype>
…
)
The SQL syntax for inserting Data into a Table is as follows:
INSERT INTO <TableName> (<Column1>, <Column2>, …)
VALUES(<Data for Column1>, <Data for Column2>, …)
Example: Insert Data into Tables
We will insert some data into our tables:
The following SQL Query inserts some example data into these tables:
--CUSTOMER
INSERT INTO [CUSTOMER] ([FirstName],[LastName],[Address],[Phone],[PostCode],[PostAddress])
VALUES ('Per', 'Nilsen', 'Vipeveien 12', '12345678', '1234', 'Porsgrunn')
GO
INSERT INTO [CUSTOMER] ([FirstName],[LastName],[Address],[Phone],[PostCode],[PostAddress])
VALUES ('Tor', 'Hansen', 'Vipeveien 15', '77775678', '4455', 'Bergen')
GO
44 Creating and Using Tables
Tutorial: Database Communication in LabVIEW
INSERT INTO [CUSTOMER] ([FirstName],[LastName],[Address],[Phone],[PostCode],[PostAddress])
VALUES ('Arne', 'Nilsen', 'Vipeveien 17', '12345778', '4434', 'Porsgrunn')
GO
--PRODUCT
INSERT INTO [PRODUCT] ([ProductName],[ProductDescription],[Price],[ProductCode]) VALUES
('Product A', 'This is product A', 1000, 'A-1234')
GO
INSERT INTO [PRODUCT] ([ProductName],[ProductDescription],[Price],[ProductCode]) VALUES
('Product B', 'This is product B', 1000, 'B-1234')
GO
INSERT INTO [PRODUCT] ([ProductName],[ProductDescription],[Price],[ProductCode]) VALUES
('Product C', 'This is product C', 1000, 'C-1234')
GO
--ORDER
INSERT INTO [ORDER] ([OrderNumber],[OrderDescription],[CustomerId]) VALUES ('10001', 'This is
Order 10001', 1)
GO
INSERT INTO [ORDER] ([OrderNumber],[OrderDescription],[CustomerId]) VALUES ('10002', 'This is
Order 10002', 2)
GO
INSERT INTO [ORDER] ([OrderNumber],[OrderDescription],[CustomerId]) VALUES ('10003', 'This is
Order 10003', 3)
GO
--ORDER_DETAIL
INSERT INTO [ORDER_DETAIL] ([OrderId],[ProductId]) VALUES (1, 1)
GO
INSERT INTO [ORDER_DETAIL] ([OrderId],[ProductId]) VALUES (1, 2)
GO
INSERT INTO [ORDER_DETAIL] ([OrderId],[ProductId]) VALUES (1, 3)
GO
INSERT INTO [ORDER_DETAIL] ([OrderId],[ProductId]) VALUES (2, 1)
GO
INSERT INTO [ORDER_DETAIL] ([OrderId],[ProductId]) VALUES (2, 2)
GO
INSERT INTO [ORDER_DETAIL] ([OrderId],[ProductId]) VALUES (3, 3)
GO
INSERT INTO [ORDER_DETAIL] ([OrderId],[ProductId]) VALUES (3, 1)
GO
INSERT INTO [ORDER_DETAIL] ([OrderId],[ProductId]) VALUES (3, 2)
GO
INSERT INTO [ORDER_DETAIL] ([OrderId],[ProductId]) VALUES (3, 3)
GO
Executing the following Queries then gives:
select * from CUSTOMER
select * from PRODUCT
45 Creating and Using Tables
Tutorial: Database Communication in LabVIEW
select * from [ORDER]
select * from ORDER_DETAIL
EXERCISES
Run the queries above from LabVIEW.
46
10 CREATING AND USING VIEWS
In database theory, a view consists of a stored query accessible as a virtual table composed of the result set of
a query. Unlike ordinary tables in a relational database, a view does not form part of the physical schema: it is a
dynamic, virtual table computed or collated from data in the database. Changing the data in a table alters the
data shown in subsequent invocations of the view.
Views can provide advantages over tables:
Views can represent a subset of the data contained in a table
Views can join and simplify multiple tables into a single virtual table
Views can act as aggregated tables, where the database engine aggregates data (sum, average etc)
and presents the calculated results as part of the data
Views can hide the complexity of data; for example a view could appear as Sales2000 or Sales2001,
transparently partitioning the actual underlying table
Views take very little space to store; the database contains only the definition of a view, not a copy of
all the data it presents
Depending on the SQL engine used, views can provide extra security
Views can limit the degree of exposure of a table or tables to the outer world
Just as functions (in programming) can provide abstraction, so database users can create abstraction by using
views. In another parallel with functions, database users can manipulate nested views, thus one view can
aggregate data from other views.
Syntax:
CREATE VIEW <ViewName>
AS
…
EXERCISES
Create a simple view based on the example tables and run the view from LabVIEW.
47
11 CREATING AND USING STORED PROCEDURES
A stored procedure is a subroutine available to applications accessing a relational database system. Typical uses
for stored procedures include data validation (integrated into the database) or access control mechanisms.
Furthermore, stored procedures are used to consolidate and centralize logic that was originally implemented in
applications. Large or complex processing that might require the execution of several SQL statements is moved
into stored procedures, and all applications call the procedures only.
A stored procedure is a precompiled collection of SQL statements and optional control-of-flow statements,
similar to a macro. Each database and data provider supports stored procedures differently. Stored procedures
offer the following benefits to your database applications:
Performance—Stored Procedures are usually more efficient and faster than regular SQL queries because SQL
statements are parsed for syntactical accuracy and precompiled by the DBMS when the stored procedure is
created. Also, combining a large number of SQL statements with conditional logic and parameters into a stored
procedure allows the procedures to perform queries, make decisions, and return results without extra trips to
the database server.
Maintainability—Stored Procedures isolate the lower-level database structure from the application. As long as
the table names, column names, parameter names, and types do not change from what is stated in the stored
procedure, you do not need to modify the procedure when changes are made to the database schema. Stored
procedures are also a way to support modular SQL programming because after you create a procedure, you
and other users can reuse that procedure without knowing the details of the tables involved.
Security—When creating tables in a database, the Database Administrator can set EXECUTE permissions on
stored procedures without granting SELECT, INSERT, UPDATE, and DELETE permissions to users. Therefore, the
data in these tables is protected from users who are not using the stored procedures.
Stored procedures are similar to user-defined functions. The major difference is that functions can be used like
any other expression within SQL statements, whereas stored procedures must be invoked using the CALL
statement.
The syntax for creating a Stored Procedure is asfollows:
CREATE PROCEDURE <ProcedureName>
@<Parameter1> <datatype>
…
Example: Create a Stored Procedure
This Procedure gets Customer Data based on a specific Order Number.
IF EXISTS (SELECT name
FROM sysobjects
WHERE name = 'sp_CustomerOrders'
AND type = 'P')
DROP PROCEDURE sp_CustomerOrders
GO
CREATE PROCEDURE sp_CustomerOrders
48 Creating and using Stored Procedures
Tutorial: Database Communication in LabVIEW
@OrderNumber varchar(50)
AS
/*-------------------------------------------------------------------------
Last Updated Date: 2009.11.03
Last Updated By: hans.pr.halvorsen@hit.no
Description: Get Customer Information from a specific Order Number
-------------------------------------------------------------------------*/
SET NOCOUNT ON
declare @CustomerId int
select @CustomerId = CustomerId from [ORDER] where OrderNumber = @OrderNumber
select CustomerId, FirstName, LastName, [Address], Phone from CUSTOMER where
CustomerId=@CustomerId
SET NOCOUNT OFF
Og
Example: Using a Stored Procedure
Using the Stored procedure like this
exec sp_CustomerOrders '10002'
gives the following result:
EXERCISES
Run the Stored Procedure created above from LabVIEW.
49
12 CREATING AND USING TRIGGERS
A database trigger is procedural code that is automatically executed in response to certain events on a
particular table or view in a database. The trigger is mostly used for keeping the integrity of the information on
the database. For example, when a new record (representing a new worker) added to the employees table,
new records should be created also in the tables of the taxes, vacations, and salaries.
Triggers are commonly used to:
prevent changes (e.g. prevent an invoice from being changed after it's been mailed out)
log changes (e.g. keep a copy of the old data)
audit changes (e.g. keep a log of the users and roles involved in changes)
enhance changes (e.g. ensure that every change to a record is time-stamped by the server's clock, not
the client's)
enforce business rules (e.g. require that every invoice have at least one line item)
execute business rules (e.g. notify a manager every time an employee's bank account number
changes)
replicate data (e.g. store a record of every change, to be shipped to another database later)
enhance performance (e.g. update the account balance after every detail transaction, for faster
queries)
The major features of database triggers, and their effects, are:
do not accept parameters or arguments (but may store affected-data in temporary tables)
cannot perform commit or rollback operations because they are part of the triggering SQL statement
can cancel a requested operation
can cause mutating table errors, if they are poorly written.
Microsoft SQL Server supports triggers either after or instead of an insert, update, or delete operation.
Syntax:
CREATE TRIGGER <TriggerName> ON <TableName>
FOR INSERT, UPDATE, DELETE
AS
…
EXERCISES
Create a Trigger that adds “+47” to all Phone numbers in the CUSTOMER table.
Test and see if the Trigger works properly by inserting and updating some data in the CUSTOMER table.
50
13 CREATING AND USING FUNCTIONS
In SQL databases, a user-defined function provides a mechanism for extending the functionality of the
database server by adding a function that can be evaluated in SQL statements. The SQL standard distinguishes
between scalar and table functions. A scalar function returns only a single value (or NULL), whereas a table
function returns a (relational) table comprising zero or more rows, each row with one or more columns.
Stored Procedures vs. Functions:
Only functions can return a value (using the RETURN keyword).
Stored procedures can use RETURN keyword but without any value being passed[1]
Functions could be used in SELECT statements, provided they don’t do any data manipulation and also
should not have any OUT or IN OUT parameters.
Functions must return a value, but for stored procedures this is not compulsory.
A function can have only IN parameters, while stored procedures may have OUT or IN OUT
parameters.
A function is a subprogram written to perform certain computations and return a single value.
A stored procedure is a subprogram written to perform a set of actions, and can return multiple values
using the OUT parameter or return no value at all.
User-defined functions in SQL are declared using the CREATE FUNCTION statement.
Syntax:
CREATE FUNCTION <FunctionName>
(@Parameter1 <datatype>,
@ Parameter2 <datatype>,
…)
RETURNS <datatype>
AS
…
EXERCISES
Create a simple function that finds number of order for a specific customer and use it in the following query:
“Select FirstName, LastName, fn_NumberOfOrders(CustomerId) from CUSTOMER”
51
14 SQL TOOLKIT
I have made a simple and easy to-use SQL Toolkit. The SQL Toolkit is available for download from my Blog:
http://home.hit.no/~hansha/
14.1 INSTALLATION
The installation procedure is as follows:
1. Download the zip file SQLToolkit.zip from my Blog
2. Unzip the file
3. Copy "SQLToolkit.mnu" to ...\LabVIEW 2009\menus\Categories\
4. Copy "SQLToolkit.llb" to ...\LabVIEW 2009\vi.lib\
5. The SQL Toolkit is ready to use and in the Functions palette in LabVIEW a new palette named "SQL"
will appear.
The SQL Toolkit palette in available in LabVIEW:
The SQL Toolkit contains the following VIs:
“SQL Open.vi” - This VI open a connection to the database specified in the Connection string. The
connection string may be as follows:
“PROVIDER=SQLOLEDB; DATA SOURCE=xxx;UID=xxx;PWD=xxx;DATABASE=xxx”
You need to replace the “xxx” with the parameters from your database.
“SQL Select.vi” -This VI get data from the database specified in the SQL Query. The output is a 2D string
array with data.
“SQL Execute.vi” - This VI executes a Query with no return Data, e.g., an INSERT statement
“SQL Close.vi” - This VI Close the connection to the database opened by "SQL Open.vi"
http://home.hit.no/~hansha/
52 SQL Toolkit
Tutorial: Database Communication in LabVIEW
Two examples are also included:
“SQL – Example 1.vi” – This example selects data from a table. The example uses “SQL Select.vi” in
order to get data from the database.
Front panel:
Block Diagram:
“SQL – Example 2.vi” – This example inserts data into a table. The example uses “SQL Execute.vi” in
order to insert data into the database. No data is returned.
Front panel:
53 SQL Toolkit
Tutorial: Database Communication in LabVIEW
Block Diagram:
54
15 WHATS NEXT?
15.1 MY BLOG
For more information about LabVIEW, visit my Blog: http://home.hit.no/~hansha/
15.2 TRAINING
This Training is a part of a series with other Training Kits I have made, such as:
Introduction to LabVIEW
Data Acquisition in LabVIEW
Control and Simulation in LabVIEW
LabVIEW MathScript
Linear Algebra in LabVIEW
Datalogging and Supervisory Control in LabVIEW
Wireless Data Acquisition in LabVIEW
Intermediate Topics in LabVIEW
Advanced Topics in LabVIEW
These Training Kits are available for download from my blog: http://home.hit.no/~hansha
15.3 ADDITIONAL RESOURCES
www.ni.com
15.4 EXAMPLES
In the NI example Finder (Help→Find Examples…) you find lots of useful examples that you can play with or use
as a start when creating your own applications.
http://home.hit.no/~hansha/
http://home.hit.no/~hansha
http://www.ni.com/
55 Whats Next?
Tutorial: Database Communication in LabVIEW
15.5 DOCUMENTATION
As part of the LabVIEW installation there comes a lots of useful documentation.
15.6 LABVIEW WIKI
LabVIEW Wiki is the free LabVIEW information resource that anyone can edit.
http://labviewwiki.org/Homehttp://labviewwiki.org/Home
56 Whats Next?
Tutorial: Database Communication in LabVIEW
15.7 LABVIEW ON YOUTUBE
There are lots of LabVIEW videos available at YouTube:
http://www.youtube.com/results?search_query=labview&search=Search
http://www.youtube.com/results?search_query=labview&search=Search
57
QUICK REFERENCE
58 Quick Reference
Tutorial: Database Communication in LabVIEW
Telemark University College
Faculty of Technology
Kjølnes Ring 56
N-3914 Porsgrunn, Norway
www.hit.no
Hans-Petter Halvorsen, M.Sc.
Telemark University College
Department of Electrical Engineering, Information Technology and Cybernetics
Phone: +47 3557 5158
E-mail: hans.p.halvorsen@hit.no
Blog: http://home.hit.no/~hansha/
Room: B-237a
http://www.hit.no/
mailto:hans.p.halvorsen@hit.no
http://home.hit.no/~hansha/
Telemark University College
Department of Electrical Engineering, Information Technology and Cybernetics
Faculty of Technology, Postboks 203, Kjølnes ring 56, N-3901 Porsgrunn, Norway. Tel: +47 35 57 50 00 Fax: +47 35 57 54 01
OPC AND REAL-TIME SYSTEMS IN
LABVIEW
HANS-PETTER HALVORSEN, 2010.01.27
PREFACE
OPC (OLE for process control) is a standard interface between numerous data sources, – such as programmable
logic controllers (PLCs), remote terminal units (RTUs), and sensors on a factory floor – to HMI/SCADA
applications, application tools, and databases. With OPC, your device-side server and application software can
communicate without your duplicating device driver development and providing support for hardware feature
changes. The OPC Foundation defines the standards that allow any client to access any OPC-compatible device.
iii
INSTALLATION REQUIREMENTS
NI LabVIEW
Name Required
LabVIEW Professional Development System Yes
NI LabVIEW Core Components
Name Required
LabVIEW Control Design and Simulation Module
LabVIEW MathScript RT Module
NI Vision Development Module
Vision Builder for Automated Inspection
LabVIEW Digital Filter Design Toolkit
LabVIEW Modulation Toolkit
LabVIEW System Identification Toolkit
LabVIEW Desktop Execution Trace Toolkit
LabVIEW Report Generation for Microsoft Office Toolkit
LabVIEW Database Connectivity Toolkit
LabVIEW Internet Toolkit
NI LabVIEW SignalExpress
LabVIEW Basics 1 and 2 Computer Based Training
Extended Development Suite Components
Name Required
LabWindows/CVI Full Development System
LabWindows/CVI Real-Time Module
LabWindows/CVI PID Control Toolkit
LabWindows/CVI Signal Processing Toolkit
LabWindows/CVI Spectral Measurements Toolkit and Run-time Engine
LabWindows/CVI SQL Toolkit
Measurement Studio Enterprise Edition
DIAdem Professional
Control and Embedded Systems Option Components
Name Required
LabVIEW FPGA Module
LabVIEW Real-Time Module Yes
LabVIEW Statechart Module
LabVIEW Mobile Module
LabVIEW Datalogging and Supervisory Control Module
LabVIEW PID and Fuzzy Logic Toolkit
NI Real-Time Execution Trace Toolkit
LabVIEW Simulation Interface Toolkit
NI Motion Assistant
NI-DAQ Base
Signal processing and Communications Option Components
Name Required
LabVIEW FPGA Module
LabVIEW Sound and Vibration Measurement Suite
LabVIEW Spectral Measurement Toolkit
LabVIEW Advanced Signal Processing Toolkit
LabVIEW Adaptive Filter Toolkit
NI Device Drivers
Name Required
FieldPoint Yes
NI-DAQmx Yes
NI LabVIEW SignalExpress
NI Instrument I/O Assistant
NI-IMAQ
NI Measurement & Automation Explorer Yes
NI PXI
NI-VISA
In addition the following software will be needed in this Tutorial:
NI OP Servers (Evaluation version available from www.ni.com)
MatrikonOPC Simulation Server (free download from http://matrikon.com/)
http://www.ni.com/
http://matrikon.com/
vi
TABLE OF CONTENTS
Preface .................................................................................................................................................................... 2
Installation Requirements ....................................................................................................................................... iii
Table of Contents .................................................................................................................................................... vi
1 Introduction to LabVIEW ............................................................................................................................... 1
1.1 Dataflow programming.......................................................................................................................... 1
1.2 Graphical programming ......................................................................................................................... 1
1.3 Benefits .................................................................................................................................................. 2
1.4 LabVIEW MathScript RT Module ........................................................................................................... 2
2 Introduction to OPC ....................................................................................................................................... 3
2.1 OPC Server ............................................................................................................................................. 4
2.2 OPC Client .............................................................................................................................................. 6
2.3 Tags ........................................................................................................................................................ 6
2.4 Why Do We Need OPC Standards? ........................................................................................................ 6
3 Introduction to Real-Time Systems ............................................................................................................... 7
4 Introduction to Embedded Systems .............................................................................................................. 8
5 Multithreading in LabVIEW ......................................................................................................................... 10
5.1 Multitasking ......................................................................................................................................... 10
5.2 Multithreading ..................................................................................................................................... 10
6 DataSocket ................................................................................................................................................... 12
6.1 Architecture ......................................................................................................................................... 12
6.2 DataSocket Server ............................................................................................................................... 13
6.3 DataSocket in LabVIEW........................................................................................................................ 13
7 OPC Servers from National Instruments...................................................................................................... 15
7.1 NI OPC Servers ..................................................................................................................................... 15
7.1.1 OPC Quick Client ......................................................................................................................... 16
7.2 Shared Variable Engine ........................................................................................................................18
vii Table of Contents
Tutorial: OPC and Real-Time Systems in LabVIEW
8 MatrikonOPC Simulation Server .................................................................................................................. 19
8.1 MatrikonOPC Server ............................................................................................................................ 19
8.2 Aliases .................................................................................................................................................. 20
8.3 Matrikon OPC Explorer (Client) ........................................................................................................... 21
9 Using OPC from LabVIEW ............................................................................................................................ 23
9.1 OPC URL ............................................................................................................................................... 23
9.2 Read OPC Data ..................................................................................................................................... 24
9.3 Write OPC Data .................................................................................................................................... 25
10 LabVIEW Datalogging and Supervisory Control ........................................................................................... 27
10.1 Functions and VIs Palettes ................................................................................................................... 28
10.2 DSC Module Controls Palettes ............................................................................................................. 28
10.3 Citadel Database .................................................................................................................................. 29
10.4 Historical Data Viewer ......................................................................................................................... 29
10.5 Distributed System Manager ............................................................................................................... 30
10.6 SQL Server ............................................................................................................................................ 31
Exercises ........................................................................................................................................................... 32
11 LabVIEW I/O Server ..................................................................................................................................... 52
11.1 Connect LabVIEW to OPC Tags by Creating an I/O Server ................................................................... 52
11.2 Create Shared Variables that Connect to the OPC Tags through the I/O Server ................................. 53
11.3 Viewing Shared Variables with Distributed System Manager ............................................................. 54
11.4 Using OPC Tag Data in LabVIEW .......................................................................................................... 55
12 LabVIEW Real-Time Module ........................................................................................................................ 59
12.1 Real-Time Development in LabvIEW ................................................................................................... 59
13 Compact FieldPoint ..................................................................................................................................... 62
14 Whats Next? ................................................................................................................................................ 70
14.1 My Blog ................................................................................................................................................ 70
14.2 Training ................................................................................................................................................ 70
Quick Reference .................................................................................................................................................... 71
viii Table of Contents
Tutorial: OPC and Real-Time Systems in LabVIEW
1
1 INTRODUCTION TO LABVIEW
LabVIEW (short for Laboratory Virtual Instrumentation Engineering Workbench) is a platform and development
environment for a visual programming language from National Instruments. The graphical language is named
"G". Originally released for the Apple Macintosh in 1986, LabVIEW is commonly used for data acquisition,
instrument control, and industrial automation on a variety of platforms including Microsoft Windows, various
flavors of UNIX, Linux, and Mac OS X. The latest version of LabVIEW is version LabVIEW 2009, released in
August 2009. Visit National Instruments at www.ni.com.
The code files have the extension “.vi”, which is an abbreviation for “Virtual Instrument”. LabVIEW offers lots of
additional Add-Ons and Toolkits.
This paper is part of a series with LabVIEW papers:
Introduction to LabVIEW
Data Acquisition in LabVIEW
Control and Simulation in LabVIEW
Linear Algebra in LabVIEW
Database Communication in LabVIEW
Datalogging and Supervisory Control in LabVIEW
Intermediate Topics in LabVIEW
Advanced Topics in LabVIEW
Etc.
Each paper may be used independently of each other.
1.1 DATAFLOW PROGRAMMING
The programming language used in LabVIEW, also referred to as G, is a dataflow programming language.
Execution is determined by the structure of a graphical block diagram (the LV-source code) on which the
programmer connects different function-nodes by drawing wires. These wires propagate variables and any
node can execute as soon as all its input data become available. Since this might be the case for multiple nodes
simultaneously, G is inherently capable of parallel execution. Multi-processing and multi-threading hardware is
automatically exploited by the built-in scheduler, which multiplexes multiple OS threads over the nodes ready
for execution.
1.2 GRAPHICAL PROGRAMMING
LabVIEW ties the creation of user interfaces (called front panels) into the development cycle. LabVIEW
programs/subroutines are called virtual instruments (VIs). Each VI has three components: a block diagram, a
front panel, and a connector panel. The last is used to represent the VI in the block diagrams of other, calling
VIs. Controls and indicators on the front panel allow an operator to input data into or extract data from a
running virtual instrument. However, the front panel can also serve as a programmatic interface. Thus a virtual
instrument can either be run as a program, with the front panel serving as a user interface, or, when dropped
as a node onto the block diagram, the front panel defines the inputs and outputs for the given node through
the connector pane. This implies each VI can be easily tested before being embedded as a subroutine into a
larger program.
http://www.ni.com/
2 Introduction to LabVIEW
Tutorial: OPC and Real-Time Systems in LabVIEW
The graphical approach also allows non-programmers to build programs simply by dragging and dropping
virtual representations of lab equipment with which they are already familiar. The LabVIEW programming
environment, with the included examples and the documentation, makes it simple to create small applications.
This is a benefit on one side, but there is also a certain danger of underestimating the expertise needed for
good quality "G" programming. For complex algorithms or large-scale code, it is important that the
programmer possess an extensive knowledge of the special LabVIEW syntax and the topology of its memory
management. The most advanced LabVIEW