LabVIEW Core 1
TOPICS
ni.com/training
Lesson 1
Navigating LabVIEW
TOPICS
A.
B.
C.
D.
E.
What Is LabVIEW?
Project Explorer
Parts of a VI
Front Panel
Block Diagram
F. Searching for Controls, VIs
and Functions
G. Selecting a Tool
H. Dataflow
I. Building a Simple VI
ni.com/training
LabVIEW Language Characteristics
LabVIEW Core 1
Topics
Graphical
Dataflow-oriented
Compiled
Multi-platform
Synchronous
LabVIEW Core 2
and Later Topics
Event-driven
Multi-threaded
Object-oriented
Multi-target
MemoryManaged
ni.com/training
Project Explorer
Find, access, and organize
project files
Prevent, detect, and resolve
incorrect links
Deploy or download files to
targets
Manage code for build options
Executables, installers, and zip files
Integrate with source code
control providers
ni.com/training
LabVIEW Files
Common LabVIEW file
extensions:
LabVIEW project .lvproj
Virtual instrument (VI) .vi
Custom control .ctl
ni.com/training
C. Parts of a VI
Front Panel
Block Diagram
Icon
Connector Pane
ni.com/training
Parts of a VI
VIs have 3 main components:
Icon/Connector pane
Block diagram
Front panel
ni.com/training
Parts of a VI Front Panel
Front Panel User interface for the VI
You build the front
panel with
controls (inputs) and
indicators (outputs).
ni.com/training
Parts of a VI Block Diagram
Block Diagram Contains the
graphical source code
Front panel objects
appear as terminals
on the block diagram.
ni.com/training
Parts of a VI Icon/Connector Pane
Icon Graphical representation of a VI
Connector Pane Map of the inputs
and outputs of a VI
Icons and connector panes are necessary to use a VI as a
subVI.
A subVI is a VI that appears on the block diagram of another VI.
A subVI is similar to a subroutine or function in a text-based
programming language.
ni.com/training
Front Panel
ni.com/training
Controls and Indicators
Controls
Input devices
Knobs, buttons, slides
Supply data to the block
diagram
Indicators
Output devices
Graphs, LEDs
Display data the block diagram
acquires or generates
ni.com/training
Numeric Controls and Indicators
The numeric data in a control or indicator can represent
numbers of various types, such as integer or floating-point.
Numeric control
Increment/Decrement buttons
Numeric indicator
ni.com/training
Boolean Controls and Indicators
The Boolean data type represents data that has only two
options, such as True/False or On/Off.
Use Boolean controls and indicators to enter and display
Boolean (TRUE/FALSE) values.
Boolean objects simulate switches, push buttons, and LEDs.
Boolean
control
Boolean
indicator
ni.com/training
Strings
The string data type is a sequence of ASCII characters .
Use string controls to receive text from the user, such as a
password or user name.
Use string indicators to display text to the user.
ni.com/training
E. Block Diagram
Terminals
Nodes
Wires
Context Help
ni.com/training
Block Diagram
ni.com/training
Block Diagram
Block diagram items:
Terminals
Constants
Nodes
Functions
SubVIs
Structures
Wires
Free labels
ni.com/training
Terminals
Same label name
ni.com/training
Terminals for Front Panel Objects
Terminals are:
Entry and exit ports that exchange information between the
front panel and block diagram.
Analogous to parameters in text-based programming
languages.
Double-click a terminal to locate the corresponding front
panel object.
ni.com/training
View Terminals as Icons
By default, View as Icon option
enabled.
Deselect View as Icon for a more
compact view.
ni.com/training
Nodes
Nodes are objects on the block diagram that have inputs
and/or outputs and perform operations when a VI runs.
Nodes
ni.com/training
Function Nodes
Functions are:
Fundamental operating elements of LabVIEW.
Do not have front panels or block diagrams, but do have
connector panes.
Has a pale yellow background on its icon.
Double-clicking a function only selects the function.
Functions do not open like VIs and subVIs.
ni.com/training
SubVI Nodes
SubVIs :
Are VIs that you use on the block diagram of another VI.
Have front panels and block diagrams.
Use the icon from the upper-right corner of the front panel as
the icon that appears when you place the subVI on a block
diagram.
When you double-click a subVI, the front panel and block
diagram open.
Any VI has the potential to be used as a subVI.
ni.com/training
Express VIs
Express VIs:
Are a special type of subVI.
Require minimal wiring because you configure them
with dialog boxes.
Save each configuration as a subVI.
Icons for Express VIs appear on the block diagram
as icons surrounded by a blue field.
ni.com/training
Wires
Wires transfer data between block diagram objects.
Wires are different colors, styles, and thicknesses,
depending on their data types.
A broken wire appears as a dashed
black line with a red X in the middle.
Floating-point
Integer
String
Boolean
Scalar
1-D Array
2-D Array
ni.com/training
Context Help
Displays basic information
about wires and nodes when
you move the cursor over an
object.
Can be shown or hidden in
the following ways.
Select HelpShow Context
Help from the LabVIEW menu.
Press <Ctrl-H>.
Click the following button on the
toolbar:
ni.com/training
LabVIEW Help
Contains detailed descriptions and instructions for most
palettes, menus, tools, VIs, and functions.
Can be accessed by:
Selecting Help
LabVIEW Help from the
menu.
Clicking the Detailed help
link in the
Context Help window.
Right-clicking an object
and selecting Help from
the shortcut menu.
ni.com/training
Examples
LabVIEW includes
hundreds of example
VIs.
Use NI Example Finder
to browse and search
installed examples.
Select HelpFind
Examples in the menu.
Click the example buttons in LabVIEW Help topics.
ni.com/training
Searching for Controls, VIs, and Functions
Ways to find controls, VIs, and functions:
Search or navigate the palettes.
Controls palette
Functions palette
Search by name of object.
Quick Drop dialog box
Search palettes, LabVIEW Help, and ni.com.
Search text box in toolbar
ni.com/training
Controls Palette
Contains the controls and
indicators you use to create
the front panel.
Navigate the subpalettes or
use the Search button to
search the Controls palette.
ni.com/training
Functions Palette
Contains the VIs, functions,
and constants you use to
create the block diagram.
Navigate the subpalettes or
use the Search button to
search the Functions palette.
ni.com/training
Searching with Quick Drop
Lets you quickly find controls,
functions, VIs, and other
items by name.
Press the <Ctrl-Space> keys
to display the Quick Drop
dialog box.
ni.com/training
Global Search
Use the Search bar in the top right of the front panel and block
diagram windows to search palettes, LabVIEW Help, and
ni.com.
ni.com/training
Selecting a Tool
A tool is a special operating mode of the
mouse cursor.
Create, modify, and debug VIs using the
tools provided by LabVIEW.
By default, LabVIEW automatically selects
tools based on the context of the cursor.
If you need more control, use the Tools
palette to select a specific tool.
Select ViewTools Palette to open the
Tools palette.
ni.com/training
Wiring Tips
Press <Ctrl-B> to delete all broken wires.
Right-click and select Clean Up Wire to reroute the wire.
ni.com/training
Wiring Tips Clean Up Diagram
Use the Clean Up Diagram tool to reroute multiple wires and
objects and to improve readability.
1. Select a section of your block diagram.
2. Click the Clean Up Diagram button on the block diagram
toolbar.
ni.com/training
Cloning and Moving Items
Clone an object in LabVIEW using the following steps:
1. Select the Positioning tool.
2. Press the <Ctrl> key while clicking an object.
3. Drag the copy to new location.
Move an object using the following steps:
1. Select the Positioning tool.
2. Click and drag the object to new location.
Note: Avoid cutting and pasting objects as this can impact related items.
For example, cutting and pasting a block diagram terminal also moves the
front panel object.
ni.com/training
Dataflow
LabVIEW follows a dataflow model for running VIs.
A node executes only when data are available at all of its
required input terminals.
A node supplies data to the output terminals only when the
node finishes execution.
ni.com/training
Dataflow Quiz Answers
No single correct answer.
Which node executes first?
a) Add Possibly
b) Subtract Definitely not
c) Random Number Possibly
d) Divide Possibly
e) Sine Definitely not
ni.com/training
Acquire Express VIs
DAQ Assistant Express VI
Instrument I/O Assistant Express VI
Simulate Signal Express VI
Read from Measurement File Express VI
ni.com/training
Analyze Express VIs
Amplitude and Level Measurements Express VI
Statistics Express VI
Spectral Measurements Express VI
Tone Measurements Express VI
Filter Express VI
ni.com/training
Present Express VIs and Indicators
Display Message Express VI
Play Waveform Express VI
Report Express VI
Write Measurement File Express VI
DIAdem Report Express VI
ni.com/training
Building and Running a VI
1.
2.
3.
4.
Place Express VI on the block diagram.
Configure the dialog box that opens.
Wire Express VIs together.
Save and run the VI.
The Run button appears broken when the VI you
are creating or editing contains errors.
ni.com/training
SummaryQuiz Answer
1. Which function executes first:
Add or Subtract?
a) Add
b) Subtract
c) Unknown
ni.com/training
SummaryQuiz Answer
2. Which function executes first:
Sine or Divide?
a) Sine
b) Divide
c) Unknown
ni.com/training
SummaryQuiz Answer
3. Which of the following
functions executes first:
Random Number, Add or
Divide?
a)
b)
c)
d)
Random Number
Divide
Add
Unknown
ni.com/training
SummaryQuiz Answer
4. Which of the following
functions executes last:
Random Number, Subtract or
Add?
a)
b)
c)
d)
Random Number
Subtract
Add
Unknown
ni.com/training
SummaryQuiz Answer
5. What are the three parts of a VI?
a) Front panel
b) Block diagram
c) Project
d) Icon/Connector pane
ni.com/training
Lesson 1
Setting Up Hardware
TOPICS
A.
B.
C.
D.
DAQ Hardware
Using DAQ Software
Instrument Control
GPIB
E. Serial Port
Communication
F. Using Instrument Control
Software
ni.com/training
Setting Up Hardware
LabVIEW is a graphical programming environment used by
millions of engineers and scientists to develop sophisticated
measurement, test, and control systems
LabVIEW can integrate with wide variety of hardware
devices
In this course, you will interact with DAQ, GPIB, and serial
hardware
ni.com/training
A. DAQ Hardware
1.
2.
3.
4.
5.
Signal
Terminal Block
Cable
DAQ Device
Computer
ni.com/training
DAQ Hardware Terminal Block & Cable
DAQ Signal Accessory
Quadrature Encoder
4 LEDs for Digital I/O
Digital Trigger
Counter I/O
Function Generator
Function Generator Frequency Control
Temperature Sensor
Analog Input
Analog Output
Microphone Input
ni.com/training
DAQ Hardware Terminal Block & Cable
BNC-2120
Quadrature Encoder
8 LEDs for Digital I/O
Counter I/O
Function Generator
Function Generator Frequency
and Amplitude Control
Temperature Sensor
Analog Input
Analog Output
ni.com/training
DAQ Hardware DAQ Device
Most DAQ devices have four standard elements: analog
input, analog output, digital I/O, and counters
You can transfer the signal you measure with the DAQ
device to the computer through a variety of different bus
structures
ni.com/training
DAQ Hardware Analog Input
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 most commonly measures voltage or current
ni.com/training
DAQ Hardware Analog Output
The process of generating analog signals from your computer
Performing digital-to-analog (D/A)
conversions generates analog output
The available analog output types
are voltage and current
To perform a voltage or current
output, a compatible device must be
installed that can generate that
type of signal
ni.com/training
DAQ Hardware Digital I/O
Digital signals:
Electrical signals that transfer digital data (on/off, high/low, 1/0)
using a wire
Used to control or measure digital or finite state devices, such
as switches and LEDs
Used to transfer data
program devices
communicate between devices
Use digital signals as clocks or triggers to
control or synchronize other measurements
ni.com/training
DAQ Hardware Counters
A counter is a digital timing device typically used for event
counting, frequency measurement, period measurement,
position measurement, and pulse generation
A counter has a fixed number it can count to as determined
by the resolution of the counter
For example, a 24-bit counter
can count to:
2(Counter Resolution) 1 = 224 1 = 16,777,215
ni.com/training
B. Using DAQ Software Configuration
Configure and test your DAQ device using the Measurement
& Automation Explorer (MAX)
ni.com/training
Simulating a DAQ Device
Using NI-DAQmx simulated devices, you can try NI products
in your application without the hardware
With NI-DAQmx simulated devices, you also can export a
physical device configuration onto a system that does not
have the physical device installed
ni.com/training
C. Instrument Control
Use software on a PC to control an instrument over an
instrument control bus
Mix and match instruments from various categories
Understand the properties of the instrument, such as the
communication protocols to use
ni.com/training
C. Instrument Control
Benefits of Instrument Control
Automate processes
Save time
One platform for multiple tasks
Ease of use
Many types of instruments available
ni.com/training
D. GPIB
GPIB (general purpose
interface bus) is a
standard interface for
communication between
instruments and controllers
from various vendors
ni.com/training
GPIB
The bus supports one system controller, usually a computer,
and up to 14 additional instruments
Controller:
Defines the communication links
Responds to devices that request service
Sends GPIB commands
Passes/receives control of the bus
ni.com/training
E. Serial Port Communication
Serial communication
Transmits data between a computer and a peripheral
device, such as a programmable instrument or another
computer
Uses a transmitter to send data one bit at a time over a
single communication line to a receiver
Best method when data transfer rates are low, or you must
transfer data over long distances
ni.com/training
F. Using Instrument Control Software
Interface Drivers: Instrument interfaces such as GPIB
include a set of drivers for the interface
Configuration: Use MAX to configure the interface
ni.com/training
SummaryQuiz Answer
1. You can use the Measurement & Automation Explorer
(MAX) to examine, configure, and test your DAQ device
and GPIB instruments.
a) True
b) False
ni.com/training
SummaryQuiz Answers
2. Which of the following are benefits of instrument control?
a)
b)
c)
d)
Automate processes
Save time
One platform for multiple tasks
Limited to only one type of instrument
ni.com/training
Lesson 2
Troubleshooting and Debugging VIs
TOPICS
A.
B.
C.
D.
Correcting Broken VIs
Debugging Techniques
Undefined or Unexpected Data
Error Handling
ni.com/training
Common Causes of Broken VIs
Broken wires exist on the block
diagram.
You wired a Boolean control to a
String indicator.
You wired a numeric control to a
numeric control.
A required block diagram
terminal is unwired.
A subVI is broken.
ni.com/training
Debugging Techniques
What to look for if a VI produces unexpected data or behavior:
Are there any unwired or hidden subVIs?
Is the default data correct?
Does the VI pass undefined data?
Are numeric representations correct?
Are node executed in the correct order?
ni.com/training
Execution Highlighting
Use execution highlighting to watch the data flow through
the block diagram.
If the VI runs more slowly than expected, confirm that you
turned off execution highlighting in subVIs.
ni.com/training
Single-Stepping
Single-step through the VI to view each action of the VI on
the block diagram.
Suspend the execution of a subVI to edit values of controls
and indicators, to control the number of times it runs, or to
go back to the beginning of the execution of the subVI.
Open subVI and select OperateSuspend When Called from
the shortcut menu.
ni.com/training
Probes
Use the Probe tool to observe intermediate data
values and check the error output of VIs
and functions, especially those performing I/O.
Specify to retain the values in the wires so that
you can probe wires for data after execution.
ni.com/training
Breakpoints
When you reach a breakpoint during execution, the
VI pauses and the Pause button appears red.
You can take the following actions at a breakpoint:
Single-step through execution using the single-stepping buttons.
Probe wires to check intermediate values.
Change values of front panel controls.
Click the Pause button to continue running to the next breakpoint
or until the VI finishes running.
ni.com/training
Undefined or Unexpected Data
Check for unexpected Inf values or NaN values in your
mathematical operations:
(Inf)
Infinity
Produced by dividing a number by zero.
NaN
Not a number
Produced by invalid operations, such as taking the square root
of a negative number.
ni.com/training
D. Error Handling
Automatic and Manual Error Handling
Merge Errors Function
Error Clusters
Warnings
ni.com/training
Error Handling
Error Handling Anticipation, detection,
and resolution of warnings and errors
You cannot predict every problem a user can encounter.
Without a mechanism to check for errors, you know only that
the VI does not work properly.
Error handling tells you why and where errors occur.
Automatic error handling
Manual error handling
ni.com/training
Automatic Error Handling
By default, LabVIEW automatically handles any known error
when a VI runs by:
Suspending execution.
Highlighting the subVI or function where the error occurred.
Displaying the Error list window.
Automatic error handling is:
Acceptable for quick prototypes.
Not recommended for professional application development.
Not included in LabVIEW-built executables.
ni.com/training
Manual Error Handling
You control when dialog boxes appear.
Propagate errors by wiring the error out cluster to error in
cluster of next node to execute.
Terminate the error chain with a call to Simple Error Handler
VI.
ni.com/training
Disable Automatic Error Handling
Options Dialog Box
Block Diagram page
Uncheck
Enable automatic error handling in new VIs
Enable automatic error handling dialogs
Other suggested changes
Front Panel page
Set Control Style for New VIs to Silver style
Block Diagram page
Uncheck
Place front panel terminals as icons
Configure Block Diagram Cleanup to customize your block diagram
ni.com/training
Merge Errors
Propagate errors along wires.
Merge errors from different wire paths.
ni.com/training
Merge Errors Function
Merge Errors function returns the first error found. If no error
is found, it returns the first warning.
The Merge Errors function does not concatenate errors.
ni.com/training
Error Clusters
Use the error cluster controls and indicators to create error
inputs and outputs in subVIs.
The error in and error
out clusters include the
following components
of information:
Status
Code
Source
ni.com/training
Errors and Warnings
Status = TRUE
Status = FALSE
Code = Non-zero
Error
Warning
ni.com/training
Errors and Warnings Recommendations
Report errors and warnings with the Simple Error Handler VI
Modify Type of Dialog to detect warnings.
Call the Simple Error Handler VI from the top-level VI.
Avoid error dialogs in subVIs.
ni.com/training
SummaryQuiz Answer
1. Which of the following will result in a broken run arrow?
a) A subVI is broken.
b) The diagram includes a divide by zero.
c) A required subVI input is unwired.
d) A Boolean terminal is wired to a numeric indicator.
ni.com/training
SummaryQuiz Answer
2. Which of the following are the components and data types
of the error cluster?
a) Status: Boolean
b) Error: String
c) Code: 32-bit integer
d) Source: String
ni.com/training
SummaryQuiz Answer
3. All errors have negative error codes and all warnings have
positive error codes.
a) True
b) False
In an error cluster, a status of TRUE is always an error
regardless of the code value. A non-zero code with a
status of FALSE is considered a warning.
ni.com/training
SummaryQuiz Answer
4. Merge Errors function concatenates error information from
multiple sources.
a) True
b) False
Merge Errors function returns the first error found. If no error
is found, it returns the first warning.
The Merge Errors function does not concatenate errors
ni.com/training
Lesson 4
Implementing a VI
TOPICS
A.
B.
C.
D.
E.
F.
Front Panel Design
LabVIEW Data Types
Documenting Code
While Loops
For Loops
Timing a VI
G. Iterative Data Transfer
H. Plotting Data
I. Case Structures
ni.com/training
A. Front Panel Design
Inputs and outputs lead to front panel design
Retrieve the inputs by the following methods:
Acquiring from a device
Reading directly from a file
Manipulating controls
Output data by the following methods:
Displaying with indicators
Logging to a file
Outputting to a device
ni.com/training
A. Front Panel Design Labels/Captions
Labels short descriptions
Captions long descriptions
Captions do not appear on block diagram
ni.com/training
A. Front Panel Design Color Tips
Start with a gray scheme
Select one or two shades of gray
Add highlight colors sparingly for important settingson
plots, abort buttons, and the slider thumbs
ni.com/training
A. Front Panel Design Spacing
ni.com/training
A. Front Panel Design Text & Fonts
Bad Example
ni.com/training
A. Front Panel Design Tab Controls
Use tab controls to
overlap front panel
controls and indicators
in a smaller area
ni.com/training
A. Front Panel Design Decorations
Use decorations to visually
group or separate objects on
a front panel with boxes, lines,
or arrows
These objects are for
decoration only
ni.com/training
B. LabVIEW Data Types Terminals
Terminals visually communicate information about the data
type represented
ni.com/training
B. LabVIEW Data Types Numerics
The numeric data type represents
numbers of various types
To change the representation
of a numeric, right-click the
control, indicator, or constant,
and select Representation
from the shortcut menu
ni.com/training
B. LabVIEW Data Types Boolean
Behavior of Boolean controls is specified by the mechanical
action
In LabVIEW, the Boolean
data type is represented
with the color green
ni.com/training
B. Data Types String
A sequence of displayable or non-displayable
ASCII characters
On the front panel, strings appear as tables,
text entry boxes, and labels
Change the display type from the short-cut
menu: Normal, \ Codes, Password and Hex
Edit and manipulate strings with the String functions on the
block diagram
In LabVIEW, the string data type is represented with the
color pink
ni.com/training
B. Data Types Enum
An enum
represents a
pair of values,
a string and a
numeric, where the
enum can be one
of a defined list of
values
ni.com/training
B. Data Types Enum
Enum: enumerated
control, constant, or
indicator
Enums are useful because it is easier
to manipulate numbers than strings
on the block diagram
ni.com/training
B. Data Types Dynamic
Stores the information generated or acquired by an Express
VI
Non-Express VIs do not accept the dynamic data type
To use a built-in VI or function to analyze or process the
dynamic data type, you must convert the data type
Numeric, waveform, or Boolean data indicators or inputs
automatically convert the dynamic data type when wired
In LabVIEW, the dynamic data type is represented with the
color dark blue
ni.com/training
C. Documenting Code Front Panels
Tip Strips
Descriptions
VI Properties
Good Design
ni.com/training
C. Documenting Code Naming
Giving controls and indicators logical and descriptive names
adds usability to front panels
ni.com/training
C. Documenting Code Block Diagram
Use block diagram comments to:
Describe algorithms
Explain the data contents of wires
Use the Labeling tool or place a
free label from the Functions
palette
ni.com/training
Configuring Your LabVIEW Environment
Options Dialog Box
Controls/Functions Palettes page
Select Load palettes during launch to make Search Palettes
immediately usable after launch
Set Palette to Category (Icons and Text)
Block Diagram page
Uncheck Place front panel terminals as icons to place control
and indicator terminals in a compact format
Configure Block Diagram Cleanup to customize your block
diagram
ni.com/training
Configuring Your LabVIEW Environment
Functions Palette
Tack the Functions palette and select CustomizeChange
Visible Palettes then click Select All
Controls Palette
Tack the Controls palette and select CustomizeChange
Visible Palettes then click Select All
ni.com/training
D. While Loops
Iteration terminal: returns number of times loop has
executed; zero indexed
Conditional terminal: defines when the loop stops
Iteration Terminal
Conditional Terminal
ni.com/training
D. While Loops Tunnels
Tunnels transfer data into and out of structures
The tunnel adopts the color of the data type wired to the
tunnel
Data pass out of a loop after the loop terminates
When a tunnel
passes data into
a loop, the loop
executes only
after data arrive
at the tunnel
ni.com/training
D. While Loops - Error Checking and Error
Handling
Use an error cluster in a While Loop to stop the While Loop if
an error occurs
ni.com/training
E. For Loops
N=100;
i=0;
Until i=N:
Repeat (code;i=i+1);
End;
LabVIEW For Loop
Flowchart
Pseudo Code
ni.com/training
E. For Loops
Create a For Loop the same way you create a While Loop
If you need to replace an existing While Loop with a For
Loop, right-click the border of the While Loop, and select
Replace with For Loop from the shortcut menu
The value in the count terminal (an input terminal)
indicates how many times to repeat the subdiagram
ni.com/training
E. For Loops Conditional Terminal
You can add a conditional terminal to configure a For Loop to
stop when a Boolean condition or an error occurs
ni.com/training
E. For Loops Conditional Terminal
For Loops configured for a conditional exit have:
Red glyph next to the count terminal
Conditional terminal in the lower right corner
ni.com/training
E. For Loop/While Loop Comparison
For Loop
While Loop
Executes a set number of times unless
a conditional terminal is added
Can execute zero times
Tunnels automatically output an array
of data
Stops executing only if the value at the
conditional terminal meets the
condition
Must execute at least once
Tunnels automatically output the last
value
ni.com/training
E. For Loops Numeric Conversion
The number of iterations a For Loop executes must be specified in
nonnegative integers
If you wire a double-precision, floating-point numeric value to the
count terminal, LabVIEW converts the larger numeric value to a 32-bit
signed integer
ni.com/training
E. For Loops Numeric Conversion
Normally, when you wire different representation types to the
inputs of a function, the function returns an output in the larger
or wider format
Coercion Dot
LabVIEW chooses the
representation that
uses more bits
However, the For Loop
count terminal always
coerces to a 32-bit signed
integer
ni.com/training
E. For Loops Numeric Conversion
Avoid coercion for better performance
Choose matching data type
Programmatically convert to the matching data type
ni.com/training
F. Timing a VI
Why do you need timing in a VI?
Control the frequency at which a loop executes
Provide the processor with time to complete other tasks,
such as processing the user interface
ni.com/training
F. Timing a VI Wait Functions
A wait function inside a loop allows the VI to sleep for a set
amount of time
Allows the processor to address other tasks during the wait
time
Uses the operating system millisecond clock
ni.com/training
F. Timing a VI Elapsed Time Express VI
Determines how much time elapses after some point in your
VI
Keep track of time while the VI continues to execute
Does not provide the processor with
time to complete other tasks
ni.com/training
G. Iterative Data Transfer
When programming with loops, you often need to know the
values of data from previous iterations of the loop
Shift registers transfer values from one loop iteration to the
next
ni.com/training
G. Iterative Data Transfer Shift Registers
Right-click the border and select Add Shift Register from
the shortcut menu
Right shift register stores data on completion of an iteration
Left shift register provides stored data at beginning of the
next iteration
ni.com/training
G. Iterative Data Transfer Initializing
Run once
VI finishes
Block Diagram
Run again
1st run
2nd run
Initialized
Shift
Register
Output = 5
Output = 5
Not
Initialized
Shift
Register
Output = 4
Output = 8
ni.com/training
G. Iterative Data Transfer
Stacked Shift Registers
Stacked shift registers remember values from multiple
previous iterations and carry those values to the next
iterations
Right-click the left shift register and select Add Element
from the shortcut menu
ni.com/training
H. Plotting Data Waveform Chart
Special type of numeric indicator that displays one or more
plots of data, typically acquired at a constant rate
Displays single or multiple plots
ni.com/training
H. Plotting Data Chart Update Modes
Right-click the chart and select AdvancedUpdate Mode
from the shortcut menu
Strip chart is the default update mode
Scope chart and Sweep chart modes display plots
significantly faster than the strip chart mode
ni.com/training
H. Plotting Data
ni.com/training
H. Plotting Data Waveform Graphs
Use the Context Help window to determine how to wire multiplot data to Waveform Graphs and XY Graphs
ni.com/training
I. Case Structures
Have two or more subdiagrams or cases
Execute and displays only one case at a time
An input value determines which subdiagram to execute
Similar to case statements or if...then...else
statements in text-based programming languages
ni.com/training
I. Case Structures
Case Selector Label: contains the name of the current case
and decrement and increment buttons on each side
Selector Terminal: Wire an input value, or selector, to
determine which case executes
ni.com/training
I. Case Structures Default Case
You can specify a default case
for the Case structure
If you specified cases for 1, 2,
and 3, but you get an input of
4, the Case structure executes
the default case
Right-click the Case structure
border to add, duplicate,
remove, or rearrange cases
and to select a default case
ni.com/training
I. Case Structures Input & Output Tunnels
You can create multiple input and output tunnels
Inputs are available to all cases if needed
You must define each output tunnel for each case
ni.com/training
I. Case Structures Use Default if Unwired
Default values are:
Data Type
Default Value
Numeric
Boolean
FALSE
String
Empty
Avoid using the Use Default If Unwired option on Case
structure tunnels
Adds a level of complexity to your code
Complicates debugging your code
ni.com/training
I. Case Structures Boolean
Boolean input creates two cases: True and False
ni.com/training
I. Case Structures Integer
Add a case for each integer as necessary
Integers without a defined case use the default case
ni.com/training
I. Case Structures String
Add a case for each string as necessary
Strings without a defined case use the default case
ni.com/training
I. Case Structures Enum
Gives users a list of items from which to select
The case selector displays a case for each item in the
enumerated type control
ni.com/training
I. Case Structures - Error Checking and Error
Handling
Use Case Structures inside VIs to execute the code if there
is no error and skip the code if there is an error
ni.com/training
SummaryQuiz Answer
1. Which identifies the control or indicator on the block
diagram?
a) Caption
b) Location
c) Label
d) Value
ni.com/training
SummaryQuiz Answer
2. Which structure must run at least one time?
a) While Loop
b) For Loop
ni.com/training
SummaryQuiz Answer
3. Which is only available on the block diagram?
a)
b)
c)
d)
Control
Constant
Indicator
Connector Pane
ni.com/training
SummaryQuiz Answer
4. Which mechanical action causes a Boolean in the False state to
change to True when you click it and stay True until you release
it and LabVIEW has read the value?
a)
b)
c)
d)
Switch Until Released
Switch When Released
Latch Until Released
Latch When Released
ni.com/training
Lesson 6
Managing Resources
TOPICS
A. Understanding File I/O
B. Understanding High-level
File I/O
C. Understanding Low-level
File I/O
D. DAQ Programming
E. Instrument Control
Programming
F. Using Instrument Drivers
ni.com/training
A. Understanding File I/O
File I/O writes to or reads from a file
A typical file I/O operation involves the following process:
Open/
Create/
Replace File
Read
and/or
Write to File
Close
File
Check for
Errors
ni.com/training
A. Understanding File I/O File Formats
LabVIEW can use or create the following file formats:
BinaryUnderlying file format of all other file formats
ASCIISpecific type of binary file that is a standard used by
most programs
LVM The LabVIEW measurement data file (.lvm) is a tabdelimited text file you can open with a spreadsheet
application or a text-editing application
TDMSType of binary file created for NI products
consisting of two separate files: a binary file and a binary
index file
ni.com/training
A. Understanding File I/O File Formats
In this course, you learn about creating text (ASCII) files
Use text files in the following situations:
You want to access the file from another application
Disk space and file I/O speed are not crucial
You must not perform random access reads or writes
Numeric precision is not important
ni.com/training
B. Understanding High-level File I/O
High-level VIs
Perform all three steps (open,
read/write, close) for common file I/O
operations
Might not be as efficient as the
functions configured or designed for
individual operations
Low-level VIs
Individual VI for each step
If you are writing to a file in a loop, use
low-level file I/O functions
ni.com/training
B. Understanding High-Level File I/O
Write to Spreadsheet File
Converts an array of double-precision numbers to a text string and
writes the string to an ASCII file
Read From Spreadsheet File
Reads a specified number of lines or rows
from a numeric text file and outputs a
2D array of double-precision numbers
Write to/Read from Measurement File
Express VIs that write data to or read data
from an LVM or TDMS file format
ni.com/training
C. Understanding Low-Level File I/O VIs
ni.com/training
D. DAQ Programming
1.
2.
3.
4.
5.
Signal
Terminal Block
Cable
DAQ Device
Computer
ni.com/training
D. DAQ Programming Software Overview
NI-DAQmx
Driver level software
Detects DAQ devices
Installs NI-DAQmx functions in LabVIEW
Measurement & Automation Explorer
Configure and test DAQ device
DAQ Assistant
Configurable Express VI used to create a DAQ
application
DAQmx API
Provides a set of VIs to program DAQ applications
ni.com/training
D. DAQ Programming Basic Flow
A basic DAQmx application involves the following process:
Create
Task
Configure
Task
Start
Task
Acquire or
Generate
Data
Clear
Task
ni.com/training
D. DAQ Programming Create Task
Create Virtual Channel VI
Creates a virtual channel and adds it to a task
Use pull-down menu to select the appropriate instance of this
VI
ni.com/training
D. DAQ Programming Configure Task
Configure timing if reading multiple samples
Sample rate, timing source, etc
Configure triggering if necessary for application
Configures the task to start or stop on a rising or falling digital
edge, analog edge, or analog windows
ni.com/training
D. DAQ Programming Start Task
Starts the task after the task has been configured
ni.com/training
D. DAQ Programming Acquire or Generate Data
Acquire or generate data from the DAQ device
Make sure pull-down menu selection is compatible with task
configuration
ni.com/training
D. DAQ Programming Clear Task
DAQmx Clear Task VI
Stops the task
Releases any resources the task reserved
Clears the task
ni.com/training
E. Instrument Control Programming
Virtual Instrument Software Architecture (VISA):
High-level API that calls low-level drivers
Can control VXI, GPIB, serial, or computer-based instruments
and makes the appropriate driver calls depending on the type
of instrument used
ni.com/training
VISA
VISA
Virtual Instrument System Architecture
Serial
GPIB
VXI
USB
ni.com/training
VISA Programming Terminology
Resource
Any instrument in the system, including serial and parallel ports
Session
You must open a VISA session to a resource to communicate
with it, similar to a communication channel. When you open a session
to a resource, LabVIEW returns a VISA session number, which is a
unique refnum to that instrument. You must use the session number in
all subsequent VISA functions
Instrument Descriptor
Specifies the interface type (GPIB,VXI, ASRL), the address of the device,
and the VISA session type (INSTR or Event)
ni.com/training
VISA Alias
Assign a user-defined name to a device or resource in place
of the instrument descriptor
ni.com/training
VISA Programming
VISA functions operate similar to File I/O functions
Open Session
to
Instrument(s)
Perform I/O
Operation(s)
Close
Session to
Instrument(s)
Check for
Errors
ni.com/training
VISA Open Function
Establishes communication line to resource
Generally used once per resource
Returns VISA Resource Name
ni.com/training
VISA I/O Functions
VISA Write and VISA Read Functions
ni.com/training
VISA Close Function
Sessions take up system resources
Close sessions before program ends
ni.com/training
VISA Write and Read Example
ni.com/training
VISA Serial
The VISA Configure Serial Port VI initializes the port identified
by VISA resource name to the specified settings
ni.com/training
F. Using Instrument Drivers
Organized set of VIs that control a
programmable instrument
Each VI performs multiple instructions
Grouped by operation type
(configuration, data, etc)
Reduce development time
Application Development
Environment (ADE)
Instrument Commands
(*idn?, meas?)
Instrument
Driver
Bus Communication Protocol
(configure, read, write, trigger)
Simplify instrument control
Reusable
Common architecture and interface
Instrument
ni.com/training
Using Instrument Drivers
When you use an instrument driver, the driver contains the
code specific to the instrument
If you change instruments, replace the instrument driver VIs
with the instrument driver VIs for the new instrument, which
greatly reduces your redevelopment time
ni.com/training
Using Instrument Drivers Where are they?
You can locate most LabVIEW Plug and Play instrument drivers
in the Instrument Driver Finder
Access within LabVIEW by selecting Tools
InstrumentationFind Instrument Drivers or HelpFind
Instrument Drivers
Connects you with ni.com to find instrument drivers
When you install an instrument driver
An example program using the driver is added to the NI Example
Finder
Instrument driver VIs are added to the Instrument I/OInstrument
Drivers palette in the Functions palette
ni.com/training
Using Instrument Drivers Example
ni.com/training
SummaryQuiz Answer
1. Your continuously running test program logs to a single file the
results of all tests that occur in one hour as they are calculated. If
you are concerned about the execution speed of your program,
should you use low-level or high-level File I/O VIs?
a) Low-level file I/O VIs
b) High-level file I/O VIs
ni.com/training
SummaryQuiz Answer
2. If you want to view data in a text editor like Notepad, what file
format should you use to save the data?
a) ASCII
b) TDMS
ni.com/training
SummaryQuiz Answer
3. Which of the following conveys the basic DAQmx programming
flow?
a) Create TaskConfigure TaskAcquire/Generate DataStart Task
b) Acquire/Generate DataStart TaskClear Task
c) Start TaskCreate TaskConfigure TaskAcquire/Generate
DataClear Task
d) Create TaskConfigure TaskStart TaskAcquire/Generate
DataClear Task
ni.com/training
SummaryQuiz Answer
4. VISA is a high-level API that calls low-level drivers.
a) True
b) False
ni.com/training
Lesson 7
Developing Modular Applications
TOPICS
A. Understanding Modularity
B. Icon and Connector Pane
C. Using SubVIs
ni.com/training
A. Understanding Modularity
Modularity - The degree to which a program is
composed of discrete modules such that a change to
one module has minimal impact on other modules
Modules in LabVIEW are called subVIs
ni.com/training
A. Understanding Modularity SubVIs
SubVI- A VI within another VI
SubVIs correspond to subroutines in text-based
programming languages
The upper right corner of the front panel and block diagram
displays the icon for the VI
This icon identifies the VI when you place the VI on the
block diagram
ni.com/training
A. Understanding Modularity SubVIs
ni.com/training
A. Understanding Modularity SubVIs
ni.com/training
A. Understanding Modularity SubVIs
Function Code
function average (in1, in2,
out)
{
out = (in1 + in2)/2.0;
}
SubVI Block Diagram
Calling Program Code
main
{
average (point1, point2,
pointavg)
}
Calling VI Block Diagram
ni.com/training
B. Icon and Connector Pane
After you build a VI, build the icon and the connector pane
so you can use the VI as a subVI
The icon and connector pane correspond to the function
prototype in text-based programming languages
Every VI displays an icon in the upper-right corner of the
front panel and block diagram windows
An icon is a graphical representation of a VI
If you use a VI as a subVI, the icon identifies the subVI on
the block diagram of the VI
ni.com/training
B. Icon and Connector Pane Good VI Icon
Characteristics of a good VI icon
Conveys the functionality of the VI using:
Relevant graphics
Descriptive text
ni.com/training
B. Icon and Connector Pane Create Icon
Create custom icons by right-clicking the icon in the upper
right corner of the front panel or block diagram and selecting
Edit Icon or by double-clicking the icon
You also can drag a graphic from anywhere in your file
system and drop it on the icon
ni.com/training
B. Icon and Connector Pane Create Icon
Use the editing tools to modify an icon manually
ni.com/training
B. Icon and Connector Pane Create Icon
Use the Glyphs tab to display glyphs you can include in the icon
Select ToolsSynchronize with ni.com Icon Library to update
ni.com/training
B. Icon and Connector Pane Create Icon
Use the Icon Text tab to specify the text to display in the icon
ni.com/training
B. Icon and Connector Pane Create Icon
Use the Templates tab to display icon templates you can use as
a background for the icon
ni.com/training
B. Icon and Connector Pane Setting up the
Connector Pane
Right-click the icon in the upper
right corner of the front panel
and select Show Connector
Each rectangle on the connector
pane represents a terminal
Use the terminals to assign inputs
and outputs
Select a different pattern by
right-clicking the connector pane
and selecting Patterns from the
shortcut menu
ni.com/training
B. Icon and Connector Pane Standards
Use this connector pane layout as a standard
Top terminals are usually reserved for references, such as a
file reference
Bottom terminals are
usually reserved for
error clusters
ni.com/training
C. Using SubVIs
To place a subVI on the block diagram
Click Select a VI on the Functions palette
Navigate to the VI you want to use as a subVI
Double-click to place it on the block diagram
To place an open VI on the block diagram of another open
VI
Click the icon of the VI you want to use as a subVI
Drag the icon to the block diagram of the other VI
ni.com/training
C. Using SubVIs Terminal Setting
Bold: Required terminal
Plain: Recommended
terminals
Dimmed: Optional terminals
ni.com/training
C. Using SubVIs Handling Errors
Use a Case structure to handle errors passed into the subVI
ni.com/training
C. Using SubVIs Handling Errors
Avoid using LabVIEW error handler VIs inside subVIs
ni.com/training
C. Using SubVIs Section to SubVI
To convert a section of a VI into a subVI:
Use the Positioning tool to select the section of the block
diagram you want to reuse
Select EditCreate SubVI
ni.com/training
SummaryQuiz Answer
1. On a subVI, which terminal setting causes an error if the
terminal is not wired?
a) Required
b) Recommended
c) Optional
ni.com/training
SummaryQuiz Answer
2. You must create a custom icon to use a VI as a subVI.
a) True
b) False
You do not need to create a custom icon to use a
VI as a subVI, but it is highly recommended to
increase the readability of your code.
ni.com/training
Lesson 7
Using Sequential and
State Machine Algorithms
TOPICS
A. Using Sequential Programming
B. Using State Programming
C. State Machines
ni.com/training
Using Sequential Programming
Many of the VIs you write accomplish sequential tasks.
By default, LabVIEW does not force sequential programming.
Example: Nothing forces the execution order of these tasks.
Any one of these tasks could happen first.
ni.com/training
Flow-Through Parameters Force Execution Order
Use error clusters and refnums to force order of execution.
ni.com/training
Sequence Structures Force Execution Order
Sequence structures are a structure with frames, where each frame
executes in order.
The second frame cannot begin execution until everything in the first
frame completes execution.
ni.com/training
Avoid Overuse of Sequence Structures
You cannot stop the execution in the middle of a sequence.
ni.com/training
Better to Use Error Case Structures
The best way to write this VI is to enclose the dialog boxes in
Case structures, wiring the error cluster to the case selectors.
ni.com/training
State Programming
State programming helps you solve the following issues that
sequential programming or flow-through parameters do not:
What if you need to change the order of the sequence?
What if you need to repeat one item in the sequence more
often than other items?
What if some items in the sequence execute only when
certain conditions are met?
What if you need to stop the program immediately, rather
than waiting until the end of the sequence?
ni.com/training
State Transition Diagram
A state transition diagram is a type of flowchart that indicates
the states of a program and transitions between states.
State Part of a program that satisfies a condition,
performs an action or waits for an event
Transition Condition, action, or event that causes
the program to move to the next state
ni.com/training
State Transition Diagram
Furnace
Example:
ni.com/training
State Machines
The state machine design pattern implements a state
diagram or flow chart.
Common uses of state machines:
To create user interfaces, where different user actions send the
user interface into different states.
For process tests, where a state represents each segment of
the process.
ni.com/training
State Machines Infrastructure
A state machine consists of a set of states and a transition
function that maps to the next state.
Each state can lead to one or multiple states or end the
process flow.
While Loop
Type-Defined
Enum
Case Structure
Shift Register
ni.com/training
State Machines Default Transition
ni.com/training
State Machines Transition Between Two
States
ni.com/training
State Machines Case Structure Transition
ni.com/training
State Machines Transition Array Transition
ni.com/training
Course Project Transition Diagram
ni.com/training
SummaryQuiz Answer
1. When using a Sequence structure, you can stop the execution in
the middle of a sequence.
a) True
b) False
You cannot stop the execution in the middle of a
sequence.
ni.com/training
SummaryQuiz Answers
2. Which of the following are benefits of using a state machine
instead of a sequential structure?
a) You can change the order of the sequence.
b) You can repeat individual items in the sequence.
c) You can set conditions to determine when an item in the
sequence should execute.
d) You can stop the program at any point in the sequence.
ni.com/training
Lesson 8
Solving Dataflow Challenges with Variables
TOPICS
A.
B.
C.
D.
E.
Communicating Between Parallel Loops
Writing to Controls & Reading from Indicators
Variables
Local Variables
Race Conditions
ni.com/training
Writing to Controls & Reading from Indicators
How would you handle the following dataflow challenges?
Initialize front panel controls with values from a configuration file?
Copy a Ship To address to a Bill To address?
Initialize indicators that will be written to later in your code?
Write to an indicator in two cases of a Case structure without
writing to it in all cases?
Sometimes you need to write to a control or read from an
indicator.
ni.com/training
Variables
Variables Block diagram elements that allow
you to access or store data in another location
Variables can be of the following types:
LocalStores data in front panel controls and indicators.
Global Stores data in special repositories that can be
accessed from multiple VIs.
Functional GlobalStores data in While Loop shift
registers.
SharedTransfers data between various distributed
targets connected together over a network.
ni.com/training
D. Local Variables
When To Use Local Variables
Local Variables and Boolean Mechanical Actions
How To Create Local Variables
ni.com/training
Local Variables
Use local variables to pass data within a single VI.
ni.com/training
Local Variables
Use local variables to modify front panel control values.
ni.com/training
Use Switch Mechanical Action
Boolean controls with
associated local
variables must use
switch mechanical
action.
Boolean latch action
is incompatible with
local variables.
ni.com/training
Race Conditions
Race Condition A situation where the timing of
events or the scheduling of tasks may unintentionally
affect an output or data value
Race conditions are a common problem for programs
that execute multiple tasks in parallel and share data
between the tasks.
ni.com/training
What is the final value of the Value variable?
Four possible outcomes:
Value = (Value * 5) +2
Value = (Value + 2) * 5
Value = Value * 5
Value = Value +2
ni.com/training
Race Conditions
Race conditions are very difficult to identify and debug.
Often, code with a race condition can return the same result
thousands of times in testing, but still be capable of
returning a different result.
Avoid race conditions by:
Controlling shared resources.
Use one writer, multiple readers.
Properly sequencing instructions.
Reducing use of variables.
ni.com/training
Controlling Shared Resources
ni.com/training
SummaryQuiz Answer
1. You should use variables in your VI whenever possible.
a) True
b) False
You should use variables only when necessary. Use
wires to transfer data whenever possible.
ni.com/training
SummaryQuiz Answer
2. When controlling resources, which combination of writers and
readers reduces chance of race conditions?
a) One writer, one reader
b) One writer, multiple readers
c) Multiple writers, one reader
d) Multiple writers, multiple readers
ni.com/training
Lesson 9
Using Variables
TOPICS
A.
B.
C.
D.
Parallelism
Variables
Functional Global Variables
Race Conditions
ni.com/training
A. Parallelism
Execute multiple tasks at the same time
ni.com/training
A. Parallelism
Passing data among parallel loops is a challenge
How do the loops stop in this example?
ni.com/training
A. Parallelism
How do the loops stop in this example?
ni.com/training
A. Parallelism
Read the Stop button from a file
Each loop independently accesses the file
However, reading and writing to files can consume much
processor time
ni.com/training
B. Variables
Cannot pass data between parallel loops with a wire
Variables allow you to circumvent normal dataflow by
passing data from one place to another without connecting
the two places with a wire
ni.com/training
B. Variables
Variables - Block diagram elements that allow
you to access or store data in another location
Variables can be of the following types:
LocalStores data in front panel controls and indicators
Global Stores data in special repositories that can be
accessed from multiple VIs
Functional GlobalStores data in While Loop shift
registers
SharedTransfers data between various distributed
targets connected together over a network
ni.com/training
B. Variables Using in a Single VI
Use local variables to pass data within a single VI
ni.com/training
B. Variables
Boolean controls with associated local variables must use
switch mechanical action
Boolean latch action is incompatible with local variables
ni.com/training
B. Variables Using Between VIs
Use a global variable or a single process shared variable to
share data between multiple VIs
Use a global variable to share data among VIs on the same
computer, especially if you do not use a project file
Use a single process shared variable if you may need to
share the variable information among VIs on multiple
computers in the future
ni.com/training
B. Variables Using Between VIs
Single Process Shared Variables
ni.com/training
B. Variables Creating Shared Variables
You must have a project open to
create a shared variable
Variable configuration data is
stored in Project Libraries
LabVIEW will automatically
create a library if the variable
was not created from an existing
library
ni.com/training
Shared Variables Configuration Options
Set Variable Type to Single Process
ni.com/training
B. Variables Using Carefully
ni.com/training
B. Variables Using Carefully
ni.com/training
B. Variables Initializing
Verify that variables contain known data values before the VI
runs
If you do not initialize
the variable before the
VI reads it for the
first time, it contains the
default value of the
associated front
panel object
ni.com/training
B. Variables Initializing
ni.com/training
C. Functional Global Variables
The general form of a functional global variable includes
an uninitialized shift register (1) with a single iteration For
or While Loop
ni.com/training
C. Functional Global Variables
A functional global variable usually has an action input
parameter that specifies which task the VI performs
The VI uses an uninitialized shift register in a While
Loop to hold the result of the operation
ni.com/training
C. Functional Global Variables Timing
Very useful for performing customized elapsed time
measurements
ni.com/training
D. Race Conditions
Race Condition - A situation where the timing of events
or the scheduling of tasks may unintentionally affect an
output or data value
Race conditions are a common problem for programs
that execute multiple tasks in parallel and share data
between the tasks
ni.com/training
D. Race Conditions
Race conditions are very difficult to identify and debug
Often, code with a race condition can return the same result
thousands of times in testing, but still be capable of
returning a different result
Avoid race conditions by:
Controlling shared resources
Properly sequencing instructions
Identifying and protecting critical sections within your code
Reducing use of variables
ni.com/training
D. Race Conditions Shared Resources
ni.com/training
D. Race Conditions Critical Code
A critical section of code is code that may behave
inconsistently if some shared resource is altered while it is
running
If one loop interrupts another loop while it is executing
critical code, then a race condition can occur
Eliminate race conditions by identifying and protecting
critical code with:
Functional Global Variables
Semaphores
ni.com/training
D. Race Conditions Critical Code
ni.com/training
D. Race Conditions Critical Code
Functional Global Variable used
to protect critical code:
ni.com/training
D. Race Conditions Critical Code
Run the top VI first
Run the bottom VI second
ni.com/training
D. Race Conditions Sequencing
What is the final value?
Four possible outcomes:
Value = (Value * 5) +2
Value = (Value + 2) * 5
Value = Value * 5
Value = Value +2
ni.com/training
SummaryQuiz
1. You should use variables in your VI whenever possible.
a) True
b) False
ni.com/training
SummaryQuiz Answer
1. You should use variables in your VI whenever possible.
a) True
b) False
You should use variables only when necessary. Use
wires to transfer data whenever possible.
ni.com/training
SummaryQuiz
2. Which of the following cannot transfer data?
a) Semaphores
b) Functional global variables
c) Local variables
d) Single process shared variables
ni.com/training
SummaryQuiz Answer
2. Which of the following cannot transfer data?
a) Semaphores
b) Functional global variables
c) Local variables
d) Single process shared variables
ni.com/training
SummaryQuiz
3. Which of the following must be used within a project?
a) Local variable
b) Global variable
c) Functional global variable
d) Single-process shared variable
ni.com/training
SummaryQuiz Answer
3. Which of the following must be used within a project?
a) Local variable
b) Global variable
c) Functional global variable
d) Single-process shared variable
ni.com/training
SummaryQuiz
4. Which of the following cannot be used to pass data between
multiple VIs?
a) Local variable
b) Global variable
c) Functional global variable
d) Single-process shared variable
ni.com/training
SummaryQuiz Answer
4. Which of the following cannot be used to pass data between
multiple VIs?
a) Local variable
b) Global variable
c) Functional global variable
d) Single-process shared variable
ni.com/training
Asynchronous Communication
LabVIEW is a dataflow language.
Functions depend on other functions for data.
Dependent functions do not execute until their
dependencies have completed execution.
Wires transfer data between functions.
However, sometimes you need break dataflow and program
using asynchronous communication.
ni.com/training
Asynchronous Communication
Asynchronous Communication Transfer
information without using wires
Asynchronous communication is between the following:
Parallel loops
UI and Block Diagram
VIs
Application instances (LabVIEW projects, executables, etc.)
Information includes the following:
Data
Notification that something happened
ni.com/training
B. Queues
Queues
Queue Operations
Producer/Consumer (Data) Design Pattern
ni.com/training
Queues
Are used for communicating data between parallel loops.
Store multiple pieces of data (i.e. buffer data).
Work in a FIFO (first in, first out) manner by default.
Can hold data of any type.
ni.com/training
Drawbacks of Variables
Drawbacks of using variables to communicate between loops:
Its possible to read duplicate
data.
Its possible to miss data.
You can create read-modifywrite race conditions.
ni.com/training
Queue Operations
Use the Queue Operations functions to
create and use a queue for communicating data between:
Different sections of a VI.
Different VIs.
ni.com/training
Producer/Consumer Design Pattern (Data)
ni.com/training
C. Event-Driven Programming
Events Definition
Event-Driven Programming Definition
Polling Versus Event Structures
Parts of an Event Structure
Configuring the Event Structure
Caveats and Recommendations
ni.com/training
Events
Event An asynchronous notification that something
has occurred
Events originate from the user interface, external I/O, or
other parts of the program.
Events do things TO event sources.
Example: Value change happens TO front panel controls.
ni.com/training
Event-Driven Programming
Event-Driven Programming Method of
programming where the program waits for an event to
occur before executing one or more functions
User Action
on
Front Panel
Execution
Block Diagram
ni.com/training
Polling versus Event Structures
Polling
Method of event-based programming where a loop must continually
run code to check if changes have occurred.
Polling the front panel requires a significant amount of CPU time.
Polling can fail to detect changes if they occur too quickly.
Event Structures
Events in Event structures eliminate the need to poll the front panel.
Benefits of using Event structures:
Reduces the CPU requirements of the program.
Simplifies the block diagram code.
Guarantees that the block diagram can respond to all interactions
the user makes.
ni.com/training
Using Event Structures for Event-Driven
Programming
An Event structure works like a Case structure with a builtin Wait on Notification function.
Use an Event structure to
handle user-interface (static)
events such as:
Pressing a button on the mouse.
Pressing a key on the keyboard.
Changing the value of a numeric
control.
ni.com/training
Parts of an Event Structure
Event Selector LabelIdentifies the event case viewed.
TimeoutSpecifies time in ms to wait for events.
Default value is 1 (indefinite).
Event Selector Label
Timeout
ni.com/training
Parts of an Event Structure (continued)
Event Data NodeIdentifies the data LabVIEW provides when the
event occurs; similar to the Unbundle By Name function.
Event Filter NodeIdentifies the subset of data available in the
Event Data node that the event case can modify.
Event Data
Node
Event Filter
Node
ni.com/training
Using an Event Structure
In general, place Event structures inside While Loops.
Event structures handle exactly one event per iteration of
the While Loop.
Event structures sleep when no events occur.
ni.com/training
Configuring the Event Structure
Use a dialog box to configure each event by
right-clicking the Event structure border and
selecting Edit Events Handled by This
Case from the shortcut menu.
ni.com/training
Edit Events Dialog Box
Configured
Events
Event Sources
Events
ni.com/training
Notify and Filter Events
Notify Events (green arrow)
User action has already occurred and
LabVIEW has processed the event.
Filter Events (red arrow)
User action has already occurred and
LabVIEW has NOT processed the event.
Filter events allow you to override default
behavior for event.
ni.com/training
Caveats and Recommendations
Avoid using an Event structure outside of a loop.
Place only one Event structure in a loop.
Avoid configuring two Event structures for the same event.
Use a Value Change event to detect value changes.
Keep event handling code short and quick.
Place Boolean control terminals inside an event case for latched
operations to work properly.
ni.com/training
SummaryQuiz Answer
1. Which of the following buffer data?
a) Queues
b) Events
c) Local Variables
Both Queues and Events buffer data. Events are queued
until the Event structure configured for the event executes.
Queues store multiple pieces of data and work like a FIFO.
Local variables to not buffer data.
ni.com/training
SummaryMatch the Following Answer
1. Obtain Queue
2. Get Queue Status
3. Release Queue
4. Enqueue Element
a. Destroys the queue
reference
b. Assigns the data type of
the queue
c. Adds an element to the
back of a queue
d. Determines the number
of elements currently in
the queue
ni.com/training
SummaryQuiz Answer
3. Which of the following are valid data types for queues?
a) String
b) Numeric
c) Enum
d) Array of Booleans
e) Cluster of a String and a Numeric
ni.com/training
SummaryQuiz Answer
4. The Event structure handles only one event each time it
executes.
a) True
b) False
ni.com/training
A. Design Patterns
Design Patterns Code implementations and
techniques that are solutions to specific
problems in software design.
Design patterns typically evolve through the efforts of many
developers and are fine-tuned for simplicity, maintainability,
and readability.
ni.com/training
A. Design Patterns LabVIEW Templates
ni.com/training
B. Single Loop Design Patterns
Simple
Single VI that takes a measurement, performs calculations,
and either displays the results or records them to disk
Usually does not require a specific start or stop action from
the user
ni.com/training
B. Single Loop Design Patterns
General VI
Three phases: Start-up, Main Application, and Shut-down
ni.com/training
B. Single Loop Design Patterns
General VI
ni.com/training
B. Single Loop Design Patterns
State Machine
Usually has a start-up and shut-down state, but also
contains other states
ni.com/training
B. Single Loop Design Patterns
State Machine
ni.com/training
C. Multiple Loop Design Patterns
Parallel Loop
ni.com/training
C. Multiple Loop Design Patterns
Producer/Consumer
ni.com/training
D. Timing a Design Pattern Execution
Execution Timing
Provides the design pattern with a function that specifically
allows the processor time to complete other tasks
In some cases, a Wait function is not necessary
Use of Timeout inputs can provide execution timing
ni.com/training
D. Timing a Design Pattern Execution
ni.com/training
D. Timing a Design Pattern Software Control
Software Control Timing
Consider implementing a state machine design pattern for a
data acquisition system
If you must acquire data for 5 minutes, you could remain in
the acquisition state until the 5 minutes elapses
However, during that time you cannot process any user
interface actions such as stopping the VI
To process user interface actions, you must implement
timing so that the VI continually executes for the specified
time
ni.com/training
D. Timing a Design Pattern
Execution Timing
Software Control Timing
ni.com/training
SummaryQuiz Answer
1. The state machine is an example of a design pattern.
a) True
b) False
ni.com/training
SummaryQuiz Answer
2. Which of the following are reasons for using a multiple
loop design pattern?
a)
b)
c)
d)
Execute multiple tasks concurrently
Execute different states in a state machine
Execute tasks at different rates
Execute start up code, main loop, and shutdown code
ni.com/training
SummaryQuiz Answer
3. Software control timing allows the processor time to
complete other tasks.
a) True
b) False
Software control timing is a method for monitoring a real-time
clock. Execution timing allows the processor time to complete
other tasks.
ni.com/training
Lesson 2
Implementing Design Patterns
TOPICS
A. Design Patterns
B. Simple Design Patterns
C. Multiple Loop Design
Patterns
D. Error Handlers
E. Generating Error Codes
and Messages
F. Timing a Design Pattern
G. Functional Global
Variable Design Pattern
ni.com/training
Why Use Design Patterns?
They have proven themselves useful for developing
software.
You dont have to start a program from scratch.
They make it easier for others to read and modify your code.
Design Patterns Code implementations and
techniques that are solutions to specific
problems in software design
Design patterns typically evolve through the efforts of many developers
and are fine-tuned for simplicity, maintainability, and readability.
ni.com/training
B. Simple Design Patterns
Simple VI
General VI
State Machine
Event-Based State Machine
Simple State Machine
ni.com/training
Simple VI Pattern
Single VI that takes a measurement, performs calculations,
and either displays the results or records them to disk.
Usually does not require a specific start or stop action from
the user.
ni.com/training
General VI Pattern
This pattern has three phases:
Start-up
Main application
Shut-down
ni.com/training
General VI Framework
ni.com/training
State Machine Pattern
Usually has a start-up and shut-down state, but also contains
other states.
ni.com/training
State Machine Framework
ni.com/training
Event-Based State Machine
Combines event programming with a State Machine design.
Includes a Wait on Event case to processes user-interface
events.
ni.com/training
Simple State Machine Template
Use the Create Project dialog box to expedite implementing
an event-based state machine application.
ni.com/training
C. Multiple Loop Design Patterns
Producer/Consumer (Events)
ni.com/training
Producer/Consumer Design Patterns
ni.com/training
D. Error Handlers
Examples
Producer/Consumer Error Handler
ni.com/training
Examples of Error Handlers
Simple Error Handler VI
State machine error handler
I/O error handler
Error Handler A VI or code that changes normal
flow of program execution when an error occurs
ni.com/training
Producer/Consumer Error Handler
Both producer and consumer loops gracefully stop when an
error occurs.
Producer loops pass error information to consumer loops.
Consumer loops send stop information to producer loops.
Transition to a Shutdown case in the consumer loop to
execute shutdown code prior to stopping the VI.
Report error information to the user.
ni.com/training
Error Handler VI
ni.com/training
E. Generating Error Codes and Messages
Error Reporting Options
Error Ring
ni.com/training
Error Reporting Options
Use existing error reporting
mechanisms to report error conditions
detected with your code. Errors to
include:
Invalid inputs to subVIs
File and resource errors
LabVIEW-generated messages
Options for error reporting:
Pre-defined errors
User-defined errors
Overriding LabVIEW-generated
messages
ni.com/training
F. Timing a Design Pattern
Execution Timing
Software Control Timing
Synchronized Timeout
Get Data/Time in Seconds
ni.com/training
Timing a Design Pattern
Execution Timing
Provides the design pattern with a function that specifically
allows the processor time to complete other tasks.
Software Control Timing
Times a real-world operation to perform within a set time
period.
Controls the frequency at which a loop executes.
ni.com/training
Timing a Design Pattern
Execution Timing
Software Control Timing
ni.com/training
Execution Timing
Design patterns where the timing is based on the
occurrence of events do not need execution timing.
Default Timeout = -1,
Wait Indefinitely
ni.com/training
Software Control Timing
Software control timing must allow the design pattern to run
continuously without stopping.
The following functions are better for execution timing rather
than software control timing.
Wait (ms)
Wait Until Next ms Multiple
ni.com/training
Synchronized Timeout
Even if no other events occur or the queue is empty, both the
producer and consumer loops continue to execute at regular
intervals.
Timeout in ms
ni.com/training
Get Date/Time in Seconds
Use the Get Date/Time In Seconds function for working with
elapsed times.
ni.com/training
G. Functional Global Variable Design
Pattern
Motivation
Problem: Read-Modify-Race Conditions
Solution: Use FGV SubVI
Function Global Variable (FGV)
Definition
Basic Framework
Other Use Cases for FGVs
ni.com/training
Problem: Read-Modify-Write Race Conditions
The block diagram below has a read-modify-write race
condition.
Simultaneous transactions can generate incorrect data.
ni.com/training
Solution: Use a SubVI Based on the Functional
Global Variable (FGV) Design Pattern
Wrap the shared global resource and all functions that work
on the resource into a FGV subVI.
FGV
ni.com/training
The Up Down Counter VI Example
Up Down Counter VI is an FGV VI that:
Eliminates the read-modify-write race condition for
simultaneous transactions.
Encapsulates methods for resetting, incrementing, and
decrementing.
Simultaneous
transactions
ni.com/training
Up Down Counter VI
Action SelectionUses
an Enum to select the
counter operation:
Reset
Increment
Decrement
Get Current Value
Running TotalOutputs
the current value of the Up
Down Counter VI.
ni.com/training
Up Down Counter VI Framework
ni.com/training
Functional Global Variable
Functional Global Variable A non-reentrant VI that
uses uninitialized shift registers to hold global data. The
VI often allows for actions to be performed on the data.
Functional
Can perform calculations or manipulate data.
Global
Make data globally available within an Application Instance.
Variable
Stores data.
Can be written to or read from like a variable.
ni.com/training
The FGV Basic Framework
The general form of a functional global variable VI includes:
An uninitialized shift register with a single iteration While
Loop.
A Case structure.
Functional Global
Variable Code
ni.com/training
Other Use Cases for FGVs
ni.com/training
SummaryQuiz
1. Which of the following are reasons for using a multiple
loop design pattern?
a)
b)
c)
d)
Execute multiple tasks concurrently
Execute different states in a state machine
Execute tasks at different rates
Execute start up code, main loop, and shutdown code
ni.com/training
SummaryQuiz Answer
1. Which of the following are reasons for using a multiple
loop design pattern?
a)
b)
c)
d)
Execute multiple tasks concurrently
Execute different states in a state machine
Execute tasks at different rates
Execute start up code, main loop, and shutdown code
ni.com/training
SummaryQuiz
2. Which of the following are examples of error handling
code?
a)
b)
c)
d)
Displays a dialog box used to correct a broken VI
Generates a user-defined error code
Displays a dialog box when an error occurs
Transitions a state machine to a shutdown state when an
error occurs
ni.com/training
SummaryQuiz Answer
2. Which of the following are examples of error handling
code?
a)
b)
c)
d)
Displays a dialog box used to correct a broken VI
Generates a user-defined error code
Displays a dialog box when an error occurs
Transitions a state machine to a shutdown state when
an error occurs
ni.com/training
SummaryQuiz
3. What is the default timeout value of an Event structure?
a)
b)
c)
d)
0
100 ms
Never time out
The input value of the Wait (ms) function that exists in the
same loop as the Event structure
ni.com/training
SummaryQuiz Answer
3. What is the default timeout value of an Event structure?
a)
b)
c)
d)
0
100 ms
Never time out
The input value of the Wait (ms) function that exists in same
loop as the Event structure
ni.com/training
Lesson 3
Controlling the User Interface
TOPICS
A.
B.
C.
D.
VI Server Architecture
Property Nodes
Invoke Nodes
Control References
ni.com/training
A. VI Server Architecture
VI Server Architecture
Properties and Methods
VI Class Hierarchy
ni.com/training
VI Server Architecture
The VI Server provides programmatic access to LabVIEW.
Use the VI Server to:
Programmatically control front panel objects & VIs
Dynamically load and call VIs
Run VIs on a computer or remotely across a network
Programmatically access to the LabVIEW environment and
editor (Scripting)
ni.com/training
Properties and Methods
Properties Single-valued attributes of the object:
read/write, read only, write only
Properties include color, position, size, visibility, label text, and label
font.
Methods Functions that operate on the object
Methods include reinitializing values to default and exporting graph
images.
ni.com/training
VI ServerClass Hierarchy
Class
Control
Property: Visible
Method:
Reinitialize to Default
Sub-Class
Boolean
Array
Numeric
Property:
Boolean Text
Object
Property Values
Label Text: Stop Button
Visible: Yes
Boolean Text: Stop
ni.com/training
VI ServerClass Hierarchy
Generic
GObject
VI
Application
Generic
Etc.
GObject
Control
Control
Boolean
GraphChart
Numeric
Cluster
Etc.
Boolean
ni.com/training
B. Property Nodes
Definition
Creating Property Nodes
Execution Order
ni.com/training
Property Nodes
Property Nodes read and write the properties of an object.
Property Nodes can:
Change the color of a chart plot.
Disable and enable controls.
Get the location of a control or indicator.
Property Nodes allow you to make these
modifications programmatically.
Use Context Help to get information about
properties.
There are two types of Property Nodes.
Implicitly linked
Explicitly linked
ni.com/training
Execution Order
Property Nodes can have multiple properties.
Properties execute from top to bottom.
ni.com/training
C. Invoke Nodes
Definition
Control Methods
VI Methods
ni.com/training
Invoke Nodes
Invoke Nodes call methods or actions on objects.
Get VI Version
Print VI panel
Reinitialize All to Default
Invoke Nodes perform actions on referenced
items such as VIs and controls.
Most methods have parameters.
Use Context Help to get information on methods.
There are two types of control Invoke Nodes.
Implicitly linked
Explicitly linked
ni.com/training
Control Methods
To create an implicitly linked Invoke Node:
1.
2.
Right-click the control terminal on the block diagram and select
CreateInvoke Node.
Select a method from the submenu.
Examples of control methods:
Reinitialize to Default
Export Image
ni.com/training
VI Methods
Use a VI Server Reference to associate an Invoke Node
with the current VI.
To create a VI method:
1. Place an Invoke Node on the block diagram.
2. Right-click and select Select Class to choose a class.
3. Right-click again and select Select Method to choose a
method.
Class Name
Method Name
Parameter
ni.com/training
D. Control References
Implicitly and Explicitly Linked Property Nodes
Create SubVIs
Use the Create SubVI Tool
Create Manually
Select a VI Server Class
ni.com/training
Control References
Implicitly Linked Property Node
Explicitly Linked Property Node
Main VI
VI
Main VI
VI
SubVI
ni.com/training
Control References
A control reference is a reference to a front panel object.
Wire control references to
generic Property Nodes.
Pass control references
to subVIs.
ni.com/training
Creating a SubVI
To create explicitly linked Property Nodes in a subVI:
1. Create your VI.
2. Select the portion of the block
diagram that will be in the subVI.
3. Select EditCreate SubVI.
LabVIEW automatically creates
the control references needed
for the subVI.
4. Customize and save the subVI.
ni.com/training
Creating a SubVI
SubVI Front Panel
SubVI Block Diagram
ni.com/training
Create Control References Manually
Control Reference
SubVI Front Panel
SubVI Block Diagram
Ctl Refnum
ni.com/training
Selecting the VI Server Class
After you place a Control Refnum on the front panel of a
subVI, specify the VI Server class of the control.
Right-click and select VI Server Class from the shortcut
menu.
Alternatively, drag a control into a control refnum to specify
the type.
The class specifies the type of control references that the
subVI accepts.
ni.com/training
SummaryQuiz Answer
1. For each of the following items, determine whether they
operate on a VI class or a Control class.
a.
b.
c.
d.
Format and Precision: Control
Visible: Control
Reinitialize to Default Value: Control
Show Tool Bar: VI
ni.com/training
SummaryQuiz Answer
2. You have a Numeric control refnum in a subVI.
Which control references could you wire to the
control refnum terminal of the subVI?
a.
b.
c.
d.
Control reference of a Knob
Control reference of a Numeric Array
Control reference of a Thermometer indicator
Control reference of an LED
ni.com/training
Lesson 4
File I/O Techniques
TOPICS
A.
B.
C.
D.
E.
Compare File Formats
Create File and Folder Paths
Write and Read Binary Files
Work with Multichannel Text Files with Headers
Access TDMS Files in LabVIEW and Excel
ni.com/training
Compare File Formats
At their lowest level, all files written to your computers hard
drive are a series of bits.
TDMS
ASCII
Binary
ni.com/training
Compare File Formats
Numeric
Precision
Share
data
Efficiency
Ideal Use
ASCII
TDMS
Direct Binary
Good
Best
Best
Best
(Any program easily)
Better
(NI Programs easily;
Excel)
Good
(only with detailed
format information)
Good
Best
Best
Share data with other
programs when file
space and numeric
precision are not
important.
Store measurement
data and related
metadata. High-speed
streaming without loss
of precision.
Store numeric data
compactly with
ability to random
access .
ni.com/training
B. Create File and Folder Paths
Methods of Creating
Creating Relative Paths and Folders
Dynamically Creating Filenames
ni.com/training
Methods of Creating File and Folder Paths
Hard-coded paths
Useful for quick prototypes.
Not recommended for applications.
File Dialog
Allow user to specify the path to a file or directory.
Customize dialog options to limit options (*.txt).
Programmatic creation
Create consistent filenames and extensions.
Example: testdata_001.txt, testdata_002.txt, etc.
Specify a consistent location.
ni.com/training
Creating Relative Paths
Relative paths set paths relative to the application or system
directory.
Use the Application Directory VI to get project directory paths.
Use the Get System Directory VI to get system directory
paths.
Paths differ based on the operating system and user.
ni.com/training
Creating Folders
Check if folder already exists before creating. Otherwise,
attempting to create an existing folder will result in an error.
ni.com/training
Dynamically Creating Filenames
ni.com/training
C. Write and Read Binary Files
Using Binary File Functions
Demonstration
ni.com/training
Using Binary File Functions
Use Binary File functions to read and write binary files.
You can create custom file types.
You must know the required file formats for your system.
ni.com/training
D. Work with Multichannel Text Files with
Headers
Review of Text Files
Add Headers to the File
Write Multichannel Data
Read Data and Extract Information
ni.com/training
Review of Text Files
Use ASCII characters to store information in text files.
Each character (number, letter, punctuation) takes 1 byte.
Many applications can open text files, including Excel.
Files are typically larger and slower to write/read than binary.
You cannot randomly access text files.
ni.com/training
Creating Text Files with Headers
No Header Data
Header Data
24.45
34.54
Operator Name
David
23.41
35.32
UUT S/N
A1234
22.97
35.98
Test Name
Pressure
21.56
36.76
Channel Name
Temperature
Pressure
Units
Kelvin
PSI
Max. Value
24.45
36.76
24.45
34.54
23.41
35.32
22.97
35.98
21.56
36.76
Tab
CR/LF
ni.com/training
Creating Text Files with Headers
Hard Coding
Hard coding header information becomes difficult to maintain.
ni.com/training
Creating Text Files with HeadersSubVIs
Using subVIs to build strings is a scalable solution.
With subVIs you can add and remove header data easily.
The block diagram is more readable.
ni.com/training
Writing Multiple Channels
LabVIEW stores multi-dimensional arrays in row-major
order.
Rows are identified by the first index of a 2-D array.
Columns are identified by the second index.
Transpose data before writing to file to view channel data in
column format.
ni.com/training
Reading Channel Data
Use Array Subset to skip over header information.
Transpose data after reading to convert data back to rowmajor order.
Use Index Array to extract one column or row of data.
ni.com/training
Read Data and Extract Information
After reading a spreadsheet file,
how do you extract information?
How do you find a property
value?
How do you read the UUT
Serial Number value?
How do you extract channel
data for column 1?
ni.com/training
Given a Property Name, Find the Value
Use Index Array to put column 0 in a 1-D array.
Use Search 1D Array to find Property Name:
Return row index if found.
Return -1 if not found.
Use Index Array to get element at row index and column 1.
What should you do if Property Name is not found?
ni.com/training
Extracting a Data Channel
Identify row index of first data value.
Use Array Subset to extract Data Channel.
Output is one channel of data in a 2-D string array.
Convert to 1-D numeric array.
ni.com/training
E. Access TDMS Files in LabVIEW and
Excel
TDMS File Format
Data Hierarchy and Properties
TDMS Functions
File Viewer
ni.com/training
TDMS File Format
The Technical Data Management Streaming (TDMS) file format
contains two types of data:
Meta data Names and properties
Raw data Measurement data in binary format
Use TDMS files for the following purposes:
To store test or measurement data.
To create structures for grouping your data.
To store headers/properties about your data.
To read and write data at high speeds.
A variety of applications, including Microsoft Excel, can access TDMS
files.
ni.com/training
TDMS FilesData Hierarchy and Properties
ni.com/training
TDMS Functions
ni.com/training
TDMS FilesFile Viewer
Open TDMS files and present the file data in the
TDMS File Viewer dialog box.
ni.com/training
SummaryQuiz Answer
1. Consider the following code. The resulting Log File Path
contains a text file path in which folder?
a) Same folder as VI that executed the code
b) Same folder as the LabVIEW project
c) Current users AppData directory
d) Same folder as the Application Directory VI
ni.com/training
SummaryQuiz Answer
2. What index value is returned from Search 1D Array
function if Property Name is not found in the input array?
a) NaN (Not a Number)
b) 0
c) -1
d) Negative Infinity
ni.com/training
SummaryQuiz Answer
3. You need to store data that other engineers will later
analyze with Microsoft Excel. Which file storage format(s)
should you use?
a) Tab-delimited ASCII
b) Custom binary format
c) TDMS
ni.com/training
SummaryQuiz Answer
4. TDMS File store properties at which of the following
levels?
a) File
b) Channel Group
c) Channel
d) Value
ni.com/training
Lesson 5
Controlling the User Interface
TOPICS
A.
B.
C.
D.
Property Nodes
Invoke Nodes
VI Server Architecture
Control References
ni.com/training
A. Property Nodes
Property Nodes access the properties of an object
In some applications, you might want to modify the
appearance of front panel objects programmatically in
response to certain inputs
If a user enters an invalid password, you might want a red LED
to start blinking
If a data point is above a certain value, you might want to show
a red trace instead of a green one
Property Nodes allow you to make these modifications
programmatically
ni.com/training
Property Nodes Execution Order
Property Nodes execute in order from top to bottom
By default, if an error occurs on a terminal, the node stops at
that terminal, returns an error, and does not execute any
further terminals
To override default, right-click and select Ignore Errors Inside
Node
ni.com/training
B. Invoke Nodes
Use the Invoke Node to perform actions, or methods, on
referenced items
Control
VI
Most methods have parameters
ni.com/training
Invoke Nodes Control Methods
To create an Invoke Node, right-click the control and select
CreateInvoke Node and choose a method
An example of a method that is common to all controls is the
Reinitialize to Default method
The Waveform Graph has the
method Export Image:
ni.com/training
Implicit vs Explicit Nodes
Implicitly Linked Node
Explicitly Linked Node
Main VI
VI
Main VI
VI
SubVI
ni.com/training
Invoke Nodes VI Methods
Use a reference to associate an Invoke Node with the
current VI
To create a VI method
Drop a VI Server Reference, then select This VI
Right-click and select CreateMethod for VI Class and
choose a method
Method Name
Parameters
ni.com/training
Invoke Nodes VI Methods
Examples of VI Methods:
Front Panel: Center
Default Values: Reinitialize all to Default
Print: VI to HTML
ni.com/training
C. VI Server Architecture
VI Server performs many functions; however, this lesson
concentrates on using VI Server to control front panel objects
and edit the properties of a VI.
ni.com/training
VI Server Terminology
An object is a member of a class.
A class defines what an object is able to do, what operations
it can perform (methods), and what properties it has.
Methods perform an operation on an object.
Properties are the attributes of an object.
ni.com/training
VI Server Architecture Example
Control
Boolean
Stop
Boolean Sub-Class
Property: Boolean Text
Control Class
Property: Visible
Method: Reinitialize to Default
Array
Array Sub-Class
Property: Number of Rows
Stop Object
Properties:
Visible: Yes
Boolean Text: Stop
Method:
Reinitialize to Default
ni.com/training
VI Server Classes
Control Classes
LabVIEW front panel objects inherit properties and methods
from a specific control class
VI Class
Your VI belongs to the VI Class and has its own properties and
methods associated with it
ni.com/training
Class Hierarchy
Generic Object
GObject
Control
Boolean
ni.com/training
Property Nodes Class Browser
Find and create explicitly
linked methods and
properties using the Class
Browser dialog box
Select ViewClass Browser
ni.com/training
D. Control References
A control reference is a reference to a front panel object
Wire control references to
generic Property Nodes
Pass control references
to subVIs
ni.com/training
Control References Create SubVI
To create explicitly-linked Property Nodes in a subVI:
1. Create your VI.
2. Select the portion of the block
diagram that will be in the subVI.
3. Select EditCreate SubVI;
LabVIEW automatically creates
the control references needed
for the subVI.
4. Customize and save the subVI.
ni.com/training
Control References Create SubVI
SubVI Front Panel
SubVI Block Diagram
ni.com/training
Control References Create Yourself
Control Reference
SubVI Front Panel
SubVI Block Diagram
Ctl Refnum
ni.com/training
Control References Selecting Class
After you place a Control Refnum on the front panel of a
subVI, specify the VI Server class of the control
Right-click and select VI Server Class from the shortcut menu
Specifies the type of control references that the subVI
accepts
In the previous example, Control was the VI Server class
Allows the VI to accept a reference to any type of front panel
control
ni.com/training
Control References Selecting Class
Specifying a more specific class for the refnum makes the
subVI more restrictive
For example, you can select Digital as the class, and the
subVI can only accept references
to numeric controls of the class Digital
Selecting a more generic class for a control refnum allow it
to accept a wider range of objects but limits the properties
available
ni.com/training
SummaryQuiz Answer
1. For each of the following items, determine whether they
operate on a VI class or a Control class.
a.
b.
c.
d.
Format and Precision: Control
Blinking: Control
Reinitialize to Default Value: Control
Show Tool Bar: VI
ni.com/training
SummaryQuiz Answer
2. You have a GraphChart control refnum in a subVI.
Which control references could you wire to the
control refnum terminal of the subVI? (multiple answers)
a.
b.
c.
d.
Control reference of an XY Graph
Control reference of a Numeric Array
Control reference of a Waveform Chart
Control reference of a Boolean
ni.com/training
Lesson 5
Improving an Existing VI
TOPICS
A. Refactoring Inherited Code
B. Typical Refactoring Issues
ni.com/training
A. Refactoring Inherited Code
Definition
When To Refactor
The Refactoring Process
ni.com/training
Refactoring Inherited Code
Inherited VIs may be poorly designed, making it difficult to add
features later in the life of the VI.
Refactoring:
Is the process of redesigning software to make it more
readable and maintainable so that the cost of change does
not increase over time.
Changes the internal structure of a VI to
make it more readable and maintainable,
without changing its observable behavior.
ni.com/training
When to Refactor
When you are adding a feature to a VI or debugging it.
Good candidates for complete rewrites:
VIs that do not function.
VIs that satisfy only a small portion of your needs.
ni.com/training
Refactoring Process
When you refactor to improve
the block diagram, make small
cosmetic changes before
tackling larger issues.
ni.com/training
B. Typical Refactoring Issues
Disorganization
Poor Naming
Overly Complicated
Duplicated Logic
Breaks Dataflow
Outdated Practices
ni.com/training
Disorganization
The block diagram is too disorganized, too big, or includes too
many nested structures
Solution:
Move objects within the block diagram.
Create subVIs to make it smaller and more organized.
Place comments to improve readability.
ni.com/training
Poor Naming
The block diagram uses incorrect object names and poor
icons.
Best
Better
Good
8
ni.com/training
Overly Complicated
The block diagram uses complicated or unnecessary logic.
ni.com/training
Duplicate Logic
The block diagram uses duplicate logic.
Solution:
Refactor the VI by creating a subVI for the duplicated logic.
ni.com/training
Breaks Dataflow
The block diagram does not use dataflow programming.
Solution:
Replace Sequence structures with state machines.
Delete local variables and wire directly to controls or
indicators.
ni.com/training
Outdated Practices
The VI was created in an earlier version of LabVIEW and has
outdated practices.
Solutions:
Replace polling-based design with event-based design.
Use new features that simplify code.
ni.com/training
SummaryRefactoring Checklist
Use the following refactoring checklist to help determine if
you should refactor a VI:
VI is too disorganized, too big, or includes too many
nested structures.
VI uses incorrect object names and poor icons.
VI uses unnecessary logic or has complicated
algorithms.
VI has duplicated logic.
VI does not use dataflow programming.
VI uses outdated development practices.
ni.com/training
Lesson 6
Creating and Distributing Applications
TOPICS
A.
B.
C.
D.
Preparing the Files
Build Specifications
Create and Debug an Application
Create an Installer
ni.com/training
A. Preparing the Files
Building Applications Checklist
VI Properties
Paths and System Paths
Quit Application
ni.com/training
Preparing the Files
To create a professional, stand-alone application for your VIs,
you must first prepare your files:
Recompile and save changes to VIs.
Verify desired VI Properties settings.
Ensure paths generate correctly.
Conditionally call the Quit LabVIEW function.
ni.com/training
Building Applications Checklist
Refer to the Building Applications Checklist topic of the
LabVIEW Help for more information about:
Preparing files.
Configuring build specifications.
Distributing builds.
ni.com/training
Preparing the Files VI Properties
To set VI Properties
settings:
Manually edit the VI
Properties dialog
box.
Programmatically
change VI Properties
using VI Server.
ni.com/training
Preparing the Files Paths
Set paths relative to Application Directory VI path.
If the VI is called:
The VI returns:
From a stand-alone application
The path to the folder containing
the application executable
From a LabVIEW project (.lvproj)
in the LabVIEW Development
Environment
The path to the project folder
ni.com/training
Preparing the Files System Paths
Use the Get System Directory VI to get system directory
paths.
Paths differ based on the operating system and user.
Windows XP User Documents:
C:\Documents and Settings\<user>\My Documents
Windows 7 User Documents:
C:\Users\<user>\Documents
ni.com/training
Preparing the Files Quit Application
Programmatically quit your application using the Quit
LabVIEW Function.
To conditionally call the Quit LabVIEW function, use the
App.Kind property.
ni.com/training
Build Specifications
A build specification contains all the settings for the build,
such as files to include, directories to create, and settings for
VIs.
ni.com/training
Why Use Build Specifications?
Use build specifications to build the following:
Stand-alone applications
Installers
Source distributions
Zip files
Shared libraries
Packed Project libraries
.NET Interop Assemblies
Web services
11
ni.com/training
C. Create and Debug an Application
System Requirements for Applications
Configure the EXE Build Specification
Build and Run the EXE
Debug the EXE
ni.com/training
System Requirements for Applications
Applications that you create with Build Specifications
generally have the same system requirements as the
LabVIEW development system used to create the VI or
application.
Memory requirements vary depending on the size of the
application created.
13
ni.com/training
Configure the EXE Build Specification
In the Application Properties dialog box:
Specify name of executable.
Specify known destination for generated executable files
Identify a startup VI and include any dynamically linked files.
Enable debugging, if desired.
Preview the build.
ni.com/training
EXE Properties Information
ni.com/training
EXE Properties Source Files
Always include a Startup VI.
Do not include statically
linked files.
Include any dynamically linked
files in Always Included section.
ni.com/training
EXE Properties Advanced
Enable debugging to identify runtime problems in deployed EXEs.
Enabling debugging increases the
EXE size.
ni.com/training
EXE Properties Preview
1
1. Preview the build to see the
directory structure and files that
generate.
2. Dont build yet. First save the
project.
2
ni.com/training
Save the Project and Build the Executable
1
ni.com/training
Run EXE and Verify Execution
ni.com/training
Debug EXE LabVIEW on Same Machine
1
2
3
ni.com/training
Debug the EXE from LabVIEW
ni.com/training
Why Executables Might Behave Differently
File paths may change, which can lead to errors.
Drivers or support files are missing.
System resources like memory or CPU speed may differ,
which can lead to timing changes.
The application INI file differs from the LabVIEW INI file.
Not all features are supported in the Run-Time Engine.
ni.com/training
D. Create an Installer
Why Create an Installer?
Configure the Installer Build Specifications
Deploy the Application to Another Machine
Debug the Executable
ni.com/training
Why Create an Installer?
Executables need the LabVIEW Run-Time Engine (RTE) to
execute on a target system.
If an application relies on drivers, those drivers need to be
installed on the target system.
An installer ensures files are copied to the right places.
Professional applications use installers.
ni.com/training
Configuring Installer Build Specifications
In the Installer Properties dialog box:
Include the LabVIEW Run-Time Engine.
From the Additional Installers page, select the NI LabVIEW
Run-Time Engine.
Include drivers used in the application.
For example, if you use DAQmx VIs in your application, then
include the NI-DAQmx driver.
Refer to the Caveats and Recommendations for Building
Installers topic of the LabVIEW Help for more information.
27
ni.com/training
Installer Properties Product Information
ni.com/training
Installer Properties Additional Installers
ni.com/training
Install and Run on Destination Computer
ni.com/training
Debug Executable on Destination Computer
1. Find IP address of destination computer.
Type ipconfig in command prompt window of the
destination computer to discover IP address.
2. Launch LabVIEW on development machine.
3. Enter the IP address or machine name in Debug
Application or Shared Library dialog box.
4. Click the Connect button in the Debug Application or
Shared Library dialog box.
Control is transferred to development machine.
5. Debug the executable using LabVIEW debugging tools.
ni.com/training
Summary
The Application Builder enables you to create stand-alone
applications and installers.
To create a professional, stand-alone application you must
understand:
The architecture of your application.
The programming issues particular to your application.
The application building process.
The installer building process.
Test your application and installer regularly as you develop.
ni.com/training
Lesson 2
Synchronization Techniques
TOPICS
A. Notifiers
B. Queues
ni.com/training
Need for Synchronization
Variables are one method for passing data between
parallel processes
Using variables breaks the LabVIEW dataflow paradigm,
allows for race conditions, and incurs more overhead
than passing the data by wire
ni.com/training
A. Notifiers
Use the Notifier Operations functions to suspend the
execution of a block diagram until you receive data from
another section of the block diagram or from another VI.
ni.com/training
Master/Slave Design Pattern
ni.com/training
Notifiers Benefits
The following benefits result from using notifiers to transfer
data between parallel loops:
Both loops are synchronized to the master loopthe slave
loop only executes when the master loop sends a
notification
You can use notifiers to create globally available data,
making it possible to send data with a notification
Using notifiers creates efficient codethere is no need to
poll to determine when data is available from the master
loop
ni.com/training
Notifiers Disadvantages
Notifiers do not buffer data.
If the master loop sends another piece of data before the
first piece of data has been read by the slave loops, that
data is overwritten and lost.
ni.com/training
B. Queues
Queues are similar to notifiers, except that a queue can
store multiple pieces of data
By default, queues work in a FIFO (first in, first out) manner
Use a queue when you want to process all data placed in
the queue
Use a notifier if you only want to process the current data
ni.com/training
B. Queues
Use the Queue Operations functions to create a queue for
communicating data between sections of a block diagram or
from another VI.
ni.com/training
Producer/Consumer Design Pattern (Data)
ni.com/training
SummaryQuiz Answer
1. Which of the following buffer data?
a) Notifiers
b) Queues
c) Global Variables
d) Local Variables
ni.com/training
Match the Following Answer
1. Obtain Queue
2. Get Queue Status
3. Release Queue
4. Enqueue Element
a. Destroys the queue
reference
b. Assigns the data type of
the queue
c. Adds an element to the
back of a queue
d. Determines the number
of elements currently in
the queue
ni.com/training
SummaryQuiz Answer
3. Which of the following are valid data types for queues and
notifiers?
a) String
b) Numeric
c) Enum
d) Array of Booleans
e) Cluster of a String and a Numeric
ni.com/training
Lesson 3
Event Programming
TOPICS
A.
B.
C.
D.
Events
Event-Driven Programming
Caveats and Recommendations
Event-Based Design Patterns
ni.com/training
A. Events
Event An asynchronous notification that something
has occurred
Events originate from the user interface, external I/O, or
other parts of the program
Event-Driven Programming Method of
programming where the program waits on an event to
occur before executing one or more functions
ni.com/training
A. Events Why Use Events?
Event Programming
User Action
on
Front Panel
Execution
Block Diagram
ni.com/training
B. Event-Driven Programming
Parts of an Event structure
Notify and filter events
Configure and use the Event structure
Event Registration and Panel Locking
ni.com/training
The Event Structure
Examples of User Interface
(Static) Events
Pressing a button on the mouse
Pressing a key on the keyboard
Changing the value of a numeric
control
ni.com/training
Parts of an Event Structure
Timeout
Event Selector
Label Identifies
event case viewed
Timeout Value in
ms to wait for events;
default value is 1
(indefinite)
Event Selector Label
ni.com/training
Parts of an Event Structure (continued)
Event Data Node
Identifies the data
LabVIEW provides
when the event
occurs; similar to
the Unbundle By
Name function
Event Filter Node
Identifies the
subset of data
available in the
Event Data node
that the event case
can modify
Event Data Node
Event Filter Node
ni.com/training
Notify and Filter Events
Notify Events
User action has already occurred
LabVIEW has processed the event
Available only in the Event Data node
Filter Events
User action has already occurred
LabVIEW has NOT processed the event
Allows you to override default behavior for event
Available in the Event Filter node and Event Data node
ni.com/training
Using an Event Structure
Normally used in a While Loop
Event structure handles exactly one event per iteration
Sleeps when no events occur
ni.com/training
Configuring the Event Structure
Use a dialog box to configure events by
right-clicking the Event structure border and
selecting Edit Events Handled by This Case
from the shortcut menu.
ni.com/training
Edit Events Dialog Box
Configured
Events
Event Sources
Events
ni.com/training
Notify and Filter Events
Notify Events (green arrow)
User action has already occurred
Filter Events (red arrow)
User performed action but event is not
processed. Allows you to customize event
handling.
ni.com/training
Event Registration and Panel Locking
When you run a VI, LabVIEW automatically registers events
that you configured with the Edit Events dialog box
When a registered event occurs, it is queued until the Event
structure(s) configured for it executes
It is not possible to miss events or process them out of order
By default, the front panel is locked until the event is
handled
You can turn off locking, but only for Notify Events
Events are unregistered when the VI becomes idle
ni.com/training
C. Caveats and Recommendations
For a complete list, refer to LabVIEW Help topic: Caveats and
Recommendations when Using Events in LabVIEW
Latched Boolean controls
You must read the control terminal inside the event case for the
mechanical action to work correctly
Programmatic update of front panel
LabVIEW does not generate events if you use the VI Server or
variables to programmatically update the front panel VI or
objects
Exception: Value (Signaling) property
ni.com/training
C. Caveats and Recommendations
Avoid using an Event structure outside of a loop
The Event structure handles only one event each time it
executes
Place only one Event structure in a loop
If you place two Event structures in a single loop, the loop
cannot iterate until both Event structures handle an event
The loop can become unresponsive
Avoid configuring two Event structures to handle the same
event
ni.com/training
C. Caveats and Recommendations
Use Value Change event to detect value changes
Value change will generate events regardless of how the user
modifies the control
Keyboard shortcut, increment/decrement arrow buttons, keyboard
entry in digital display
Keep event handling code short and quick
It is possible to lock the user interface if code takes too long to
execute
ni.com/training
D. Event-Based Design Patterns
User Interface Event Handler
Producer/Consumer (Events)
ni.com/training
User Interface Event Handler
Use the user interface event
handler design pattern for
detecting when a user changes
the value of a control, moves or
clicks the mouse, or presses a
key
The user interface event handler
allows you to minimize
processor use without
sacrificing interactivity
ni.com/training
Producer/Consumer (Events)
Benefits
Efficiently
responds
asynchronously
to the user
interface
Queues can
transfer any
data type
ni.com/training
SummaryQuiz Answer
1. Using user interface events allows you to synchronize
user actions on the front panel with block diagram
execution.
a) True
b) False
ni.com/training
SummaryQuiz Answer
2. The Event structure handles only one event each time it
executes.
a) True
b) False
ni.com/training
SummaryQuiz Answer
3. Which of the following are examples of user interface
events?
a) Mouse click
b) Keystroke
c) Event Filter Node
d) Value change of a control
ni.com/training
SummaryQuiz Answer
4. Which of the following operations will generate a Value
Change event for a numeric control?
a) Click inside the digital display window and enter a
number from the keyboard
b) Click the increment or decrement arrow buttons
c) Place the cursor to the right of the digit you want to
change and press the up or down arrow keys
d) Update the numeric control using a local variable
ni.com/training
Lesson 3
Implementing a VI
TOPICS
A.
B.
C.
D.
E.
Front Panel Basics
LabVIEW Data Types
Documenting Code
While Loops
For Loops
F.
G.
H.
I.
Timing a VI
Data Feedback in Loops
Plotting Data Waveform Chart
Case Structures
ni.com/training
Front Panel Basics
Front panel controls and indicators create terminals on the
block diagram.
ni.com/training
B. LabVIEW Data Types
Shortcut Menu and Properties Dialog Box
Numeric Types
Boolean Types
String Types
Enums and Other Types
ni.com/training
LabVIEW Data Types
Terminals visually communicate information about the data
type represented
ni.com/training
Shortcut Menus
All LabVIEW objects have
associated shortcut
menus.
Use shortcut menu items
to change the look or
behavior of objects.
To access the shortcut
menu, right-click the
object.
ni.com/training
Properties Dialog Box
All LabVIEW objects have
properties.
To access properties,
right-click the object and
select Properties.
Property options are
similar to shortcut menu
options.
Select multiple objects to
simultaneously configure
shared properties.
ni.com/training
Numerics
Various data type
representations:
Floating-point
Unsigned integers
Signed integers
ni.com/training
Numeric Conversion
Coercion Dot
Coercion dots indicate that LabVIEW
converted the value passed into a node to
a different representation.
Occurs when a node expects an input with a
different representation.
LabVIEW chooses the representation that
uses more bits.
Avoid coercion by programmatically
converting to a matching data type.
ni.com/training
Booleans
Behavior of Boolean
controls is specified by the
mechanical action.
Boolean have only
TRUE/FALSE values.
ni.com/training
Strings
A string is a sequence
of ASCII characters.
Strings have various
display styles.
Backslash codes
Password
Hex
ni.com/training
Enums
Enums give users a list of
items from which to
select.
Each item represents a
pair of values.
String
16-bit Integer
ni.com/training
Other Data Types
Refer to LabVIEW Help for complete list of terminal symbols
for different types of controls and indicators.
Dynamic
Stores the information generated or acquired by an Express VI.
Path
Stores the location of a file or directory using the standard
syntax for the platform you are using.
Waveform
Carries the data, start time, and dt of a waveform.
ni.com/training
C. Documenting Code
VI Descriptions
Tip Strips
Labels
Free
Owned
ni.com/training
Documenting Code
VI
Name
Description
Front Panel
Block Diagram
Label Names
Tip Strips
Descriptions
Free Labels
Label Names
Free Labels
Owned
Labels
SubVI
Descriptions
ni.com/training
Creating Descriptions and Tip Strips
Use the Properties
dialog box to create
documentation for
an object.
ni.com/training
Documenting Block Diagram Code
Free labels:
Owned labels:
Describe algorithms.
Have pale yellow backgrounds.
Double-click in any open space
to create.
Explain data contents of wires
and objects.
Move with object.
Have transparent
backgrounds.
Select Visible ItemsLabel
from the shortcut menu to
create.
ni.com/training
D. While Loops
Iteration and Conditional Terminals
Tunnels
Error Checking
ni.com/training
While Loops
Repeat (code);
Until Condition met;
End;
LabVIEW While Loop
Flowchart
Pseudo Code
ni.com/training
While Loops
Iteration terminal
Conditional terminal
Returns number of times loop
has executed.
Is zero-indexed.
Defines when the loop stops.
Has two options.
Stop if True
Continue if True
Iteration Terminal
Conditional Terminal
ni.com/training
While Loops Tunnels
Tunnels transfer data into and out of structures.
Data pass out of a loop after the loop terminates.
When a tunnel passes
data into a loop, the loop
executes only after
data arrive at the tunnel.
ni.com/training
While Loops Error Checking and Error Handling
Use an error cluster in a While Loop to stop the While Loop if
an error occurs.
ni.com/training
E. For Loops
Conditional Terminal
Comparison with While Loops
Numeric Conversion for Count Terminal
ni.com/training
For Loops
N=100;
i=0;
Until i=N:
Repeat (code;i=i+1);
End;
LabVIEW For Loop
Flowchart
Pseudo Code
ni.com/training
For Loops
Create a For Loop the same way you create a While Loop.
You can replace a While Loop with a For Loop by rightclicking the border of the While Loop and selecting
Replace with For Loop from the shortcut menu.
The value in the count terminal (an input terminal)
indicates how many times to repeat the subdiagram
in the For Loop.
ni.com/training
For Loops Conditional Terminal
You can add a conditional terminal to configure a For Loop to
stop when a Boolean condition is true or an error occurs.
ni.com/training
For Loops Conditional Terminal
For Loops configured with a conditional terminal have:
A red glyph next to the count terminal.
A conditional terminal in the lower right corner
ni.com/training
For Loop/While Loop Comparison
For Loop
Executes a set number of times
unless a conditional terminal is
added.
Can execute zero times.
Tunnels automatically output an
array of data.
While Loop
Stops executing only if the value
at the conditional terminal meets
the condition.
Must execute at least once.
Tunnels automatically output the
last value.
ni.com/training
For Loops Numeric Conversion
The number of iterations a For Loop executes must be specified in
non-negative integers.
If you wire a double-precision, floating-point numeric value to the
count terminal, LabVIEW converts the numeric value to a 32-bit
signed integer.
ni.com/training
F. Timing a VI
Reasons To Use Timing
Wait Functions and Express VIs
ni.com/training
Timing a VI
Why do you need timing in a VI?
To control the frequency at which a loop executes.
To provide the processor with time to complete other tasks,
such as processing the user interface.
ni.com/training
Wait Functions
A wait function inside a loop:
Allows the VI to sleep for a set amount of time.
Allows the processor to address other tasks during the wait
time.
Uses the operating system millisecond clock.
ni.com/training
Elapsed Time Express VI
Determines how much time elapses after some point in
your VI.
Keeps track of time while the VI continues to execute.
Does not provide the processor with
time to complete other tasks.
ni.com/training
G. Data Feedback in Loops
Shift Registers
Initializing Shift Registers
Default for Unwired Values
Compound Shift Registers
ni.com/training
Data Feedback in Loops
When programming with loops, you often need to know the
values of data from previous iterations of the loop.
Shift registers transfer values from one loop iteration to the
next.
ni.com/training
Shift Registers
Right-click the border and select Add Shift Register from
the shortcut menu.
Right shift register stores data on completion of an iteration.
Left shift register provides stored data at beginning of the
next iteration.
ni.com/training
Initializing Shift Registers
Run once
VI finishes
Block Diagram
Run again
1st run
2nd run
Initialized
Shift
Register
Output = 5
Output = 5
Not
Initialized
Shift
Register
Output = 4
Output = 8
ni.com/training
Use Default if Unwired
Default values vary by data type:
Data Type
Default Value
Numeric
Boolean
FALSE
String
Empty
Uninitialized shift registers use default values for first run.
ni.com/training
Multiple Previous Iterations
Stacked shift registers remember values from multiple
previous iterations and carry those values to the next
iterations.
Right-click the left shift register and select Add Element
from the shortcut menu to stack a shift register.
ni.com/training
H. Plotting Data Waveform Chart
ni.com/training
Plotting Data Waveform Chart
Waveform chart
is a special type
of numeric
indicator.
Waveform charts
display single or
multiple plots.
ni.com/training
Waveform Chart Properties
Extensive plot
customization lets you:
Show or hide legends.
Change color and line
styles.
Change interpolation
styles.
ni.com/training
I. Case Structures
Parts of a Case Structure
Enum Case Structures
Error Case Structures
Input and Output Tunnels
ni.com/training
Case Structures
Have two or more subdiagrams or cases.
Use an input value to determine which case to execute.
Execute and display only one case at a time.
Are similar to case statements or if...then...else statements
in text-based programming languages.
ni.com/training
Case Structures
Case Selector Label
Contains the name of the current
case.
Has decrement and increment
arrows.
Case Selector Label
Selector Terminal
Lets you wire an input value, or
selector, to determine which
case executes.
Selector Terminal
ni.com/training
Case Structures
Selector terminal data types:
Boolean
True case and False Case
Error Cluster
Error Case and No Error Case
Integer, string, or enum
Structure can have any
number of cases.
Include a Default diagram to
avoid listing every possible
input value.
ni.com/training
Enum Case Structure
Gives users a list of items from which to select
The case selector displays a case for each item in the
enumerated type control
ni.com/training
Shortcut Menu
Use the shortcut menu of a
Case structure to:
Customize the structure and
diagrams.
Remove or replace the
structure.
Add, duplicate, remove, or
rearrange cases.
Specify the Default case.
Switch cases.
ni.com/training
Error Case Structure
Use Case structures inside VIs to execute the code if there is
no error and skip the code if there is an error.
ni.com/training
Input and Output Tunnels
You can create multiple input and output tunnels.
Inputs tunnels are available to all cases if needed.
You must define each output tunnel for each case.
ni.com/training
SummaryQuiz Answer
1. If an input to a function is marked with a red dot (known
as a coercion dot), what does the dot indicate?
a) Data was transferred into a structure.
b) A For Loop was configured with a conditional terminal.
c) A For Loop iteration terminal is unwired.
d) The value passed into a node was converted to a
different representation.
ni.com/training
SummaryQuiz Answer
2. Which structure must run at least one time?
a) While Loop
b) For Loop
ni.com/training
SummaryQuiz
3. Which is only available on the block diagram?
a)
b)
c)
d)
Control
Constant
Indicator
Connector Pane
ni.com/training
SummaryQuiz Answer
3. Which is only available on the block diagram?
a)
b)
c)
d)
Control
Constant
Indicator
Connector Pane
ni.com/training
SummaryQuiz
4. Which mechanical action causes a Boolean control in the
FALSE state to change to TRUE when you click it and stay
TRUE until LabVIEW has read the value?
a)
b)
c)
d)
Switch Until Released
Switch When Released
Latch Until Released
Latch When Released
ni.com/training
SummaryQuiz Answer
4. Which mechanical action causes a Boolean control in the
FALSE state to change to TRUE when you click it and stay
TRUE until LabVIEW has read the value?
a)
b)
c)
d)
Switch Until Released
Switch When Released
Latch Until Released
Latch When Released
ni.com/training
Lesson 4
Error Handling
TOPICS
A.
B.
C.
D.
E.
Importance of Error Handling
Detect and Report Errors
Errors and Warnings
Ranges of Error Codes
Error Handlers
ni.com/training
A. Importance of Error Handling
Error Handling Anticipation, detection,
and resolution of warnings and errors
Essential for:
Debugging: Helps to catch programming errors
Stress testing: Helps to test application boundary cases
Robustness: Helps detect errors introduced by system and
environment differences
ni.com/training
B. Detect and Report Errors
Propagate errors along wires
Merge errors from different wire paths
ni.com/training
Merge Error VI
Merge Error VI returns the first error found. If no error is
found, it returns the first warning.
This VI does not concatenate errors.
ni.com/training
C. Errors and Warnings
Error
Status = True
Warning
Status = False and Code is nonzero
ni.com/training
Errors and Warnings
Report errors and warnings with the Simple Error Handler VI
Modify Type of Dialog to detect warnings
Call the Simple Error Handler VI from the top-level VI
Avoid error dialogs in subVIs
ni.com/training
Errors and Warnings
Use shift-registers to detect errors and warnings in all loop
iterations
Use error status as a condition to stop a loop
While Loops
Conditional For Loops
ni.com/training
D. Ranges of Error Codes
Refer to the LabVIEW Help for complete list of error code
ranges:
Fundamentals>>Running and Debugging VIs>>HowTo>>Error Codes and Messages>>Ranges of LabVIEW
Error Codes
Codes are subdivided into ranges according to product and
VI grouping
Most codes are unique, but some error codes are used by
more than one product or VI grouping
ni.com/training
E. Error Handlers
Error Handler A VI or code that changes normal
flow of program execution when an error occurs.
Examples:
Simple Error Handler VI Optionally display a dialog box
with error information when an error occurs.
State machine error handler Transitions the state machine
to an error or shutdown state when an error occurs.
I/O error handler If an I/O operation times out, retry for a
certain period of time before reporting an error.
ni.com/training
SummaryQuiz Answer
1. Merge Errors VI concatenates error information from
multiple sources.
a) True
b) False
ni.com/training
10
SummaryQuiz Answer
2. All errors have negative error codes and all warnings have
positive error codes.
a) True
b) False
ni.com/training
11
Lesson 5
Creating and Leveraging Data Structures
TOPICS
A.
B.
C.
D.
E.
F.
Arrays
Common Array Functions
Polymorphism
Auto-Indexing
Clusters
Type Definitions
ni.com/training
A. Arrays
1D and 2D Arrays
Creating an Array Control and Constant
Initializing Arrays
ni.com/training
Arrays
An array:
Is a collection of data elements
that are of same type.
Has one or more dimensions.
Contains up to (231)1 elements
per dimension, memory
permitting.
Accesses elements by its index.
Note: The first element is index 0.
ni.com/training
Arrays 1D and 2D Examples
ID array
One row of 10-elements
0
1.2 3.2 8.2 8.0 4.8 5.1 6.0 1.0 2.5 1.7
2D array
Five-row by seven-column table of 35
elements
0
Index
numbers
0
1
2
3
4
ni.com/training
Why Use Arrays?
Use arrays when you work with a collection of similar data and
when you perform repetitive computations.
ni.com/training
Viewing Arrays on the Front Panel
The elements at
index 0 are not
shown because
element 1 is selected
in the index display.
First element
at index 1
Second
element at
index 2
The element selected in the index display always refers to the
element shown in the upper-left corner of the element display.
ni.com/training
Creating an Array Control
For a new array:
1. Select an Array control from the
Controls palette on the front panel.
2. Place a data object, such as a
numeric control, into the array
shell.
3. Add a second dimension, if necessary, by
resizing the index.
From a block diagram terminal or wire:
1. Right-click the object and select CreateControl
or CreateIndicator.
ni.com/training
Creating an Array Constant
For a new array:
1.
2.
3.
Select Array Constant from the Functions
palette on the block diagram.
Place a constant, such as a numeric,
into the array shell.
Add a second dimension, if necessary, by
resizing the index.
From a block diagram terminal or wire:
1. Right-click and select CreateConstant.
ni.com/training
Initializing Arrays
You can initialize an array or leave it uninitialized.
For initialized arrays, you define the number of elements in
each dimension and the contents of each element.
Uninitialized arrays have dimension but no elements.
ni.com/training
2D Arrays
2D arrays:
Store elements in a grid.
Require a column index and a row index to locate an element,
both of which are zero-based.
Create a multidimensional array on the front panel by rightclicking the index display and selecting Add Dimension
from the shortcut menu.
Resize the index display until you have as many dimensions
as you want.
ni.com/training
B. Common Array Functions
Array Size
Initialize Array
Array Subset
Build Array
Index Array
ni.com/training
Common Array Functions
Array Size
Initialize Array
Array Subset
Build Array
Index Array
ni.com/training
Array Size
ni.com/training
Initialize Array
ni.com/training
Array Subset
ni.com/training
Build Array
ni.com/training
Index Array
ni.com/training
Polymorphism
Polymorphism - The ability of VIs and functions to
automatically adapt to accept input data of different
data types
Functions are polymorphic to varying degrees:
None, some, or all of their inputs can be polymorphic.
Some accept numeric or Boolean values.
Some accept numeric or strings.
Some accept scalars, numeric arrays, or clusters of
numerics.
ni.com/training
Arithmetic Functions Are Polymorphic
Combination
Result
ni.com/training
D. Auto-Indexing
Use in For Loops and While Loops
Waveform Graphs
Auto-Indexing with a Conditional Terminal
Creating 2D Arrays
Auto-Indexing Input to a Loop
ni.com/training
Auto-Indexing
Auto-Indexing Enabled
Wire becomes thicker
Allows For Loops and While
Loops to accumulate arrays at
their boundaries.
1D Array
Is the default behavior for
0 1 2 3 4 5
For Loops.
Is disabled by default for
Auto-Indexing Disabled
While Loops.
Wire remains the same size
Is enabled/disabled by rightclicking on a tunnel.
Produces arrays that are always
Only one value (last
equal in size to the number of
iteration) is passed out of
iterations of the loop.
the loop
ni.com/training
Waveform Graph
Is a graphical display of data.
Displays one or more plots of
evenly sampled measurements.
Is used to plot pre-generated
arrays of data.
Can display plots with any
number of data points.
ni.com/training
Charts vs. Graphs Single-Plot
ni.com/training
Auto-Indexing with a Conditional Tunnel
Right-click on a tunnel and select
Tunnel ModeConditional.
ni.com/training
Creating 2D Arrays
1D Array
0 1
3 4
2D Array
Inner loop creates column elements.
Outer loop stacks column elements into rows.
ni.com/training
Auto-Indexing Input
If the iteration count terminal is wired and arrays of different
sizes are wired to auto-indexed tunnels, the actual number of
iterations becomes the smallest of the choices.
ni.com/training
Auto-Indexing Input
Use an auto-indexing input array to perform calculations
on each element in an array.
Wire an array to an auto-indexing tunnel on a For Loop.
You do not need to wire the count (N) terminal.
The For Loop executes
the number of times
equal to the
number of
elements in the array.
The Run button is not broken.
ni.com/training
E. Clusters
Reasons To Use Clusters
Cluster vs. Arrays
Creating a Cluster Control and Constant
Ordering Items and Resizing Clusters
Disassembling and Modifying Clusters
Plotting Data
ni.com/training
Clusters
Clusters group data elements of mixed types.
Clusters are similar to a record or a struct in text-based
programming languages.
ni.com/training
Why Use Clusters?
Keep data organized.
Logically group related data values together.
Improve diagram readability by eliminating wire clutter.
Reduce the number of connector pane terminals.
ni.com/training
Clusters vs. Arrays
Clusters are a fixed size.
Clusters can contain mixed
data types.
Clusters can be a control, an
indicator, or a constant.
Arrays vary in size.
Arrays contain only one data
type.
Arrays can be a control, an
indicator, or a constant.
All elements have to be controls,
indicators, or constants.
ni.com/training
Create a Cluster Control
For a new cluster:
1. On the front panel, select Cluster
from the Controls palette.
2. Place a data object into the
cluster shell.
3. Place additional data objects,
if necessary, into the shell.
From block diagram terminal or wire:
1. Right-click and select CreateControl or CreateIndicator.
ni.com/training
Create a Cluster Constant
For a new cluster:
1. On the block diagram, select Cluster
Constant from the Functions palette.
2. Place a constant into the cluster shell.
3. Place additional data objects, if
necessary, into the cluster shell.
From block diagram terminal or wire:
1. Right-click and select CreateConstant.
ni.com/training
Cluster Order
Cluster elements have a logical
order unrelated to their position
in the shell.
You can view and modify the
cluster order by right-clicking
the cluster border and
selecting Reorder Controls
In Cluster.
ni.com/training
Autosizing Clusters
Autosizing helps you
arrange elements in
clusters.
NI recommends the
following:
Arrange cluster elements
vertically.
Arrange elements compactly.
Arranges elements in their
preferred order.
ni.com/training
Disassembling a Cluster
Use the Unbundle By Name function whenever possible.
Use Unbundle function when some or all cluster elements
are unnamed.
ni.com/training
Modifying a Cluster
Use Bundle By Name whenever possible to access
elements in a cluster.
Use Bundle when some or all cluster elements are
unnamed.
You must
wire the
input
cluster
terminal.
ni.com/training
Creating a Cluster on the Diagram
Use the Bundle function to programmatically create a
cluster on a block diagram.
If the elements that are bundled have labels, you can
access them using the Unbundle By Name function.
Otherwise use the Unbundle function.
ni.com/training
Charts vs. Graphs Multi-plot and XY Graph
ni.com/training
Plotting Data
Use the Context Help window to determine how to wire
multi-plot data to Waveform Graphs, Charts and XY Graphs.
ni.com/training
Error Clusters
LabVIEW uses error clusters to pass error information.
An error cluster contains the following elements:
statusBoolean value that reports True if an error occurs.
code32-bit signed integer that identifies the error.
sourceString that identifies where the error occurred.
ni.com/training
F. Type Definitions
Type Definitions and Custom Data Types
Creating and Identifying Type Definitions
Controls
Strict Type Definitions
ni.com/training
Type Definitions (Type Def)
A type definition is a master copy of a custom data type
(control, indicator, or constant).
A custom data type is saved in a .ctl file.
Instances of a type def are linked to the .ctl file.
Instances can be controls, indicators, or constants.
When the type def changes, instances automatically update.
Changes include data type changes, elements added,
elements removed, and adding items to an enum.
ni.com/training
You can use type definitions to define
custom arrays and clusters.
A type definition is a master copy of a custom
data type (custom control, indicator, or
constant) that multiple VIs can use.
When you use type definitions, you can update
of all instances or copies of the custom data
type in a single edit.
ni.com/training
Creating Type Definitions (Type Def)
1. Right-click a control, indicator or constant and select
Make Typedef.
1. Right-click the object again and select Open Type Def.
2. Edit control, if needed.
3. Save control as a .ctl file.
ni.com/training
Identifying Type Definitions (Type Def)
Look for a glyph marking the upper left corner of terminals
and constants.
Hover cursor over glyph to view tip strip.
View Context Help while hovering cursor over terminal or
constant.
ni.com/training
Other Control Options
You can save a custom control as:
Control
Type Definition
Strict Type Definition
ni.com/training
LabVIEW has three kinds of custom controls (.ctl files):
A regular custom control
Used to create controls that behave like existing controls but
look different.
A type def or type definition control
Used for changing all instances of a linked control in a single
edit.
A strict type def control
Used for changing instances in a single edit.
Used to ensure all instances have same appearance.
ni.com/training
Control
Instances are not linked to a.ctl file.
Each instance is an independent copy of the control.
Used to create controls that behave like existing controls but
look different.
ni.com/training
Strict Type Definition
Strict type definitions are similar to a type definition in that:
All instances link to .ctl file.
When attributes or data types change, all instances update.
Examples: Changing a knob to a dial, a round LED to a square
LED, or a double to an integer.
Strict type definitions enforce every aspect of a instance
except label, description, and default value.
Use strict type definitions to ensure all front panel instances
have the same appearance.
ni.com/training
SummaryQuiz Answer
1. You can create an array of arrays.
a) True
b) False
You cannot drag an array data type into an array
shell. However, you can create two-dimensional
arrays.
ni.com/training
SummaryQuiz Answer
2. What is the value of the Iterations indicator
after running this VI?
4
ni.com/training
SummaryQuiz Answer
3. Which of the following custom control settings defines the
data type of all instances of a control but allows for
different colors and font styles?
a) Control
b) Type definition
c) Strict type definition
d) Cluster control
ni.com/training
SummaryQuiz Answer
4.
You have input data representing a circle: X Position, Y Position,
and Radius. In the future, you might need to modify your data to
include the color of the circle.
What data structure should you use to represent the circle in your
application?
a) Three separate controls for the two positions and the radius
b) A cluster containing all of the data
(X,Y)
c) A custom control containing a cluster
d) A type definition containing a cluster
R
e) An array with three elements
ni.com/training
Lesson 5
Relating Data
TOPICS
A. Arrays
B. Clusters
C. Type Definitions
ni.com/training
A. Arrays
An array consists of elements and dimensions
Elements: data that make up the array
Dimension: the length, height, or depth of an array
An array can have one or more dimensions
and as many as (231)1 elements per
dimension, memory permitting
Consider using arrays when you work with
a collection of similar data and when you
perform repetitive computations
ni.com/training
A. Arrays
The first element shown in the array (3.00) is at index 1 and
the second element (1.00) is at index 2
The element at index 0 is not shown in this image, because
element 1 is selected in the index display
The element selected in the index display always refers to
the element shown in the upper left corner of the element
display
ni.com/training
A. Arrays Creating
1. Place an array shell on the front panel
2. Drag a data object or element into the array shell
ni.com/training
A. Arrays 2D Array
Stores elements in a grid
Requires a column index and a row index to locate an
element, both of which are zero-based
To create a multidimensional array on the front panel, rightclick the index display and select Add Dimension from the
shortcut menu
You also can resize the index display until you have as
many dimensions as you want
ni.com/training
A. Arrays Initializing
You can initialize an array, or leave it uninitialized
For initialized arrays, you define the number of elements in
each dimension, and the contents of each element
Uninitialized arrays have dimension but no elements
ni.com/training
A. Arrays Creating Constants
To create an array constant:
Select an array constant on the
Functions palette
Place the array shell on the block diagram
Place a constant in the array shell
You can use an array constant to store
constant data or as a basis for comparison
with another array
Array constants also are useful for passing data into a subVI
ni.com/training
A. Arrays Auto-indexing
If you wire an array to or from a For Loop or While Loop, you
can link each iteration of the loop to an element in that array
by enabling auto-indexing on tunnel
The tunnel changes from a solid square to the image shown
above to indicate auto-indexing
ni.com/training
A. Arrays Auto-indexing Input
For Loop executes
a number of times
equal to the number
of elements in the
array
ni.com/training
A. Arrays Auto-indexing Input
If the iteration count terminal is wired and arrays of different
sizes are wired to auto-indexed tunnels, the actual number of
iterations becomes the smallest of the choices.
ni.com/training
A. Arrays Auto-indexing Output
When you auto-index an array output tunnel, the output
array receives a new element from every iteration of the
loop
Auto-indexed output arrays are always equal in size to the
number of iterations
ni.com/training
A. Arrays Creating 2D Arrays
You can use two For Loops, one inside the other, to create a
2D array
ni.com/training
Intensity Graph
GOAL
POLYMORPHIC - functions
GOAL
MODIFY this VI
Extract THIRD ROW
Extract SECOND COLUMN
Use:
GOAL
Exercise 5-1
Concept: Manipulating Arrays
How would you programmatically create a 3-dimensional
array?
DISCUSSION
B. Clusters
Clusters group data elements of mixed types
Similar to a record or a struct in text-based programming
languages
ni.com/training
B. Clusters Array vs Cluster
Clusters differ from arrays in that they are a fixed size
Clusters can contain mixed data types; arrays contain only
one data type
Like an array, a cluster is either a control or an indicator and
cannot contain a mixture of controls and indicators
ni.com/training
B. Clusters Creating
To create a cluster control or indicator on the front panel:
Place a cluster shell on the front panel
Drag a data object or element,
which can be a numeric, Boolean,
string, path, refnum, array, or
cluster control or indicator into
the cluster shell
ni.com/training
B. Clusters Constants
To create a cluster constant:
1. Select a cluster constant on the Functions palette
2. Place the cluster shell on the block diagram
3. Place a constant in the cluster shell
If you have a cluster control or indicator, right-click the
cluster on the block diagram and select CreateConstant
from the shortcut menu
ni.com/training
B. Clusters Order
Cluster elements have a logical order unrelated to their
position in the shell
You can view and modify the
cluster order by right-clicking
the cluster border and
selecting Reorder Controls
In Cluster from
the shortcut menu
ni.com/training
B. Clusters Assembling a Cluster
Use the Bundle function to assemble a new cluster
ni.com/training
B. Clusters Modifying a Cluster
Use the Bundle By Name or the Bundle function to modify an
existing cluster
ni.com/training
B. Clusters Disassembling a Cluster
Use the Unbundle By Name or Unbundle function to use
individual items in a cluster
ni.com/training
B. Clusters Error Clusters
LabVIEW uses error clusters to pass error information
An error cluster contains the following elements:
statusBoolean value that reports True if an error occurs
code32-bit signed integer that identifies the error
sourceString that identifies where the error occurred
ni.com/training
C. Type Definitions Custom Controls
Use custom controls and indicators to extend the available set
of front panel objects
1. Create and save a
custom control
or indicator
2. Use the custom control
or indicator on other
front panels
ni.com/training
C. Type Definitions Control Editor
Use the Control Editor window to customize controls and
indicators
To display the Control Editor
window, right-click a control
or indicator and select
AdvancedCustomize
ni.com/training
C. Type Definitions
You can save a custom control as:
Control
Type Definition
Strict Type Definition
ni.com/training
C. Type Definitions Control Type
Control
No connection between the custom control or indicator you
saved and the instance of the custom control or indicator in
the VI
Update the file, but the
instances are not updated
ni.com/training
C. Type Definitions Type Definition
Type Definition (type def):
Edit the saved file, and have all instances update with the
changes made
Forces the data type of each instance to be identical
Example:
Add an item to the type definition of an
enum, the instances of the enum
update with the new item
If you resize the enum front panel
control type definition, the instances
of the enum do not resize
ni.com/training
C. Type Definitions Strict Type Definition
Strict Type Definition:
Similar to a type definition, except a strict type definition
forces everything about an instance to be identical to the
strict type definition, except:
label
description
default value
ni.com/training
SummaryQuiz
1. You can create an array of arrays.
a) True
b) False
ni.com/training
SummaryQuiz Answer
1. You can create an array of arrays.
a) True
b) False.
You cannot drag an array data type into an array
shell. However, you can create two-dimensional
arrays.
ni.com/training
SummaryQuiz
2. What is the value of the Iterations indicator
after running this VI?
ni.com/training
SummaryQuiz Answer
2. What is the value of the Iterations indicator
after running this VI? Value of Iterations = 4
ni.com/training
SummaryQuiz
3. You customize a control, select Control from the Control
Type pull-down menu, and save the control as a .ctl
file. You then use an instance of the custom control on
your front panel. If you open the .ctl file and modify the
control, does the control on the front panel change?
a) Yes
b) No
ni.com/training
SummaryQuiz Answer
3. You customize a control, select Control from the Control
Type pull-down menu, and save the control as a .ctl
file. You then use an instance of the custom control on
your front panel. If you open the .ctl file and modify the
control, does the control on the front panel change?
a) Yes
b) No
ni.com/training
SummaryQuiz
4.
You are inputting data that represents a circle. The circle data
includes three double precision numerics: x position, y position and
radius. In the future, you might need to expand all instances of the
circle data to include the color of the circle, represented as an
integer. How should you represent the circle on your front panel?
a) Three separate controls for the two positions and the radius
b) A cluster containing all of the data
c) A custom control containing a cluster
d) A type definition containing a cluster
e) An array with three elements
ni.com/training
SummaryQuiz Answer
4.
You are inputting data that represents a circle. The circle data
includes three double precision numerics: x position, y position and
radius. In the future, you might need to expand all instances of the
circle data to include the color of the circle, represented as an
integer. How should you represent the circle on your front panel?
a) Three separate controls for the two positions and the radius
b) A cluster containing all of the data
c) A custom control containing a cluster
d) A type definition containing a cluster
e) An array with three elements
ni.com/training
Lesson 8
Common Design Techniques and Patterns
TOPICS
A. Using Sequential Programming
B. State Programming
C. State Machines
ni.com/training
A. Using Sequential Programming
Many of the VIs you write accomplish sequential tasks
There is nothing in this block diagram to force the
execution order of these tasks - any one of these tasks
could happen first
ni.com/training
A. Using Sequential Programming
Use error clusters to force order of execution
ni.com/training
A. Using Sequential Programming
To force execution order, use a Sequence structure
A structure with frames, where each frame executes in order
The second frame cannot begin execution until everything in the first
frame completes execution
ni.com/training
A. Using Sequential Programming
Avoid overusing Sequence structures
You cannot stop the execution part way through a sequence
ni.com/training
A. Using Sequential Programming
The best way to write this VI is to enclose the dialog boxes in
Case structures, wiring the error cluster to the case selectors
ni.com/training
B. Using State Programming
Although Sequence structures or sequentially wired subVIs
accomplish the purpose, it is not always the best choice:
What if you need to change the order of the sequence?
What if you need to repeat one item in the sequence more
often than the other items?
What if some items in the sequence execute only when
certain conditions are met?
What if you need to stop the program immediately, rather
than waiting until the end of the sequence?
ni.com/training
B. Using State Programming
State Transition Diagram
Type of flowchart that indicates the states of a program and
transitions between states
State - Part of a program that satisfies a condition,
performs an action or waits for an event
Transition - Condition, action, or event that causes the
program to move to the next state
ni.com/training
B. Using State Programming
State Transition Diagram
Furnace
Example:
ni.com/training
C. State Machines
The state machine design pattern implements a state
diagram or flow chart
When to use state machines?
Commonly used to create user interfaces, where different user
actions send the user interface into different states
Commonly used for process tests, where a state represents
each segment of the process
ni.com/training
C. State Machines Infrastructure
A state machine consists of a set of states and a transition
function that maps to the next state
Each state can lead to one or multiple states or end the
process flow
While Loop
Type-defined
Enum
Case Structure
Shift Register
ni.com/training
C. State Machines Default Transition
ni.com/training
C. State Machines
Transition Between Two States
ni.com/training
C. State Machines
Case Structure Transition
ni.com/training
C. State Machines
Transition Array Transition
ni.com/training
SummaryQuiz Answer
1. When using a Sequence structure, you can stop the execution
part way through a sequence.
a) True
b) False
You cannot stop the execution part way through a
sequence.
ni.com/training
SummaryQuiz Answers
2. Which of the following are benefits of using a state machine
instead of a sequential structure?
a) You can change the order of the sequence
b) You can repeat individual items in the sequence
c) You can set conditions to determine when an item in the
sequence should execute
d) You can stop the program at any point in the sequence
ni.com/training
Appendix A
Measurements Fundamentals
TOPICS
A. Computer-based Measurement Systems
B. Measurement Concepts
C. Increasing Measurement Quality
ni.com/training
Computer-Based Measurement System
ni.com/training
A. Computer-Based Measurement Systems
Temperature Example:
A thermocouple converts temperature to voltage
Applying gain raises voltage from micro level and applying
filter removes noise
Data acquisition board circuitry measures the signal
The driver communicates the measurement from the DAQ
board to the application program
ni.com/training
B. Measurement Concepts Transducers
A measurement starts with using a transducer to convert a
physical phenomenon into an electrical signal
Temperature: thermocouples, RTDs, thermistors, and IC
sensors
Light: vacuum tube photosensors, and photoconductive cells
Sound: microphones
Force and Pressure: strain gages, piezoelectric transducers,
and load cells
Position: potentiometers, LVDTs, and optical encoders
ni.com/training
B. Measurement Concepts
Grounded Signal Source
Voltage signals are referenced to a
system ground, such as the earth or
a building ground
Because such sources use the
system ground, they share a
common ground with the measurement device
Common examples are devices that plug into a building
ground through wall outlets, such as signal
generators and power supplies
ni.com/training
B. Measurement Concepts Ground Loop
The grounds of two independently grounded signal sources
generally are not at the same potential
The difference in ground potential between two instruments
connected to the same building ground system is typically
10200 mV
The difference can be higher if power distribution circuits are
not properly connected
ni.com/training
B. Measurement Concepts
Floating Signal Source
In a floating signal source, the voltage
signal is not referenced to any
common ground, such as the earth
or a building ground
Some common examples of floating
signal sources are batteries, thermocouples, transformers,
and isolation amplifiers
Neither terminal of the source is connected to
the electrical outlet ground - each terminal is
independent of the system ground
ni.com/training
B. Measurement Concepts
Signal Conditioning
Many stand-alone instruments and DAQ devices have builtin signal conditioning
Signal conditioning also can be applied externally, by
designing a circuit to condition the signal or by using devices
specifically made for signal conditioning
To measure signals from transducers, you must convert
them into a form a measurement device can accept
Common types of signal conditioning include amplification,
linearization, transducer excitation, and isolation
ni.com/training
ni.com/training
B. Measurement Concepts Amplification
Most common type of signal conditioning
For the highest possible accuracy, amplify the signal so the
maximum voltage range of the signal equals the maximum
input range of the analog-to-digital converter (ADC)
Amplifying electrical signals improves accuracy in the
resulting digitized signal and reduces the effects of noise
Signals should be amplified close to the signal source
If you amplify near the measurement device instead, any
noise that attached to the signal is also amplified
ni.com/training
B. Measurement Concepts Amplification
Amplifying near the signal source results in the largest
signal-to-noise ratio (SNR)
If you amplify the signal at the DAQ device while digitizing
and measuring the signal, noise might have entered the lead
wire, which decreases SNR
ni.com/training
B. Measurement Concepts Linearization
Many transducers, such as thermocouples, have a nonlinear
response to changes in the physical phenomena you
measure
LabVIEW can linearize the voltage levels from transducers
so you can scale the voltages to the measured phenomena
LabVIEW provides scaling functions to convert voltages
from strain gages, RTDs, thermocouples, and thermistors
ni.com/training
B. Measurement Concepts Excitation
Signal conditioning systems can generate excitation, which
some transducers require for operation
Strain gages and RTDs require external voltage and
currents, respectively, to excite their circuitry into measuring
physical phenomena
This type of excitation is similar to a radio that needs power
to receive and decode audio signals
ni.com/training
B. Measurement Concepts Isolation
Isolates the transducer signals from the computer for safety
purposes
When the signal you monitor contains large voltage spikes
that could damage the computer or harm the operator, do
not connect the signal directly to a DAQ device without
some type of isolation
ni.com/training
B. Measurement Concepts Isolation
You also can use isolation to ensure that differences in ground
potentials do not affect measurements from the DAQ device
If the potential difference between the signal ground and
the DAQ device ground is large, damage can occur to the
measuring system
Isolating the signal eliminates the ground loop and ensures
that the signals are measured accurately
ni.com/training
B. Measurement Concepts
Measurement Systems
Differential
AIGND (analog input
ground) pin is the
measurement system
ground
Requires two channel
pins to measure a signal
ni.com/training
B. Measurement Concepts
Measurement Systems
Referenced SingleEnded (RSE)
AIGND is the
measurement system
ground
Need only one channel
to measure a signal
ni.com/training
B. Measurement Concepts
Measurement Systems
Non-referenced SingleEnded (NRSE)
AISENSE pin is the
measurement system
ground
Need one channel and
AISENSE to a measure
a signal
ni.com/training
ni.com/training
C. Increasing Measurement Quality
When you design a measurement system, you may find that
the measurement quality does not meet your expectations
Achieving smallest detectable changeyou might want to
record the smallest possible change in a voltage level
Increasing Shape Recoveryperhaps you cannot tell if a
signal is a triangle wave or a sawtooth wave and would like
to see a better representation of the shape of a signal
Decreasing Noiseyou may need to decrease the noise
level to read your signal
ni.com/training
C. Achieving Smallest Detectable Change
The following reasons affect ability to achieve the smallest
detectable change in voltage:
The resolution and range of the ADC
The gain applied by the instrumentation amplifier
The combination of the resolution, range, and gain to
calculate a property called the code width value
ni.com/training
C. Achieving Smallest Detectable Change
Resolution
ni.com/training
C. Achieving Smallest Detectable Change
Range
ni.com/training
C. Achieving Smallest Detectable Change
Amplification
ni.com/training
C. Achieving Smallest Detectable Change
Code Width
The range, resolution, and amplification available on a DAQ
device determine the smallest detectable change in the
input voltage
This change in voltage represents one least significant bit
(LSB) of the digital value and is also called the code width
Code width is the smallest change in a signal that a system
can detect
ni.com/training
C. Achieving Smallest Detectable Change
Code width is calculated using the following formula:
1
CD R
2
C = code width
D = device input range (ADC range/amplification)
R = bits of resolution
The smaller the code width, the more accurately a device can
represent the signal
A 12-bit DAQ device with a 0 to 10 V ADC range and an
amplification of one detects a 2.4 mV change, while the same
device with a 10 to 10 V ADC range would detect a change of
4.8 mV
ni.com/training
C. Achieving Smallest Detectable Change
1
CD R
2
C = code width
D = device input range (ADC range/amplification)
R = bits of resolution
The formula confirms what you have already learned in the
discussion on resolution, range, and gain:
Larger resolution = smaller code width = more accurate
representation of the signal
Larger amplification = smaller code width = more accurate
representation of the signal
Larger ADC range = larger code width = less accurate
representation of the signal
ni.com/training
C. Increasing Shape Recovery
The most effective way of increasing the shape recovery of
a signal is to reduce your code width and increase your
sampling frequency
The faster the sample, the better the shape recovery of the
signal. However, available hardware often limits the
sampling rate
To measure the frequency of your signal effectively, you
must sample the signal at least at twice the signal frequency
ni.com/training
C. Increasing Shape Recovery
Nyquist Theorem:
f sampling 2 f signal
The Nyquist Theorem states that you must sample a signal at
a rate greater than twice the highest frequency component of
interest in the signal to capture the highest frequency
component of interest
ni.com/training
C. Increasing Shape Recovery
Original Signal
Sampled Signal
ni.com/training
C. Decreasing Noise
To reduce noise take the following precautions:
Use shielded cables or a twisted pair of cables
Minimize wire length to minimize noise the lead wires pick up
Keep signal wires away from AC power cables and monitors to reduce
50 or 60 Hz noise
Increase the signal-to-noise (SNR) ratio by amplifying the signal close
to the signal source
Acquire data at a higher frequency than necessary, then average the
data to reduce the impact of the noise, as noise tends to average to
zero
ni.com/training
SummaryQuiz
1. Calculate the code-width for a signal acquired using a 16 bit data
acquisition board with a device input range of 5 volts.
1
CD R
2
ni.com/training
SummaryQuiz Answer
1. Calculate the code-width for a signal acquired using a 16 bit data
acquisition board with a device input range of 5 volts.
76.29 microvolts
C 5.
7 6.2 9 V
16
2
ni.com/training
SummaryQuiz
2. You are acquiring a triangle wave with a frequency of 1100 Hertz.
Which sampling frequency should you use for best shape
recovery of the signal?
a)
b)
c)
d)
1 kHz
10 kHz
100 kHz
1000 kHz
ni.com/training
SummaryQuiz Answer
2. You are acquiring a triangle wave with a frequency of 1100 Hertz.
Which sampling frequency should you use for best shape
recovery of the signal?
a)
b)
c)
d)
1 kHz
10 kHz
100 kHz
1000 kHz
ni.com/training
SummaryQuiz
3. You are acquiring a triangle wave with a frequency of 1100 Hertz.
You can sample the signal at the following rates. Which is the
minimum sampling frequency you should use to reliably acquire
the frequency of the signal?
a)
b)
c)
d)
1 kHz
10 kHz
100 kHz
1000 kHz
ni.com/training
SummaryQuiz Answer
3. You are acquiring a triangle wave with a frequency of 1100 Hertz.
You can sample the signal at the following rates. Which is the
minimum sampling frequency you should use to reliably acquire
the frequency of the signal?
a)
b)
c)
d)
1 kHz
10 kHz
100 kHz
1000 kHz
ni.com/training