Você está na página 1de 115

uti ts

uti ts
TM
LabVIEW Core 1

rib en

rib en
Course Manual

on

on
ist um

ist um
r D str

r D str
Course Software Version 2012
August 2012 Edition
Part Number 325290D-01
t fo l In

t fo l In
LabVIEW Core 1 Course Manual
Copyright
19932012 National Instruments.ts. All
ll rights reserved.
ublication
ation may not be reproduced
Under the copyright laws, this publication ced
ed or transmitted in
i aany form, electronic or mechanical, including
photocopying, recording, storing
ing in information retrieval system
n an information system, translating, in whole or in part, without the prior written
ystem,, or translating
No na

No na
ments Corporation.
consent of National Instruments orporation.
National Instruments respects
pects the intellectual property
p of others, and we ask our users to do the same. NI software is protected by
ellectual
tual property laws.
copyright and other intellectual la
law Where NI software
soft
oft mayay be uused to reproduce software or other materials belonging
se NI software
to others, you may use oftware only to t reproduce
ce materials
ateria ththat you may reproduce in accordance with the terms of any
applicable license or other
her legal restric
restrict
restriction.
tio

tio
ense Agreements a
End-User License Party Legal Notices
and Third-Party
You can find
d end-user
user license agreements
agr (EULAs)
EULAs) and third-party
third-p
third-pa legal notices in the following locations:
Noticess aree located in the <National
<
<N Instruments>
nstruments>
Instruments>\_Legal Information and <National Instruments>
directories.
tories.
EULAs
ULAs are located in theth <National nal Instruments>\Shared\MDF\Legal\License
onal I
In umen
men directory.
Review <National
<Nationa Instruments>\_Legal
ments>\_Leg
nts>\_ Information.txt for more information on including legal information
Na

in installers built with


Trademarks
CVI, LabVIEW, National
National
N
wi NI products.

Instruments Corporation.
ional Instru
In
trademarks.
arks.
ucts.

Instruments,
struments, NI, ni.com,
nstruments,

The mark LabWindows is used under a lli


ni.co the National Instruments corporate logo, and the Eagle logo are trademarks of
ni.co
poration. Refer to the Trademark Information at ni.com/trademarks for other National Instruments

license from Microsoft Corporation. Windows is a registered trademark of Microsoft


Na
Support
dwide T
Worldwide
ni.com
Te Produc Information
Produ
Technical Support and Product

Corporation in the United Statess and other


ot countries. Other product and company names mentioned herein are trademarks or trade
o Worldwide Offices
names of their respective companies. Visit ni.com/niglobal to access the branch office Web sites, which provide up-to-date contact information, support phone
Members of the National Instruments Alliance Partner Program are business entities independent from National Instruments and numbers, email addresses, and current events.
have no agency, partnership, or joint-venture relationship with National Instruments. National Instruments Corporate Headquarters
Patents 11500 North Mopac Expressway Austin, Texas 78759-3504 USA Tel: 512 683 0100
For patents covering National Instruments products/technology, refer to the appropriate location: HelpPatents in your software, For further support information, refer to the Additional Information and Resources appendix. To comment on National Instruments
the patents.txt file on your media, or the National Instruments Patent Notice at ni.com/patents. documentation, refer to the National Instruments Web site at ni.com/info and enter the Info Code feedback.
Contents

Contents
Lesson 4
Developing Modular Applications
Student Guide A. Understanding Modularity ....................................................................................4-2
.................
..........
B. Building the Icon and Connector Pane .................................................................4-3
.......................
..............

uti ts

uti ts
A. NI Certification .....................................................................................................v
.........................
.....................
B. Course Description ...............................................................................................vi
.........................
.................... C. Using SubVIs ........................................................................................................4-7
.........................
.....................
C. .........................
..................
What You Need to Get Started .............................................................................vii
D. ........................
................. ....
Installing the Course Software..............................................................................viii Lesson 5

rib en

rib en
E. Course Goals.........................................................................................................viii
.........................
................. ..........vii
....vii Creating and Leveraging Data Structures
F. .........................
................. ..............ix
.......ix
Course Conventions ..............................................................................................ix A. Arrays....................................................................................................................5-2
.........................
................. ..............5-2
........5-2

on

on
B. ........................
................... .................5-5
Common Array Functions ....................................................................................5-5 ...........5-5
Lesson 1 C. .........................
................ ....................5-6
.............5-6
Polymorphism .......................................................................................................5-6

ist um

ist um
Navigating LabVIEW D. .........................
................... ........................5
.......................5
Auto-Indexing .......................................................................................................5-8
A. What is LabVIEW ................................................................................................1-2
........................
................... .........................
.................... E. ........................
................... .........................
......................
Clusters .................................................................................................................5-13
B. .........................
................... .........................
...................
Project Explorer ....................................................................................................1-5 F. ........................
................ .........................
...................
Type Definitions ...................................................................................................5-18
C. .........................
.................. ..........................
...................
Parts of a VI ..........................................................................................................1-10
D. ........................
.................. .........................
.................
Front Panel ............................................................................................................1-14 Lesson 6
r D str

r D str
E. ........................
................... .........................
Block Diagram ......................................................................................................1-20 Managing File and Hardware Resources
sources
ources
F. Searching for Controls, VIs and Functions... ........................
..........................
Functions...........................................................1-31 A. Understanding Hardware and d Software
oftware Res Reso
Resources...............................................6-2
........................
..........................
G. .........................
.............. ..........................
......................
Selecting a Tool ....................................................................................................1-33 B. ........................
.............. .........................
....................
File I/O ..................................................................................................................6-4
H. ........................
................... .........................
.................
Dataflow................................................................................................................1-38 C. Acquiring Measurementss with ith a DAQ S ..........................
..................
System.....................................................6-7
I. ........................
......................... ..........................
.......................
Building a Simple VI ............................................................................................1-39 D. Controlling Instruments ts .....................
................. ..........................
................
.......................................................................................6-16
t fo l In

t fo l In
Lesson 2 Lesson 7
Troubleshooting and Debu
Debugging
gVVIs d Stat
Using Sequential and Stat Machine
State ch Algorithms
gorithms
A. Correcting Broken
roken VIs.....
VIs..........................................................................................2-2
..........................
....................... A. Using Sequential
ntial Programm
Programming ............................................................................7-2
..........................
.........................
B. Debuggingg Techni
chniques
ques .....
Techniques ..........................
.........................
.........................................................................................2-3 B. Using Statee Progr
ogramming
amming ......................................................................................7-4
Programming ..........................
.........................
No na

No na
C. ed orr Unexpected Data.............................................................................2-9
Undefined ........................
.................... chiness ..............
C. State Machines ............... ....................
.......................
......................................................................................................7-4
D. Error Handling
ling ............ .... .............
..............
......................................................................................................2-10
Lesson 8
Lesson 3 ataflow
low Cha
Solving Dataflow Challe
ll s with
Challenges ith Variab
Vari
Variables
nting a VI
Implementing
tio

tio
A. Communicating Between
Communicatin een Parallel Loop Loops .............................................................8-2
A.. Front
ont Panel BBasics ...............................................................................................3-2
.........................
....................... B. Writing to Co Controls and nd Reading
Reading fro from Indicators ................................................8-4
B. LabVIEW D Data Typess ...................
..........................................................................................3-3 C. Variables ..... .....................
...................
...............................................................................................................8-4
C. Documen
Documenting Code de ... ............
........
...............................................................................................3-14 D. Conditions ....................................................................................................8-13
Race Con ...... ............
........
D. While L ...............
........
Loops..........................................................................................................3-16
Na

E.
F.
G.
H
H.
II.
For L
Tim
D
........................
...................
Loops ..............................................................................................................3-19
Timing a VI.......................
VI......................
VI...........................................................................................................3-22
dback in Loops .......................................................................................3-23
Data Feedback
g Data Wavef
Plotting
tructures
tructur
Case Structures
Waveform
es .......
f Chart ..........................................................................3-26
.....................................................................................................3-28
Na
Appendix
ppendix A
Additional IInformation

Glossary
ssar
ation and R
Re
Resources

National Instruments | iii iv | ni.com


Student Guide

Student Guide
B. Course Description
Thank you for purchasing the LabVIEW Core 1 course kit. You can begin in developi
developing an The LabVIEW Core 1 course teaches you programming concepts, techniques, ques,
s, features,
ffea VIs, and
application soon after you complete this course. This course manual and functions you can use to create test and measurement, data acquisition, instrument
rument co ccontrol,
nd accompanying
d the accomp
accompa

uti ts

uti ts
software are used in the three-day, hands-on LabVIEW Core 1 course.e. ns.. This course assumes
datalogging, measurement analysis, and report generation applications. a that
you are familiar with Windows and that you have experience writingng algorithms
algorithms in the form of
responding
onding course
You can apply the full purchase of this course kit toward the corresponding cou registration
cours str fee re divided
flowcharts or block diagrams. The course and exercise manuals are ivided into lelessons, described

rib en

rib en
/training for online
if you register within 90 days of purchasing the kit. Visit ni.com/training
com/training line cou
course as follows.
schedules, syllabi, training centers, and class registration.
g:
In the course manual, each lesson consists of the following:

on

on
A. NI Certification son and what yo
An introduction that describes the purpose of the lesson you will learn
n

ist um

ist um
A description of the topics in the lesson
The LabVIEW Core 1 course is part of a series of courses
ourses
es designed to buildd your proficienc
proficiency with
rtant
nt concepts aand skills
A summary quiz that tests and reinforces important ls taught in the llesson
LabVIEW and help you prepare for the NI Certified ied LabVIEW A Associatete Developer exam.
exa
ex The
following illustration shows the courses that aree part
rt of the
the LabVIEW
Lab
La ning series. Refer
training R to In the exercise manual, each lesson consists off thee following:
ni.com/training for more information about out NI Certific
Certifica
Certification.
ics
cs
A set of exercises to reinforce those topics
r D str

r D str
hallenge
nge exercise
Some lessons include optional and challenge exercis sections
ns or a set of ad
add
additional exercises
New User U
Experienced User Advanced
Advanc User
to complete if time permits
Courses

LabVIEW Core 1* LabVIEW


L abVIE Core 3* Managing Software
Note For course and exercise
ercise
se manual uupdates and
nd corrections, refer to ni.com/info
t fo l In

t fo l In
LabVIEW Core 2*
En
Engineering in LabVIEW and enter the Info Codee Core1.
abVIE Connectivity
LabVIEW y Advanced Architectures
in LabVIEW
Object-Oriented
Obje dDDesign
gn Several exercises use one off th wing
wing N
the following Nationall Instruments h
ha
hardware products:
mming
and Programming
in LabVIEW A plug-in multifunction
ion data acq
acquisition (DAQ)
AQ) connected to a BNC-2120 containing
Q) device conn
LabVIEW
W Perform
Performance
ance or, function
a temperature sensor, unction gen
gene
generator, and
nd LEDs
Certifications
No na

No na
A GPIB interfacee connected
nected to an
a NI Instrument Simulator
trument Simu
Simula
Certified LabVIEW
VIEW Certified
dLLabVIEW
abVIEW Certified LabVIEW
loper Exam
Associate Developer Exam Developer Ex
Exam
am Architect Exam
If you do not have
ve this
his hardware,
hardware you still an ccomplete
till can lete the exercises. Alternate instructions are
ses
Other Courses provided for completing
pleting the exercises
ompleting ex
e s without
hout hardware.
hhard You also can substitute other hardware
for those previously
eviously mentioned.
mention Forr example,
ample, you can c use a GPIB instrument in place of the
tio

tio
LabVIEW
bVIEW In
Instrument
strument C
Control LabVIEW
bVIEW Real-Time
Re 1 LabVIEW Real-Time 2 ment
ent Simulator, or
NI Instrument o another
her National Instruments
Inst
Inst DAQ device connected to a signal
L abVIEW FPGA
LabVIEW LabVIEW DAQ and
LabVIEW an Signal Conditioning Modular Instruments Series uch as a function
source, such functio
functi generator.
ator.
tor.
*Core
Core co
courses
rses a
are
re strongly recommended to realize
lize m
maximum
a productivity gains when using LabVIEW.
Na

Na
National Instruments | v vi | ni.com
LabVIEW Core 1 Course Manual Student Guide

C. What You Need to Get Started NI Instrument Simulator Wizard installed from the NI Instrument Simulator software CD

LabVIEW Core 1 course CD, which installs the following folders:


Suggested Reading

uti ts

uti ts
The suggested reading material ensure that all students have a minimumm knowledge oof key theories Directory Description
and concepts related to the LabVIEW Core 1 course. To get the most ost out of this co
course, complete
all the suggested reading material.
Exercises Folder for saving VIs created during the course and for
f completing
ubVIs nece
certain course exercises; also includes subVIs necessary for some

rib en

rib en
To access each of the following suggested reading materials, refer
er to ni.com
ni.com/info and enter tthe exercises and zip file (NI Instrumentent Siumlator.zip
Siuml )
Info Code that corresponds to each topic: containing the LabVIEW instrumentt driver for the NI Instrument
rument

on

on
Simulator
LabVIEW Core 1 - The Software Development Method
hodd (Info Cod
Code: SoftDev
Dev)

ist um

ist um
Solutions Contains the solutions to all the
he course ex
exercises
Introduction to Data Acquisition (Info Code: DAQ
AQ)

GPIB Instrument Control Tutorial (Info Code:


de: GPIB)
D. Installing the Course Software
ware
re
Complete the following steps to install the course
ourse
se software.
Course Materials
r D str

r D str
1. Insert the course CD in your computer.
r. The LabVIEW Setup dialog box
LabVIE Coree 1 Course Setu
Before you begin this course, ensure you
ou have all the ffo
following
ng
g items: appears.
2. Click Install the course materials.
ls.
Computer running Windows 7/Vista/XP
Vista/XP
a/XP
3. Follow the onscreen instructions
ns too complete installation
i on and setup.
tion
t fo l In

t fo l In
Multifunction DAQ device configured
onfigured as D
Dev1 using
ing Measuremen
Measurement & Automation Explorer
Exercise files are located in the <Exercises>\LabVIEW
Exercises
Exercises> W Core 1\ folder.
VIEW
(MAX)

BNC-2120, wires, and


d cable
able Note Folder names
ames
mes in aangle brackets, such
uch as <Exerc
<Exercises>, refer to folders on the
compu
root directory of your computer.
GPIB interface
No na

No na
NI Instrumentt Simulator
mulator and ppower supp
supply
E. Course Goals
als
LabVIEW
W Full
ll or Professional
Profess
Professi Development
evelopment
opmen Sy
System 2012 or later
This course prepares
epares
es you to do the following:
lowing:
ing:
Understand
and front panels,
panels block diagrams, icons, and connector panes
grams, icon
tio

tio
DAQmx
mxx 9.5.5 or later hee programming structures
Use the ures
res and data ty
typ
types that exist in LabVIEW
NI-488.2
-488.2
8.2 3.0.2 or llater Usee various
arious editing and debugging
gging techniques
ging techni
techniq
Create
ate and save VIs so you
ou can
ca use them
he as subVIs
NI VISA 5.2 oor later
Na

A GPIB cable
cab
ca



Na Display and log
app
l data
applications
Create ap
Create applications
a
plug-in DAQ devices
ns that use plug
plug-i
ions that use serial
ser port and GPIB instruments
ser

This course does nott describe tthe following:


cti or object; refer to the LabVIEW Help for more information about
Every built-in VI, function,
LabVIEW features not described in this course
Analog-to-digital (A/D) theory

National Instruments | vii viii | ni.com


LabVIEW Core 1 Course Manual

Operation of the GPIB bus


Developing an instrument driver
he NI Example
Developing a complete application for any student in the class; refer to the Ex Finder,

uti ts

uti ts
available by selecting HelpFind Examples, for example VIs you can an us
usee and inc
inco
incorporate into
VIs you create

F. Course Conventions

rib en

rib en
The following conventions appear in this course manual:

on

on
The symbol leads you through nested sted menu it items and
ite d dialog
log box

ist um

ist um
options to a final action. The sequence
equence
ence Tools
ToolsInstrumentationFind
mentationFin
mentationFind
Instrument Drivers directs youu to drop dow down the Toolsools menu, sele
select the
Instrumentation item, and d finally
ally select tthe Find d Instrument
nstrument Drivers
D
option.

ip,
p, which al
This icon denotes a tip, alerts you to advisory
visory inform
information.
r D str

r D str
This icon denotess a note, which aalerts you
ou to important information.

This icon denotes


notess a caution, which
w advises
d ses you of precautions
ppr to take to
y, data loss, or a system
avoid injury, m crash.
t fo l In

t fo l In
bold notes items that you
Bold text denotes ou must select
select or click in the software, such as
menuu items
item and dialog
dialo box options. Bold text
te also denotes sections of dialog
xes and ha
boxes s.
hardware labels.

italic Italic
ic text denotes
deno
denot variables,
ables,
ab les, emphasis, a cross-reference, or an introduction
No na

No na
to a key conc ext also den
concept. Italic text deno
denotes text that is a placeholder for a word
or value tha
that you must supply. ly.

monospace Text in this font


nt denotes
notes te
text oor characters that you enter from the keyboard,
tio

tio
sect
sectio
sections of code,, programming
programm
programmi examples, and syntax examples. This font
also is usedd for the proper names
n of disk drives, paths, directories, programs,
ssubprograms,
ams,
ms, subroutines,
subroutine device names, functions, operations, variables,
mes and
filenames, d extensi
exten
extensions.
Na

monospace
onospace bold

Platform
orm
bol Text
xt in this font denotes
automatically
that are different

followin
differe
diffe

Text in this
d
omatically prints
pr
the messages and responses that the computer
to the screen. This font also emphasizes lines of code
from the other examples.

thi font denotes a specific platform and indicates that the text
th
following it applies only to that platform.
Na
National Instruments | ix
Lesson 1 Navigating LabVIEW

Navigating LabVIEW
1 A. What is LabVIEW
LabVIEW is a graphical programming environment you can use to quickly kly and efficiently
e create
applications with professional user interfaces. Millions of engineers andd scientists
ientists use
u LabVIEW
us

uti ts

uti ts
cations
ations using intuitive
to develop sophisticated measurement, test, and control system applications in icons
fferent
f ent targets and
and wires. In addition, the LabVIEW platform is scalable across different an OSs. In fact,
This lesson introduces how to navigate the LabVIEW environment. nt. This includes using the menus, LabVIEW offers unrivaled integration with thousands of hardware re devices
evices and pr
provides hundreds

rib en

rib en
bVIE
toolbars, palettes, tools, help, and common dialog boxes of LabVIEW. EW.
W. You also
als learn how to run n for you to cre
of built-in libraries for advanced analysis and data visualization crea ual
create virtual
ck diagram.
a VI and gain a general understanding of a front panel and block diagram. At tthe end of this
his lesso
lesson, instruments you can customize to your needs.

on

on
you create a simple VI that acquires, analyzes, and presentss data.
a.
Because LabVIEW programs imitate the appearance andd operation
eration of physical
ph ruments, such
instruments, su
suc
Topics as oscilloscopes and multimeters, LabVIEW programs aree called virtuvirt uments or, more
virtual instruments

ist um

ist um
grams.
commonly, VIs. VIs have front panels and block diagrams.ms. The fron
front panel iss the user inter
interf
interface.
A. What is LabVIEW The block diagram is the programming behind the user er interface. A ou
After you u build the fr
fron
front panel,
you add code using graphical representations of ffunctions
ctions to con
control thee front
ont panel obj
obje
objects. The
B. Project Explorer lso known as G code orr block
code on the block diagram is graphical code, also ck diagram code.
C. Parts of a VI
uages,
ages, like C+
In contrast to text-based programming languages, C++ and Visual
sual Basic, LabV
su LabVIEW uses icons
r D str

r D str
D. Front Panel
ons.. In text-base
instead of lines of text to create applications. text-bas gramming, inst
text-based programming, instru
instructions determine
E. Block Diagram the order of program execution. LabVIEW IEW
W uses graphi taflow
flow programming.
graphical dataflow pr
programm
ogramm In graphical
F. Searching for Controls, VIs and Functions
nctions dataflow programming, the flow of dataa throug
through h the nodes on the
he block diagram
dia
dia determines the
mming
execution order. Graphical programming ing and dataf xecution
cution are the ttwo major ways
dataflow execution
G. Selecting a Tool
t fo l In

t fo l In
LabVIEW is different from most ot other
her general-p
general-purposee programming
rogramming la languages.
H. Dataflow
I. Building a Simple VI In this course, you see how yoyou can use Lab
LabV
LabVIEW to effectively cre create simple data acquisition
applications using the threee steps:
steps: acquire, analyze,e,, and present. Although
A this course is taught on
VIEW
a Windows system, LabVIEW W is multi-
mul ti-
multi-platform. . You can develo
develop applications on a Windows, Mac
hermore, you can deploy
OS, or Linux system. Furthermore, eploy
ploy LabVIEW applications to a variety of real-time
No na

No na
and FPGA targets.

LabVIEW
W Characteristics
Characte cs
LabVIEW programs have th
the following
wingg characteris
characteri
characteristics:
tio

tio
A graphical
aphical compiled nature
hical and comp ature
ture
ataflow
ow and/or ev
Dataflow event-based programmin
rogrammin
programming
Multi-target
lti-target and platform
rm capabilities
m cap
capab es
Na



Na Object-oriented
Object-orient flexibility
Multi-thr
Multi-threa
Multi-threading
ibility
ity
ossibilities
possibilities

National Instruments | 1-1 1-2 | ni.com


LabVIEW Core 1 Course Manual Lesson 1 Navigating LabVIEW

In LabVIEW Core 1, you learn about the graphical and compiled nature of LabVIEW and dataflow Multithreading and Memory Management
programming. The following courses explore other characteristics:
LabVIEW enables your code to have automatic parallelism. In other languages
uages if you want to run
LabVIEW Core 2Learn about event-based programming. code in parallel, you have to manage multiple threads manually. The LabVIEW
VIEW environment, with
EW env
the compiler and execution system working together, automatically runs parallel whenever
ns code in paral
parall

uti ts

uti ts
Object-Oriented Design and Programming in LabVIEWLearn about
boutt object-ori
object-or
object-oriented
programming in LabVIEW. possible. Most of the time the details of the execution system are unimportant
impor
mportant you because the
tant to yo
system does the right thing without intervention. However, LabVIEW EWW also provid
provides you with
abVIEW'
IEW'ss multithreading
LabVIEW PerformanceLearn how to take advantage of LabVIEW's multit and options for improving performance.

rib en

rib en
memory management to improve program execution and memory
ory usage.

Launching the LabVIEW Environment


ent

on

on
Graphical and Compiled
While represented graphically, with icons and wires instead
teadd of with tex
text, G code
de onn the block When you launch LabVIEW, the Getting Started window
ow appears as sh
shown in
n Figure
gure 1-1.

ist um

ist um
diagram contains the same programming concepts found undd in most trad
traditional languages. For Figure 1-1. LabVIEW Getting
ting Started W
Win
Window
example, G code includes data types, loops, event handling,
dling, variab ursion,
rsion, and
variables, recursion,
object-oriented programming. LabVIEW compiles es G code direc
direct hine code so the
directly to machine t
computer processors can execute it. You do not have
ve to compil
compi
compile G code de in a separate step.
s

Dataflow and Event-Driven Programming


Programmin
ogrammi
r D str

r D str
LabVIEW programs execute according to dataflow pro programming
ing rules instea
instead of the procedural
ogrammi
mming
approach found in most text-based programming ng la
lang
languages suchh as C and CC++. Dataflow
pendent.
dent. The flo
execution is data-driven, or data-dependent. ata between no
flow of data nod
nodes in the G code
determines the execution order.
t fo l In

t fo l In
Event-driven programming featuress extend theth LabVIEWIEWW dataflow environment
en to allow the user's
direct interaction with the progr
rogr without
program hout the need
ed for polling.
polling. Ev
Event-based programming also
allows other asynchronous us activity
ctivity to
t influence the execution
xecution of G code on the block diagram.

Multi-Target and
nd Multi-Platform
Multi-Pl
Multi-Pla m
No na

No na
With LabVIEW applications,
pplications,
cations, you can target
get multicore
m cor coree pro
processors and other parallel hardware such
mmable
as field-programmablele gate arrays
arra (FPGAs).
GAs).
s). You
Y can automatically scale LabVIEW applications
to CPUs with two,
o, four, or m
mo es, often
more cores, ten wit
with no additional programming effort.
tio

tio
G code, with
th the exception of a few
ew platform-spe
platform-sp
platform-specific functions, is portable between the different
EW
LabVIEWW systems for ddifferent operating syste
systems. Therefore, you can often use the same code
her running
whether unning LabV
LabVIEW onn Windows,
W dows, M Ma
Mac OS X or Linux systems. Use the
he Getting Started
Start windowdow to create
reate new
n projects and VIs. You can create items from scratch
or from templates aand samples.
ples.
es. You
Y can al l open existing LabVIEW files and access LabVIEW
also
Na

Object-Oriented
Object-Orien
bject-Orie
Object-oriented programming
Object-oriente
programmin
programming languages.
classs of ob
amming is a p
ages.
pop
popular programming approach across a wide variety of
ges. It allows a variety of similar, yet different items, to be represented as a
objects in software. LabV
niques
niqu
programming techniques
La bV
LabVIEW
es in G ccode.
provides tools and functions so you can use object-oriented
Na
ommunity
mmunity resou
community resources and

The Getting S
appears when
reappears w
d help.
elp.

Started window disap


disapp
disappears when you open an existing file or create a new file, and
youu close all open front panels and block diagrams. You can display the window
tim by selecting
at any time ecting ViewG
ViewGetting Started Window.

National Instruments | 1-3 1-4 | ni.com


LabVIEW Core 1 Course Manual Lesson 1 Navigating LabVIEW

B. Project Explorer 2. Search for the template or sample project that supports the goal you want the project to
p projects:
accomplish. Use the following features to search for templates and sample
VIs are LabVIEW programs, and you can use multiple VIs together to makee a LabVIEW
La
L FiltersDisplays only results of a certain type, such as templatess orr sample
sampl
sam projects for a
application. To group these application-related VIs together, use a LabVIEW
VIEW project. When you
W projec specific target.

uti ts

uti ts
save a LabVIEW project from the Project Explorer window, LabVIEW IEW
W creates a ppr
project file
(.lvproj), that includes references to all the LabVIEW files and non-LabVIEW
-LabVIEW files
f in the criptions
tions of the fi
Additional SearchSearches the keywords, titles, and descriptions filtered results.
yment
ent information.
project, configuration information, build information, and deployment informati More InformationOpens the help file for the item. Reviewvieww the help fi
file to ensure that

rib en

rib en
antt the
the template or sample project supports the goal you want he project to
t accomplish.
mplish
Some LabVIEW applications, such as simple VIs, do not need ed too use a LabVIEW
LabV project.
ct.
3. Click the Next or Finish button to configure details of thee project,
oject, including
incl
includ
ud how w thee project is
ationss and share
However, you must use a project to build stand-alone applications sha ries. In addition,
shared libraries.

on

on
saved. After you finish configuring the project, LabVIEWEWW saves the project
p pens the
and opens
achine
you must use a project to work with non-development machine ine targets su such as real-time
-time (RT),
Project Explorer window and the top-level VI of the he project.
roject.
gital
field-programmable gate array (FPGA), or personal digitalal assistant (PDA)
((P argets. Refer to th
targets. the

ist um

ist um
specific module documentation for more information n about
out using propr
projects with
ith the LabVIE
LabVIEW 4. Use the Project Explorer window to modify the project.ject. Refer
Refer to the comments
mments on the bblock
Real-Time, FPGA, and PDA modules. ion about how to modify
diagrams of VIs in the project for more information fy the project. Al
Also refer
to the Project Documentation folder in the Project Explorer window
ect Explor
Explore ow for more inf
information
about how to modify the project.
Project Explorer Window
Projects in LabVIEW consist of VIs, files necessary
ecessary for tth
those VIss to run properly
properly, and
r D str

r D str
supplemental files such as documentationn or related links.
link Use the Project Ex Explorer window to
Exp
Project-Related Toolbars
manage projects in LabVIEW. Use the Standard, Project, Build, and Source Control toolbar
urce Contro arr buttons to perf
pe
perform
r operations in a
vailabl
blee at the tto
LabVIEW project. The toolbars are available top of thee Project Explorer window, as shown
oject Explor
cludes
es the follow
The Project Explorer window includes ms by default:
following items xpand
nd the Proje
in Figure 1-2. You might need to expand Project Explorerlorerr window to view all of the toolbars.
t fo l In

t fo l In
Project rootContains all other items in th the Project window. The label on the
ect Explorer wi
w Figure
gure 1-2. Proje
Pro
Project Explorer
plorerr Window
me for the pproject.
project root includes the filename
1 2 3 4
sents the local
esents
My ComputerRepresents al ccomputer
er as a target in tthe project.
cludes
es VIs and items that
DependenciesIncludes at VIs under a target
tar require.
ta
Includes build
Build SpecificationsIncludes
ionsIncludes b configurations
nfigurations for source distributions and other types
No na

No na
of builds available
able in LabVIEW toolkits andd modules. If you have the LabVIEW Professional
Developmentt System
stem or Appl
App
Applicationn Build
uild installed,
Builder stalle you can use Build Specifications to
tand-alone
d-alone applications,
configure stand-alone appli s, shared
ared libr
libraries, installers, and zip files.
tio

tio
Tip
ip A targett is any device
vice that can run a VI.

When you add another target to thee project


project, LLabVIEW creates an additional item in the Project
plorer
Explorer ent
nt the
er window to represent th target.
ett. Each
E target also includes Dependencies and Build
Specifications se
sec
pecifications sections. fi under each target.
You can add files
Na

Complete the ffollowing


Projects.
elect FileCreate
1. Select
ng steps to use th
the Project Explorer window to create and edit LabVIEW

reate Project tto display the Create Project dialog box. The Create Project
des a list of templates and sample projects you can use to ensure that the project
dialog box includes
Na
1
2
3
4
Standard Toolbar
Project Toolbar
Proje
Build
uild Toolbar
Source Control Toolbar
8 7

5
6
7
8
6 5

Project Root
Target
Dependencies
Build Specifications
ble ddesigns and programming practices.
you create uses reliable
Tip The Source Control toolbar is only available if you have source control configured
in LabVIEW.

National Instruments | 1-5 1-6 | ni.com


LabVIEW Core 1 Course Manual Lesson 1 Navigating LabVIEW

You can show or hide toolbars by selecting ViewToolbars and selecting the toolbars you want to Select the VI icon in the upper right corner of a front panel or block diagram window and drag
show or hide. You can also right-click an open area on the toolbar and select the toolbars you want the icon to the target.
to show or hide. Select an item or folder from the file system on your computer and dragg it to
t the
th target.

uti ts

uti ts
Creating a LabVIEW Project Removing Items from a Project
Complete the following steps to create a project. You can remove items from the Project Explorer window in thee following
llowing way
ways:

rib en

rib en
1. Choose one of the following actions to create a new LabVIEW
IEW
W project
project. Right-click the item you want to remove and select Remove Project from the shor
ove from Projec
Proj shortcut
In the Getting Started window, click Blank Project ct to open a blan ect orr click the
blank project menu.

on

on
emplate.
plate.
Create Project button to create a project from a template. e>.
Select the item you want to remove and press <Delete>.
In an open LabVIEW project or VI, select FileCreate
Create
reate Proje
Projec
Project.

ist um

ist um
Select the item you want to remove and click the Remove Project button on the
move From P
In any LabVIEW window, select FileNew. Then en select ProjectEmpty
Pr
Pro pty Project in the
Empty Standard toolbar.
New dialog box to display the Project Explorer
rer window.
plorer window
ct under
2. Add items you want to include in the project nder a target.
targe
target Note Removing an item from a project
ect does not delete
del the item
m on disk.
oject..
3. Select FileSave Project to save the project.
Organizing Items in a Project
oject
ect
r D str

r D str
Adding Existing Files To
o A Project
Projec The Project Explorer window includess two wo pages, the Items page and the File Files page. The Items
Fi
y exist
page displays the project items as they st in the project
pro
p e. The Files pag
tree. page displays the project
You can add existing files to a project.
ct. Use the My C Computer ter item
tem (or othe
other target) in the Project
items that have a corresponding file on disk. You ca nize filenames aan
can organize and folders on this page.
Explorer window to add files such h as VIs or text files, to
o a LabVIEW project.
pr
age both reflect aand update
Project operations on the Files page date
te the contents
conte on disk. You can switch
t fo l In

t fo l In
followin ways:
You can add items to a project in the following
ght-clicking a ffolder orr item
from one page to the other by right-clicking m under a ta
target and selecting Show in
Items View or Show in Files View from the shortcut ut menu.
enu
Right-click My Computer
uter ct AddFile
ter and select A e from the shor
shortc
shortcut menu to add a file. You also
can select ProjectAdd ProjectFile from
dd To Proj m thee Project E
Explorer menu to add a file. tems in the Project Explorer
Use folders to organize items orer window. Y
plorer You can add two types of folders
get and select Ad
Right-click the target A d der (Auto-populating)
AddFolder (Auto-popu from the shortcut menu to to a LabVIEW project, virtual ual folders and
a auto-populating
-populating folders.
fold Virtual folders organize project
arget in the Proj
items. Right-click a target Pro lorer window
plorer
Project Explorer ndow aand select NewVirtual Folder from
No na

No na
ulating
add an auto-populating g folder. Y
Yo
You also can
an sele
select Proje
Pro
ProjectAdd To ProjectAdd Folder
(Auto-populating) a pu
ting)) to add an auto-populatingg folder. L
LabVIEW continuously monitors and the shortcut menu too create
reate a new
new virtual
v r. Auto-populating
folder. Auto-pop folders update in real time to
updates the folderr according to changes
nges made
mad
m in the project and on disk. ts off folders on ddisk. Add
reflect the contents dd an aauto-populating
popu
popul folder to the project to view project
ppear
items as they appearar on disk.
Right-clickck the
he target or M mputer
My Computer er and sele
select AddFolder (Snapshot) from the shortcut
tio

tio
menu to add a virtual ffo ou also
folder. You lso can sele
selec
select ProjectAdd To ProjectAdd Folder lating
ating folders ar
Auto-populating are visiblee only on the Ite
te page of the Project Explorer window. You
IItems
ot) to add a vvirtual folder.
pshot)
(Snapshot) older. When yo you select a directory on disk, LabVIEW creates a can view thehe disk content
contents of ann auto-populating
auto-populatin folder but you cannot perform disk operations
w virtual
new irtual folder in the project
ject
ct with the same
sa name as the directory on disk. LabVIEW also such ass renaming,
naming, reorganizing,
reorg
reor nd removing project items. To perform disk operations of items
and
reates
es project items
creates ite that rep ent
nt the contents
represent cco of the entire directory, including files and n auto-populating
in an to-populatin folder, use tthe Files
iles pa
ppage of the Project Explorer window. The Files page
contents
tents of subdirectories.
subd ies.
s. Selecting
Sel
Select a folder on disk adds contents of the entire folder, plays the locati
displays locatio oject
ect fold
location of project folder
folders on disk. Project operations on the Files page both update
Na

including file

Note
No After
ter
ontents
ents of subfo
files and contents subfolders.

er you add a virtual


aautomatically
vir
vi folder on disk to a project, LabVIEW does not
ically update the folder in the project if you make changes to the folder on disk.
Na
nd
andd reflect the co
auto-populating
LabVIEW.

You can
contents of the

n aarrange items
he folder on disk. Likewise, LabVIEW automatically updates the
auto-populatin folderr in the projec
project if you make changes to the folder on disk outside of

tems in a folde
folder. Right-click a folder and select Arrange ByName from the
get and select NewVI from the shortcut menu to add a new, blank VI. You
Right-click the target nge item
shortcut menu to arrange items in alphabetical order. Right-click a folder and select Arrange By
also can select FileNew VI or ProjectAdd To ProjectNew VI to add a new, blank VI. Type from the shortcut menu en to arrange items by file type.

National Instruments | 1-7 1-8 | ni.com


LabVIEW Core 1 Course Manual Lesson 1 Navigating LabVIEW

Viewing Files in a Project C. Parts of a VI


When you add a file to a LabVIEW project, LabVIEW includes a reference ce to tthe file on disk.
LabVIEW VIs contain three main componentsthe front panel window, thee block
bloc
bl diagram, and
Right-click a file in the Project Explorer window and select Open from the shortcut menu to open
the icon/connector pane.
the file in its default editor.

uti ts

uti ts
Right-click the project and select ViewFull Paths from the shortcut
ut menu to view where files that Front Panel Window
a project references are saved on disk.

rib en

rib en
The front panel window is the user interface for the VI. Figure 1-3 shows an exeexample of a ffront
Use the Project File Information dialog box to view wheree fileses that a proj erences
nces are
project references panel window. You create the front panel window with controls ols and indicato ch are
indicators, which re the
ly.
interactive input and output terminals of the VI, respectively.

on

on
located on disk and in the Project Explorer window. Select
ct ProjectFile
rojectFile Information
mationn to display
ght-click
click the project
the Project File Information dialog box. You also can right-click pro andd select
lect ViewF
ViewFile Figure 1-3. VI Frontt Panel
anel

ist um

ist um
Information from the shortcut menu to display the Project
roject
ct File Info
Infor
Information n dialog box.

Saving a Project
You can save a LabVIEW project in the following
wing
g ways:
Select FileSave Project.
r D str

r D str
Select ProjectSave Project.
Right-click the project and select Save from the sshortcut menu.
nu.
Click the Save Project button on the
he Project ttoolbar.
t fo l In

t fo l In
You must save new, unsaved filess in a project before
b you can save the project. When you save a
project, LabVIEW does not save dependencies
pendenci
pende nci as part
art of the project file.

Note Make a backup


ckup copy of a project
ect when you pre
prepare to make major revisions to
the project.
No na

No na
tio

tio
Na

Na
National Instruments | 1-9 1-10 | ni.com
LabVIEW Core 1 Course Manual Lesson 1 Navigating LabVIEW

Block Diagram Window Opening an Existing VI


After you create the front panel window, you add code using graphical representations
esenta of functions Select Browse in the Open list in the Getting Started window to navigate to and oopen an existing VI.
ck diagram window. The
to control the front panel objects. Figure 1-4 shows an example of a block
block diagram window contains this graphical source code. Front panell objects appear
appea as terminals

uti ts

uti ts
Tip The VIs you edit in this course are located in the <Exercises>\LabVIEW
ercises>\Lab
rcises>\La
on the block diagram. Core 1 directory.

Figure 1-4. Block Diagram

rib en

rib en
ample
le might appear.
As the VI loads, a status dialog box similar to the following example ap
app

Figure 1-5. Dialog Box Indicating the Status


atus of Loading VIs

on

on
ist um

ist um
r D str

r D str
t fo l In

t fo l In
Icon and Connector
cto Pane
ane The Loading section lists the
he su
subVIs off the V
VI as they
hey load
ad into m
mem
memory and shows the number of
The Icon and Connector pane allows you to use and view a VI in another VI. A VI that is used in subVIs loaded into memoryry so far. Y el the load at any time by clicking the Stop button.
You can cancel
ubVI,
VI, wh
another VI is called a subVI, which
ich is ssimilar to
o a function in a text-based programming language.
mmediately
diately loca
If LabVIEW cannot immediately bVI, it begins se
locate a subVI, sea
searching through all directories
VI, it must have an icon and a connec
To use a VI as a subVI, connecto
connector pane.
No na

No na
specified by the VI search
rch path. You can edit the VI searc
search path by selecting ToolsOptions and
ys ann icon in the upper rightt corner
Every VI displays cco th front panel window and block diagram
of the om the Categor
selecting Paths from Category list.
xample
window. An exampleple of the default
def
de on iss sho
icon shown below. An icon is a graphical representation of
bVIEW igno
You can have LabVIEW ignor a subVI
ignore bVI byy clicking
click the Ignore Item button, or you can click the
on can
a VI. The icon n contain bo
both text andd images. If yyou use a VI as a subVI, the icon identifies the
ton to search ffor the missing
Browse button issing
ng subVI.
tio

tio
he block diagram of the VI. The default iicon contains a number that indicates how many
subVI on the
ou opened after
new VIs you afte launching
hing
ing LabVIEW
LabVIEW.
Na

To use a VI as a subVI,, youu needd to build


set of termina
rameter list
parameter l of a function call
yed next to the
displayed
bui a connector pane, shown below. The connector pane is a
terminals on thee icon that corresponds
corr
corre to the controls and indicators of that VI, similar to the
call in text-based programming languages. The connector pane is
he VI icon in th
tthe upper right corner of the front panel window. You cannot access
Na
the connector pane fromom the icicon in the block diagram window.

National Instruments | 1-11 1-12 | ni.com


LabVIEW Core 1 Course Manual Lesson 1 Navigating LabVIEW

Saving a VI D. Front Panel


To save a new VI, select FileSave. If you already saved your VI, select File
FileSave As to access
When you open a new or existing VI, the front panel window of the VI appears.
ppears.
ears TThe front panel
the Save As dialog box. From the Save As dialog box, you can create a copypy of the VI, or delete
window is the user interface for the VI. Figure 1-7 shows an example of a front panel
pane window.
the original VI and replace it with the new one.

uti ts

uti ts
Figure 1-7. Example of a Front Panel
el
Figure 1-6. Save As Dialog Box

rib en

rib en
1

on

on
2

ist um

ist um
r D str

r D str
t fo l In

t fo l In
1 Front Panel Window 2 Toolbar 3 Controls Palette

Controls and Indicators


dicators
No na

No na
Note fer to the Save A
Refer As Dialogg Box topic of th
the LabVIEW Help for detailed
tion about each option
information o n the Save
in ave As ddi
dialog box. You create the front
nt panel
anel with con
controls and
nd indicators,
cators, w
which are the interactive input and output
respectively Controls
terminals of the VI, respectively. ols are knobs,
kn pu buttons, dials, and other input devices.
push
Indicators are graphs,
phs, LEDs anaand other
er displays.
plays. Con
Controls simulate instrument input devices and
supply data to the block didiag
diagram off thee VI. Indicato
Indicat
Indicators simulate instrument output devices and
tio

tio
ataa the block diagram
display data diag cquires or gene
acquires genera
generates.

Figuree 1-7 has the following


foll ts: two cont
objects: co
controls: Number of Measurements and Delay(sec). It
raph
has one indicator: an XY graphph named
nam
n Tem
Temperature Graph.
Na

Na
he user can change
The

about
cha
ch
s the value generate
The user can see
thee input
put value for the Number of Measurements and Delay(sec) controls.
generated bby the VI on the Temperature Graph indicator. The VI
th valuess for the indicators
generates the indicato based on the code created on the block diagram. You learn
Control and Indicators section.
Contr
ut this in the Numeric Controls

tor has
Every control or indicator ha a data type associated with it. For example, the Delay(sec) horizontal
slide is a numeric data type. The most commonly used data types are numeric, Boolean value and
string. You learn about other data types in Lesson 3, Implementing a VI.

National Instruments | 1-13 1-14 | ni.com


LabVIEW Core 1 Course Manual Lesson 1 Navigating LabVIEW

Numeric Controls and Indicators String Controls and Indicators


The numeric data type can represent numbers of various types, such as integer
eger or real. The The string data type is a sequence of ASCII characters. Use string controls to re
receive text from the
two common numeric objects are the numeric control and the numeric indicator,
cator, aas shown in
ndicator, user such as a password or user name. Use string indicators to display text
ext to the user.
uus The most
Figure 1-8. Objects such as meters and dials also represent numeric data.
ata.
a. common string objects are tables and text entry boxes as shown in Figure
ure 1-10.
gure

uti ts

uti ts
Figure 1-8. Numeric Controls and Indicators
ators
rs Figure 1-10. String Controls and Indicators
ators
rs

rib en

rib en
1 2

on

on
ist um

ist um
3

1 Increment/Decrement Buttons 3 Numeric Indicator


Nu tor
2 Numeric Control

To enter or change values in a numeric control,


trol,
ol, click the increment
iinc and decrement bbuttons with the
r D str

r D str
er with
Operating tool or double-click the number ith either the Labeling
ng tool
tool or the Operating
Op
O tool, enter Controls Palette
a new number, and press the <Enter> key. The Controls palette contains the controls
trols and indicators
indicat
indica youu use to create th
the front panel. You
nt panel window
access the Controls palette from the front wind by selecting
win ecting View
ViewControls Palette. The
Boolean Controls and Indicators
ndicators
icators rious
us categories;
Controls palette is broken into various categories you canan
n expose some or all of these categories
t fo l In

t fo l In
hows a Control
to suit your needs. Figure 1-11 shows Controls palettee with all of the categories exposed and the
The Boolean data type representss data that only
onl has twoo possible
ossible states,
states such as TRUE and FALSE
Silver category expanded. During this course cises use controls
course, most exercises con
co from the Silver
or ON and OFF. Use Boolean controlss and indindicators to enter
nter and disp
display Boolean values. Boolean
category.
bu
objects simulate switches, push buttons, an LEDs.
and s.. The vertical toggle
t
to switch and the round LED
wn in Figure 1-9.
Boolean objects are shown
Figure 1-9.
1-9 Boolean
an Controls a
and Indicators
No na

No na
tio

tio
Na

Na
National Instruments | 1-15 1-16 | ni.com
LabVIEW Core 1 Course Manual Lesson 1 Navigating LabVIEW

Figure 1-11. Controls Palette While the VI runs, the Run button appears as shown below if the VI is a top-level VI, meaning it
has no callers and therefore is not a subVI.

uti ts

uti ts
wn below.
If the VI that is running is a subVI, the Run button appears as shown

rib en

rib en
on

on
The Run button appears broken when the VI you are creating tingg or editing co
contains errors.
ors. If the Ru
R
Run
lockk diagram,
button still appears broken after you finish wiring the block diagram, the
th VI iss broken and cannot
can

ist um

ist um
w, which lists aall errorss and warnings.
run. Click this button to display the Error list window,

Click the Run Continuously button to run the hee VI until you aabort orr pause
use execution
execution. You also can
r D str

r D str
us running.
click the button again to disable continuous
t fo l In

t fo l In
ecution button appears.
While the VI runs, the Abort Execution s. Click this
this bu
butt
button to stop the VI
ay to stop th
immediately if there is no other way the VI. If more
re than one rru
running top-level VI uses the
VI, the button is dimmed.
To view or hide categories (subpa
(subpalettes), select
se thee Customize but
bu
button on the palette, and select or
deselect in the Change Visible Palettes option.
ble Palett
No na

No na
Front Panel Window Toolbar
T ar Caution The
he Abort ExExecutionn bbutton
n stops th
the VI immediately, before the VI finishes
Each window has as a toolbar
oolbar associated
assoc
asso with it. Use
U the
he front
ffr panel window toolbar buttons to run rrent iteration. A
the current g a VI ttha
Aborting es external
that uses e resources, such as external
I.
and edit the VI. dware,
re, might leave
hardware, lea
leav the resources
rces in an unknown state by not resetting or releasing
em properly. Design
them Des
De Is with
VIs ith a stop but
bu
button to avoid this problem.
tio

tio
wing
ing toolbar appears
The following app
appe on the front panel w
window.
Click thee Pause
Paus button to pause a running VI. W When you click the Pause button, LabVIEW
ightss on the block
highlights bloc diagram
am the location where you paused execution, and the Pause button
ears red. Click th
appears the Pausee butto
button again
inn tto continue running the VI.
Na

lick
ick the Run but
Click
app
Run button appears
can use the VI
V as a subVI
un a VI. LabVIEW
button to run LabV
lid white arrow,
as a solid arr
ubVI if you create
compiles the VI, if necessary. You can run a VI if the
shown below. The solid white arrow also indicates you
cre a connector pane for the VI.
crea Naect the Text
Select T ettings pull-dow
Settings pull-down menu to change the font settings for the selected portions of
the VI, iincluding size, style, and color.

National Instruments | 1-17 1-18 | ni.com


LabVIEW Core 1 Course Manual Lesson 1 Navigating LabVIEW

Select the Align Objects pull-down menu to align objects along axes, including vertical, top edge, E. Block Diagram
left, and so on.
Block diagram objects include terminals, subVIs, functions, constants, structures,
uctures,
ures aand wires, which
transfer data among other block diagram objects.

uti ts

uti ts
Figure 1-12. Example of a Block Diagram and Corresponding
onding
ing Front Panel
Pa
Select the Distribute Objects pull-down menu to space objects evenly,
ly, including gaps,
venly,
compression, and so on.

rib en

rib en
on

on
ultiple
ple front pa
Select the Resize Objects pull-down menu to resize multiple pan cts to the same ssize.
panel objects

ist um

ist um
Select the Reorder pull-down menu when you u ha
haveve objects th rlap each other aand you want
that overlap
otther.
her. Select on
to define which one is in front or back of another. one of thee objects
ects with th
the Positioning
r D str

r D str
tool and then select from Move Forward, Move ove Backwa
Backwar Move
Backward, Front and Move To Back.
ve To Front,
t fo l In

t fo l In
Enter search terms to locate content LabV
LabVI
ent in the LabVIEW elp
p.
Help.
4 3 2 1

1 Indicator Terminals 2 Wires


s 3 Nodes 4 Control Terminals

Select the Show Context Windo buttonn to toggle the


xt Help Window the display
ddis of the Context Help window.
Terminals
No na

No na
Objects on the frontt panel
nel window aappear as term
terminals
inals on tthe block diagram. Terminals are entry
and exit ports that exchange
hange information
inform betw
between fron panel and block diagram. Terminals are
the front
rameters
analogous to parametersters and co
con
constants in text-b
ext- a
text-based programming languages. Types of terminals
pears
rs to remind you
Enter Text appears y thatt a new
ew value
v is available to replace an old value. The Enter ol orr indicator terminals
include control te s and node terminals.
tterm Control and indicator terminals belong
Text button disappears when you click
lick it, press the <Enter> key, or click the front panel or block
tio

to front panel

tio
nel controls and iindicators.
ors. Dataa you enter
en
ent into the front panel controls (a and b in the
orkspace.
diagram workspace. previous front
nt panel) enter the block
ock diagram through
thro
thr the control terminals. The data then enter the
Add and d Subtract functi
funct
functions. When en
n the Add and Subtract functions complete their calculations, they
uce new data values.
produce valu
val Thee data
da values
alues flow
fl
flo to the indicator terminals, where they update the
nt panel
front anel indicato
indicators (a+b and ndd ab he previous front panel).
a in the
Na

Tip

En
E
The <Enter>
T

ment
Environment
ter>
key aadds a new

ey option.
Enter key
> key on the numeric keypad ends a text entry, while the main <Enter>
ew line. To m
mod
modify this behavior, select ToolsOptions, select the
ent from the Ca
Category list, and place a checkmark in the End text entry with
C Na
The terminals in Figuree 1-12
represent the inputs
or exampl
For example
displayy the
i
12 belong to four front panel controls and indicators. Because terminals
nd outputs off your
and
onnector panes of
example, the connector
th terminals
als of the func
funct
y
you VI, subVIs and functions also have terminals shown below.
o the Add and Subtract functions have three node terminals. To
function on the block diagram, right-click the function node and select
minals from the shortcut menu.
Visible ItemsTerminals

National Instruments | 1-19 1-20 | ni.com


LabVIEW Core 1 Course Manual Lesson 1 Navigating LabVIEW

Controls, Indicators, and Constants You can view terminals with or without icon view. Figure 1-15 shows the same block diagram
without using the icon view of the terminals; however, the same distinguishing characteristics
Controls, indicators, and constants behave as inputs and outputs of the block
ck ddiagram algorithm.
between controls and indicators exist.
Consider the implementation of the algorithm for the area of a triangle:

tio s
Figure 1-15. Area of a Triangle Block Diagram without Icon

uti ts
on
n Terminal View
Vie
Area = .5 * Base * Height

ibu nt
In this algorithm, Base and Height are inputs and Area is an output,
put,, as shown in Figure 1-13.

rib en
Figure 1-13. Area of a Triangle Front
ont Panel

on
str me

ist um
Block Diagram Nodes
Nodes are objects on the block diagram that havee inputs
nputs and/or outputs
o andd perform operations
op

Di tru ents,, operators, ffunctions,


when a VI runs. They are analogous to statements,
text-based programming languages. Nodes can be functions
ns, and subroutines
subroutin in
Is, or structures. Structures are
functions, subVIs,

r D str
uctures,
tures, For Loops,
process control elements, such as Case structures, Loo
Lo Th Add and
or While Loops. The
Subtract functions in the Figure 1-12 aree function
nction nodes
nodes.
s
The user never changes or accessess thee constant .5
.5, so it does
es not appear oon the front panel unless Functions
l In

t fo l In
included as documentation of thee algorithm. Functions are the fundamental operating
perating
pe rating element
elements of LabVIEW.
bVIEW.
VIEW. Functio
F
Functions
uncti do not have front panel
windows or block diagram windows ws but do have
hav connector
ha ector
or panes. Double-clicking
Dou a function only
Figure 1-14 shows a possiblee implementation
i entation of this algorithm on a LabVIEW
L block diagram. This io has a pale y
selects the function. A function ye ackground on its icon.
yellow background
ferent
erent te
block diagram has four different terminals created by two controls
controls, one constant, and one indicator.
Figure 1-14.
14. Area of a Tr
Triangle Block Diagram w
with Icon Terminal View SubVIs
SubVIs are VIs that you create
reate to us
use inside of another VI or that you access on the Functions
No na

No na
palette.

Any VI has thee potential


tential to be uused as a subVI.
ubV When
W you double-click a subVI on the block
diagram, its front panel wind pears.
window appears. s. The front
fron panel
p includes controls and indicators. The
tio

tio
ram
block diagramam includes wires,
wi
wir icons,ns, functions, pos
possibly subVIs, and other LabVIEW objects. The
ghtt corner of the front panel
upper right anel
nel window and
an block diagram window displays the icon for the
is iss the icon that
VI. This tha appears whenhen you place
pla the VI on a block diagram as a subVI.

bVIs can also b


SubVIs be Express
ss VIs. Exp
E
Express V
VIs are nodes that require minimal wiring because you
Na

1 3 2

Na
configure
nfigure them with
w dialog og boxes.
boxes. Use EExpress VIs for common measurement tasks. You can save
t

configuration of an Express VI as a subVI. Refer to the Express VIs topic of the LabVIEW Help
the configuratio
1 Controls 2 Indicator 3 Constant
for more info
information n about creating a subVI from an Express VI configuration.
Notice
ce that
tha the Base
ase (cm) and He
Height (cm) block diagram terminals have a different appearance
H
from the Area (cm2) terminal. There
T are two distinguishing characteristics between a control and EW uses colored
LabVIEW olored icons to distinguish between Express VIs and other VIs on the block
ck diagram.
an indicator on the block diag
dia The first is an arrow on the terminal that indicates the direction xpress VIs
diagram. Icons for Express VI appear on the block diagram as icons surrounded by a blue field
V
of data flow. The controls have arrows showing the data leaving the terminal, whereas the indicator whereas subVI icons havee a yellow field.
has an arrow showing the data entering the terminal. The second distinguishing characteristic is the
border around the terminal. Controls have a thick border and indicators have a thin border.

National Instruments | 1-21 1-22 | ni.com


LabVIEW Core 1 Course Manual Lesson 1 Navigating LabVIEW

Expandable Nodes versus Icons Wires


You can display VIs and Express VIs as icons or as expandable nodes. Expandable
pand nodes appear You transfer data among block diagram objects through wires. In Figure 1-12,-12, w
wires connect the
as icons surrounded by a colored field. SubVIs appear with a yellow field,
d, and
nd Express
Expr VIs appear control and indicator terminals to the Add and Subtract function. Each wiree has a single
si data
with a blue field. Use icons if you want to conserve space on the block
k diagram. Use expandable source, but you can wire it to many VIs and functions that read the data.
a. Wires are different
dif
diff colors,

uti ts

uti ts
nodes to make wiring easier and to aid in documenting block diagrams.
ms. By de ult, ssubVIs appear
default, styles, and thicknesses, depending on their data types.
ble nodes. To di
as icons on the block diagram, and Express VIs appear as expandable dis
display a subVI or
ess VI and
Express VI as an expandable node, right-click the subVI or Express and rem
remo
remove the chcheckmark A broken wire appears as a dashed black line with a red X in the middle,
ddle, as show
sho ow Broken
shown below.

rib en

rib en
next to the View As Icon shortcut menu item. wires occur for a variety of reasons, such as when you try to wiree two objects with incompatible
ncompati
mpati
data types.

on

on
asier,
er, but it also takes a largee amount of
You can resize the expandable node to make wiring even easier,
ps too resize a no
space on the block diagram. Complete the following steps node on the block diagram
diagra
diagram:

ist um

ist um
1. Move the Positioning tool over the node. Resizingg handles
ndles appear at the top
op and bottom oof the Table 1-1 shows the most common wire types.
node.
ange
ge the cursor to the resizing
2. Move the cursor over a resizing handle to change zing cursor. Table 1-1. Common
mon
n Wire Types
Type

3. Use the resizing cursor to drag the border off the node dow isplaay additional terminals.
down to display Wire Type Scalar 1D Array 2D A
Array Color
Co
4. Release the mouse button.
r D str

r D str
Numeric Orange (fl
(floating-point),
Blue (i
(integer)
To cancel a resizing operation, drag thee node
de border past the block
border pa window before you
lock diagram w
release the mouse button.
Boolean Green
Gr
ction Generator
Figure 1-16 shows the Basic Function Generator VI as a resized
esized expand
expan
expandable node.
t fo l In

t fo l In
String Pink
Figure 1-16. Basic Function Generator
G or VII in Different Display Modes
In LabVIEW, you use wiress to connect
co mul
multiple rminals together
terminals togethe to pass data in a VI. You must
ts andd outpu
connect the wires to inputs ompatible
mpatible with th
outputs that are compatible the data that is transferred with the
wire. For example, you u cannot
nnot wire an
an array output
utput to a numer
numeric input. In addition the direction of
rrect. You must cconnect the
the wires must be correct. he wires to on
only one input and at least one output. For
No na

No na
not wire two indi
example, you cannot her. The com
indicators together. co
components that determine wiring
cludee the data type
compatibility include typ
ty of thee cont
ont and/or
control nd/or the indicator and the data type of the
terminal.
tio

tio
Data Types
pes
Data types
ypess indicate what
wha
wh objects,, inputs, and ooutputs you can wire together. For example, if a
switchh has
as a green bo ou ca
border, you ire
re a sw
can wire switch to any input with a green label on an Express VI.
If a knobb has an ora rder,
er, you
orange border, yo ccan wi
wire a knob to any input with an orange label. However,
Na

Note If youu display


the terminals
als
play a subVI
subV or Express VI as an expandable node, you cannot display
ls for that node and you cannot enable database access for that node. Na
youu cannot wire aan orange
as the terminal.
ge knob to an ininput with a green label. Notice the wires are the same color

National Instruments | 1-23 1-24 | ni.com


LabVIEW Core 1 Course Manual Lesson 1 Navigating LabVIEW

Automatically Wiring Objects Figure 1-17. Functions Palette


As you move a selected object close to other objects on the block diagram,, LabVIEW
Lab draws
temporary wires to show you valid connections. When you release the mouse button to place the
se butto
object on the block diagram, LabVIEW automatically connects the wires.res. ccan
es. You also ca

uti ts

uti ts
automatically wire objects already on the block diagram. LabVIEW connects
onnects the terminals
ter that
best match and does not connect the terminals that do not match.

rib en

rib en
Toggle automatic wiring by pressing the spacebar while you movee an object using
us thee Positioning
Positio
sitio
tool.

on

on
ons palette oor
By default, automatic wiring is enabled when you select an object from the Functions
nctions
when you copy an object already on the block diagram m byy pressing th
the <Ctrl>
> key and drag
draggi
dragging

ist um

ist um
the object. Automatic wiring is disabled by default whenn you use th ioning
ning tool to mo
the Positioning move an
object already on the block diagram.

You can adjust the automatic wiring settings byy selecting


electing Tool
Too ions and selectin
ToolsOptions selecting Block
Diagram from the Category list.
r D str

r D str
Manually Wiring Objects
When you pass the Wiring tool over a terminal,
rminal, a ti
tip strip appears
ppears
ars with the nname of the terminal.
In addition, the terminal blinks in thehe Context Help window ow and
nd on the ico
icon to help you verify that
t fo l In

t fo l In
minal. To wire o
you are wiring to the correct terminal. ob ogether,
ether, pass the
objects together, th Wiring tool over the first
terminal, click, pass the cursor overver the second
secon terminal,
nal, and click again.
ag
aga After wiring, you can
right-click the wire and selectct Clean Up W Wire from
Wi m the shortcut me
menu to have LabVIEW To view or hide categories, clic
click the Customize
usto
ustom button
utton on the pa
pale
palette, and select or deselect the
automatically choose a path thh for th
the wire. IIf you have
ave
ve broken wire
wires to remove, press <Ctrl-B> to Change Visible Palettes option.
tion.
res on the bloc
delete all the broken wires block diagram.m.

Block Diagram
am
m Toolbar
Toolba
No na

No na
Functions Palette
ette
When you run a VI, buttons appea
appear on thee blo
block diagram
agram toolbar that you can use to debug the VI.
The Functions palette te contains the
t VIs, s, functions
functio
ncti andd constants
c you use to create the block The following toolbar
ar appears oon the block
k dia
diagr
diagram.
diagram. You accessess the Func
Functions palette
Fun alettee from the block diagram by selecting ViewFunctions
pale is broken
Palette. The Functions palette roken n into various
variou
vario categories; you can show and hide categories
tio

tio
ur needs. Figure 1-17 shows
to suit your hows a Function
Functions palette with all of the categories exposed and
Functio
amming cat
the Programming
gramming categ anded.
nded. During tthis course, you work mostly in the Programming
category expanded.
ory, but you also use other
category, he categories,
tegories, or subpalettes. Click the Highlight EExecution buttontton to display
disp an animation of the block diagram execution
dis
whenn you
ou run the VI.
VI Noticee the flow
fflo off dat
data through the block diagram. Click the button again to
sable execution hhighlighting.
disable hting.
g.
Na

Na
National Instruments | 1-25 1-26 | ni.com
LabVIEW Core 1 Course Manual Lesson 1 Navigating LabVIEW

Click the Retain Wire Values button to save the wire values at each point in the flow of execution LabVIEW Help Utilities
so that when you place a probe on the wire you can immediately retain the most recent value of the
ast once
data that passed through the wire. You must successfully run the VI at least onc before you can Use the Context Help window, the LabVIEW Help, and the NI Example Finder
inder to help you create
retain the wire values. and edit VIs. Refer to the LabVIEW Help and manuals for more information
ationn about LabVIEW.

uti ts

tio s
Context Help Window

ibu nt
The Context Help window displays basic information about LabVIEW
bVIEW
EW objects when you
y move

rib en
Click the Step Into button to open a node and pause. When you ou click the Step Into button
on ag
again, p window se
the cursor over each object. To toggle display of the Context Help select HelpShow
elpSho
Sho
VI or structure.
it executes the first action and pauses at the next action of the subVI structu Youu alsoo can press Context Help, press the <Ctrl-H> keys, or click the Show Context
text Help Window
W button the
ton on th

on

n
str me
the <Ctrl> and down arrow keys. Single-stepping through a VI steps steps through
throu the VI node
ode by node.
node toolbar.
Each node blinks to denote when it is ready to execute.

ist um
When you move the cursor over front panel and blockock diagram ob he Context Help window
objects, the
nts, controls, an
displays the icon for subVIs, functions, constants, and indicators,
ators, with wires attached to

Di tru
Click the Step Over button to execute a node and pause at the next node.
ode. You also cacan press the
er the
<Ctrl> and right arrow keys. By stepping over he node, you execute
te thee node without
witho
with each terminal. When you move the cursor over er dialog box op
ooptions, the Context Hel
He window
Help
single-stepping through the node. displays descriptions of those options.
r D str
In the Context Help window, the labels of required term ppear bold, recommended
terminals appear recom
reco terminals
minals appear dimmed.
appear as plain text, and optional terminals dim
d laabels of optional
The labels opti
opt terminals do not

s
appear if you click the Hide Optionalnal Terminals and
a Full ath button iin the Context Help
ull Path
sh executing the
Click the Step Out button to finish th current
nt node and papause
pause. When the VI finishes window.
t fo l In

l In
executing, the Step Out button iss dimmed. Yo
You also can
an pre
ress
ss the <Ct
press <Ctrl> and up arrow keys. By
stepping out of a node, you completee single-s g through
single-stepping rough the nonode and navigate to the next
node.
Figure 1-18. Context
ontext
ntext Help Wind
Window
No na

No na
Click the Clean Up Diagram buttonbutt to automatically
auto cally
cally reroute
rer all existing wires and rearrange
lock diagram to ggenerate
objects on the block te a cleane
clea
cleaner layout. To configure the clean up options, select
ToolsOptions ns too display the Options
ns dialog
log box and
an select Block Diagram from the Category
n configure the ssettings in the
list. You can he Block Di
Dia
Diagram Cleanup section.
tio

tio
Thee Warning button
butt
but earss if a VI in
appears includes a warning and you placed a checkmark in the Show
Na

arning chec
Warnings check
checkbox in the Error List w window. A warning indicates there is a potential problem

Na
t
with the block diagram,
m, but it does no
not stop the VI from running.
Click
lick the
th Show
Sh Optional Termina and Full Path button located on the lower left corner of the
ptional Terminals
Termina
ext H
Context ndow to displa
Help window display the optional terminals of a connector pane and to display the full
al terminal
path to a VI. Optional terminals are shown by wire stubs, informing you that other connections
disp
exist. The detailed mode displays all terminals, as shown in Figure 1-19.

National Instruments | 1-27 1-28 | ni.com


LabVIEW Core 1 Course Manual Lesson 1 Navigating LabVIEW

Figure 1-19. Detailed Context Help Window NI Example Finder


Use the NI Example Finder to browse or search examples installed on yourr com
computer or on the NI
Developer Zone at ni.com/zone. These examples demonstrate how to use LabVIEWLabVIE to perform
a wide variety of test, measurement, control, and design tasks. Select HelpFind Examples
Exa
Ex or

uti ts

tio s
click the Find Examples link in the Examples section of the Getting Started wind
ng Starte window to launch
the NI Example Finder.

ibu nt
rib en
Examples can show you how to use specific VIs or functions. You can right-c
right-cli
l a VII or fun
right-click function
ples from the sho
on the block diagram or on a pinned palette and select Examples shortcut menuu to display

on

n
str me
a help topic with links to examples for that VI or function. You can
an modify
modif an example
mple VI to fit an
application, or you can copy and paste from one or moree examples
amples into a VI that
hat you
ou create.

ist um
Figure 1-20. NI Example
ample
ple Finder

Di tru
Click the Lock Context Help button to lock the
he current
urrent contents
conte of the Context Hel Help window.
ursor
rsor over anoth
When the contents are locked, moving the cursor ct does
another object oes nott chang
chan
change the contents
r D str ck the button ag
of the window. To unlock the window, click aga
again. Youu also
also can access this option from
the Help menu.

Ins
t fo l In

If a corresponding LabVIEW Help lp topic exist


exists for an object
ct the Conte
Context Help window describes,
p
a blue Detailed help link appears in the Con
Context Helpelp window. Als
Also, the More Help button is
he butt
enabled. Click the link or the isp the LabVIEW Help for more information about the
button to display
object.
No na

LabVIEW Help
elp
ss thee LabVIEW Help by clicking
You can access icking the M
More Help button in the Context Help window,
tio

elpLabVIEW Help, or clicking the bblue Detailed Help link in the Context Help
selecting HelpLabVIEW
window. You also can rig
ri k an object and select Help from the shortcut menu.
right-click

ti
VIEW Help contains
The LabVIEW c s deta
detailed descri
descr
descriptions of most palettes, menus, tools, VIs, and
ctions. The Lab
nctions.
functions. La
LabVIEW Help p also iinc
includes step-by-step instructions for using LabVIEW features.
Na

he LabVIEW H
The Help includes
ludes
es links to th
the following resources:

Na
t
No
entation Resou
LabVIEW Documentation Resour
Resources, which describes online and print documents to help new
and exp
expe d users and inclu
experienced includes PDF versions of all LabVIEW manuals.
Technical
chn support
port resources on the National Instruments Web site, such as the NI Developer
dgeBas and the Product Manuals Library.
dgeBase
Zone, the KnowledgeBase,

National Instruments | 1-29 1-30 | ni.com


LabVIEW Core 1 Course Manual Lesson 1 Navigating LabVIEW

F. Searching for Controls, VIs and Functions Double-click the search result to highlight its location on the palette. If the object is one you need
to use frequently, you can add it to your Favorites category. Right-click the object on the palette
When you select ViewControls or ViewFunctions to open the Controls
ols and Functions and select Add Item to Favorites, as shown in Figure 1-22.
palettes, two buttons appear at the top of the palette.

tio s

uti ts
Figure 1-22. Adding an Item to the Favorites Category
y of a Palette
SearchChanges the palette to search mode so you can perform text-based ext-based searches to locate
-based search

ibu nt
controls, VIs, or functions on the palettes. While a palette is in search
rch mode, click tthe Return button

en
to exit search mode and return to the palette.

on
str me
CustomizeProvides options for selecting a format for or the palette, showing
he current ppa hiding
howing and hidi

is um
ext and Tree formats
categories for all palettes, and sorting items in the Text for lphabetically.
phabetically. Se
alphabetically. Select
Options from the shortcut menu to display the Controls/Functions
ntrols/Function
ols/Function Palettes es page of the O
tes Options
dialog box, in which you can select a format for all palettes. This
Thi button n appears
pears only if you click

Di tru ette to pin the palette.


the thumbtack in the upper left corner of a palette pa

r D str
Until you are familiar with the locationn of VIs and
and fun
functions, search
earch for the fufunction or VI using
s
the Search button. For example, if you want to find the Random
andomm Number ffunction, click the
Search button on the Functions palettette toolbar an yping Random Number in the text box
and start typing
l In

t fo l In
W lists all matc
at the top of the palette. LabVIEW match ems that either sst
matching items start with or contain the text
you typed. You can click one of thee search results
res andd drag
rag it to the block
b diagram, as shown in
Figure 1-21.
Figure
e 1-21.
21. Search
Searching for an
n Object in the Functions
F Palette
No na

No na
Similar to the
he Search butto
button
button, you use thehe Quick DDrop dialog box to specify a palette object by
Dr
tio

tio
hen place the object
name and then o onn the
the block dia
diagr
diagram or front panel. In addition to palette objects,
you cann also
lso specify a project
p em
itemm by name in the Quick Drop dialog box.

lay the Quick Drop dialog bbox, pres


To display press <Ctrl-Space> or select ViewQuick Drop. Type the
Na

Na
ame
me of the objec
name ant to
object you want o add to tth
the block diagram or front panel. LabVIEW displays the
t

results in the Na atch


Name Match List. To att
h List. attach the object you select to the cursor, press the <Enter>
key, double-c
double-cl
double-click the name of the obobj
object in the list, or click the block diagram or front panel. Click
he location on the block diagram or
the o front panel where you want to add the object.

National Instruments | 1-31 1-32 | ni.com


LabVIEW Core 1 Course Manual Lesson 1 Navigating LabVIEW

Figure 1-23. Searching for an Object in the Quick Drop Dialog Box Operating Tool
When the mouse cursor changes to the icon shown below, the Operating tool ool is in operation. Use
re 1-25
the Operating tool to change the values of a control. For example, in Figure -25 the Operating
O tool
moves the pointer on the Horizontal Pointer Slide. When the mouse hovers vers over the pointer,
overs p the

uti ts

uti ts
cursor automatically accesses the Operating tool.

rib en

rib en
Figure 1-25. Using the Operating
ating Tool

on

on
ist um

ist um
r D str

r D str
G. Selecting a Tool
You can create, modify and debug VIss using the tools
to provided
ovided
vided by LabVIEW.
LabVI A tool is a special
t fo l In

t fo l In
rsor. The operating
operating mode of the mouse cursor. operati mode
operat de of the cursor corresponds to the icon of
ses which to
the tool selected. LabVIEW chooses too lect based on the current location of the
tool to select
mouse.
Figure 1-24.. Tools Palette
Fig
No na

No na
The Operating tool iss mostly used
us
use on the
he front
ront panel
pa window,
i but you also can use the Operating
ock diagram window
tool on the block win o change
to nge the val
value of a Boolean constant.
tio

tio
Positioning
ioning
oning Tool
Too
When n the mouse curs
curso
cursor changes
ges to the icon sh
shown below, the Positioning tool is in operation. Use
itioning tool to select
the Positioning ct orr resize
re
resiz bjec
je
objects. For example, in Figure 1-26 the Positioning tool
Na

Tip You can manually


Yo ually choo
choose
choos the tool you need by selecting it on the Tools palette.
ols Palette tto
Select ViewTools
Tools o display the Tools palette.
Na
elects
lects the Numb
selects
copy, or delete tthe object.
automatically accesses
urements numeric control. After selecting an object, you can move,
easurements
Number of Measurements
ect. When the mo
es the Position
Positionin
mouse hovers over the edge of an object, the cursor
Positioning tool.

National Instruments | 1-33 1-34 | ni.com


LabVIEW Core 1 Course Manual Lesson 1 Navigating LabVIEW

Figure 1-26. Using the Positioning Tool to Select an Object Labeling Tool
When the mouse cursor changes to the icon shown below, the Labeling tooll is in operation. Use the
bels.. For exa
Labeling tool to enter text in a control, to edit text, and to create free labels. example, in
Figure 1-28 the Labeling tool enters text in the Number of Measurements nts numeric cco
ents control. When

tio s

uti ts
tically
the mouse hovers over the interior of the control, the cursor automatically ally accesses the Labeling
click
tool. Click once to place a cursor inside the control. Then double-click k to select the
th current text.

ibu nt

rib en
n

on
str me
Figure 1-28. Using the Labeling
beling
ng Tool

ist um
Di tru

r D str
s
If the mouse hovers over a resizingg node
de of an obje
object, the cursor
ursor mode chchanges to show that you
l In

t fo l In
can resize the object, as shown inn Figure 1-27. N hatt the cursor is
Notice that i hovering over a corner of
the XY Graph at a resizing node, and the curso
cu rs modee changes
cursor anges to a double-sided
do arrow.
Figure 1-27.
-27. Using the
he Positioning
ning Tool to Re
Res
Resize an Object
na

No na
When you are not in a specific area
a of a frontnt panel
pa w window or block diagram window that accesses
use mode, the cursor
a certain mouse cu pears
rs as cross-hairs.
appears cross-ha
cross-h If automatic tool selection is enabled, you
tio

tio
e-click
-click any open space to access the Lab
can double-click Lab
Labeling tool and create a free label.

Wiring
ring
g Tool
When
hen the mouse cursor
ccu changes
hanges
nges to the icon shown below, the Wiring tool is in operation. Use the
Na

Na
Wiring
iring tool to wire

sses tth
accesses
ho
the mouse hovers
wi
w objects
tool wires the Number
N
ver
cts together on the
r of Measurements
er the exit or entry
over
ng tool.
the Wiring
Measure
Measurem
t block diagram. For example, in Figure 1-29 the Wiring
terminal to the count terminal of the For Loop. When
en point of a terminal or over a wire, the cursor automatically

You can use the Positioning tool on both the front panel window and the block diagram.

National Instruments | 1-35 1-36 | ni.com


LabVIEW Core 1 Course Manual Lesson 1 Navigating LabVIEW

Figure 1-29. Using the Wiring Tool Use the Object Shortcut Menu tool to access an object shortcut menu with the left mouse button.

uti ts

uti ts
ollbars.
ars.
Use the Scrolling tool to scroll through windows without using scrollbars.

rib en

rib en
on

on
ns, nodes,
Use the Breakpoint tool to set breakpoints on VIs, functions, des, wires,
wires and structures
ructures
res to pause
execution at that location.

ist um

ist um
Use the Probe tool to create probes on wires onn thee block diagram.
diag se thee Probe tool
Use too to check
estionable
onable or unexpected
intermediate values in a VI that produces questionable un ed results.
sults.
r D str

r D str
The Wiring tool works mainly with the block
lock
k diagram w
window and when you ccr
create a connector
pane on the front panel window.

olorss for pasting with the


Use the Color Copy tool to copy colors he Coloring
oloring tool.
tool
Other Tools Accessed
ed from the Palette
alette
ette
t fo l In

t fo l In
You can access the Operating, Positioning,
ositioning, Labeling,
La
Lab and Wiring tools
tool directly from the Tools
palette, rather than using the A tic tool selection
Automatic on mode.
ode. Select V
ViewTools Palette to access
the Tools palette.
Use the Coloring tool andd thee color picker to color
or an object. The Coloring tool also displays the
Figure 1-30. The Tools Pale
Figur Palette current foreground and background
ckground co ngs.
color settings.
No na

No na
an right-click
Select the Coloring tool and click
k an object
object o
or workspace to display the color picker.
tio

tio
H. Dataflow
ataflow
taflow
LabVIEW
bVIEW
EW follows a dataflow ow
w mo
model for ru
running VIs. A block diagram node executes when it
Na

The
he top item in the

automatic to
a
auto
t Toolss palette
LabVIEW automatically

are some additional


tion
alette is the Automatic Tool Selection button. When this is selected,
lly chooses a tool
on by deselect
tool selection
too based on the location of your cursor. You can turn off
deselecting the item, or by selecting another item in the palette. There
al tools on the ppalette, as described below:
Na
eceives
ceives all requir
receives uts. When a no
required inputs.
the next node in the dataflow
execution order
taflow
nod
node executes, it produces output data and passes the data to
ow path. The movement of data through the nodes determines the
ord of thee VIs and functions

Visuall Basic,
Ba
func
functi

+, JAVA, and most


C++,
on the block diagram.

mo other text-based programming languages follow a control flow


m
xecution. In control flow, the sequential order of program elements determines
model of program execution.
the execution order of a prog
program.

National Instruments | 1-37 1-38 | ni.com


LabVIEW Core 1 Course Manual Lesson 1 Navigating LabVIEW

For a dataflow programming example, consider a block diagram that adds two numbers and then Figure 1-33. Acquire, Analyze, and Present Example Front Panel Window and
subtracts 50.00 from the result of the addition, as shown in Figure 1-31. In this case, the block Block Diagram Window
diagram executes from left to right, not because the objects are placed in that order, but because the
hat ord
order
Subtract function cannot execute until the Add function finishes executing ting and passe
passes the data to

uti ts

tio s
the Subtract function. Remember that a node executes only when dataa are available aat all of its
input terminals and supplies data to the output terminals only when n thee node finishes
finish execution.

ibu nt
Figure 1-31. Dataflow Programming Example
mple

rib en
on

n
str me
ist um
In Figure 1-32, consider which code segment would ld execute
xecute first
firstthe Add, dd,
d, Random NumN
Number, or
Divide function. You cannot know because inputs ts to the Add and Dividee functions
func
nctions
tions are available
a at

u
the same time, and the Random Number functiontion has no inpu
input
inputs. In a situation
ation where one code
segment must execute before another, and noo data dependen
dependency exists sts between
tween the ffunctions, use
r D str

str
other programming methods, such as errorr clusters,
cluste
lusters,
rs, to force
for the order of execution.
fo executio Refer to
Lesson 5, Creating and Leveraging Datata Structures,
Structures, fofor more information ab abo
about error clusters.
Figure 1-32. Dataflow
aflow
w Example for
f Multiple
iple Code Segm
Segments
t fo l In

t fo l In
No na

No na
r
tio

tio
I. Building
lding
ding a Simple
Sim VI
V
On the Functions
unctions palett
pale
palette, the Express
xpress
press VIs are
are grouped
g together in the Express category. Express
Most LabVIEW
VIEW VIs have
hha three mainain tasksa
tasksacquiring some sort of data, analyzing the acquired
se the
VIs use he dynamic data
d typee to t pass
ass data b
be
between Express VIs.
data, andd presenting the result.
ult.
t. W
Wh ach oof these parts are simple, you can complete the entire
When each
VI using very few objects onn the block
bl diagram. Express VIs are designed specifically for
Na

completing
mpleting common,
comm frequently
that acquire, an
three tasks, as
equently
ently used operations.
analyze, and present d
a shownn in Figure 1-33
data
op In this section, you learn about some Express VIs
data. Then you learn to create a simple VI that uses these
1-33. Na
Acquire
cquire
Express VIs uused for the Acquire D
ssistant, S
Assistant, Simulatee Signal, and
Dat
Data task include the following: DAQ Assistant, Instrument I/O
and Rea
Read from Measurement File.

National Instruments | 1-39 1-40 | ni.com


LabVIEW Core 1 Course Manual Lesson 1 Navigating LabVIEW

DAQ Assistant Statistics


The DAQ Assistant acquires data through a data acquisition device.You mustt useu this Express VI The Statistics Express VI calculates statistical data from a waveform. Thiss inc
includes mean, sum,
frequently throughout this course. Until you learn more about data acquisition,
ion, you only use one
isition, standard deviation, and extreme values.
channel of the data acquisition device, CH0. This channel is connected to a temperature
temperatu sensor on

uti ts

uti ts
the BNC-2120. You can touch the temperature sensor to change the temperature
mperature the sensor reads.

rib en

rib en
Spectral Measurements

on

on
The Spectral Measurements Express VI performs spectral measurement
urement on
o a waveform,
veform,
m, such as
Instrument I/O Assistant magnitude and power spectral density.
The Instrument I/O Assistant acquires instrument control
rol data, usually
usuall from a GPIB or serial
seria

ist um

ist um
interface.

Tone Measurements
The Tone Measurements Express VI searches hes
es fo
forr a sing
single ttone with
th the highest fre
frequency or
r D str

r D str
Simulate Signal ency and amplitude
highest amplitude. It also finds the frequency amplit
amplitu of a single tone.
The Simulate Signal Express VI generates
ates simulated ddata suchh as a sine wave.
wave
t fo l In

t fo l In
Filter
Read From Measurement
re t File The Filter Express VI processes
essess a signall through
esse thr
th filters
ilters and windo
wind
windows. Filters used include the
The Read From Measurementmentt File EExpress VI reads
eads a file that w
was created using the Write To following: Highpass, Lowpass,
wpass, Bandpass, Bandstop,
s, Band stop, Smoothing. Windows used include
op, and Smooth
ress VI. It speci
Measurement File Express specifically read
eadss LVM or T
reads TD
TDM file formats. This Express VI Butterworth, Chebyshev,
ev, Inverse
nverse Chebyshev,
Ch
Cheb
eb Elliptical, and Bessel.
B
does not read ASCII files. Refer to LLesson 6,, Managing F File and Hardware Resources, for more
No na

No na
dingg data from a file.
information on reading

Present
nt
tio

tio
Analyze
yze
ze Present results
sults by using Express
E s VIs that perform
perfor a function, such as the Write to Measurement
xpress
ess VI, or ind
File Express indicators that present dat
data on the front panel window. The most commonly
Express
ess VIs used for the Analyze
alyze
y Data
ataa task
k include the followingAmplitude and Level icators for this
used indicators th task include
nclude
clud thee Wav
Waveform Chart, the Waveform Graph, and the XY Graph.
easurements,
asurements, Sta
Measurements, St
Statistics, and
d Ton
Tone M
Measurements. ommon Express VIs include
Common lude
de the Write
Wr
W it to Measurement File Express VI, the Build Text Express
Na

Amplitude and Level Measurements


The
he Amplitude
Amplit
These inc
Meas
Me
andd Level Measurements
Measure
C, rms, maximu
include DC,
rms measurements.
Express VI performs voltage measurements on a signal.
maximum peak, minimum peak, peak to peak, cycle average, and cycle
Na
VI,, the DAQ As
Instrument I/O
instrument.
Assistant, andd the In
I/ Assistant
Instrum
strum I/O Assistant. In this case, the DAQ Assistant and the
Instrument
ant provide output
outp data from the computer to the DAQ device or an external
ou

National Instruments | 1-41 1-42 | ni.com


LabVIEW Core 1 Course Manual

Write to Measurement File


The Write to Measurement File Express VI writes a file in LVM or TDMS file format. Refer to
Lesson 6, Managing File and Hardware Resources, for more information writing to
on on writin
measurement files.

uti ts

uti ts
rib en

rib en
Build Text

on

on
The Build Text Express VI creates text, usually for displaying
aying
ng on the front
fro panel
el window
indow or
anaging
ging File an
exporting to a file or instrument. Refer to Lesson 6, Managing dware Resource
and Hardware Resources
Resources, for

ist um

ist um
more information on creating strings.

r D str

r D str
Running a VI
After you configure the Express VIs and
nd wire them together,
tog you
ou can
can run the V
VI. When you finish
on on the toolb
creating your VI, click the Run button toolba ecutee the VI.
toolbar to execute
t fo l In

t fo l In
hee Run button ic
While the VI is running, the nges to the figu
icon changes figur
figure shown below. After the
execution completes, the Run button icon changes
ges back to its or
original state, and the front panel
indicators contain data..
No na

No na
Run Button
utton Errors
Error
tio

tio
If a VI does
oess not run, it is a broken,
n,, or nonexecuta
nonexecutable, VI. The Run button appears broken when the
VI youu aree creating or editing
e ntains
tains errors.
contains
Na

If the button still


nnot run.
cannot r
s appears
ears broken when
whe you finish wiring the block diagram, the VI is broken and
wh

ns that a required
Generally, this means re
req input is not wired, or a wire is broken. Press the broken run
Na
button to access the Error lis window. The Error list window lists each error and describes the
or list
li
problem. You can double-click an error to go directly to the error. Refer to Lesson 2,
Troubleshooting and Debugging VIs, for more information on debugging VIs.

National Instruments | 1-43


LabVIEW Core 1 Course Manual

Self-Review: Quiz
Refer to Figure 1-34 to answer the following quiz questions.

uti ts

uti ts
Figure 1-34. Dataflow Questions

rib en

rib en
on

on
ist um

ist um
1. Which function executes first: Add or Subtract?
btract?
ct?
a. Add
r D str

r D str
b. Subtract
c. Unknown
2. Which function executes first: Sinee or Divide?
t fo l In

t fo l In
a. Sine
b. Divide
c. Unknown
3. Which function executes
es first:
ecutes first Random
Ran
Ran Number,
umber, Divide or
o Add?
No na

No na
a. Random Number
mber
b. Divide
c. Add
d. Unknown
nown
tio

tio
4. Which
ch function executes
execu last: Number, Subtract or Add?
t: Random Num
a. Random Number
ndom Numb
b. Subtract
Na

c. Add
d. Unknown
Unkno
Unkn
5. What ar
are the three
hree parts of a V
a. Front panel window
VI?
Na
b. Block diagram window
windo
c. Project
d. Icon/connector pane

National Instruments | 1-45


LabVIEW Core 1 Course Manual Lesson 1 Navigating LabVIEW

Self-Review: Quiz Answers Notes

uti ts

uti ts
rib en

rib en
on

on
ist um

ist um
1. Which function executes first: Add or Subtract?
t?
a. Add
b. Subtract
r D str

r D str
c. Unknown
2. Which function executes first: Sine or Divide?
a. Sine
b. Divide
t fo l In

t fo l In
c. Unknown
3. Which function executess fir
first?
a. Random Number
b. Divide
No na

No na
c. Add
d. Unknown
n
4. Which function
on executes llast: Random,
nction andom, Subtract or Add?
m, Subtr
tio

tio
a. Random
ndom Number
b. Subtract
ubtract
c. Add
dd
d. Unknown
Na

5. What are th
a. Fron
b.. Bl
the three partss of a VI?
Front panel window
Block diagram
Blo
c. Project
gram window
Na
d. Icon/connector pane

National Instruments | 1-47 1-48 | ni.com


Lesson 2 Troubleshooting and Debugging VIs

Troubleshooting and Debugging VIs


Is
2 A. Correcting Broken VIs
If a VI does not run, it is a broken, or nonexecutable, VI. The Run button appears
ear bbroken when the
VI you are creating or editing contains errors.

uti ts

tio s
ibu nt
To run a VI, you must wire all the subVIs, functions, and structures
es with the corre
correct data types for

rib en
expe You can use
the terminals. Sometimes a VI produces data or runs in a way you do not expect. u lock
k diagram, the
If the button still appears broken when you finish wiring the block th VI iss broken
oken and
LabVIEW to configure how a VI runs and to identify problems ms with block ddiagram organizatio
anizatio
organization cannot run.

on

n
or with the data passing through the block diagram.

str me
Topics Finding Causes for Broken VIs

ist um
Warnings do not prevent you from running a VI. Theyey are designed to help
p you
ou avoid poten
potential
A. Correcting Broken VIs problems in VIs. Errors, however, can break a VI. You must resolv
resolve any errors
ors before yo
you can run
the VI.
B. Debugging Techniques

Di tru
C. Undefined or Unexpected Data Click the broken Run button or select ViewError
Erroror List to fin
find out why a VI is broke
brok
broken. The Error
list window lists all the errors. The Items withth errors sect
section listss thee names of aall items in
r D str
D. Error Handling memory, such as VIs and project librariess thatat have
have error
errors. If twoo or more
more items have the same
plication
cation inst
name, this section shows the specific application instanc
anc for each
instance ach item. The err
er
errors and warnings
section lists the errors and warnings for thee VI you select
se in the Items with errors section. The

s
Details section describes the errors and in some case mmends
cases recommendsends how to ccorrect the errors. Click
the Help button to display a topic in the LabVIEW
LabVIE Help that hat describes
describ th the error in detail and
t fo l In

l In
includes step-by-step instructionss for correcting the error.
ror.
Click the Show Error button n oor double-click
e-click the error
or description
description to highlight the area on the block
diagram or front panel thatt contain
contains the error.
Figure
gure 2-1. Example
E
Ex of the Error Lis
List Dialog Box
No na

No na
tio

tio
Na

Na
National Instruments | 2-1 2-2 | ni.com
LabVIEW Core 1 Course Manual Lesson 2 Troubleshooting and Debugging VIs

Common Causes of Broken VIs 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.
The following list contains common reasons why a VI is broken while youu edit it:
Determine if the data that one function or subVI passes is undefined. This
his oofte
often happens with
The block diagram contains a broken wire because of a mismatch of data
ta types or
o a loose, numbers. For example, at one point in the VI an operation could havee divided a num
number by zero,

uti ts

uti ts
unconnected end. Refer to the Correcting Broken VIs topic of the LabVIEW Help for thus returning Inf (infinity), whereas subsequent functions or subVIs
ubVIs
VIs were expeexpecting
information about correcting broken wires. numbers.
A required block diagram terminal is unwired. Refer to the Using Link Block Diagram
singg Wires to Lin If the VI runs more slowly than expected, confirm that you turned
ned off execution
exec
execu highlighting
ghl

rib en

rib en
Objects topic of the LabVIEW Help for information about settingng required inputs andd outputs.
out amss when you aare not usingg them
in subVIs. Also, close subVI front panels and block diagrams
A subVI is broken or you edited its connector pane afterr you
u placed its icon on
n thee block because open windows can affect execution speed.

on

on
diagram of the VI. Refer to the Creating SubVIs topicc of the LabVIEW
LabVIE Help for information Check the representation of controls and indicators to see if you are receiving
rec erflow becaus
overflow becau
because
about subVIs. you converted a floating-point number to an integerer orr an integer tto a smaller
aller integer. For

ist um

ist um
nction
on that only acceptss 8-bit integers.
example, you might wire a 16-bit integer to a function
B. Debugging Techniques nteger
ger to an 8-b
This causes the function to convert the 16-bit integer esentation,
entation, pote
8-bit representation, potent
potentially
causing a loss of data.
If a VI is not broken, but you get unexpected data,
ta, you can use tthe following
owing
g techniques
technique to identify
and correct problems with the VI or the block k diagram
agram data fflow: execu
ecute
te zero iterations
Determine if any For Loops inadvertently execute ite andd produce empty
em arrays.
operly
erly unless
Verify you initialized shift registers properly unless you intend
d them to save ddata from one
r D str

r D str
Wire the error in and error out parameters
rs att the bottom
ters botto of most
ost built-in
built-in VIs and
a functions.
untered
ered in each node on
These parameters detect errors encountered n the block diagram
diagr and indicate if
diag execution of the loop to another.
and where an error occurred. You also can use tthe ameters
eters in the VI
these parameters VIs you build. Check the cluster element order at the source and destination
ation
on points. LabV
LabVIEW detects data
electt ViewErr
To eliminate all VI warnings, select ViewError List and d place a checkmark
che in the Show type and cluster size mismatches at edit time, bu
but it doess nott detect
de
detect mism
mismatches of elements of
Warnings checkbox to see allll warnings for tthe VI. Determine
etermine the ca
causes and correct them in the same type.
t fo l In

t fo l In
the VI. der.
Check the node execution order.
Use the Positioning tool to triple-click
lick a wire to highlight its entire
eent path and to ensure that the Check that the VI does not contain n hidd
hidde VIs. You inadvertently
hidden subVIs. inadver might have hidden a
roper
per term
wires connect to the proper terminals. subVI by placing one directly
irectly oon top of another
herr node or by decreasing
de the size of a structure
Use the Context Help c
elp window to check thee default values for each function and subVI on the without keeping the subVI
bVI in view
view.
block diagram. VIs and
d function
functions pass default
efault
fault values if rrecommended or optional inputs are ory off subVIs the
Check the inventory th VI usess agai
agains
againstt the resu
r
results of ViewBrowse Relationships
No na

No na
xample,
ple, a Boolean
unwired. For example, Boolea
Boole input mightght be set to TRUE if unwired. VIs and ViewB
This VIs SubVIs ationships
ationshipsU
ViewBrowse RelationshipsUnopened SubVIs to determine if any
extra subVIs exist.
st. Also open the VII Hiera
era
Hierarchy wind
window to see the subVIs for a VI. To help
d dialog
Use the Find log box to ssearch for subVI
ubV text,
subVIs, xt and other objects to correct throughout
rect results caused
avoid incorrect caus by hidden en V
VIs, sspecify that inputs to VIs are required.
the VI.
tio

tio
Hierarchy to find unwired sub
Select ViewVI Hiera
Hierar subVIs. Unlike unwired functions, unwired VIs do
ways generate errors
not always er nleess
ss you config
unless configu
configure an input to be required. If you mistakenly place Execution
ution
ion Highlighting
Highl
Highli ingng
an unwired
wired subVI oon the block
ck
k diagram, itt executes when the block diagram does. View ann animation of tthe execution
onn of the bloc
block diagram by clicking the Highlight Execution
Consequently,
equently, the
th VI might
ght pperform
orm
rm ext
extr
extra actions. button.
n.
Use execution highlighting
hting
ng to w
watc
watch the data move through the block diagram.
Na

Single-step through
Use the Probe
functi
functio
P
h thee VI to view each action of the VI on the block diagram.
oll to observe intermediate
tool
ecially those per
functions, especially
Click the Retain
int
performing I/O.
data values and to check the error output of VIs and

Values button on the block diagram toolbar to retain wire values for use
n Wire Valu
Na
Execution hhighlighting
her using
another uus
ting shows the
the m
movement of data on the block diagram from one node to
bles that move along the wires. Use execution highlighting in conjunction with
bubbles
ee how data values move from node to node through a VI.
single-stepping to see
ature allows
with probes. This feature a you to easily check values of data that last passed through any
wire.
Use breakpoints to pause execution, so you can single-step or insert probes.

National Instruments | 2-3 2-4 | ni.com


LabVIEW Core 1 Course Manual Lesson 2 Troubleshooting and Debugging VIs

(MathScript RT Module) In MathScript Nodes, execution highlighting shows the progression Probe Tools
from one line of script to another using a blue arrow that blinks next to the line that is executing
currently. Use the Probe tool to check intermediate values on a wire as a VI runs.

uti ts

uti ts
Note Execution highlighting greatly reduces the speed at which the VI ru
runs.

Figure 2-2. Example of Execution Highlighting


hting
g in Use eries of operations,
Use the Probe tool if you have a complicated block diagram with a series opera any one of

rib en

rib en
utionn highlighting,
which might return incorrect data. Use the Probe tool with execution hi
highlightin
ghlightin single-stepping,
gle-step
step
ata is available,
and breakpoints to determine if and where data is incorrect. If data availa
availab the probe be

on

on
immediately updates and displays the data in the Probe Watch Window dduring execution ution
akpoint.
oint. When eexecution
highlighting, single-stepping, or when you pause at a breakpoint. on pauses
auses at a nod
no
node
n probe
because of single-stepping or a breakpoint, you also can obe the wire that just
st executed to ssee the

ist um

ist um
value that flowed through that wire.

Tip If you want a probe to display thee data


ata that
that flowed
flowe through
flow ugh the wire during
dur
duri the last
alues button on the block
VI execution, click the Retain Wiree Values ck diagram ttoolbar.
r D str

r D str
Types of Probes
You can check intermediate values on a wire re when a VI
V runs by y using a generi
ge
generic
neri probe, by using an
indicator on the Controls palette to view
w the data,
data, by using a supplied
pplied probe
probe, by using a customized
ew probe.
supplied probe, or by creating a new
t fo l In

t fo l In
Single-Stepping
Single-step through a VI to view each
ch action of the VI on the block ddiagram as the VI runs. The Note (MathScript RT Module) Yo You can view
w the data in a script in a MathScript Node
own as
single-stepping buttons, shown a follows,
ws affect execution
xecution only in a VI or subVI in single-step sing a LabVIEW
as a VI runs by using IEW MathScript
Script probe.
mode.
Generic
No na

No na
Use the generic probe
be too view the
the data
da that passes
d asses through a wire. Right-click a wire and select
eric Probe fr
Generic
Custom ProbeGeneric from thee sh
shortcutt menu tto use the generic probe.
ep mode by click
Enter single-step clicking thee Step
ep IInto or Step Over button on the block diagram
The generic probe
robee displays the
th data. You cannot configure the generic probe to respond to the data.
annot con
toolbar. Movee thee cursor over the Step nto,, Step Ov
ep Into
Into, Over, or Step Out button to view a tip strip that
tio

tio
he next step if you
describes the yo clickk that button. You
y Yo can single-step through subVIs or run them LabVIEW W displays the generic
ge
gen probe
robe when you right-click
rri a wire and select Probe, unless you
y.
normally. already specified custom or supplied
pecified a custo
cus upplied for the data type.
pplied probe fo
Whenn you
ou single-step
single-ste through
gh a VI,
V nodes
odes blink
b to indicate they are ready to execute. If you You can custom probe
n debug a cus obe similarr to a V
be sim VI. However, a probe cannot probe its own block
gle-step through a VI with
single-step ithh execution
exec
executi hi
highlighting on, an execution glyph appears on the icons diagram,
agram, nor the block
b diagram
am of any of its subVIs. When debugging probes, use the generic
agram
Na

tha are currently


of the subVIs that rrently
ntly running.
running

Na
probe.
obe.

Using Ind
Indicators
You also
rs to View Da
Data
o can use an indicator to view the data that passes through a wire. For example, if you view
numeric data, you can n use a ch
chart within the probe to view the data. Right-click a wire, select
Custom ProbeControls fr from the shortcut menu, and select the indicator you want to use. You
also can click the Select a Control icon on the Controls palette and select any custom control or

National Instruments | 2-5 2-6 | ni.com


LabVIEW Core 1 Course Manual Lesson 2 Troubleshooting and Debugging VIs

type definition saved on the computer or in a shared directory on a server. LabVIEW treats type Breakpoints
definitions as custom controls when you use them to view probed data.
Use the Breakpoint tool to place a breakpoint on a VI, node, or wire and pause execution at that
he wire yyou
If the data type of the indicator you select does not match the data type of the location.

uti ts

uti ts
right-clicked, LabVIEW does not place the indicator on the wire.

Supplied

rib en

rib en
Supplied probes are VIs that display comprehensive information n about
bout the data that passes
assess thro
through ata passes
When you set a breakpoint on a wire, execution pauses after data asses through
throug
throu the wire aand the
a wire. For example, the VI Refnum Probe returns information on about
boutt the VI nname, the
he VI path, and iagram
am to pause execution
Pause button appears red. Place a breakpoint on the block diagram ion after all

on

on
the hex value of the reference. You also can use a suppliedd probe
obe to respond
respo
respon based d on the
he data tha
that order appears rre
nodes on the block diagram execute. The block diagram border red and blinkss to reflect
flows through the wire. For example, use an Error probee on an error cluster
clu ive the status,
to receive statu the placement of a breakpoint.

ist um

ist um
code, source, and description of the error and specify if you
u want to se ditional breakpoint
set a conditional breakp
breakpo if
an error or warning occurs. When a VI pauses at a breakpoint, LabVIEW brings thee block diagr diag
diagram to thehee front and use
uses a
pt that
marquee to highlight the node, wire, or line of script hat contains tthe breakpoint.
akpoint.
point. When yoyyou move
The supplied probes appear at the top of the Customm Probe shor
tom enu. Right-click a wire and
shortcut menu. ea of the Breakpoint
the cursor over an existing breakpoint, the black area Bre
Brea t tooll cursor appears
app
appe white.
select Custom Probe from the shortcut menu to select
elect a supp obe. Only probe
supplied probe. probes that match
pear
ear on the short
the data type of the wire you right-click appear nu.
shortcut menu. on, the VI pauses
When you reach a breakpoint during execution, pause and the Pause
ause button appears red.
You can take the following actions:
r D str

r D str
Refer to the Using Supplied Probes VI inn the
he labview\
labview\examples\general\probes.llb
labview ples\genera
ples\general for Single-step through execution using thee single-step
single-stepp uttons.
ttons.
single-stepping buttons.
an example of using supplied probes.
Probe wires to check intermediatee values.
ues.
nel controls.
Change the values of front panel
Custom
t fo l In

t fo l In
ntinue running to the nextt breakpoint or until the VI finishes
Click the Pause button to continue
Use the Create New Probe dialogg box to createcrea a probe
cre obe based on an existing probe or to create a
running.
new probe. Right-click a wirere and select
ect Cu robeNew from the shortcut menu to display
Custom ProbeNew
alog
the Create New Probe dialog og box. Create a probee when you wanwant to have more control over how
LabVIEW probes the dataata that
hat flows ththrough a wire
wire.. When yo
you create a new probe, the data type Suspending Execution
xecution
cution
ata type
of the probe matches the data type of the
t wiree you right-clicked.
right
right-clicke
-click If you want to edit the probe you
Suspend execution off a subVI
bVI to edit
edi values of controls anand indicators, to control the number of
No na

No na
pen it from the
created, you must open the ddirectory where you sa
sav
saved it.
ns before
times the subVI runs efore returning
returni to the caller,
ler, or to go back to the beginning of the execution
obe from the
After you select a probe th Custom Probe shortcut
om Pro
Prob rt menu, navigate to it using the Select a
rtc of the subVI. Youu cann cause all calls
c subV
bV to start with
to a subVI w execution suspended, or you can
Control palettete option,
ption, or create
cre
crea a new w probe
obe using
us the t Create New Probe dialog box, that probe ific call to a sub
suspend a specific subVI.
becomes thee default probe forfo that data type, and LabVIEW
La
L loads that probe when you right-click
tio

tio
To suspendd all calls to a subVI,
sub
su pen the subVI an
open and select OperateSuspend when Called. The
a wire andd select Probe from
fr menu LabVIEW only loads probes that exactly match
the shortcut menu.
utomatically
omatically suspends
subVI automatically susp hen another VI calls it. If you select this menu item when
when
the dataa type
ype of the wire
wi you right-click.
ht-click.
t-click. That is,
i a double precision floating-point numeric probe
stepping,
pping, the su
single-stepping, sub
subVI does not
ot suspend im
immediately. The subVI suspends when it is called.
ot probe
cannot obe a 32-bit unsigneded integer
ger wire eeven though LabVIEW can convert the data.
To suspend a specific
specif subVII call, right-click
right
rig ck the subVI node on the block diagram and select SubVI
Na

Note
the pr
I you want a custom pprobe to be the default probe for a particular data type, save
If
probe in the user.lib\
vi.lib\_probes
vi
vi.
up
user.lib\_probes\default directory. Do not save probes in the
probes directory
upgrade or reinstall.
direct
directo because LabVIEW overwrites those files when you Na
ode Setup from the shortcut
Node
suspend execut

he VI H
The
execution only

Hie
Hierarchy
ortcut
ut menu. Pla
y at that instanc
Pl
Place a checkmark in the Suspend when called checkbox to
instance of the subVI.

y window, which you display by selecting ViewVI Hierarchy, indicates


er a VI is paused
whether aused or suspe
suspen
suspended.

An arrow glyph indicatess a V


VI that is running regularly or single-stepping.

National Instruments | 2-7 2-8 | ni.com


LabVIEW Core 1 Course Manual Lesson 2 Troubleshooting and Debugging VIs

A pause glyph indicates a paused or suspended VI. Before you convert data to integer data types, use the Probe tool to check intermediate
floating-point values for validity. Check for NaN by wiring the Not A Number/Path/Refnum?
function to the value you suspect is invalid.
A green pause glyph, or a hollow glyph in black and white, indicates
cates a VI that ppauses when

uti ts

uti ts
called. termine
ermine if a VI pproduces
Do not rely on special values such as NaN, Inf, or empty arrays to determine
undefined data. Instead, confirm that the VI produces defined data byy making
aking the VI report an error
dicates
tes a VI that is currently
A red pause glyph, or a solid glyph in black and white, indicates a.
if it encounters a situation that is likely to produce undefined data.
paused.

rib en

rib en
For example, if you create a VI that uses an incoming array to o auto-index For Loop,
uto-index a F determine
p, determi
etermi
ended.
ed.
An exclamation point glyph indicates that the subVI is suspended. what you want the VI to do when the input array is empty. Either er produce aan output
ut error
rror code,

on

on
st
s
substitute defined data for the value that the loop creates, or use a Case structure thatt does not
execute the For Loop if the array is empty.

ist um

ist um
Note A VI can be suspended and paused
d at the same tim
time.
D. Error Handling
Determining the Current Instance
ce of a SubVI
SubV No matter how confident you are in the VI you create,
ate, you cann
cannot predict
ict ev
every
very
ery problem a user can
When you pause a subVI, the Call list pull-down own
wn menu on the toolbar ar listss the chain of
o callers from encounter. Without a mechanism to check forr errors,
rors, you kn
kno
know only y thatt the VI doe
do
does not work
d where errors oc
properly. Error checking tells you why and occur.
r D str

r D str
the top-level VI down to the subVI. This list istt is not the sa
sam
same list you see when you yo select View
Browse RelationshipsThis VIs Callers, ers, which lists aall calling
ng VIs regardles
re gardle of whether they
regardless
are currently running. Use the Call listt menunu to determ
determine thee current instanc
instance of the subVI if the ticipation,
pation, detection,
Error handling is the mechanism for anticipation, de
detec
tec ndd resolution off warnings
and w and errors.
block diagram contains more than onene instance.
innstance.
stance. Wh When you select
ect a VI from the Call list menu, its nentt in your LabVIEW
Error handling is an essential component Lab
La W application
plication development.
dev With error
block diagram opens and LabVIEW W highlights
highlights th the current
nt instance of the subVI. handling you quickly pinpoint the source
rce of pr
progra
ogra
programming g errors.
ors. Without it, you might observe
t fo l In

t fo l In
unexpected behavior but strugglee to find the source
sour of the
sou he problem.
unction to v
You also can use the Call Chain function vi
view the chain
in of callers
callers from the current VI to the
top-level VI. uable when
Error handling is also extremely valuable wh you test your application
applica to ensure that your error
reporting is meaningful andd that the
th error handling
ha stop your application when an error
code safely stops
ring stress
occurs. For example, during stress tes re setting values or conditions that are beyond the
testing you are
C. Undefined or Unexpected
Unexpe d Data pacity
normal operational capacityty of your ap
aapplication
p on which often rresult in errors. When such errors
No na

No na
nsure proper
occur, you want to ensure proper shu
shutdown off your applicat
applic
application.
Undefined data, which
hich are NaN
aN (not
(no a number)) or Inf
In (in
(infinity), invalidate all subsequent
(inf
ing-point
point operati
operations. Floating-point urn th
operations return lowing two symbolic values that indicate faulty
the following ontinues
nues to be important
Error handling continues iim nt after
ter an
a application
plica is deployed. Error handling can help
eaningless results:
computations or meaningless re detect system and environment
environmen differencessuch
ncessuch
ssu aas differences in file systems, memory, and disk
NaN (nott a number) represents
repre a floating-point
oating-point value
v that invalid operations produce, such as ational Instrume
resources. National ongly recomme
Instruments strongly recommen
recommends using error handling.
tio

tio
taking the
he square root of a negative
gative number.
number
Inf (infinity)
infinity) represents
repres
repr a floating-point
oati
ating-point
ng-point value
va that valid operations produce, such as dividing Automatic
omatic
matic Error
Erro
Err Handling
ndling
mber by zero
a number zero.
By default,
ult, LabVIEW automatically
matical
atica handles
handle
andle any error when a VI runs by suspending execution,
ghlighting the su
highlighting subVI or functi
nction
on w
function whe
where the error occurred, and displaying an error dialog box. In
Na

LabVIEW
abVIEW does nno
underflow for fl
Floating-Poi
Floating-Poin

ing-p
Floating-point
not check
k for overflow or underflow conditions on integer values. Overflow and

metic.
metic
Floating-Point Arithmetic.
nt numbers iis in accordance with IEEE 754, Standard for Binary
point
floating-point

erations propa
operations propag
propagate NaN and Inf reliably. When you explicitly or implicitly
convert NaN or Inf to integers or Boolean values, the values become meaningless. For example,
Na
thee error dialog bbox, each
the user.
to display to tth

To disable automatic
Execution from the
h error
rror has a num
numeric code to identify it and a corresponding error message

handling for the current VI, select FileVI Properties and select
atic error handli
handlin
he Category ppull-down menu. To disable automatic error handling for any new,
uces Inf. Converting Inf to a 16-bit integer produces the value 32,767,
dividing 1 by zero produces elect T
blank VIs you create, select ToolsOptions and select Block Diagram from the Category list. To
which appears to be a normal value. disable automatic error handling
d for a subVI or function within a VI, wire its error out parameter
to the error in parameter of another subVI or function or to an error out indicator.

National Instruments | 2-9 2-10 | ni.com


LabVIEW Core 1 Course Manual Lesson 2 Troubleshooting and Debugging VIs

Manual Error Handling Warnings


You may choose to handle errors without relying on automatic error handling.
ling. FFor example, if an A warning is defined as an error cluster with a nonzero code value and a FALSE
AL status value.
icatiion
on to sto
I/O VI on the block diagram times out, you might not want the entire application stop and display Although most errors have negative code values and warnings have positive values, this is not
ve code va
an error dialog box. You also might want the VI to retry for a certain period
eriod of time. universally true. Therefore you should rely on both the status value and
ndd the code valu
value to detect
va

uti ts

uti ts
errors and warnings.
In LabVIEW, you can make these manual error handling decisions on the block dia
diagram of the VI
di
using the following methods: Warnings are typically considered less severe than errors. Some APIs Is and functions,
funct
functi such as the

rib en

rib en
ver, other APIs, such ass thee VI
Match Regular Expression function, only report errors. However, VISA
Use the LabVIEW error handling VIs and functions on thee Dialog face palette to
Use Interface
ialog & User
arnings.
ngs.
API for controlling stand-alone instruments, often reports warnings.
notify and prompt users. For example, if LabVIEW encounters
counters error, you can
ers an error an display the

on

on
error message in different kinds of dialog boxes. Unlike when an error occurs, nodes execute normally when hen LabVIEW ddetects a warning.
arning. Even
Use error clusters and the error in and error out parameters
arameters most VIs and functions to
meters of mo though code executes normally, it is important that youu monitor
onitor warn
warni
warnings ring developm
during developmen
development to

ist um

ist um
cted you can fix the
manage errors. For example, when an error is detected t errorr programmatically
programmatical and ensure proper behavior of your application.
ction
n to the error in input
then wire the error out output of the VI or function ut of the Clear E
Er
Errors VI.
Explain Error Dialog Box
Tip Use error handling in conjunction
tion with the deb
debugging
g tools
ols to find and
an manage
When an error occurs, right-click within the cluster
ster border an
and
a select
ct Explain Error from the
xplain Erro
errors.
shortcut menu to open the Explain Error dialog
ialog box. Th
The Explain
in Error dialog box contains
r D str

r D str
nu includes an Explain
information about the error. The shortcut menu plain Warning ooption if the VI
Error Clusters contains warnings but no errors.
VIs and functions return errors in one
ne of two ways
wayswith numeric
meric error cco
codes or with an error rrorr dialog box from the
You also can access the Explain Error he HelpExplai
HelpExplain Error menu.
umeric
ric error code
cluster. Typically, functions use numeric cod
codes, and VIs
Is use an error ccluster, usually with error
t fo l In

t fo l In
inputs and outputs. Use the errorr cluster control
contro ndicators
ators to crea
controls and indicators create error inputs and outputs
in subVIs. Detect and Report Errors
rrors
Error handling in LabVIEW
W follows
follow the ddataflow model. Just as ddata values flow through a VI, so
Tip All error clusters
ers on a block diagram
gram
ram typically pr
provide the same standard error in can error information.
and standard error
or out functio
functi
functionality.
No na

No na
To implement good error handling,
handling, yyou must determine th the aactions to take when an error occurs at
The standard errorr in and error oout clusters
te include
clude the ffollowing components of information: any point in your applic
cation.
ation. To b
application. be ith you
begin with, u must
must uti
util
utilize the error terminals on functions and
status is a Boolean
an value th rts TRUE
that reports TRU if an error occurred. rror cluster is implemented
VIs. Since the error im nted as a flow-through
w-th
w-thr parameter, you should propagate
ng the
errors by wiring he error ou he first
out cluster of the fir node
no you want to execute to the error in cluster
code is a 32-bit
bit signed integer
in that
hat identifies the
th error numerically. A nonzero error code of the next node you want to execute.te. You mustt con
co
continue to do this for sequences of nodes.
tio

tio
coupledd with a status oof FALSE warning rather than a error.
SE signals a war
rcee is a string that
source ttha identifies
es where the error
fies e occurred. As the VI runs, LabVIEW tests fo orr errors at eac
for each node. If LabVIEW does not find any errors, the
xecutes
utes normall
node executes normally. If LabVIEWEW detects an error or warning, the node passes the error to the
de. Any subVIs
next node. subV that you create
ccr e should
shou also implement this flow-through behavior.
Errors
rorss
Na

Ann error is defin

he code.
of the code
cod
defined as an
n error
ror cluster w

If LabVIEW detects an error, the no


with a status value of TRUE, regardless of the code value.

node passes the error to the next node without executing that part
nod Na Tip
error
erro
ch
When you
W ou perform any kkind of input and output (I/O), consider the possibility that
errors mightt occur. Almos
Almost all I/O functions return error information. Include error
checking in VIs, especial
especiall
especially for I/O operations (file, serial, instrumentation, data
ion, and comm
acquisition,
tely.
appropriately.
commu
communication), and provide a mechanism to handle errors

National Instruments | 2-11 2-12 | ni.com


LabVIEW Core 1 Course Manual Lesson 2 Troubleshooting and Debugging VIs

Propagating Errors and Warnings OK message with warningsDisplays a dialog box with any warnings and a single OK
button. After the user acknowledges the dialog box, the VI returns control to the main VI.
To ensure that error and warning information is propagated correctly, it is important
impo to use
shift-registers for error cluster wires in loops so that the warning information propagated through
ion is propa
prop Continue/Stop + WarningsDisplays a dialog box with any warnings gs and but
buttons, which the
all iterations. Refer to Figure 2-3 for proper use of the shift-register to propagate err
errors and
erro user can use to either continue or stop. If the user selects Stop, the VII calls the Stop
Sto function to

uti ts

uti ts
warnings to successive loop iterations. halt execution.

Figure 2-3. Use Shift Registers to Propagate Errors


rors and Warnin
Warnings
Ranges of Error Codes

rib en

rib en
VIs and functions in LabVIEW can return numeric error codes. des. Each produc
produ
product or group
oup of VIs

on

on
IEW Error Cod
defines a range of error codes. Refer to the Ranges of LabVIEW Code
Codes topic of thee LabVIEW
Help for error code tables listing the numeric error codes andd descri
description
ption for each
descriptions ach product and VVI
grouping.

ist um

ist um
W reserves
In addition to defining error code ranges, LabVIEW serves some error code
ode
de ranges for y
yo
you to use
Merging Errors and Warnings des in the range
in your application. You can define custom error codes ran of 8999
89999 through 8000,
8 5000
through 9999, or 500,000 through 599,999.
Use the Merge Error function to merge the error
ror out cluster
luster values
v from parallel
parallel sequences.
seq Refer
rro
orr information
to Figure 2-4 for an example of merging error informatio from parallel
arallel node sequences.
sequ
seq
r D str

r D str
Some numeric error codes are used by more re thann one gro
grou Is and functions
group of VIs functions. For example,
ating
ng a serial po
error 65 is both a serial error code, indicating out, and a netw
port timeout, netwo
networking error code,
Figure 2-4. Merge
erge
e Errors From Multiple
ple Sources
indicating that a network connection iss already
eady establi
established.
t fo l In

t fo l In
No na

No na
At the end of yourr application
plication after
af
afte
fter
te all error
ror sources
ces are merged
m into one error cluster, you must
report errors to the user
ser using th
the Simplele Erro
rror H
Error ler VI or another error reporting mechanism.
Handler

Simple Error Handler


Handl VI
Hand
tio

tio
By default,
ult,
t, the Simple E
Error Handler
ndler
dler VI display
displays a dialog with a description of any errors that
occurred
ed and does not report warnings.
nings. However, the Simple Error Handler VI can be configured
ings. Howe
Howev
for otherr error handling
handl
handli behavior.
avior.
vior. Youu can select
s the type of dialog from the following options:
Na

dialogD
dialogD
No dialogDisplays
handlin errors.
over handling
mess
OK message
ackno
acknow
acknowledges
s.
no dialog box

efault)
fault)Display
(default)Displays
box. This is useful if you want to have programmatic control

Displa a dialog box with a single OK button. After the user


the dialog box, the VI returns control to the main VI.
Continue or stop messageDisplays a dialog box with buttons, which the user can use to
op message
Na
top. If the user selects Stop, the VI calls the Stop function to halt execution.
either continue or stop.

National Instruments | 2-13 2-14 | ni.com


LabVIEW Core 1 Course Manual

Self-Review: Quiz
1. Which of the following will result in a broken run arrow?

uti ts

uti ts
a. A subVI is broken
b. The diagram includes a divide by zero
c. A required subVI input is unwired

rib en

rib en
d. A Boolean terminal is wired to a numeric indicator

on

on
ist um

ist um
2. Which of the following are the components and data types of the error cluster?
luster?
uster?
a. Status: Boolean
b. Error: String
c. Code: 32-bit integer
r D str

r D str
d. Source: String

3. All errors have negative error codes


des and
and all w
wa
warnings have positive er
error codes.
t fo l In

t fo l In
a. True
b. False
No na

No na
4. Merge Errors function
nction concatenates errorr information from
on concatena fr multiple sources.
a. True
b. False
tio

tio
Na

Na
National Instruments | 2-15
LabVIEW Core 1 Course Manual Lesson 2 Troubleshooting and Debugging VIs

Self-Review: Quiz Answers Notes


1. Which of the following will result in a broken run arrow?

uti ts

uti ts
a. A subVI is broken
b. The diagram includes a divide by zero
c. A required subVI input is unwired

rib en

rib en
d. A Boolean terminal is wired to a numeric indicatorr

on

on
ist um

ist um
2. Which of the following are the contents of the error
or cluster?
a. Status: Boolean
b. Error: String
c. Code: 32-bit integer
r D str

r D str
d. Source: String

3. All errors have negative error codes


des and
and all w
wa
warnings have positive er
error codes.
t fo l In

t fo l In
a. True
b. False
No na

No na
4. Merge Errors function
nction concatenates errorr information from
on concatena fr multiple sources.
a. True
b. False
tio

tio
Na

Na
National Instruments | 2-17 2-18 | ni.com
Lesson 3 Implementing a VI

Implementing a VI
3 A. Front Panel Basics
In the design phase of the software development method, you identify the inputs
uts and
an outputs of the
problem. This identification leads directly to the design of the front panel
nel window.

uti ts

uti ts
Inputs for the design can come from the following actions:
This lesson teaches you how to implement code in LabVIEW. These se skills
sk
kills
ills include designing a user acquiring from a device such as a data acquisition device or a multimeter

rib en

rib en
interface, choosing a data type, documenting your code, using looping
ing structur h as W
structures such While
Loops and For Loops, adding software timing to your code, displaying
playing your data as a plot,
ot, and reading directly from a file
manipulating controls on the front panel

on

on
making decisions in your code using a Case structure.

You can display the inputs of the problem on the front panel controls, such
nel with con
contr ch as numeric
numeric,
Topics

ist um

ist um
boolean, or string controls, but not all input appears on the
he front panel.
pan
pane
A. Front Panel Basics
You can display the outputs of the problem with indicators,
ators, such as
ndicators, a graphs, LEDs, or log
hs, charts, or LE
LED
B. LabVIEW Data Types the outputs to a file. You also can output data too a device using
using signal generation.
eration.
C. Documenting Code
r D str

r D str
D. While Loops Designing Controls and Indicators
ndicators
dicators
E. For Loops When choosing controls and indicators,, make
ake sure that they are
ree appropriate fo
for the task you want
F. Timing a VI to perform. For example, when you wantt to determine
determin
determi the frequency
requenc
ency
y of a sine
sin wave, choose a dial
ay te
control, or when you want to display emperature,
mperature, choose a thermometer
temperature, ermometer iindicator.
G. Data Feedback in Loops
t fo l In

t fo l In
hart
H. Plotting Data Waveform Chart Labels
I. Case Structures Make sure to label controlss and iindicators
ors cclearly. These labels h
he
help
l users identify the purpose of
r. Also,
each control and indicator. so, clea
clear labeling helps
elps you docum
doc um your code on the block
document
ndicator
cator labels
diagram. Control and indicator laabels correspond
c ond
nd to the names
name of terminals on the block diagram,
-1.
as shown in Figure 3-1.
No na

No na
Figure
e 3-1.
1. Front Panel
Pan Controls
trols and Indicators
ndicat Appear on Block Diagram
tio

tio
Na

Na
1 Front Pa
Panel Window
w 2 Block Diagram

National Instruments | 3-1 3-2 | ni.com


LabVIEW Core 1 Course Manual Lesson 3 Implementing a VI

Control and Indicator Options Block Diagram Terminals and Data Types
You can set default values for controls and indicators. Figure 3-2 shows thee Up
Upper Temperature The block diagram terminals visually communicate to the user some informationmati about the data
control with a default value of 35 C. By setting a default value, you can assume reasonable value
me a re type the terminals represent. For example, in Figure 3-3, Height (cm) iss a double-p
double-precision,
for a VI if the user does not set another value during run-time. floating-point numeric. This is indicated by the color of the terminal, orange,
range, the text shown
ange, and by th

uti ts

tio s
on the terminal, DBL.
Complete the following steps to set the default value of a control orr indicator:
ndicator:

ibu nt
1. Enter the desired value. Figure 3-3. Terminal Data Type Example
ample
ple

rib en
2. Right-click the control or indicator and select Data OperationsMake
rationsMake
onsMake C
Currentt Value
lue
Default from the shortcut menu.

on

n
str me
Figure 3-2. Setting Default
faultt Values

ist um
Tip Terminal names correspond to thee labels
bels of the controls
cco and indicators on
o the front

Di tru
ect Find control or Find
panel. Right-click a terminal and select dicator from the shortcut
d indicator
cator
ator on the fron
menu to locate the control or indicator front panel.
r D str
Shortcut Menus

s
All LabVIEW objects have associateded shortcut
shortc
hortcut
ut men
menu
menus, also known
own as conte
context menus, pop-up
menus, and right-click menus. As youu create a VI, use thee shortcut menu items to change the
t fo l In

l In
appearance or behavior of front panel and block diagramm objects.
objects. To ac
aaccess the shortcut menu,
right-click the object.

utt menu
Figure 3-4 shows a shortcut menu for a control and
nd
d terminal.

Figure 3-4.
4. Shortcut Men
Menus for Front Panel and Block Diagram Objects
No na

na
Tip Youu can also re
reinitialize
ze values
alues to th
their default values.
tio

tio
Tip
p To initializ
initialize or re-initialize
initialize all
ll controls
con
co and indicators on the front panel at the same
time, select Ed
E
EditMake kee Current Values
Va
Val Default or EditReinitialize to Default
Values from the LabVIEW
bV W menu menu.
Na

B.. LabVIEW Data


Many differe
ata

dataa types in
dynamic
a Types
different data types
i Lesson
ypes exist for ddata. You already learned about numeric, Boolean, and string
on 1, Navigating LabVIEW. Other data types include the enumerated data type,
ic data, andd others. Even within numeric data types, there are different data types, such as
Na
ctional numbers.
whole numbers or fractional n

National Instruments | 3-3 3-4 | ni.com


LabVIEW Core 1 Course Manual Lesson 3 Implementing a VI

Property Dialog Boxes Numeric Data Types


Objects also have property dialog boxes that you can use to change the lookok oor behavior of the The numeric data type represents numbers of various types. To change the representation
repre type of a
objects. Right-click an object and select Properties from the shortcut menu
nu to access
acce the property tation,, aas shown in
number, right-click the control, indicator, or constant, and select Representation,
sentation
dialog box for an object. Figure 3-5 shows the property dialog box forr the Height (cm)
(cm terminal
(c Figure 3-6.

uti ts

bu nts
shown in Figure 3-4. The options available on the property dialog box
ox for an object are similar to
the options available on the shortcut menu for that object. Figure 3-6. Numeric Representation
n

rib en
Figure 3-5. Property Dialog Box for a Numeric
mericc Terminal

on

n
e
tio
ist um

um
r D str

str
tri
t fo l In

t fo l In
No na

No na
You can selectt multiple
ultiple objects
objec on thee frontnt pan
panel or the block diagram and edit any properties the

r
objects share.e. To select multiple
mult jects,
s, use the Positioning
objects, P
Po tool to drag a selection rectangle
tio

tio
around all of the objects yo
you wantt to edit
dit or hold down
d the <Shift> key while clicking each object.
ick
Right-clickck an object from
fr
fro the selection
election
lection and sel
select Properties from the shortcut menu to display When you ou wire two or mom
more numeric
mer
eric
ic inputs of d
di
different representations to a function, the function
rties dialog box. The Properties
the Properties
roperties operties didialog box only displays tabs and properties that the usuallyy returns
turns the dat
data in the larger,
ger,
er, or wider, representation. The functions coerce the smaller
ects you select sh
objects lect
ect sim
share. Select si
similar obje
objects to display more tabs and properties. If you select esentations
tations to the
representations th widestt repre
repr ntation
ation bbefore execution. LabVIEW places a coercion dot on
representation
bjects
jects that do not
objects no share any common pproperties, the Properties dialog box does not display any the terminal where
wher the conversion
version
rsion takes
ttake place.
l Refer to Numeric Conversion for more information.
Na

tabs or propertie
properties.
Na da type includes
The numeric data
sign integers,
sig
numbers, signed egers,
ludes the following
fo
fol
gers, unsigned integers,
i
subcategories of representationfloating-point
and complex numbers.

National Instruments | 3-5 3-6 | ni.com


LabVIEW Core 1 Course Manual Lesson 3 Implementing a VI

Floating-Point Numbers Integer word lengthThe number of integer bits in the bit string that LabVIEW uses to represent
all possible values of the fixed-point data, or, given an initial position to the left or right of the most
Floating-point numbers represent fractional numbers. In LabVIEW, floating-point
ng-po numbers are
significant bit, the number of bits to shift the binary point to reach the most ost sign
signi
significant bit. The
represented with the color orange.
integer word length can be larger than the word length, and can be positive tive or negative.
negat
negativ

uti ts

uti ts
Single-precision (SGL)Single-precision, floating-point numbers have ave 32-bit IEEE
IEE
ers when memo
single-precision format. Use single-precision, floating-point numbers mem
memory savings are Integers
important and you will not overflow the range of the numbers Integers represent whole numbers. Signed integers can be positive
ive or negative.
negative Use thee unsigned
un

rib en

rib en
ve. In LabVIEW,
integer data types when you know the integer is always positive. LabVIEW integers
gers are
Double-precision (DBL)Double-precision, floating-point numbers mbers have 64-bit
6 IEEE
EEE
represented with the color blue.

on

on
ormat for nume
double-precision format. Double-precision is the default format numer cts. For most
numeric objects.
situations, use double-precision, floating-point numbers gers,, the VI rounds
When LabVIEW converts floating-point numbers to integers, roun the inputut to the nearest
near

ist um

ist um
wo integers,
integer. If the value of the input is midway between two ntegers, the function
n returns the ne
nea
nearest
ded-precisi
-precision
Extended-precision (EXT)When you save extended-precision on nu
numbers to o disk, LabVIE
LabVIEW
even integer.
mat. In memory
stores them in a platform-independent 128-bit format. memory, y the sizee and precision vvary
ion, floating-poi
depending on the platform. Use extended-precision, berss only when nnecessary.
floating-point numbers Byte (I8)Byte integer numbers have 8 bits of storage
rage and a ra
range of 128
28 to 127.
meticc vary among platforms.
The performance of extended-precision arithmetic orms.
6 bits
Word (I16)Word integer numbers have 16 ts of storage and a rangee of 32,768
32,76 to 32,767.
r D str

r D str
Fixed-Point Data Type Long (I32)Long integer numbers havee 32 2 bits of stora
storage andd a range of 2
2,14
2,147,483,648 to
The fixed-point data type is a numeric dataa type that re representstss a set of rationa
ration
rational numbers using 2,147,483,647. In most cases, it is bestt to use a 32-bit integer.
ting-point
-point data type,
binary digits, or bits. Unlike the floating-point t hich allows the ttotal number of bits
which
LabVIEW uses to represent numbers rs too vary, you can
ca configure
figuree fixed-point
fixe
fixed-poin
poin numbers to always use rs have
Quad (I64)Quad integer numbers ave 64 bits oof storage
ge and
nd a range oof 1e19 to 1e19.
t fo l In

t fo l In
a specific number of bits. Hardwareare and targets tth
that onlyy can
an store and process
p data with a limited
or fixed number of bits then can store and procpro
process thee numbers.
mbers. You ccan specify the range and Byte (U8)Byte unsigned integer have 8 bits
ger numbers h
ha ts off storage and a range of 0 to 255.
mb
precision of fixed-point numbers.
ned in
Word (U16)Word unsigned integer numb ve 16 bits
numbers have bits of sto
stor
storage and a range of 0 to 65,535.
Note To represent
resent
nt a rational
rationa numberr using the fixed-point
fixed data type, the denominator Long (U32)Long unsigned
ed integer nnumbers have 32 bits
signed bits of sstorage and a range of 0 to
nal number
of the rational umber must be a power
ower
wer of 2, becau
because the binary number system is a 4,294,967,295.
No na

No na
mber
base-2 number er system.
Quad (U64)Quad integer numbers
uad unsigned inte umbe have
ave 64 bbits of storage and a range of 0 to 2e19.
oint data type w
Use the fixed-point u doo not nneed the dynamic functionality of floating-point
when you
representationn or when you want
w to workk with a target
targ
t that does not support floating-point Complexx Numbers
umbers
tio

tio
FPG target.
arithmetic, such as an FPGA t.
Complex numbers
umbers are concatenated
conc ed versions of flo
floa
floating-point numbers with a real and an imaginary
y the
Specify he encoding, w th,
h, and integer w
word length, word length of a fixed-point number when you want abVIEW, because
part. In LabVIEW, becau complex
plex
ex numbers are a type of floating-point number, complex numbers
umber
er to conform to a certain
the number ert bitt size. are alsoo represented
presented with
wi the color orange.
orange. There
The are three types of complex numbers.
T

Complex
omplex single-precision,
omplex Single (CSG)Complex
Complex (C sin floating-point numbers consist of real and
Na

The bbinary encoding


ncodingThe
ncoding
EncodingThe

lengt
Word lengthThe
ncoding
signe the sign
you select signed,

e total
ding of the fixed-point number. You can select signed or unsigned. If
ign bit is always the first bit in the bit string that represents the data.

otal number of
ble vvalues off the fixed-poin
possible
Certain targets might
o bits in the bit string that LabVIEW uses to represent all
fixed-point data. LabVIEW accepts a maximum word length of 64 bits.
ht limit data to smaller word lengths. If you open a VI on a target and the VI
Na
imaginary
maginary values

Complex Do
value in 32-bit
bit IEEE single

CDB)
DB)Comple
Double (CDB)Complex
single-
single-precision format.

Comple double-precision, floating-point numbers consist of real and


ginary values in 64-bitt IEEE double-precision
imaginary d format.

CXT)
CXT)
Complex Extended (CXT)Complex extended-precision, floating-point numbers consist of real
contains fixed-point dataa wit
with larger word lengths than the target can accept, the VI contains
EE extended-precision format. In memory, the size and precision of
and imaginary values in IEEE
broken wires. Refer to the documentation for a target to determine the maximum word length the
extended-precision numbers vary depending on the platform. In Windows, they have 128-bit IEEE
target accepts.
extended-precision format.

National Instruments | 3-7 3-8 | ni.com


LabVIEW Core 1 Course Manual Lesson 3 Implementing a VI

Numeric Conversion Latch when releasedChanges the control value only after you release the mouse button
within the graphical boundary of the control. When the VI reads it once,, the control reverts to
LabVIEW can represent numeric data types as signed or unsigned integers,, floating-point
float numeric ox but
its default value. This behavior works in the same manner as dialog box butto
buttons and system
epresentatio
esentatio types to the
values, or complex numeric values. Normally, when you wire different representation buttons. You cannot select this behavior for a radio buttons control.
inputs of a function, the function returns an output in the larger or widerr format. If you use a signed

uti ts

uti ts
integer with an unsigned integer, it will coerce to the unsigned integer.ger. If you use an unsigned Latch until releasedChanges the control value when you clickk itt and retains
retains the
th value until
integer with a floating point, it will coerce to the floating point. If you use a floatin
floating point number the VI reads it once or you release the mouse button, dependingg onn which one occurs
o last. You
with a complex number, it will coerce to the complex number. If you u use two nunum
numbers of the same cannot select this behavior for a radio buttons control.

rib en

rib en
type with different bit widths, LabVIEW will coerce to the larger rgerr of the two bbit widths.
hs.
To learn more about mechanical action, experiment with the Mechanical
chanical Act
Acti
Action of Booleans
eans VI in

on

on
gned
If the number of bits is the same, LabVIEW chooses unsigned d over signe
signed integers.
ers. For example
example, the NI Example Finder.
if you wire a DBL and an I32 to a Multiply function, thee result
ult is a DBL own
DBL, as shown n in Figure 33-
3-7. Figure 3-8. Boolean Mechanical
hanical
nical Action

ist um

ist um
LabVIEW coerces the 32-bit signed integer because itt useses fewer bits than the
he double-precision,
double-precis
double-preci
floating-point numeric value. The lower input of thee Multiply
ultiply func
funct ows
ws a red dot, ca
function shows called a
coercion dot, that indicates LabVIEW coerced thee data.
a.
r D str Figure 3-7. Numeric
ric Conversion Example
E e

r D str
1
t fo l In

t fo l In
1 Coercion Dot

Boolean Values
LabVIEW stores Booleanan data
ata as 8-
8-bit
bit values.
v Iff the 8-bit value is
i zero, the Boolean value is FALSE.
epresents
nts TRUE.
Any nonzero value represents TRUE In LabVIEW,
VIEW, thee colcolor green represents Boolean data.
No na

No na
Boolean values also mechanical action
lso have a mech on associated
ciated with them. The two major actions are
latch and switch. h. You
ou can selec
select from the follo
followin
following button behaviors:
Switch when pressedChanges
pressed
pressed es the
he control vavalue
v each time you click it with the Operating
Strings
tio

tio
tool. Thehe frequency with
w which
wi ch the VI reads tthe control does not affect this behavior. A string is a sequence of displayable
di
d ble or non-displa
non-displayable ASCII characters. Strings provide a
-independent
ndependent format
platform-independent for forr information
information and
an data. Some of the more common applications of
Switch h when releasedChanges
tch releas
relea nges the control
hanges contr value only after you release the mouse button
clude the following:
strings include follo
foll
uring
during g a mouse cl hin the graphical
click within graphic boundary of the control. The frequency with which
the VI reads the control does no fectt this behavior.
not affect ating simple text messages.
Creating essages.
sage
Na

Switch until releasedChanges

ope
op
re
until you release
to the operation
th behavior.
affect this
Latch when pressedChanges
Changes the
dChanges
he mouse button
the

Cha
ressedCha
ressed
buzze
th control value when you click it and retains the new value
button. At this time, the control reverts to its default value, similar
off a door buzzer.
buzzer The frequency with which the VI reads the control does not
avior. You cann
canno
cannot select this behavior for a radio buttons control.
the control value when you click it and retains the new value


Na Controlling instruments
in

Storing numeric
n
nts by sending ttext commands to the instrument and returning data values
er ASCII
in the form of either SCII or binary
bina strings which you then convert to numeric values.
data to disk. To store numeric data in an ASCII file, you must first convert
numer data to strings befo
numeric before writing the data to a disk file.
ompting th
Instructing or prompting the user with dialog boxes.
until the VI reads it once.
once At this point, the control reverts to its default value even if you keep
pressing the mouse button. This behavior is similar to a circuit breaker and is useful for
stopping a While Loop or for getting the VI to perform an action only once each time you set
the control. You cannot select this behavior for a radio buttons control.

National Instruments | 3-9 3-10 | ni.com


LabVIEW Core 1 Course Manual Lesson 3 Implementing a VI

On the front panel, strings appear as tables, text entry boxes, and labels. LabVIEW includes built-in Enums
VIs and functions you can use to manipulate strings, including formatting strings, parsing strings,
and other editing. An enum (enumerated control, constant or indicator) is a combination of data tytypes. An enum
represents a pair of values, a string and a numeric, where the enum can be one of a list of values.
For example, if you created an enum type called Month, the possible value
alue pairs for a Month

uti ts

uti ts
Refer to the ASCII Codes topic in the LabVIEW Help for more information
ation
ion about ASCII
ASC codes and
conversion functions. gure 3-9 shows
variable are January-0, February-1, and so on through December-11. Figure show an example
of these data pairs in the Properties dialog box for an enumeratedd control.
ntrol.
In LabVIEW, strings are represented with the color pink.

rib en

rib en
Figure 3-9. Properties for the Month Enumerated
merated
ated Contro
Control
Right-click a string control or indicator on the front panel too select
ect from the display
y types
pes shown

on

on
in the Table . The table also shows an example message in n each type.
ach display tty

ist um

ist um
Table 3-1. String Display
splay
y Types

Display Type Description Message


Normal Display Displays printable characters
ers Th
There are four disp
display
trol.
using the font of the control. types. \ is a ba
backslash.
racters
Non-displayable characters
r D str

r D str
oxes.
generally appear as boxes.
\ Codes Display Displays backslashh codes fo
for all There\sare\sfour\sdisplay\
re\sare\s
non-displayablee characters. stypes.\n\\\sis\sa\
types.\n\
sbackslash.
sbackslas
t fo l In

t fo In
Password Display Displays an asterisk (*) for each ******
**************************
ac including
character uding spaces. *******************
*****

Hex Display Displays


ays the AASCII valuee of each 546
5468 6572 6520 6172 6520
aracter in he
character d of the
hex instead 666F
6 7572 2064 6973 706C
aracter itse
character itself. 6179 2074 7970 6573 2E0A
No na

No na
5C20 6973 2061 2062 6163
6B73 6C61 7368 2E

ores strings as a pointerr to a structure that


LabVIEW stores th contains a 4-byte length value followed by
tio

tio
a 1D array of byte integers (8-bit characters).
Na

Na
National Instruments | 3-11 3-12 | ni.com
LabVIEW Core 1 Course Manual Lesson 3 Implementing a VI

Enums are useful because it is easier to manipulate numbers on the block diagram than strings. When you wire a dynamic data type to an array indicator, LabVIEW automatically adds the
Figure 3-10 shows the Month enumerated control, the selection of a data pair in the enumerated Convert from Dynamic Data Express VI to the block diagram. Double-click the Convert from
control, and the corresponding block diagram terminal. Dynamic Data Express VI to open the Configure Convert from Dynamic Data dialog box to
mic Dat
control how the data appears in the array.

uti ts

uti ts
Figure 3-10. Month Enumerated Control

1 2 3 C. Documenting Code

rib en

rib en
Professional developers who maintain and modify VIs know the he value
lue of good documentation.
mentati
Document the block diagram well to ease future modification n off the code
code.. In addition,
on, documen
document

on

on
the front panel window well to explain the purpose of the VI andd the fron
front panel objects.
cts.

signn to documen
Use tip strips, descriptions, VI Properties, and good design docume
document frontt panel windows
windows.

ist um

ist um
Tip Strips and Descriptions
Tip strips are brief descriptions that appear whenen you move the
th cursorr overr a control oro indicator
while a VI runs. For example, you might add a tipp strip to ind hat a temperature
indicate that temperatur is in degrees
Celsius or explain how an input works in an algor
lgorithm.
ithm. De
algorithm. Desc
Descriptionsns provide additio
additi
additional information
r D str

r D str
escriptions
iptions appe
about specific controls and indicators. Descriptions appea
appear in thee Context Help w window when you
move the cursor over the object. To addd tipp strips and descriptions
d tions
ons to controls
controls, right-click the
1 Front Panel Control 2 Selecting
ecting an Item 3 Block Di
Diagram Terminal control or indicator and select Description
ion and Tip from the
ription he shortcut
hortcut menu
menu.
t fo l In

t fo l In
Dynamic VI Properties
The dynamic data type stores es the
th information
matio generated
mati erated or acquired
acquir by an Express VI. The Use the Documentation component
mpo off the V erties dialog bo
VI Properties box to create VI descriptions and
dynamic data type appears rs ass a dark blue terminal,
al, shown below. Most Express VIs accept and/or to link from VIs to HTML L files or to compiled helpelpp files. To di
disp
sp VI Properties right-click the
display
return the dynamic dataa type.
pe. You can wire thee dynamic
dynamic data tytype to any indicator or input that nel orr block diagram
VI icon on the front panel dia andd select VI Pro
Properties from the shortcut menu or
Prop
veform,
accepts numeric, waveform, m, or Boolean
Bool
Boole data.. Wire the dynam
dynamic data type to an indicator that can rties.. Then select
select FileVI Properties. selec Documentation
mentation from the Categories drop-down menu.
No na

No na
a. Indicators
best present the data. ndicators inc
incl s, charts, or numeric indicators.
include graphs, his dialog
You cannot access this dialog box w while a VI runs.

des the
This page includes he following
followin components:
onents:
nts:
iptionContain the text
onContain
VI descriptionContains ext that
hat appears
appea in the Context Help window if you move the
tio

tio
Most other VIs and function
func tio in LabVIEW
functions abVIEW do nott accept the dynamic data type. To use a built-in icon Use <B>
cursor over the VI icon. B> and </B> tags
tag around any text in the description you want to
nction
tion to analyze or process
VI or function cess
ess the data the
the ddynamic data type includes, you must convert the at as bold. You also
format a can use the VI Description
Desc
Des property to edit the VI description
dynamicic data type. grammatically.
ammatically.
programmatically.
Help tagCont
p tagContains
tagCont HTM filename
the HTML enam
nam or index keyword of the topic you want to link to in
Usee the Convert fro amic
from Dynamicmic D
Da
Datata Express
pr VI to convert the dynamic data type to numeric,
hel file. You also can use
he
a compiled help u the Help:Document Tag property to set the help tag
Na

Boolean,
oolean, waveform,

Dynamic Da
wavefor and array
Convert from Dynamic
D

plays options
displays oop
c Data
ay data type
types for use with other VIs and functions. When you place the
ata Express
Expres VI
ogg box appears. The
Data dialog
hat let you specify
that
mic Data Express
Dynamic
V on the block diagram, the Configure Convert from
T Configure Convert from Dynamic Data dialog box
specif how you want to format the data that the Convert from
press VI retur
return
returns.
Na programmat
programmati
programmatically.
path
pat tains the path tto the HTML file or to the compiled help file you want to link
Help pathContains
ntext Help window.
to from the Context windo If this field is empty, the Detailed help link does not appear
window and the Detailed help button is dimmed.
in the Context Help window,
BrowseDisplayss a file dialog
d box to use to navigate to an HTML file or to a compiled help
file to use as the Help path.

National Instruments | 3-13 3-14 | ni.com


LabVIEW Core 1 Course Manual Lesson 3 Implementing a VI

Naming Controls and Indicators Label constants to specify the nature of the constant.
Giving controls and indicators logical and descriptive names adds usabilityy to front
f panels. For rams If you use an
Use free labels to document algorithms that you use on the block diagrams.
example, if you name a control Temperature, a user may not know which ich units to use.
u However, rmation.
ation
algorithm from a book or other reference, provide the reference information.
naming a control Temperature C adds more information to the front ont
nt panel. You nnow know to

uti ts

uti ts
enter temperatures in metric units. D. While Loops
Similar to a Do Loop or a Repeat-Until Loop in text-based programming
amming
ming languag
langua
languages, a Whi
While Loop,
Graphical Programming

rib en

rib en
shown in Figure 3-12, executes a subdiagram until a conditionn occurs.
ccurs.
While the graphical nature of LabVIEW aids in self-documentation
entation
tion of bloc
block diagrams,
ams,, extra

on

on
comments are helpful when modifying your VIs in the future.re. There are tw
two types of block
lock diagram The following illustration shows a While Loop in LabVIEW, flowchart eequivalent
EW, a flowchart lent off the While
eration
commentscomments that describe the function or operation ion of algori
algorithms andnd comments
omments thathat unctionality
onality of th
Loop functionality, and a pseudo code example of the functionality le Loop.
the While oop.

ist um

ist um
explain the purpose of data that passes through wires. Both
oth types of comments
c nts are shown in the
Figure 3-12. While
hile Loop
abelss with the L
following block diagram. You can insert standard labels La
Labeling tool,
ool, or by inserting
inser a
free label from the FunctionsProgrammingStructuresDecorations
ructuresDeco
turesDeco subpalette.
ubpalette. By default,
Code
e
free labels have a yellow background color.
No Repeat (co
(code);
Figure 3-11. Documenting
cumenting
umenting a Blo
Block Diagram
gram
Condition
r D str

r D str
Until Co
Condition met;
Code
met?
me
End;
Ye
Yess

End
En
t fo l In

t fo l In
1 2 3

1 LabVIEW While Loop 2 Flowchart 3 Pseudo Code

The While Loop is locateded on the Str


Structures palette.
alette.
ette. Select the While Loop from the palette then
use the cursor to drag a select
lection
ion rectangle
selection rectan around
recta ound the section of the block diagram you want to
No na

No na
lease the mouse button, a While Loop boundary
repeat. When you release b encloses the section you
Use the following
g guidelines
idelines for ccommenting
ntin your
ur VIs: selected.

Use comments
mentss on the block
bloc diagram explain what the code is doing.
am to ex
explai gram
m objects to the
Add block diagram t While
ile Loop by ddragging and dropping them inside the While
While LabVIEW can be self-documenting
abVIEW code cca documentin because it is graphical, use labels to describe
elf-documenting Loop.
tio

tio
how the
hee block diagram functions.
ons
ons.
Tip The Whi
While Loop always executes
execute at least once.
Usee labels
abels to identify
identif objectss on the front ppanel and block diagram. LabVIEW includes two
ident
ifferent
rent types of labelsowned
different l ow abels and
labels aan free labels. Owned labels belong to and move with
a particular object and annotate
rticular obje notat ththat obj
object
bj only. Free labels are not attached to any object, and hile Loop executes
The While exe he subdiagram
the subdia
subd m until
un the conditional terminal, an input terminal, receives
Na

you can creat


create, move,
Do not sho

Conte Help window.


Contex
Context
e, rotate
show labelss on function an
develope looking
developer
delete them independently.
tate orr dele
and subVI calls because they tend to be large and unwieldy. A
ngg at the block diagram
d can find the name of a function or subVI by using the

ls with long wires to identify their use. Labeling wires is useful for wires
Use owned labels
Na
a specific Boolean value. However,

Iff a conditional
c

conditio terminal
Whilee Loop,
minal
on never occurs.
infinitely if the condition
wever, the While Loop does not include a set iteration count and runs

nal is Stop if True,


Loo and the control is FALSE
Lo FA
F
ample. You also
in the following example.
T you place the terminal of a Boolean control outside a
when the loop starts, you cause an infinite loop, as shown
a cause an infinite loop if the conditional terminal is Continue
giste and for long wires that span the entire block diagram.Refer to the
coming from shift registers outsi the loop is set to TRUE, as shown in Figure 3-13.
outsid
if True and the control outside
Case Structures section of this lesson for more information about shift registers.
Label structures to specify the main functionality of the structure.

National Instruments | 3-15 3-16 | ni.com


LabVIEW Core 1 Course Manual Lesson 3 Implementing a VI

Figure 3-13. An Infinite Loop Tunnels through Structures


Tunnels feed data into and out of structures like While Loops. The tunnel appea
appears as a solid block
on the border of the While Loop. The block is the color of the data type wired red to th
the tunnel. Data
pass out of a loop after the loop terminates. When a tunnel passes data into
to a loop, the lo
nto lloop executes

uti ts

uti ts
only after data arrive at the tunnel.

In the following block diagram, the iteration terminal is connecteded to a tunnel. T u in the
The value

rib en

rib en
tunnel does not get passed to the Iterations indicator until thee While
hile Loop fin
finishes executing
uting
executing.

on

on
Figure 3-15. While Loop Tunnel
el

Changing the value of the control does not stop the infinite
initee loop because
beca
becau the value is only read
rea

ist um

ist um
once, before the loop starts. To stop an infinite loop, youu must abort the VI byy clicking the A
Abort
Execution button on the toolbar.

You also can perform basic error handling using ng the


he conditional
condition
conditiona terminal inal off a While Loop.
L When
rminal,
inal, only th
you wire an error cluster to the conditional terminal, the True or False
alse value oof the status
parameter of the error cluster passes to the terminal.
erminal. Also
Also, tthe Stopp if True and Co C
Continue if True
r D str

r D str
shortcut menu items change to Stop if Errorrror and Contin
Conti
Continue while ile Error.
Error
Only the last value of the iteration terminal
minall displays in the Iterations
rations indicato
erations indicator.
rminal
nal that
The iteration terminal is an output terminal that contains
cont
con thee number
mber of completed
com iterations.

Using While Loops for Error C


Checking
king
ing and Error
E Handling
t fo l In

t fo l In
You can wire an error cluster to the
he condition
conditiona
conditional terminalnal of a While L
Loop or a For Loop with a
oop alway
The iteration count for the While Loop always startss at zero. on of the
conditional terminal to stop the iteration tth loop.. If
I you
ou wire the error cluster to the conditional
terminal, only the TRUE or FALS atus parameter of the error cluster passes to the
FALSE value of the status
tatus
agram,
In the following block diagram,m, the W
While Loop executes until ththe Random Number function
urs, the loop st
terminal. If an error occurs, stops.
qual to 0.9 aand the Enable control iis True. The And function returns
output is greater than or equal
True only if both inputs
puts are
re True. O
Otherwise,e, it returns Fal
False.
F
No na

No na
ter to the conditional
If you wire an error cluster co l terminal, the shortcut
s menu items Stop if True and
ange to Stop on Error
Continue if True change ror and Continue
Continu while Error.
In the following example,
mple, there is
i an increased
se probability
crease babili of an infinite loop. Generally, the
desired behavior
or is too have one ccondition
on met to
t stop
sto the loop, rather than requiring both conditions In Figure 3-16,, thee error cluster
cluste
clust and a stop
p button
butto are
ar used together to determine when to stop the
to be met. loop. This iss the recommended
recommend method hodd for stopping
stoppin most loops.
tio

tio
Figure
igure
gure 3-14. Possible
Po
Pos Infinite Loop Figure
igure
gure 3-16. Stopping
Sto a While Loop
Na

Na
National Instruments | 3-17 3-18 | ni.com
LabVIEW Core 1 Course Manual Lesson 3 Implementing a VI

E. For Loops Adding a Conditional Terminal to a For Loop


If necessary, you can add a conditional terminal to configure a For Loop too stop when a Boolean
A For Loop, shown as follows, executes a subdiagram a set number of times.
mes.. Figure
Figu
Fig 3-17 shows a
condition or an error occurs. A For Loop with a conditional terminal executesecutes
tes until the condition
For Loop in LabVIEW, a flowchart equivalent of the For Loop functionality,
nality, ppseudo code
y, and a ps
occurs or until all iterations are complete, whichever happens first. Forr Loops you con configure for a
co

uti ts

tio s
example of the functionality of the For Loop.
nditional
tional termin
conditional exit have a red glyph in the count terminal as well as a conditional terminal in the lower
right corner. After you configure the For Loop to exit conditionally,ly, the
he lloop
oop appe
appears similar to

ibu nt
Figure 3-17. For Loop
Figure 3-19. The following For Loop generates a random number er every
very second
second until 100
00 seconds

rib en
N=100 has passed or the user clicks the stop button.

on

n
str me
Figure 3-19. For Loop Configured forr a Conditional Exit
i=0
N=100;
N=
i=i+1

ist um
i=0;
Code
No Until i=N:
i=N? Code
de
epeat (code; i=i+1);
Repeat
Yes

Di tru
End;
End
r D str 1 2 3

1 LabVIEW For Loop 2 Flowchart


owchart 3 Pseudo Code
C
To add a conditional terminal to a Forr Loop,
p, right-click
right-c
right-cli on the For Loop border
bor and select

s
The For Loop is located on the Structures
ures palette. You also
uctures so can
an ppl
place
ace
ce a W
While Loop on the block rtcutt menu. Then
Conditional Terminal from the shortcut The wire the conditional tterminal and the count
diagram, right-click the border off the While Loo
Loop elect
lect Replace w
Loop, and select with For Loop from the terminal.
t fo l In

l In
shortcut menu to change a Whilee Loop to a For Loop. The count terminal
termi is an input terminal
whose value indicates how many times mes to repeat
rep the subdiagram.
diagram. Figure 3-20. Adding
dding a Conditional
Co
C nal Terminal to a For Loop

al is ann output terminal


The iteration terminal ter
te hat
hat contains the
that t number of completed iterations.
No na

No na
The iteration count
nt for the Fo p always
For Loop ways starts at zero.
tio

tio
The For Loop
oop in Figure 33-18 generates
nerates
erates a ra
random
ndom number every second for 100 seconds and
displayss the
he random nu
numbers in a numeric indindicator.
Figure 3-18.
F
Fig 3-1 For Loop Example
Na

Na
National Instruments | 3-19 3-20 | ni.com
LabVIEW Core 1 Course Manual Lesson 3 Implementing a VI

Using For Loops for Error Checking and Error Handling Comparing For Loops and While Loops
In a For Loop with a conditional terminal, you also must wire a value to thehe co
count terminal or For Loops and While Loops differ in several distinct ways. Refer to Table 3-3 ffor a list of
auto-index an input array to set a maximum number of iterations. The For or Loop exe
executes until an differences between For Loops and While Loops.
error occurs or until the number of set iterations completes. Refer to Using Loops for Error
ing While Lo
Loop

uti ts

uti ts
Checking and Error Handling for more information. Table 3-2. Comparing For Loops and While Loops
oops

For Loop While Loop


Numeric Conversion in For Loops

rib en

rib en
Executes a set number of times unless a Stops executing
ng only if th
the value at thee
As noted in Numeric Conversion, when you wire different data ata type
types
ypess to the iinput off a function,
unction, the conditional terminal is added rminal meets
conditional terminal mee the conditionition

on

on
oweve
function generally returns the larger or wider data type. However,ever,
r, if you w
wire a double-precision
ble-precision
double-precision,
floating-point numeric value to the 32-bit count terminal al onn a For Loop
Loop, LabVIEWVIEWW coerces the Can execute zero times Must execute
cute at least once

ist um

ist um
larger numeric value to a smaller 32-bit signed integer.r. Although the conversion sion is contrary tto
Tunnels automatically output an array of data Tunnels
els automatically
automatic output
put the last value
valu
normal conversion standards, it is necessary, becausese a For Loop cca can only execute
xecute an integ
integer
number of times.
F. Timing a VI
Figure 3-21. Coercion
oercion
cion on a For
Fo Loop
When a loop finishes executing an iteration,, it immediately beginss executing
ecuting the nnext iteration,
r D str

r D str
ten,, you need to control th
unless it reaches a stop condition. Most often, thee iteration freq
frequency or timing.
For example, if you are acquiring data, and d you want
want to acquire
ree the data once every 10 seconds,
tions so they occur
you need a way to time the loop iterations oocc oncee every
very 10 seconds.
seco
secon
1
ution to occur aat a certain
Even if you do not need the execution ainn frequency,
frequency yoyou need to provide the
t fo l In

t fo l In
processor with time to complete other tasks, suc sponding
nding to the user interface. This section
such as responding
introduces some methods for timingg your loops.
loo

1 Coercion Dot
Wait Functionss
For better performance,
ce, avoid
void coercio
coercion by using
ing matching da
data types or programmatically Place a wait function insidee a loop to aallow a VI to sleep fo
for a set amount of time. This allows your
No na

No na
hingg data types, aas shown in
converting to matching n Figure 3-2
3-22
3-22. ss other
processor to address her tasks during
du
dur the waitt time. Wai
Wait functions use the millisecond clock of
tem.
the operating system.
Figure
ure 3-22. A
Avoiding
g Coercion
Coercio
erc By Using
U
Us Matching Data Types
The Wait Until til Next
ext ms Multiple
Mult nction
on monitors
function monit a millisecond counter and waits until the
tio

tio
millisecondd counter reaches
reache a multiple
tiple of the amou
amount you specify. Use this function to synchronize
activities.. Place this function
func in a loop to control
contro the loop execution rate. For this function to be
ve, your code execution
effective, ex mee must be less
time le than the time specified for this function. The
ution
executionn rate for th eratio off the loo
the first iteration lo
loop is indeterminate.
Na

Na
he Wait (m
The ction waits until
(ms) function
eci This function guara
you specify.
until the millisecond counter counts to an amount equal to the input
guaran
guarantees that the loop execution rate is at least the amount of the input
you specify.

National Instruments | 3-21 3-22 | ni.com


LabVIEW Core 1 Course Manual Lesson 3 Implementing a VI

Note The Time Delay Express VI behaves similarly to the Wait (ms) function with the You can add more than one shift register to a loop. If you have multiple operations that use previous
addition of built-in error clusters. Refer to Lesson 2, Troubleshooting and Debugging iteration values within your loop, use multiple shift registers to store the data values from those
VIs, for more information about error clusters. different processes in the structure, as shown in the following figure.

uti ts
Figure 3-23. Using Multiple Shift Registers

uti ts
s
Elapsed Time
In some cases, it is useful to determine how much time elapses afterfter some point iin your VI. The

rib en

rib en
pses after the specified
Elapsed Time Express VI indicates the amount of time that elapses sp start time.
This Express VI keeps track of time while the VI continues to o execute.
xecute. This Expresss VI does nnot
provide the processor with time to complete other tasks. Youu willl use the E
Ela
Elapsed Time Express VI

on

on
in the Weather Station course project.

ist um

ist um
G. Data Feedback in Loops Initializing Shift Registers
Initializing a shift register resets the value thee shift
hift register ppasses to
o the first iterati
iteratio
iteration of the loop
When programming with loops, you often must when the VI runs. Initialize a shift register byy wiring a conco
control or constantt to the shift
s register
r D str ust access ddata from previous iteration
itera
iterations
tio of the loop in

r D str
ring
LabVIEW. For example, if you are acquiring g one piece oof data in
n each iteration
iteration oof a loop and must hown
terminal on the left side of the loop, as shownwn in Figure 3-24.
st retain the data from
average every five pieces of data, you must om
m previous iterations
itera of the loop.
Figure 3-24.
4. Initialized
Initialize Shift Register
ister
Note Feedback Nodes are another me
met
method forr retaining
retaining inform
information from a previous
t fo l In

t fo l In
iteration. Refer to the Feedback Node topic of the H for more information
he LabVIEW Help
about Feedback Nodes.

Shift Registers
No na

No na
Shift registers are similar
milar
ar to static va
variables in
n text-based pr
programming languages.
In Figure 3-24, the For Loop execut
executes five times,, increment
in
incrementing
cremen the value the shift register carries by
Use shift registersrs when
hen you want
wan to pass
wa ass values
alu from
value m pprevious iterations through the loop to the fter five iteration
one each time. After teratio of the Forr L
iterations Loop, the sh
shift register passes the final value, 5, to the
next iteration. A shift
hift register appearss as a pair of te
terminals directly opposite each other on the he VI quits. Each time you
indicator and the ou run
un the
th VIVI, the shift register begins with a value of 0.
vertical sidess of the loop border.
bor
tio

tio
If you do not
ot initialize the shift
s register,
gister, the loop uses
u the value written to the shift register when
the loop last
st executed or, if the loop
oop has never exeexecuted, the default value for the data type.

minal on the rright side


The terminal dee of
o tthe loop
oop
op co
contains an up arrow and stores data on the completion Use an uninitialized
ninitialized shift
s register
ister to preserve
reserv state information between subsequent executions of
Lab
La
of an iteration. LabVIEW ansfers th
transfers the data connected to the right side of the register to the next a VI. Figure shows an
gure 3-25 ssh uninitialized
n uninitiali
uni niti shift
shh register.
Na

teration.
ration. After the
iteration.
stored in the sh

eate a ssh
Create
th loop executes,
ecutes, the te

ster by right-clic
shift register
ster.
shift register.
terminal on the right side of the loop returns the last value

right-clicking the left or right border of a loop and selecting Add Shift
er from thee shortcut menu
Register menu.
Na Figure 3-2
3-25. Uninitialized Shift Register

ny data type and automatically changes to the data type of the first object
A shift register transfers any
wired to the shift register. The data you wire to the terminals of each shift register must be the same
type.

National Instruments | 3-23 3-24 | ni.com


LabVIEW Core 1 Course Manual Lesson 3 Implementing a VI

In Figure 3-25, the For Loop executes five times, incrementing the value the shift register carries H. Plotting Data Waveform Chart
by one each time. The first time you run the VI, the shift register begins with a value of 0, which
is the default value for a 32-bit integer. After five iterations of the For Loop,p, thee shift
shi register passes
sh The waveform chart is a special type of numeric indicator that displays one or m mo
more plots of data
the final value, 5, to the indicator, and the VI quits. The next time you run un thehe VI
VI,, the shift register typically acquired at a constant rate. Waveform charts can display single
le or multiple pplots.

uti ts

uti ts
begins with a value of 5, which was the last value from the previous execution.
ecution.
cution. After
After five
ffi iterations lots
Figure 3-27 shows the elements of a multiplot waveform chart. Two plotsots are displayed:
displaye
display Raw Data
of the For Loop, the shift register passes the final value, 10, to the indicator.
dicator.
ator. If you runru the VI again, and Running Avg.
the shift register begins with a value of 10, and so on. Uninitialized ed shift
shifft registers retain the value
Figure 3-27. Elements of a Waveform
m Charts
harts

rib en

rib en
of the previous iteration until you close the VI.

on

on
Stacked Shift Registers 1
6

Stacked shift registers let you access data from previous us loop
oop iter
iterations
iterations.
ation Stackedked shift register
registers

ist um

ist um
remember values from multiple previous iterations andd car arry
ry those va
carry values to the
he next iteration
iteratio
iterations. To
rminal
nal and selec
create a stacked shift register, right-click the left terminal sele lement from th
select Add Element the
shortcut menu. 2

eft side
Stacked shift registers can occur only on the left ide of the loo use the
loop because he right term
terminal transfers
eration
ation to the next
the data generated from only the current iteration nex iteration,
tion, as shown ini Figure 3-26.
r D str

r D str
3
Figure 3-26. Using
sing Stacked Shift Registers
5
t fo l In

t fo l In
4

1 Label 3 X-scale
X 5 Graph Palette
2 Y-scale 4 Scale Legend 6 Plot Legend

Configure how the chart


hart updates
pdates tto
oddi
display new
ew data. Right-
Right-click the chart and select Advanced
No na

No na
Update Mode from m thee shortcut m
me he chart update
menu to set the upda mode. The chart uses the following
upd
If you add anotherer element
ement to the left terminal
minal in thehe previous
prev block diagram, values from the last a:
modes to display data:
arry
two iterations carry y over to the nnext iteration,
eration,
on, with
w the most recent iteration value stored in the top Shows running
rtShows
Strip ChartShows runn
run ta continuously
data ntinuo scrolling from left to right across the chart
shift register. Thee bottom term toress the data
terminal stores daata passed
pa to it from the previous iteration. a new
with old data on the left and w data
ata on the right.
ri
righ A strip chart is similar to a paper tape strip
tio

tio
ecorder.
corder. Strip C
chart recorder. Chart iss the default upd
upda
update mode.
ChartSh
pee ChartShows
Scope ChartShow tem
one itemm of data, such
suc as a pulse or wave, scrolling partway across the
hart from left to rright. For
chart or eeach new vavalu
value, the chart plots the value to the right of the last
ue. When the plot reaches
value. aches
hes the
th right
ht border
b of the plotting area, LabVIEW erases the plot and
Na

Na begins plottin

C
plotting again from
oscillosc
an oscilloscope.
Sweep ChartWorks
m the left bborder. The retracing display of a scope chart is similar to

Works similarly to a scope chart except it shows the old data on the right and
ne data onn the left separated
the new separat by a vertical line. LabVIEW does not erase the plot in a sweep
separa
t right border of the plotting area. A sweep chart is similar to an
chart when the plot reaches the
EKG display.

National Instruments | 3-25 3-26 | ni.com


LabVIEW Core 1 Course Manual Lesson 3 Implementing a VI

Figure 3-28 shows an example of each chart update mode. The scope chart and sweep chart have I. Case Structures
retracing displays similar to an oscilloscope. Because retracing a plot requires less overhead, the
scope chart and the sweep chart display plots significantly faster than the strip
ip cch
chart. A Case structure has two or more subdiagrams, or cases.

uti ts

uti ts
Figure 3-28. Chart Update Modes

rib en

rib en
xecutes
utes only one
Only one subdiagram is visible at a time, and the structure executes on case at a time. An

on

on
input value determines which subdiagram executes. The Case ase structure
tructure is similar to switch
witch
gramming
mming langu
statements or if...then...else statements in text-based programming languages.

ist um

ist um
The case selector label at the top of the Case structuree contains
ntains the name
nna of the
he selector valu
value that
Wiring Charts corresponds to the case in the center and decrementt and nd increment arrowss on each side.
side
You can wire a scalar output directly to a waveform
rm chart. The waveform
w m chart
hart terminal
termina shown in
Figure 3-29 matches the input data type.
Figure 3-29. Wiring a Single Plot to
t a Waveform
eform Chart Click the decrement and increment arrows too scroll through
throu the available
vailable
ailable cases. You
Yo also can click
r D str

r D str
the down arrow next to the case name andd select
elect a case from
f thee pull-down menu.
men
m

he selector
Wire an input value, or selector, to the elector term
termi
terminal to determine
rmine which case executes.
t fo l In

t fo l In
alue, stri
You must wire an integer, Boolean value, string, or enumerated type value to the selector terminal.
orr terminal
You can position the selector term yw
anywhere onn the left border of the Case structure. If the data
inal is Boolean,
type of the selector terminal Boolea the structureucture
cture has a TrTrue
rue case and a False case. If the
Waveform charts can display
lay multiple plots together
ogether using the
th Bundle function located on the ger, string, oor enumerated
selector terminal is an integer, erated type value
value, the structure can have any number
No na

No na
ant palette. IIn Figure 3-30, the Bundle
ariant
Cluster, Class & Variant Bund function bundles the outputs of the
Bun of cases.
he waveform chart.
three VIs to plot on the
Note By default, string
stri valuesues you wire
w too the tth selector terminal are case sensitive. To
Figure 3-3
3-30.
3 Wiring
ring Multi
Multiple P
Plots to a Waveform Chart w case-insensitiv
allow ase-insensiti matches,
case-insensitive hes, wire a sstrin
string value to the selector terminal, right-click the
order of the Ca
border Case structure,
ure, and select Ca
Case Insensitive Match from the shortcut menu.
C
tio

tio
d
If you do not specify a default ase
se for the Case structure to handle out-of-range values, you must
case
citly
explicitlyy list every po
possible inpu alue.
ue. For
input value. Fo example, if the selector is an integer and you specify
es for
cases or 1, 2, and 3, you mustst specify
spe
specif a default
d
de case to execute if the input value is 4 or any other
Na

The waveform
wave chart
art terminal ch
cha
changes to match the output of the Bundle function. To add more
oning tool to
plots, use the Positioning t resize the Bundle function.
Na
nspecified
specified integer
unspecified integ
intege value.

Note
No
Not
e.

Youu cannot specify a default case if you wire a Boolean control to the selector.
If you right-click
ght-click the cas
hortcut menu. M
in the shortcut
case selector label, Make This The Default Case does not appear
Make the Boolean control TRUE or FALSE to determine which
ute.
case to execute.

To convert a Case structure to a Stacked Sequence structure, right-click the Case structure and
select Replace with Stacked Sequence from the shortcut menu.

National Instruments | 3-27 3-28 | ni.com


LabVIEW Core 1 Course Manual Lesson 3 Implementing a VI

Right-click the Case structure border to add, duplicate, remove, or rearrange cases, and to select a Input and Output Tunnels on Case Structures
default case.
You can create multiple input and output tunnels for a Case structure. Inputs are av
available to all cases,
but cases do not need to use each input. However, you must define an output put tunnel fo
for each case.
Selecting a Case

uti ts

uti ts
Figure 3-31 shows a VI that uses a Case structure to execute different nt code depende
dependent on whether Consider the following example: a Case structure on the block diagram ram
m has an outpu
output tunnel, but
a user selects C or F for temperature units. The top block diagram am shows the True
Tr case in the unnel.
el. If you run this case,
in at least one of the cases, there is no output value wired to the tunnel.
LabVIEW does not know what value to return for the output. LabVIEW abVIEW
VIEW indicates
indicat
indica this error
er by

rib en

rib en
ed. To select a ca
foreground. In the middle block diagram, the False case is selected. ccase, enter
er th
the value
Aft you select
in the case selector identifier or use the Labeling tool to edit the values. After electt anothe
another leaving the center of the tunnel white. The unwired case mightt not ot be the case that iss currentl
rrentl
currently
case, that case displays on the block diagram, as shown in thee bottom
tom block diagram
d m of Figure 3-31.
3-31 visible on the block diagram.

on

on
Figure 3-31. Changing the Case View
ew of a Case St
S
Structure
e he unwired
To correct this error, display the case(s) that contain(s) the nwired outp nel and wire an
output tunnel

ist um

ist um
output to the tunnel. You also can right-click the outputt tunnel
nnel and select
sele
sel Use Default If Unw Unwired
unnel data type
from the shortcut menu to use the default value for the tunnel t for alll unwired tunnels.
tunn
unnel
When the output is wired in all cases, the output tunnel el is a solid ccolor.

Avoid using the Use Default If Unwired option. n. Using this opt
op
option does es not
ot document tthe block
diagram well, and can confuse other programmers mers using your code. The Use se Default If Unwired
r D str

r D str
option also makes debugging code difficult. If you use this o op
option, bee aware thatt the ddefault value used
red to the tunnel.
is the default value for the data type that is wired tun Forr example, if the
th tunnel is a Boolean
data type, the default value is FALSE. Refer to Table 3-3 for a list ist off default values
valu for data types.

Table
le 3-3.
-3. Data Type
Ty Default
ault
ult Values
t fo l In

t fo l In
Data Type Default Value
Def
Numeric 0

Boolean FALSE
No na

No na
String empty ("")

Examples
es
In the following
wing examples,
examples the
t numeric
mericc values pass
pas through tunnels to the Case structure and are
tio

tio
If you enterr a selector value
valu that iss not the same tyttype
y as the object wired to the selector terminal,
the valuee appears red. Thi ates
tes that the VI w
This indicates will not run until you delete or edit the value. Also, ed
either addedd or subtracted
subtracted depending
subtracted, nding
ding on the valu
va
value wired to the selector terminal.
becausee off the possible round-offf error inheren
inherent in floating-point arithmetic, you cannot use
ing-point
-point numbers
floating-point numbe as caseasee selector
se orr values.
valu If you wire a floating-point value to the case,
bVIEW rounds tthe valuee to the nnearest
LabVIEW ea integer. If you type a floating-point value in the case
Na

selector
lector label, the
th value appears
structure can eexecute.
pears red to indicate
i that you must delete or edit the value before the

Na
National Instruments | 3-29 3-30 | ni.com
LabVIEW Core 1 Course Manual Lesson 3 Implementing a VI

Boolean Case Structure String Case Structure


Figure 3-32 shows a Boolean Case structure. The cases overlap each other to simp
simplify the illustration. Figure 3-34 shows a string Case structure.

Figure 3-32. Boolean Case Structure Figure 3-34. String Case Structure

uti ts

uti ts
rib en

rib en
on

on
ist um

ist um
If the Boolean control wired to the selector terminal
rminal
nal is True, tthe VI adds the numeric values. If String is add, the VI adds the numeric values.
ues. If String is subtract
act, the VI subt
subtracts the
ues.
es.
Otherwise, the VI subtracts the numeric values. numeric values.
r D str

r D str
In situations where you are simply choosing
singg between two
tw valuess based
based on a boolean
boo
bo input, a Select Enumerated Case Structure
e
oolean
an Case structure.
statement can be used rather than a Boolean sstru
Figure 3-35 shows an enumerated Case
ase structure.
t fo l In

t fo l In
Figure
re 3-35. Enumerated
Enume
nume Case
se Structure

Integer Case Structure


cture
Figure 3-33 shows an integer
teger
er Case structure.
stru

Figure 3-33. Integer


nteger Case Structure
St
No na

No na
tio

tio
An enumerated
numerated
rated type ccontrol giv
gives users a list
l of items from which to select. The data type of an
merated
ated type con
enumerated cludes
udes iinformation
control includes mati about the numeric values and string labels in the
Na

er is
Integer i a text ring
ing control located
loca on the Text Controls palette that associates numeric values
loc
with text items. If thee Integer wired
w to the selector terminal is 0 (add), the VI adds the numeric
Na
ontrol.
ntrol. The case selectorr displays
control.

ype control.
plays the string
s label for each item in the enumerated type control
when you select Add Casee For Every Value from the Case structure shortcut menu. The Case
structure executes
type
exec
exe the appropriate ccas
case subdiagram based on the current item in the enumerated
control In the previous block diagram, if Enum is add, the VI adds the numeric values. If
Enum is subtract ct, the VI sub
subtracts the numeric values.
subt

values. If the value is 1 (sub


subtract), the VI subtracts the numeric values. If Integer is any other
value than 0 (add) or 1 (subtract), the VI adds the numeric values, because that is the default
case.

National Instruments | 3-31 3-32 | ni.com


LabVIEW Core 1 Course Manual

Using Case Structures for Error Handling


The following example shows a Case structure where an error cluster defines
nes the cases.

Figure 3-36. No Error Case

uti ts

uti ts
rib en

rib en
on

on
ist um

ist um
Figure 3-37.
-37.. Error Cas
Case
r D str

r D str
t fo l In

t fo l In
No na

No na
When you wire an error
rror cluster
uster to the
th selectorr terminal of a Case structure, the case selector label
sError
displays two cases rror and N No Erroro and nd the border
bor of the Case structure changes
colorred for Error
rrorr and green for No Errorror. If ann er
err
error occurs, the Case structure executes the
Error subdiagram.
gram.
m.
tio

tio
When you wire an error cl
cluster to
clu tterminal, the Case structure recognizes only the
o the selection ter
status Boolean
olean element of the cluster.
oolean luster.
uster.
Na

Na
National Instruments | 3-33
LabVIEW Core 1 Course Manual

Self-Review: Quiz
1. If an input to a function is marked with a red dot (known as a coercion
on dot), what
wh does the dot
indicate?

uti ts

uti ts
a. Data was transferred into a structure.
b. A For Loop was configured with a conditional terminal.

rib en

rib en
c. A For Loop iteration terminal is unwired.
d. The value passed into a node was converted to a different
fferent representation.
nt represent
represe

on

on
ist um

ist um
2. Which structure must run at least one time?
a. While Loop
b. For Loop
r D str

r D str
3. Which is only available on the block
ock diagram?
iagram?
a. Control
t fo l In

t fo l In
b. Constant
c. Indicator
d. Connector pane
No na

No na
nical action caus
4. Which mechanical ool
causes a Boolean ontrol in the FALSE state to change to TRUE
control
ick itt and stay T
when you click ntil Lab
TRUE until LabVIEWW hhas read the value?
a. Switch
h until
ntil released
tio

tio
b. Switch
tch when released
itch releas
relea
atch until released
c. Latch relea
rele
d.. Latch
atch when rreleased
re
Na

Na
National Instruments | 3-35
LabVIEW Core 1 Course Manual Lesson 3 Implementing a VI

Self-Review: Quiz Answers Notes


1. If an input to a function is marked with a red dot (known as a coercion
on dot), what
wh does the dot
indicate?

uti ts

uti ts
a. Data was transferred into a structure.
b. A For Loop was configured with a conditional terminal.

rib en

rib en
c. A For Loop iteration terminal is unwired.
d. The value passed into a node was converted to a different representation.
erent rep
repre ion.

on

on
ist um

ist um
2. Which structure must run at least one time?
a. While Loop
b. For Loop
r D str

r D str
3. Which is only available on the block
ock diagram?
iagram?
a. Control
t fo l In

t fo l In
b. Constant
c. Indicator
d. Connector pane
No na

No na
nical action caus
4. Which mechanical ool
causes a Boolean ontrol in the FALSE state to change to TRUE
control
ick itt and stay TRUE
when you click T ntil you release
until r se iit and LabVIEW has read the value?
a. Switch
h until
ntil released
tio

tio
b. Switch
tch when released
itch releas
relea
atch until released
c. Latch relea
rele
d.. Latch
atch when released
r d
Na

Na
National Instruments | 3-37 3-38 | ni.com
Lesson 4 Developing Modular Applications

Developing Modular Applicationss


4 A. Understanding Modularity
Modularity defines the degree to which a program is composed of discrete
te modul
mod
modules such that a
change to one module has minimal impact on other modules. Modules in LabVIEW
abVIEW are called

uti ts

uti ts
subVIs.

This lesson describes how to develop modular applications. The power wer of LabVI
LabVIEW lies in the A VI within another VI is called a subVI. A subVI corresponds to o a ssubroutine
ubroutine in text-based

rib en

rib en
hierarchical nature of the VI. After you create a VI, you can usee it on
n the block diagram
m of an
another programming languages. When you double-click a subVI, a front nt panel
anel and bloc
blo
block diagramram aappear,
y. Using
VI. There is no limit on the number of layers in the hierarchy. sing modular
modula programming
amming
ming help
helps rather than a dialog box in which you can configure options. The front panel iincludess controls
ntrols an
and
cons, functions,
indicators. The block diagram includes wires, front panel icons, function possibly ly subVIs,
ubVIs, and

on

on
you manage changes and debug the block diagram quickly.
other LabVIEW objects that also might look familiar.
Topics

ist um

ist um
ock diagram
The upper right corner of the front panel window and block diagram w w displays the ic
window ico
icon for
A. Understanding Modularity rs when
the VI. This icon is the same as the icon that appears hen you place
plac
plac the VI on the block di
ddiagram.

B. Building the Icon and Connector Pane form


As you create VIs, you might find that you performm a certain operation
oop n frequently.
quently. Consider
Con using
C. Using SubVIs petitively.
tively. For ex
subVIs or loops to perform that operation repetitively. example, the following bblock diagram
contains two identical operations.
r D str

r D str
Figure 4-1. Block Diagram
gram with Tw
Two Identical
tical
ical Operations
t fo l In

t fo l In
No na

No na
Figure 4-2. Block Diagram
ram with SubVIs
Su for Identical Operations
tio

tio
Na

Na
The example calls the Temperature
Temp
Temper VI as a subVI twice on its block diagram and functions the
k ddiagram. You also can reuse the subVI in other VIs.
same as the previous block

National Instruments | 4-1 4-2 | ni.com


LabVIEW Core 1 Course Manual Lesson 4 Developing Modular Applications

The following pseudo-code and block diagrams demonstrate the analogy between subVIs and Creating an Icon
subroutines.
Icons are graphical representations of VIs.
Function Code Calling Program
rogram Cod
Code Every VI displays an icon in the upper right corner of the front panel and
ndd bloc
block diagram windows.
k diagr
diagra

uti ts

uti ts
function average (in1, in2, out) main
{ {
out = (in1 + in2)/2.0; average (point1,
nt1, point2,
poin pointavg)

rib en

rib en
} }
any new VIs, up to nine VIs,
The default VI icon contains a number that indicates how many s, you have
hav

on

on
SubVI Block Diagram Calling
ing VI Block
Bl Diagram
m opened since launching LabVIEW. To disable this numbering,ng, select
lect Tools
Tool onsFront
Front Panel
ToolsOptionsFront
and remove the checkmark from the Use numbers in icons ons of new VIs (1 throughh 9) checkbo
ough checkbox.

ist um

ist um
An icon can contain text or images. If you use a VI ass a subVI, the ic
iicon identifies
tifies
fies the subVI on the
ette,, th
block diagram of the VI. If you add the VI to a palette, thee VI icon also appears
ppears
ears on the Fu
F
Functions
palette.

n. Double-click
Use the Icon Editor dialog box to edit a VI icon. Double-cl the icon in the uppe
upper right corner
B. Building the Icon and Connector
onnecto Pane
ne
r D str

r D str
w to display the
of the front panel or block diagram window th Icon Editor
ditor dialog bo
box
box.

After you build a VI front panel and block


ock diagram, build
bu the icon
iccon
on and the con
connector pane so you tom control
Create an icon to represent a VI or custom control grap y. Use the Icon E
graphically. Editor dialog box to
can use the VI as a subVI. The icon and connector
connector ppane correspond
rrespond ffunction prototype in
pond to the fu create or edit icons.
text-based programming languages. Every
s. Ev
very displays an icon
ery VI displ pper right corner of the front
on in the upper
t fo l In

t fo l In
panel and block diagram windows.ws. elated VIs. Natio
You can use banners to identify related trument
umentss recom
National Instruments recomm
recommends creating and saving
a banner as a template. You then can use this te
templatee forr a related VI
V icon and modify the body
fo
of the VI icon to provide information t specific
about the cific VI.

A VI icon is a graphicall representation


presentation of a VI.. It can contain
contain ttext, images, or a combination of Saving a Banner
er as a Template
Tem
both. If you use a VI as a subVI, the iicon identifies
ntifies
ntifi es the subV
subVI on the block diagram of the VI. If Complete the following
ing steps
eps to save a banner
er as an icon tem
template for a VI.
No na

No na
you add the VI to a palette,
ette, the
the VI ic ears on the F
icon also appears Functions palette. You can double-click
ont panel window or block
the icon in the front ock diagram
d
di m window
win to customize or edit it. 1. Double-click the icon upper right
con in the up ght corner
err of the front panel window or block diagram
window, or right-click icon and select
click the ic
ico ct Ed
Edit Icon
E n ffrom the shortcut menu, to display the Icon
alog box.
Editor dialog
Note
te Customizin the icon
Customizing on iss recomme
recommend
recommended, but optional. Using the default LabVIEW
tio

tio
con
on does not affe
icon aff ctionality.
affect functionality. 2. Press the key to select
hee <Ctrl-A> keys ctt alll user layers of the icon, and press the <Delete> key to delete
lection.
on. The default
the selection. def on
n is a single us
icon use
user layer called VI Icon.
so need to build a connector pane to us
You also use the VI as a subVI. 3. Onn the Templates page, selectt the _blan
_blank.png icon template from the VIFrameworks
_bl
gory. You can
category. ca browse
see templates
temp
tem es by category or by keyword.
Na

connecto pane iss a set of termi


The connector
milar to the
similar
pane defin
th parameter
termin
terminals that correspond to the controls and indicators of that VI,
meter list off a function
nputs and outpu
defines the inputs
fun call in text-based programming languages. The connector
outputs you can wire to the VI so you can use it as a subVI. A connector
pane receives data at its input tterminals and passes the data to the block diagram code through the
Na
4.. Use the Fill tool
with a color.

the text
color
to on the

tex by pressing
he right
ight side of the Icon Editor dialog box to fill the banner of the icon

T tooll to enter text in the banner of the icon. While the text is active, you can move
5. Use the Text
ssing the arrow keys.
6. Select FileSavee AsTemplate
AsTemp to display the Save Icon As dialog box and save the icon as a
ece
front panel controls and receives the results at its output terminals from the front panel indicators. template for later use. LabVIEW saves icon templates as 256-color .png files.
e. La
Lab

National Instruments | 4-3 4-4 | ni.com


LabVIEW Core 1 Course Manual Lesson 4 Developing Modular Applications

Creating a VI Icon from a Template Setting up the Connector Pane


Complete the following steps to create a VI icon that uses the template you
u cre
created. Define connections by assigning a front panel control or indicator to each of ththe connector pane
1. Press the <Ctrl-A> keys to select all user layers of the icon, and press the <Delete> key to delete terminals. The connector pane is located to the left of the VI icon in the upper
per right corner of the
front panel window. When you open LabVIEW, you see a default connector ector pattern.
nector

uti ts

uti ts
the selection.
n browse
2. On the Templates page, select the template you created. You can rowse templa
templates by category Each rectangle on the connector pane represents a terminal. Use thee rectangles aassign inputs and
ctangles to as
or by keyword. outputs. The default connector pane pattern is 4 2 2 4. Youu can
an select a di
ddifferent pattern
pa by

rib en

rib en
3. On the Icon Text page, enter up to four lines of icon text for the body of tthe icon. n. You
ou ca
can he shortcut men
right-clicking the connector pane and selecting Patterns from the me
menu. If you ou antici
anticipate
configure the font, alignment, size, and color of the text. Iff youu place a che
checkmarkk in the Center eep the default cconnector
changes to the VI that would require a new input or output, keep or pane
ane pattern

on

on
text vertically checkbox, the Icon Editor dialog box centers ters the icon text
t vertically
rtically
lly within th
the to leave extra terminals unassigned.
body of the icon.

ist um

ist um
The front panel in Figure 4-3 has four controls and onee indicator,
dicator so LabVIEW
La
L W displays four input
i
4. On the Glyphs page, drag and drop glyphs onto the Preview are
aarea.
terminals and one output terminal on the connector pane. e.
ph horizontally or rotate
Press the <F> key or the <R> key to flip a glyph te a glyph clockw
clock
clockwise,
so can
respectively, as you move the glyph. You also an double-cl lyph
double-click a glyph h to place the glyph in Figure 4-3. Slope
pe VI Front Pan
Panel
owsee glyphs by category
the top-left corner of the icon. You can browse ry orr by keyword
keyword.
5. Use the Move tool to move any glyph. Each ach glyph
glyph iis on a separate
arate layer
layer and therefore
th moves
r D str

r D str
con become
separately. Notice that the rest of the icon becom
becomess dim
dimmed when hen you select a glyph so you can
oving.
identify which selection you are moving. ng.
6. Use the editing tools on the rightt side
de of the Icon
Ico Editorr dialog
ialog box to edit the icon further if
necessary.
t fo l In

t fo l In
reates a new user
The Icon Editor dialog box creates us layerr for each non-consecutive
non-co use of the editing
tools. Select LayersCreate New te a new user lay
w Layer to create layer during consecutive uses of
the editing tools.

Note You cannot not modify the


th icon template or icon
icon text with the editing tools on the
No na

No na
right side of the Icon Edito
Editor dialog box. Use the Te
Templates page and the Icon Text page
to modifyfy thee icon template
templ andd icon
i ext, respe
text, respectively.
Selecting and
d Modifying
Modify Terminal
Terminal Patterns
P
7. (Optional) Select
lect Layers
Layers
LayersShow Layers Pa to display the Layers page. Use this page to
rs Page Select a different
ent terminal
erminal pattern
patt
patte for a VII by rright
right-clicking the connector pane and selecting
re the name, opa
configure sibility,
lity, and ord
opacity, visibility, orde
order of the layers of the icon. Patterns fromm thee shortcut menu.
m or example,
For xample, you
yo can select a connector pane pattern with extra
tio

tio
tth extraa terminals uncon
terminals. You can leave the unconnected until you need them. This flexibility
8. Click the OK
K button tto save the
he icon inform
informa
information with the VI and close the Icon Editor dialog enables you
ou to make cha
changes withith
h minimal
minimal effe
effect on the hierarchy of the VIs.
box..
You also can dra phic
hic fr
drag a graphic fro
from anywh
nywh in the file system and drop it in the upper right
anywhere You also can have mmo nt pan
more front ontrols
ntrols or indicators than terminals. You can assign up to 28
panel controls
corner of the ffr el window
front panel window to use the graphic as a VI icon. You can drag and drop .png, minals to a con
terminals conn ane.
e.
connector pane.
Na

.bmp, or .jp

Note
No
L
.jpg files.
.j

LabVIEW
If you modify an icon
W creates a us
con informa
existing icon
use
i by dragging and dropping a graphic from the file system,
user layer called VI Icon for the graphic and deletes any other
information from the Icon Editor dialog box.
Na
The most comm
commonly used pattern is sh
simplifying w
wiring.
shown below. This pattern is used as a standard to assist in

National Instruments | 4-5 4-6 | ni.com


LabVIEW Core 1 Course Manual Lesson 4 Developing Modular Applications

Figure 4-4 shows an example of the standard layout used for terminal patterns. The top inputs and Opening and Editing SubVIs
outputs are commonly used for passing references and the bottom inputs and outputs are used for
error handling. To display the front panel of a subVI from the calling VI, use the Operating ng or P
Positioning tool to
double-click the subVI on the block diagram. To display the block diagram ram of a sub
subVI from the
Figure 4-4. Example Terminal Pattern Layout calling VI, press the <Ctrl> key and use the Operating or Positioning tool
oll to double-click
double-cl the subVI
double-clic

uti ts
out
ut

uti ts
on the block diagram.

You can edit a subVI by using the Operating or Positioning tool to double-click
double-clic the subVI
bV on the

rib en

rib en
block diagram. When you save the subVI, the changes affect all calls to the su
subVI, not just
ust th
the
current instance.

on

on
Setting Required, Recommended,
d, and Opti
Opt
Optional
al Inputs an
and

ist um

ist um
Outputs
Note Avoid using connector panes with h more
ore than 16 terminals.
als.. Although connector
ccon
In the Context Help window, the labels of requireded termin
terminals
erminals
als appear
appe bold,
app d, recommended
commended terminals
ght seem useful, they are
pane patterns with more terminals might re very
ery difficult to
t wire.
ear dimmed. The
appear as plain text, and optional terminals appear Th labels of optional
ptional terminals
term do not
lusters.
ers.
If you need to pass more data, use clusters.
appear if you click the Hide Optional Terminalsinals
ls and Full P utton
Path buttonn in the Con
Context Help
window.
r D str

r D str
Assigning Terminals to Controls
ntrols and
an Indicators
ndicators
After you select a pattern to use for thee connect
connector
nnector
or p
pan
pane, you can n assign a fron
front panel control or
ane terminals.
indicator to each of the connector pane terminals. WWhen you ou assign
ssign control
contro
controls and indicators to the
You can designate which inputs andd outputs
utputs are required,
re recomme
ecommended,
ed, and
recommended, a optional to prevent
connector pane, place inputs on thehe left and outpu
out
tputs
p on the
outputs hee right to prevent
preven
preve complicated or
t fo l In

t fo l In
bVI terminals.
users from forgetting to wire subVI
confusing wiring patterns.
Right-click a terminal on the connectortor pane and select
lect This Connection
Conne Is from the shortcut
ont ppanel control
To assign a terminal to a front ontro or indicator,
ontrol icator, click a tter
terminal of the connector pane,
menu. A checkmark indicatestes
es the
the tterminall setting. Select Required
Required, Recommended, or Optional.
Require
ntrol or indicator youu want to assign to that terminal. Click an open
then click the front panel control
You also can select ToolsOptionsFront
lsOptionsF
OptionsF Panel el and place a ch
checkmark in the Connector pane
space on the front panell window.
ndow. The tterminal change
changess to the ddata type color of the control to
uired checkb
terminals default to required checkbox. This iss option sets terminals
ter on the connector pane to
nected
indicate that you connectedd the termin
terminal.
No na

No na
ecommended.
mmended. This
required instead of recommended. T applies es to connections
connectio made using the wiring tool and to
connect
ct thee control or indicator
You also can select or first
f nd then select the terminal.
and ing Create SubV
subVIs created using SubVI.

Note
e Although yo you use the Wiring tool
too to
t assign terminals on the connector pane to Note
e You can sele
select Dynamic
amic Dispatch
Dispa Input (Required) or Dynamic Dispatch
(Recommended)) forr dynamic dispatch
utput (Recom
Output (Recomm ddi member VIs.
tio

tio
ront
ont panel contro
front contr
controls and indi
in cators, no w
indicators, wires are drawn between the connector pane and
thesee controls aand indicators.
cators.
minal
For terminalnal inputs, re
req
required meansannss that the blo
block diagram on which you placed the subVI will be
en iff you do not w
broken wire thee req
required ed
d inpu
inputs
inputs. Required is not available for terminal outputs. For
C. Using
sing Sub
SubVIs minall inputs and outputs,
terminal s, recommended
recomme
recom edd or optional means that the block diagram on which you
Na

To place a subVI
subV on the block
Navigate to th
the VI you
ock diagram, click the Select a VI button on the Functions palette.
u want to use as a subVI and double-click to place it on the block diagram.

You also ccan placee an open VI on the block diagram of another open VI. Use the Positioning tool
to click the icon in the upper rig
righ
right corner of the front panel or block diagram of the VI you want to
Na
laced
aced the subVI can execute
placed

puts and outputs


Inputs
Optional.
o
ter
not wire the terminals,

nal LabVIEW
cutee if you do nnot wire the recommended or optional terminals. If you do
the VI does not generate any warnings.

vi.lib are already marked as Required, Recommended, or


of VIs in vi.l
EW sets inputs and outputs of VIs you create to Recommended by default. Set a
quired on
terminal setting to required onl
only if the VI must have the input or output to run properly.
use as a subVI and drag g the iic
icon to the block diagram of the other VI.

National Instruments | 4-7 4-8 | ni.com


LabVIEW Core 1 Course Manual Lesson 4 Developing Modular Applications

Handling Errors in SubVIs Avoid using the Simple Error Handler VI and General Error Handler VI inside subVIs. If
necessary, use these VIs in the calling VI, as shown in Figure 4-7.
You pass errors in and out of a subVI using error clusters. Using a Case structure,
cture you handle errors
passed into the subVI with a No Error case and Error case. Figure 4-7. Block Diagram of Calling VI

tio s

tio s
The No Error case, as shown in Figure 4-5, contains the code for the norma
rmall operation of the subVI.
normal

ibu nt

ibu nt
Figure 4-5. No Error Case of Sample SubVI
bVI

n
str me

str me
Creating a SubVI from an Existing
xisting
sting VI
Di tru

Di tru
You can simplify the block diagram of a VI by converting ssectionss of the block dia diagram into
ubVI
VI by using th
subVIs. Convert a section of a VI into a subVI ioning
oning tool to sel
the Positioning select the section of
the block diagram you want to reuse and selecting
ecting Edit SubVI.. An ico
EditCreate SubVI icon for the new subVI
ock diagram. L
replaces the selected section of the block La
LabVIEW W creates
crea
reates
tes controls
control and indicators for
contro
s

s
gures
the new subVI, automatically configures es the connector
connec
conne ne based
pane ased on the nnumber of control and
indicator terminals you selected, and wires
wires the ssu
subVI to the
he existing wire
w
wires.
l In

t fo l In
The Error case, as shown in Figure 4-
4-6,
6, typica
typically passes
ses th
thee error from the error in cluster control Figure 4-8 shows how to convert a selection iinto a subVI.
ubVI.
I.
icato and contains
to the error out cluster indicator onta any code necessar
ontai necessary to handle the error.
Figure 4-8. Creating
Figu ting
ng a New SubV
SubVI
Figure 4-6
4-6. Error Case of Sample SubVI
No na

No na
tio

tio
Thee new subVI us
use
uses a default
ault
lt pattern
patte for the connector pane and a default icon. Double-click the
Na

Na
subVI
bVI to edit the connector

Note
No
ctor pane and ico

nnumber of connection
connections on
ic and to save the subVI.
icon,

Doo not select more than 28 objects to create a subVI because 28 is the maximum
o a connector pane. If your front panel contains more than
ols and indicators
28 controls indica that you want to use programmatically, group some of them
aas
into a cluster and assign the cluster to a terminal on the connector pane.

National Instruments | 4-9 4-10 | ni.com


LabVIEW Core 1 Course Manual

Self-Review: Quiz
1. On a subVI, which setting causes an error if the terminal is not wired?
d?

uti ts

uti ts
a. Required
b. Recommended
c. Optional

rib en

rib en
on

on
2. You must create an icon to use a VI as a subVI.

ist um

ist um
a. True
b. False

r D str

r D str
t fo l In

t fo l In
No na

No na
tio

tio
Na

Na
National Instruments | 4-11
LabVIEW Core 1 Course Manual Lesson 4 Developing Modular Applications

Self-Review: Quiz Answers Notes


1. On a subVI, which setting causes an error if the terminal is not wired?
d?

uti ts

uti ts
a. Required
b. Recommended
c. Optional

rib en

rib en
on

on
2. You must create a custom icon to use a VI as a subVI.
VI.

ist um

ist um
a. True
b. False
You do not need to create a custom icon to use a VI as a subVI,, butt it is highly
ity of your code
recommended to increase the readability code.
r D str

r D str
t fo l In

t fo l In
No na

No na
tio

tio
Na

Na
National Instruments | 4-13 4-14 | ni.com
Lesson 5 Creating and Leveraging Data Structures

Creating and Leveraging Data


5 A. Arrays
An array consists of elements and dimensions. Elements are the data thatt makeake up the array. A
dimension is the length, height, or depth of an array. An array can havee onee or more ddimensions

uti ts

uti ts
Structures and as many as (231) 1 elements per dimension, memory permitting. g.

You can build arrays of numeric, Boolean, path, string, waveform,, andd cluster data types. Consider

rib en

rib en
using arrays when you work with a collection of similar data and
nd when you perperform repetitive
pe epetit
Sometimes it is beneficial to group data related to one another.
er. Use arrays
arrays aan
and clusters
ters to
o group om waveforms or
computations. Arrays are ideal for storing data you collect from o data generated
erated in
loops, where each iteration of a loop produces one elementt of the
he array.

on

on
related data in LabVIEW. Arrays combine data of the samee dataa type into one data ta structure,
ucture, and
clusters combine data of multiple data types into one dataa structure.
ucture. Use type definitions
efinitions
tions to defin
defi
define
s, clusters,
custom arrays and clusters. This lesson explains arrays, usters, and
and ty finitions, and
type definitions, Note Array indexes in LabVIEW are zero-based.
based.
ed. The ind
inde
index of thee first element in the

ist um

ist um
applications where using these can be beneficial. array, regardless of its dimension, is zero.

Topics Restrictions
You cannot create arrays of arrays. However, youu can use a m multidimensional
mensional
sional array or create an
A. Arrays
ns one or more
array of clusters where each cluster contains mor arrays.
a Also, you canno
cannot create an array
r D str

r D str
B. Common Array Functions trols, ActiveX
of subpanel controls, tab controls, .NET controls, Active controls,
rols, charts, or multi-plot
m XY
C. Polymorphism graphs. Refer to the clusters section of this lesson for m formation
ormation about clusters.
more information
D. Auto-Indexing ext array that lis
An example of a simple array is a text lists the twelve
ve months oof the year. LabVIEW
trings with twelve
represents this as a 1D array of strings twelv elements.
twel ments.
nts.
t fo l In

t fo l In
E. Clusters
F. Type Definitions
Array elements are ordered. An arrayy uses an index so you can readily
read access any particular
-based
based which m
element. The index is zero-based, means it iss in the range 0 to n 1, where n is the number
xample, n = 12 for the
of elements in the array. For example, he twelve mont
months of the year, so the index ranges
from 0 to 11. March is the third month
month, so it has
as an index of 22.
No na

No na
Figure 5-1 shows an example
xample of an array of numerics.
merics. The first element shown in the array (3.00)
is at index 1, andd the second element
ele
elem (1.00 .00) is at index
dex 2. The element at index 0 is not shown in
causee element 1 iis selected
this image, because cted in the ind
index display. The element selected in the index
display alwaysys refers to the eelementt shown
own in the uup
upper left corner of the element display.
tio

tio
Figure
gure
ure 5-1. Array Control of Numerics

1
Na

Na
1 Index Display 2
2

Element Display

National Instruments | 5-1 5-2 | ni.com


LabVIEW Core 1 Course Manual Lesson 5 Creating and Leveraging Data Structures

Creating Array Controls and Indicators To add a multidimensional array to the front panel, right-click the index display and select Add
Dimension from the shortcut menu. You also can resize the index display until you have as many
Create an array control or indicator on the front panel by adding an array shell tto the front panel, dimensions as you want.
ment,
as shown in the following front panel, and dragging a data object or element,nt, which can be a
numeric, Boolean, string, path, refnum, or cluster control or indicator, into the array sshell.

uti ts

uti ts
Initializing Arrays
Figure 5-2. Placing a Numeric Control in an Array
ay Shell
You can initialize an array or leave it unitialized. When an array is initialized,
nitialized, you
yo defined the

rib en

rib en
number of elements in each dimension and the contents of each h element.
ment. An uun ized aarray
uninitialized
contains a fixed number of dimensions but no elements. Figuree 5-44 shows
shows an uninitialized
u lizedd 2D arr
array
cates that the array
control. Notice that the elements are all dimmed. This indicates arr
a ninitialized.
tialized.
is uninitialized.

on

on
Figure 5-4. 2D Uninitialized
lized
d Array

ist um

ist um
If you attempt to drag an invalid control or indicator
or into
nto the array shell, you
ou are unable tto place
the control or indicator in the array shell.

efore
re you use th
You must insert an object in the array shell before the array on the block di
dia
diagram.
Otherwise, the array terminal appears blackk with an empty
emp bracket
b andd has no data type associated
r D str

r D str
In Figure 5-5, six elements are initialized.
with it.
Figure 5-5. An Initialized
alized 2D Ar
Array with
h Six Elements
Creating Array Constants
ants
ts
t fo l In

t fo l In
To create an array constant on the block diagram, select an array constan
constant on the Functions palette,
place the array shell on the block diagram, and pplace a string
ng constant,
constant, nnumeric constant, a Boolean
ray shell.
constant, or cluster constant in the array shell You can use an array constant to store constant data
shel
on
or as a basis for comparison n with another array.

Two-Dimensional
ional
al Arrays
Array
No na

No na
In a 2D array, after you initialize
nitialize an element inn a row, the reremaining elements in that row are
A 2D array stores elements
ments in a grid.
gr It requires
equ a column index and a row index to locate an pulated
ed with the default
initialized and populated d val for
value or the data type. For example, in Figure 5-6, if you
element, both off which
ch are zero-based.
zero
zero- ure 5-3
Figure 5 shows
how an 8 column by 8 row 2D array, which lement
ent in the fir
enter 4 into the element fi mn, third
first column, thir row, th the elements in the second and third column
contains 8 8 = 644 elements
elements. w are
in the third row re automatic
automatica populated
automatically pulated
ed wit
with a 00.
tio

tio
Figure 5-3. 2D Array Figure 5-6.
Fi
Fig 6. An
n Array Aut
Autopopulated with Zeroes
Column
C Index
0 1 2 3 4 5 6 7
0
Na

1
2

Na
Row Index

3
4
5
6
7

National Instruments | 5-3 5-4 | ni.com


LabVIEW Core 1 Course Manual Lesson 5 Creating and Leveraging Data Structures

B. Common Array Functions C. Polymorphism


LabVIEW groups functions you can use to manipulate arrays on the Array
ay palette
pale
palette. The following Polymorphism is the ability of VIs and functions to automatically adapt to accept
cce input data of
functions are the most common functions you use when you work withh arrays.
ays. different data types. Functions are polymorphic to varying degreesnone, one, some, or all
a of their

uti ts

uti ts
Array SizeReturns the number of elements in each dimension of array connector pane
array.. The co inputs can be polymorphic. Some function inputs accept numeric values ues
es or Boolean values.
v Some
displays the default data types for this polymorphic function. ericc values but aalso arrays of
accept numeric values or strings. Some accept not only scalar numeric
numeric values, clusters of numeric values, arrays of clusters of numeric
meric values, and so on. Some

rib en

rib en
accept only one-dimensional arrays although the array elements can be of any tytype. Someme fun
functions
accept all types of data, including complex numeric values.

on

on
Initialize ArrayCreates an n-dimensional array in which ch every element
elem is initialized
nitialized
alized to the
value of element. Use the Positioning tool to resize the function an ase the
and increase he number oof Polymorphism for Arithmetic Functions
ctions
ons

ist um

ist um
dimensions (element, row, column, page, and so on) of the outpu
output array. The connector ppane The arithmetic functions take numeric input data. With ith some except
exceptions noted
oted
ed in the functio
functi
function
phicc function.
displays the default data types for this polymorphic descriptions, the default output has the same numeric ric representation
representatio as thee input or, if the
th inputs
have different representations, the default output is the
he larger of th ts. For
the inputs. or example, iif you add
an 8-bit integer and a 16-bit integer, the defaultt output
utput is a 16-b
16- ger. Iff you confi
16-bit integer. config
configure the
output of a Numeric function, the settings youu specify
pecify override
overri the defaultult behavior.
behavio
behavior
r D str

r D str
rs, arrays of numbers,
The arithmetic functions work on numbers, num lusters off numbers,
clusters numb arrays of
ray starting aat index
Array SubsetReturns a portion of array x and containin
containing length elements. clusters of numbers, complex numbers, andd so on.
n. A fo nd recursive definition
formal and defi
def of the
allowable input type is as follows:

calar OR array [[numericc type]


Numeric type = numeric scalar type] OR cluste
cluster [numeric types]
clust
t fo l In

t fo l In
ng-point numbers,
The numeric scalars can be floating-point num ntegers,
gers, or com
integers, comp
complex floating-point numbers.
LabVIEW does not allow youou tto use arrays of arrays.
ys.
enates
Build ArrayConcatenates ates mu
multiple arrays or appends eleme
elements to an n-dimensional array.
You also can use thee Replace
place Array Subset function
function to modify
modi an existing array. The connector
mod mberr of dimens
Arrays can have any number ny size. Clusters can have any number of elements.
dimensions of any
ctions
ns is of the same
The output type of functions ssa numeric
meric representation
representa as the input type. For functions
ult data types
pane displays the default typ for this
type his polymorphic function.
No na

No na
ons operate on each
with one input, the functions h element of the
t array or cluster.

th two
For functions with wo inputs, yyou
yo can use the following
wing input combinations:
Bothh inputs have
SimilarBoth hav the sameme structure,
ructure an
and the output has the same structure as the inputs.
tio

tio
ala One inpu
One scalarOne
alar input is a numeric
meric scalar, the other is an array or cluster, and the output is an
Index ArrayReturns the element subarr of n-dimension array at index. When you
ement or subarray array or cluster.
wiree an array to this
th function,n, the function resizes
r automatically to display index inputs for
Array fOne input
rayy of
ofOne inp is a numeric
in meric array, the
th other is the numeric type itself, and the output is
ch dimension
each mension in the arrayay youu wire to nn-dimension array. You also can add additional
ann array.
ray.
ment or subarray
element suba erminals
mina by resizing
terminals resiz
esiz the function. The connector pane displays the
Na

ty
default data types polymorp function.
for this polymorphic

Na
or similar inputs
For
For example, LabVIEW
dimensionali
dimensionalit
La
L

ddition has the same


addition
ber of
number
IEW
inputs, LabVIEW
W can
W performs the function on the respective elements of the structures.
an add two arrays

me number of el
o elements,
nts, and the res
resp
a element by element. Both arrays must have the same
w differing numbers of elements; the output of such an
dimensionality. You can add arrays with
elements as the smallest input. Clusters must have the same
respective elements must be of the same type.

ng a sc
For operations involving scalar and an array or cluster, LabVIEW performs the function on the
scalar and the respective elements of the structure. For example, LabVIEW can subtract a number
from all elements of an array, regardless of the dimensionality of the array.

National Instruments | 5-5 5-6 | ni.com


LabVIEW Core 1 Course Manual Lesson 5 Creating and Leveraging Data Structures

For operations that involve a numeric type and an array of that type, LabVIEW performs the D. Auto-Indexing
function on each array element. For example, a graph is an array of points, and a point is a cluster
on and 8 units in the y
of two numeric types, x and y. To offset a graph by 5 units in the x direction If you wire an array to or from a For Loop or While Loop, you can link eachh itera
ite
iteration of the loop
direction, you can add a point, (5, 8), to the graph. to an element in that array by enabling auto-indexing. The tunnel imagee changes
anges from
fro a solid

uti ts

tio s
square to the image to indicate auto-indexing. Right-click the tunnel and
nd select Enab
Ena
Enable Indexing
Figure 5-7 shows the possible polymorphic combinations of the Addd function.
unctio
or Disable Indexing from the shortcut menu to toggle the state of the tunnel.

ibu nt
Figure 5-7. Polymorphic Combinations of the
e Add
dd Function

rib en
on

n
str me
Array Inputs and Auto-Indexing
If you enable auto-indexing on an array wired to a For Loop op input terminal,
ter
term LabVIEW
abVIEW sets the
th

ist um
count terminal to the array size so you do not need to wiree the count
count terminal.
te . Because you can
ca use
VIEW enables
For Loops to process arrays one element at a time, LabVIEW en
enabl
abl auto-indexing
-indexing
ndexing by default
def for
able auto-indexi
every array you wire to a For Loop. You can disable auto-indexin
auto-indexing if youou do
o not need to process

Di tru
arrays one element at a time.

Polymorphism for Boolean


n Functions
Function mber
In Figure 5-9, the For Loop executes a numberber of times equal
equ to the
he number of ele
elements in the
r D str
The logical functions accept Boolean input put data, numer
numeric
ic input data, and error cl
clusters. If the input ed,
d, the run arrow is broken.
array. Normally, if the count terminal of the For Loop is not wired,
is numeric, LabVIEW performs a bitwise wise operation. If the inputput
ut is an integer, the output has the However, in this case the run arrow is not broken.

s
same representation. If the input is a floating-point
ating-point nnu
number, LabVIE VIEW
LabVIEW W round
rounds it to a 32-bit integer,
Figure 5-9.
9. Array Used to Set For
or Loop
oop Count
and the output is a 32-bit integer. Iff thee input is an error cluster,
luster,
uster, LabVIEW passes only the TRUE
t fo l In

l In
rameter of the eerror cluster
or FALSE value of the status parameter uster
er to the inpu
input terminal.

The logical functions work on arrayss of num


numb
numbers or Boolean
olean values, clusters of numbers or
cluster
luster of numbers
Boolean values, arrays of clusters mb or Boolean
oolean values, aand so on.

A formal and recursive definition


inition off th able input type is as follows, except that complex
the allowable
numbers and arrays off arrays
ays are not aallowed:d::
No na

No na
cal type
Logical ype = Boolea ar O
Boolean scalar meric
m
OR numeric scalar OR array [logical type]
eric ssc
ORR cluster all types]
uster [[logical
ctions with two iinputs can have the sam
Logical functions same input combinations as the arithmetic
tio

tio
functions. However, the lo unctions have the further restriction that the base operations can
logical functions
only be between
etween two Boo
Bo alues
lues or two num
Boolean values numbers. For example, you cannot have an AND
en a Boolean val
between umber.
mber. Figur
value and a number. Figure 5-8 shows some combinations of Boolean values
he AND function
for the functio
function.
Na

Figure 5-8.
Fig 8. Combinations
Combinatio
ombinatio of Boolean Values for the AND Function

Na
t
If you enable auto-indexing
dexing for more
mor than one tunnel or if you wire the count terminal, the actual
umber of iterations
number i s becomes the ssmaller of the choices. For example, if two auto-indexed arrays
enter the lloop, with
th 10 and 20 eele
elements respectively, and you wire a value of 15 to the count
ll only executes
terminal, the loop still exe 10 times, indexing all elements of the first array but only the
econ array.
first 10 elements of the second

National Instruments | 5-7 5-8 | ni.com


LabVIEW Core 1 Course Manual Lesson 5 Creating and Leveraging Data Structures

Array Outputs and Auto-Indexing Auto-Indexing with a Conditional Tunnel


When you auto-index an array output tunnel, the output array receives a newew element
el from every You can determine what values LabVIEW writes to the loop output tunnell base
based on a condition
quall in size to the number
iteration of the loop. Therefore, auto-indexed output arrays are always equal you specify by right-clicking the loop output tunnel and selecting Tunnel
el ModeC
ModeConditional
of iterations. from the shortcut menu.

tio s

tio s
The wire from the output tunnel to the array indicator becomes thicker
ckerr as it changes
chang to an array at
change In Figure 5-12, the array Input Array contains the following elements:
ments: 3 1, 9, 5, and 7.
ts: 7, 2, 0, 3,

ibu nt

ibu nt
resenting an array,
the loop border, and the output tunnel contains square brackets representing a s
as shown Because of the conditional tunnel, the Values less than 5 array contains
tains only ththe elements
ent 2, 0, 3,
Figure 5-10. and 1 after this loop completes all iterations.

n
str me

str me
Figure 5-10. Auto-Indexed
d Output
put Figure 5-12. An Auto-Indexing For Loop with Conditional
Conditiona Tunnel

Di tru

Di tru
Right-click the tunnel at the loop border and select
elect
ct Enable In
Indexing or Disable Ind
Indexing
Inde from the
dexi
exing.
shortcut menu to enable or disable auto-indexing.ng. Auto-indexing
Auto-ind
Auto- Loop is disabled by
for While Loops
default. Waveform Graphs
VIs with a graph usually collect the data
ta in an array and
a then plott the data to th
the graph. Figure 5-13
s

s
For example, disable auto-indexing iff you
ou need only
onl the lastt value
lue passed out
oou of the tunnel.
shows the elements of a graph.
t fo l In

t fo l In
Creating Two-Dimensional
nsional Arrays
Ar s Figure 5-13. Waveform
W rm Graph

You can use two For Loops, nested onene inside


insid the other,
ther, to create a 2D
2 array. The outer For Loop 11 1 2
nd the inner For Loop creates the column
creates the row elements, and colu
colum elements, as shown in 3
Figure 5-11. 4

Figure 5-11. Creating a 2


Figu
Figur 2D Array
No na

No na
5

10
tio

tio
6
9

7
Na

Na
1
2
3
Plot Legend
Cursor
Grid Mark
Ma
8

4
5
6
Mini-Grid M
Le
Mark
Scale Legend
Cursor Mover
7
8
9
Cursor Legend
Graph Palette
X-Scale
10 Y-Scale
11 Label

The graphs locatedd on the Graph Indicators palette include the waveform graph and XY graph. The
waveform graph plots only ssin
single-valued functions, as in y = f(x), with points evenly
distributed along the x-axis, such as acquired time-varying waveforms. XY graphs display any set
of points, evenly sampled or not.

National Instruments | 5-9 5-10 | ni.com


LabVIEW Core 1 Course Manual Lesson 5 Creating and Leveraging Data Structures

Resize the plot legend to display multiple plots. Use multiple plots to save space on the front panel and Use a plot array instead of a 2D array if the number of elements in each plot is different. For
to make comparisons between plots. XY and waveform graphs automatically adapt to multiple plots. example, when you sample data from several channels using different time amounts from each
ar must have the
arr
channel, use this data structure instead of a 2D array because each row of a 2D array
Single Plot Waveform Graphs same number of elements. The number of elements in the interior arrays of an array oof clusters can

uti ts

uti ts
vary. Refer to the (Y) Multi Plot 2 graph in the Waveform Graph VI inn the
The waveform graph accepts several data types for single-plot waveform eform
rm graphs. The
Th graph labview\examples\general\graphs\gengraph.llb for an n example
ample of a gr
graph
g that
accepts a single array of values, interprets the data as points on thee graph,
raph, and inc
increments the x accepts this data type.
index by one starting at x = 0. The graph accepts a cluster of an initial
tial x value, a delta x, aand an

rib en

rib en
array of y data. The graph also accepts the waveform data type, e, which carries the data,
ta, start
tart ti
time, The waveform graph accepts a cluster of an initial x value, a delta
lta x value, and an
a arrayy thatt contains
conta
and delta t of a waveform. clusters. Each cluster contains a 1D array that contains the y data.
a. You use the Bundle
ndle function to

on

on
bundle the arrays into clusters and you use the Build Array y function
unction to bu
build the resulting
ulting clust
cluster
clusters
Refer to the Waveform Graph VI in the labview\examples\general\graphs\
mples\genera
es\gener aphs\
s\ into an array. Refer to Clusters for more information about
boutt clusters
clusters and
an the Bundle
undlee function.

ist um

ist um
gengraph.llb for examples of the data types that a waveform
veform graph
grap accepts.
pts.
ts.
You also can use the Build Cluster Array function, which
ch creates arrays
arr usters that contain
of clusters cont the
con
Multi-plot Waveform Graphs inputs you specify. Refer to the (Xo = 10, dX = 2,, Y) Multi Plot 3 graphh in the Wavefor
Waveform Graph
The waveform graph accepts several data typess forr displaying multiple
m e plot
plots.
s. The waveform
wav graph VI in the labview\examples\general\graphs\gengraph.llb
aphs\gengrap
hs\gengrap for an example of a graph
accepts a 2D array of values, where each row w of the array is a singlee plot.
t. The graph interprets the that accepts this data type.
r D str

r D str
data as points on the graph and incrementss thehe x index by one, starting
arting at x = 0. W
Wire a 2D array
sters of an x value,
The waveform graph accepts an array of clusters v a delta x value, and
a an array of y
aph,, and select T
data type to the graph, right-click the graph, Transposeose Array from the shortcut menu
ultiple
ple-plot
-plot wave
data. This is the most general of the multiple-plot waveform graph
raph data types bbecause you can
ot. This is pa
to handle each column of the array as a plot. rlyy useful when you
particularly y sample multiple ncrement
ment for the
indicate a unique starting point and increment th x-scalee off each plot. R
Refer to the (Xo = 10,
channels from a DAQ device becausee thee device can return the data as 2D ar arrays with each channel dX = 2, Y) Multi Plot 1 graph in thee Waveform
aveform Gra
Graph VI inn thee labview\
labview\examples\general\
stored as a separate column.
graphs\gengraph.llb for an example of a graph gr
g that
at accepts this da
data
d type.
t fo l In

t fo l In
h in the Waveform
Refer to the (Y) Multi Plot 1 graph Wav Graph
aph VI in the The waveform graph also accepts the dynamic data type,
hee dynam
dynami for use with Express VIs. In
e, which is fo
labview\examples\general\graphs\gengraph.llb
era phs\ aph.llb for an example of a graph that
addition to the data associated
ted with a signal,
ed wi nal the dynamic
ynamic typ includes attributes that provide
namic data type
accepts this data type. gnal, such as the name off the signal or th
information about the signal, the date and time the data was
ecify
acquired. Attributes specifyfy how the signal
si ppears
pears on the waveform
appears wav
wa graph. When the dynamic
The waveform graph also accepts a cluster cl
clu off an initial x value,
valu a delta x value, and a 2D array of
ultiplee channels,
data type includes multiple channels the graphph displays a pl
plot for each channel and automatically
No na

No na
y data. The graph interprets
rets the y dat
terprets grap and increments the x index by delta x,
data as pointss on the graph
ial x value. This data type
starting at the initial ype is
i useful
ful for ddisplaying multiple signals that are gend
formats the plot legendd and x-scale time stamp.
sampled at the same regular rate.rate
rate Referr to the (Xo
(X = 10, 0 dX = 2, Y) Multi Plot 2 graph in the
Waveform Graphraph VI in the la labview\examples\general\graphs\gengraph.llb
l w\examples\g
ample for an Single Plot
ot XY Graphs
Graph
Grap
tio

tio
example of a graph that acc ac is data
accepts this ata type. The XY graphaph accepts three
thre data types
ypes for single-plot
single-p XY graphs. The XY graph accepts a cluster
single-p
ains an x array and
that contains an a y array.
rray. Refer to tth
the (X and Y arrays) Single Plot graph in the XY
The waveform
form graph accepts
veform ac
a a plot
ott array where the array contains clusters. Each cluster contains Graph VI in the labvi
labview\examples\general\graphs\gengraph.llb
ples\gener
les\gener for an example of a
contains the y data.
a 1D arrayy that contain dat The inner aarray describes the points in a plot, and the outer array graphh that
at accepts this
th
thi data type.
ype.
p
e
has one cluster for each ot. The front
plot. fr pan
an in Figure 5-14 shows this array of the y cluster.
panel
Na

Figure 5
5-14. Array of the y Cluster

Na
The
he XY graph al
and a y value. Refer
R
pts an array of ppoints, where a point is a cluster that contains an x value
also accepts
als
Pt Single Plot graph in the XY Graph VI in the
to the (Array of Pts)
labview\examples\general\graphs\gengraph.llb
labview\ex
cepts th
accepts this data type.
ed on the x-axis
is plotted
s\general\g
s\general\gr
ype. The XY graph
for an example of a graph that
gra also accepts an array of complex data, in which the real part
-axis and the imaginary
iim part is plotted on the y-axis.

Refer to Clusters for more


re information
in about clusters.

National Instruments | 5-11 5-12 | ni.com


LabVIEW Core 1 Course Manual Lesson 5 Creating and Leveraging Data Structures

Multi-plot XY Graphs Resize the cluster shell by dragging the cursor while you place the cluster shell.
The XY graph accepts three data types for displaying multiple plots. The XY ggraph accepts an Figure 5-15. Creation of a Cluster Control
array of plots, where a plot is a cluster that contains an x array and a y array.
ray. Refer tto the (X and Y
arrays) Multi Plot graph in the XY Graph VI in the labview\examples\general\graphs\
les\general
es\general

uti ts

uti ts
gengraph.llb for an example of a graph that accepts this data type. pe.

The XY graph also accepts an array of clusters of plots, where a plott is an array oof points. A point

rib en

rib en
is a cluster that contains an x value and a y value. Refer to the (Array Multi Plot
ray of Pts) M graph in
lot grap
the XY Graph VI in the labview\examples\general\graphs\gengraph.llb
raphs\gengra
phs\gengr lb for
or an

on

on
example of a graph that accepts this data type. The XY graph aph also accepts
accept an arrayay of clusters of
plots, where a plot is an array of complex data, in whichh the real part is plotted on the x-axis and
an Figure 5-16 is an example of a cluster containing three controls:
rols: a string
string, a Boolean
oleann switch, and
an a

ist um

ist um
the imaginary part is plotted on the y-axis. nnot contain
numeric. A cluster is either a control or an indicator; it cannot contain a mixture
ture of controls aand
indicators.
Refer to Clusters for more information about clusters.
ers.
Figure 5-16. Cluster
ter Control Exa
Exam
Example
E. Clusters
r D str

r D str
Clusters group data elements of mixed types.
es. An example
example oof a cluster
ster is the
the LabVI
LabVIEW error cluster,
mericc value, and
which combines a Boolean value, a numeric and a string.
g. A cluster is sim
ssimilar to a record or
nguages.
ges.
a struct in text-based programming languages.

Bundling several data elements intonto clusters elimi


elim
eliminates wire
re clutter on th
the block diagram and
t fo l In

t fo l In
reduces the number of connector pane terminals that subVIsbVIss need. The connector
c pane has, at most,
ntains more than 28
28 terminals. If your front panel contains 8 controls
ntrols and in
indicators that you want to pass Creating Cluster Constants
nstants
the into a cluster
to another VI, group some of them cl nd assign the cluster
and cclu to a terminal on the To create a cluster constant on the block diag
dia
diagram, select
elect a cluster
cluster cco
constant on the Functions palette,
connector pane. place the cluster shell on
n the block diagram, and
lock di d place a string cconstant, numeric constant, a
luster
Boolean constant, or clusterer consta
constant
ant in the cluster
uster shell. You can use a cluster constant to store
Most clusters on the block diagram ha nk w
have a pink wire pattern aand data type terminal. Error clusters
No na

No na
compa
constant data or as a basis for comparison ith
th another clus
with cl
cluster.
have a dark yellow wiree pattern
patterrn and data type terminal. C
Clu
Cluste of numeric values, sometimes
Clusters
nts, have a brow
referred to as points, brown wire patte d data type terminal. You can wire brown
pattern and ster control or ind
If you have a cluster in
indicator on the
he front pane
panel window and you want to create a cluster
numeric clusterss to Numeric
umeric functions,
fun suchh as Add
Ad or Square Root, to perform the same operation iningg the same elements
constant containing el
e s on the block
bloc
b diagram, you can either drag that cluster from
simultaneouslyly on
n all elemen
elements of thee cluster.
uster. nel window to th
the front panel the blockk diagram
gram or righ
rig
right-click the cluster on the block diagram and
tio

tio
ateConstant fr
select CreateConstant ffrom the shortcut menu.
Orderr of Cluster
Cluste Elements
ements
ments
Although
oughh cluster and array elements
leme are bot both ordered, you must unbundle all cluster elements at Cluster
ster
er Order
ce using
once ing the Unbundle
Unb unction.
nction. You
function. Y can use the Unbundle By Name function to unbundle Cluster
uster elements hhave a logical
ogical
cal ord
order uunrelated to their position in the shell. The first object you
Na

luster
uster elements by
cluster

either a control
b name.
have a label. Clusters
Cl
e. Iff you
you use th

contr or an indicator. A cluster

Creating Cluster
uster Controls
Co
clu
cl

and Indicators
the Unbundle By Name function, each cluster element must
lso differ from aarrays in that they are a fixed size. Like an array, a cluster is
also
cannot contain a mixture of controls and indicators. Na
place
ace in the clust

as terminals on the Bundle


dify the
modify
ement
order adjusts aautomatically.
ent 0, the sec
cluster is element
ically. The clu
undle and Unb
second is element 1, and so on. If you delete an element, the
cluste
cluster order determines the order in which the elements appear
Unbundle functions on the block diagram. You can view and
th clusterr order by right-clicking
right-
righ
hortcut menu.
Cluster from the shortcut menu
the cluster border and selecting Reorder Controls In

Create a cluster control orr indicator


in on the front panel by adding a cluster shell to the front panel,
as shown in the following front panel, and dragging a data object or element, which can be a
numeric, Boolean, string, path, refnum, array, or cluster control or indicator, into the cluster shell.

National Instruments | 5-13 5-14 | ni.com


LabVIEW Core 1 Course Manual Lesson 5 Creating and Leveraging Data Structures

The toolbar and cluster change, as shown in Figure 5-17. Using Cluster Functions
Figure 5-17. Reordering a Cluster Use the Cluster functions to create and manipulate clusters. For example, you ccan perform tasks
similar to the following:
2

uti ts

uti ts
Extract individual data elements from a cluster.
Add individual data elements to a cluster.
Break a cluster out into its individual data elements.

rib en

rib en
1

le functi
Use the Bundle function to assemble a cluster, use the Bundle unction
on and Bundlee Byy Name
function

on

on
on and the Unbu
function to modify a cluster, and use the Unbundle function Unbundle Byy Name
ame function
3
to disassemble clusters.

ist um

ist um
nbundle,
You also can place the Bundle, Bundle By Name, Unbundle, ndle, and Unbundle
Un functi
By Name functions on
nal on the block
the block diagram by right-clicking a cluster terminal bloc diagram
am and selecting Cluster,
Class & Variant Palette from the shortcut menu. nu. The
The Bundle aand Unbundle
bundle
dle functions
function
erminals.
inals. The B
automatically contain the correct number of terminals. Bundle By Name and Un Unbundle By
Name functions appear with the first elementntt in the cluster. Use thee Positioning
ositioning to
too
tool to resize the
r D str

r D str
Bundle By Name and Unbundle By Namee functions
unctions to ssh other elements of the cluster.
show the other
5 4
Assembling Clusters
1 Confirm Button 3 Cluster
ster Order Cursor
C 5 New Order
2 Cancel Button 4 Current Orde
Order Use the Bundle function to assemble ble a cluster from individual
idual
ual elements
eleme oor to change the values of
t fo l In

t fo l In
individual elements in an existingg cluster without
withou having
witho ng to specify new
ne values for all elements.
The white box on each element shows ows its curr
current placece inn the cluster order. The black box shows he function oor right-click
Use the Positioning tool to resize the -click
ck an elemen
element input and select Add Input
or an element.
the new place in the order for nt. To set thee order of a cluste
clu
cluster element, enter the new order from the shortcut menu.
b and click the element.
number in the Click to sett to text box eleme The cluster order of the element
changes, and the clusterr order
der of other eelementss adjusts. Save tththe changes by clicking the Confirm Figure
ure 5-18. Asse
Assembling a Cluster on the Block Diagram
ert to the original
button on the toolbar. Revert or
o order by clicking the Cancel button.
No na

No na
Autosizing
g Clusters
lusters
Complete thee following
lowing steps to shrink
nk clusters to fi
fit their contents.
tio

tio
1. Right-click
click shell border
lick a cluster sh AutoSizingSize to Fit from the shortcut menu.
der and select A
2. Add another
nother elemen
eleme
element to the cluster
uster shell. W
When AutoSizingSize to Fit is selected, the cluster Disassembling
ssembling
sembling Clusters
C rs
s
sizess itself if nec
resizes necessary wh
when you add
add aanother element to the cluster shell. Use the
he Unbundle fun
function to
o sp
split a cluster
cluster iinto its individual elements.
3. Right-click th
the cluster shell
hell bo
bord d select AutoSizingArrange Horizontally or
border and
Na

AutoSizing
AutoSizingArrange ge Vertically fro
horizontally or vertically.
tically.
fr
from the shortcut menu to arrange the elements in the cluster

Na
Use
se the Unbundle By Name
output terminals
number of outpu

While the Unbundle


U
disp specific
set to display
unction to return the cluster elements whose names you specify. The
me function
depend on the number of elements in the input cluster.
nalss does not de

e function displays
displa all parts of a cluster, the Unbundle by Name function can be
cific elements of
o a cluster only. To select which elements the Unbundle by Name
play, use the Operating tool to click an output terminal of the function and select
function should display,
l-dow menu. You also can right-click the output terminal and select the
an element from the pull-down
element from the Select Item shortcut menu.

National Instruments | 5-15 5-16 | ni.com


LabVIEW Core 1 Course Manual Lesson 5 Creating and Leveraging Data Structures

For example, if you use the Unbundle function with the cluster in Figure 5-19, it has four output In Figure 5-21, you can use the Bundle By Name function to update the values of Command and
terminals that correspond to the four controls in the cluster. You must know the cluster order so you Function with the values of New Command and New Function.
can associate the correct Boolean terminal of the unbundled cluster with the he corresponding
corr
corre switch
tom starting with
in the cluster. In this example, the elements are ordered from top to bottom w element Figure 5-21. Bundle By Name Used to Modify a Cluster
luster
ter

uti ts

uti ts
0. If you use the Unbundle By Name function, you can have an arbitrary rary
ry number of output
o
terminals and access individual elements by name in any order.
Figure 5-19. Unbundle and Unbundle By Name

rib en

rib en
on

on
Use the Bundle By Name function for data structures that might ght change during
du development.
evelopment.
opment. If you
yo
y
add a new element to the cluster or modify its order, youu do not needd to rrewire the
he Bundle By Name
Na
N

ist um

ist um
function because the names are still valid.

Error Clusters
LabVIEW contains a custom cluster called the
he error
rror cluster. LabVIEW
EW uses error cl
cclusters to pass
r D str

r D str
error information.

Modifying a Cluster For more information about using errorr clusters, on 2, Troublesho
usters, refer to Lesson Troubleshooting and
Troublesh
If you wire the cluster input, you cann wire
re only the elements
eel s youu wantt to cha
change. For example, the he Handling Er
Debugging VIs, of this manual and the Err pic off the LabVIE
Errors topic LabVIEW Help.
Input Cluster shown in Figure 5-20 0 contains
ontains three controls.
ls..
t fo l In

t fo l In
Figure 5-20. Bundle
Bundl Used to Modify a Clus
Cluster
F. Type Definitions
You can use type definitions to ddefine custom
ustom arrayss and
and clusters. A type
t definition is a master copy
tom
of a custom data type (customm contr
control, indicator, or constant
constant) that multiple VIs can use. When you
u cann update al
use type definitions, you alll instances
es or copies of th
the custom data type in a single edit.
No na

No na
Custom Controls
ntrols
rols and Indicators
i tors
If you know the cluster
ter order,
order, you
yo can use
se the
he Bundle
B le fufunction to change the Command value by
Use custom controls
trols and indicat
indicators to extend
xtendd the
th available
b set of front panel objects. You can create
ments
ts shown in F
wiring the elements Figure 5-20..
ols and indicator
custom controls n application
indicators for an lication tha
that vary cosmetically from built-in LabVIEW
tio

tio
You can also
soo use the Bundle
Bund By Name me function to replace
aame r or access labeled elements of an existing d indicators. Yo
controls and You can save
ve a custom contr
ccontrol
ont or indicator you create in a directory or LLB
he Bundle By Name
cluster. The N unction
nction works like
function li
lik the Bundle function, but instead of referencing he custom contro
and use the dicator on othe
control or indicator other front panels. You also can create an icon for the
ements by their
cluster elements the cluster order,
der, it references
refe
refere them by their owned labels. You can access ontrol or indicator
custom control indic
indi and add
dd it to the Co
Controls palette.
only elements
ments with oowned labels.
abels.
bels Thee numb
number of inputs does not need to match the number of
er too the Creatin
Refer om
m Controls,
Creating Custom Contr
Con I d
In
Indicators, and Type Definitions topic of the LabVIEW
ments in output
elements outpu cluster.
r.
Na

to display sp
Bund function
While the Bundle
spe
ction should
function ssh
an element from the
ction displays all
lements
ements off a cluster
specific elements clu
splay, use the Op
display,
he pull-down m
l parts of a cluster, the Bundle by Name function can be set
only. To select which elements the Bundle by Name
Operating tool to click an output terminal of the function and select
menu. You also can right-click the output terminal and select the
Na
elp for more information
Help

Use the Cont


Contr
he size, color,
the
inf on about
bout creating
creatin and using custom controls and type definitions.

Control Editorr window to cus


col and relative position
ontro or indicator.
the control cator.
cu
customize controls and indicators. For example, you can change
position of the elements of a control or indicator and import images into

element from the Select ct Item shortcut menu.

National Instruments | 5-17 5-18 | ni.com


LabVIEW Core 1 Course Manual Lesson 5 Creating and Leveraging Data Structures

You can display the Control Editor window in the following ways: Customize Mode
Right-click a front panel control or indicator and select AdvancedCustomize
sto from the In the customize mode, you can move the individual components of the control
trol around
a with respect
shortcut menu. to each other. For a listing of what you can manipulate in customize mode,
de, select
selec WWindowShow
Parts Window.

uti ts

uti ts
Use the Positioning tool to select a front panel control or indicator and
nd select Edit
Edi
EditCustomize
Control.
Use the New dialog box.

rib en

rib en
ct inn its window.
The Control Editor appears with the selected front panel object window
window The Control
rol Editor
Edi
has two modes, edit mode and customize mode. 1 2 3 4 5 6 7

on

on
1 Customize Mode 5 Distribute
bute Objects
The Control Editor window toolbar indicates whether you are in edit mode
m or in customize
stomize mo
mode. 2 Type Definition Status 6 Resize
size Objects

ist um

ist um
The Control Editor window opens in edit mode. Clickk thee Change to Customize
mize Mode butt
but
button to 3 Text 7 Reorder
eorder Objects
Objec
change to customize mode. To change back to edit mode,
de, click the Changee to Edit Mode button. 4 Align Objects
You also can switch between modes by selecting OperateChan
rateChan to Customize
OperateChange Mode or
tomize Mod
One way to customize a control is to change its typee definition
definition status.
s You can save a control
c as a
OperateChange to Edit Mode.
ition,
n, depending on the selection
control, a type definition, or a strict type definition, ection visible in the Type
Def. Status ring. The control option is the sameame
me as a contro
control you would select from the Controls
r D str

r D str
palette. You can modify it in any way you need eed to, and eac
ea
each copyy you make and cchange retains its
individual properties.

Use edit mode to change the size orr color


olor of a ccont
ont or indicator
control ndicator
ator and to select options from its Saving Custom Controlss
t fo l In

t fo l In
shortcut menu, just as you do in edit mode on a ffront panel.
anel.
el. After creating a custom control, you can save it for use later.
ter. By default,
defau controls saved on disk
default
have a .ctl extension.
Use customize mode to make extensive ive chan
changes to controls or indic
indicators by changing the
oll or in
individual parts of a control indicator. You also can use the Control
rol Editor to save controls
ol Edito ls with your own
ols ow default settings. For example,
you can use the Control Editor
tor to modify
modi the defaults
faults
faults of a waveform
wavef graph, save it, and later recall
Edit Mode it in other VIs.
No na

No na
In the edit mode, you
ou can right-clic
right-click the controll and mani
manip
manipulate its settings as you would in the
amming
LabVIEW programming ming environ
environment. Type Definitions
nitions
ons
Use type definitions
nitions
ons and strict
stric type definitions
efinitions
tions tto lin
link all the instances of a custom control or
indicator to a saved custom control or indicator
ndicator file
fil
file. You can make changes to all instances of the
tio

tio
ontrol
trol or indicato
custom control diting only the sa
indicator by editing saved custom control or indicator file, which is
useful iff you use the same
sam
sa custom m control
control or in
indicator in several VIs.
1 2 3 4 5 6 7
Whenen you
ou place a cu ontrol
ntrol oor indicator
custom control dicat
ica in a VI, no connection exists between the custom
1 Edit Mode 5 Distribute Objects
Na

2
3
4
Text
Definition Status
Type Definitio

Align Obje
Objects
6
7
Resize Objects
Reorder Objects

Na
ontrol
ntrol or indicato
control
instance
tance of a cus
make to a custom
cust
cu
cu

ndicator. If you want


indicator.
aved
indicator you saved
ntrol
custom control
d and the iinstance of the custom control or indicator in the VI. Each
ol or indicato
indicator is a separate, independent copy. Therefore, changes you
trol or indicator
control indicat file do not affect VIs already using that custom control or
ant to link instan
instances of a custom control or indicator to the custom control or
ator ffile, savee the custom co
indicator
instances of a type definition or
con
control or indicator as a type definition or strict type definition. All
o a strict type definition link to the original file from which you
created them.

When you save a custom control or indicator as a type definition or strict type definition, any data
type changes you make to the type definition or strict type definition affect all instances of the type

National Instruments | 5-19 5-20 | ni.com


LabVIEW Core 1 Course Manual

definition or strict type definition in all the VIs that use it. Also, cosmetic changes you make to a
strict type definition affect all instances of the strict type definition on the front panel.

Type definitions identify the correct data type for each instance of a custom tom
m control or indicator.

uti ts

uti ts
When the data type of a type definition changes, all instances of the type ype
pe definition aau automatically
nition
update. In other words, the data type of the instances of the type definition n change
change in each VI where
the type definition is used. However, because type definitions identify ntify
y only the
the da data type, only the
mericc controls, th
values that are part of the data type update. For example, on numeric tthe data rang
range is not

rib en

rib en
part of the data type. Therefore, type definitions for numeric controlstrols do nott ddefine thehe data ran
range
em names
for the instances of the type definitions. Also, because the item ames in ring controls ls do
o not define

on

on
the data type, changes to ring control item names in a typee defini
finition
tion do no
definition not change ge the
he item name
nam
names
in instances of the type definition. However, if you changengee the item
item nnam definitio
definiti
names in the type definition

ist um

ist um
for an enumerated type control, the instances update because ause the item namess are part of the data
type. An instance of a type definition can have its ownwn unique capti el,, description,
caption, label, description, tti
tip strip,
dicator,
ator, such as a knob instead
default value, size, color, or style of control or indicator, tead of a slid
slide.

If you change the data type in a type definition,on, LabVIEW cco converts the old default value
v in
instances of the type definition to the new dataata type, if possible.
ppos canno preserve the
LabVIEW cannot
r D str

r D str
nges to an incompatible
instance default value if the data type changes incom type, such as re
rep
replacing a numeric
ol orr indicator. W
control or indicator with a string control When the hee data type of a type definition
changes to a data type incompatible withh the previous
previou
previo type definition,
nition, LabVIEW
LabV sets the default
lue you specify in the .ctl
value of instances to the default value ctl file. If you do not specify a default
t fo l In

t fo l In
value, LabVIEW uses the defaultt value for the ddata type. e. For example,
example iif you change a type
ring type, LabVIEW
definition from a numeric to a string Lab laces any default
replaces de
deff values associated with
the old numeric data type withith emptyy strings.
strings
string

Strict Type Definitions


nitions
ons
A strict type definition
on forces
ces everyth
everyt
everything about
out
ut an instance
instanc tto be identical to the strict type
No na

No na
definition, except the caption, labe
label
label, description, tip strip, and default value. As with type
definitions, the data type of a str
stri
strict type defini
ini
definition emai the same everywhere you use the strict
remains
type definition.. Strict
rict type
type defin
definitions also defi
define oother values, such as range checking on numeric
controls and the item
tem names in i ring controls.
rols. The onl
on
only VI Server properties available for strict type
tio

tio
definitions are those that affect
af thee appearance of th
the control or indicator, such as Visible, Disabled,
Key Focus,us,
s, Blinking, Position,
Po and
nd Bounds.

not prevent aan instance


You cannot nce
ce of
o a strict
trict
rict tty
y definition from automatically updating unless you
type
move the link bbe
remove he instan
between the instance and the strict type definition.
Na

Type definition
If you need to add a new
he cus
to the custo
rict type definiti
definitions and strict definitions create a custom control using a cluster of many controls.
ew control and pass a new value to every subVI, you can add the new control
trol cluster. This substitutes having to add the new control to the front panel of
custom control
b and making new wires
bV
each subVI wir and terminals.
Na
National Instruments | 5-21
LabVIEW Core 1 Course Manual

Self-Review: Quiz
1. You can create an array of arrays.

uti ts

uti ts
a. True
b. False

rib en

rib en
2. You have two input arrays wired to a For Loop. Auto-indexing ing iss enabled on both tunnels.
unnel One
array has 10 elements, the second array has five elements.s. A value of 7 isi wired to the
he Cou
Count
terminal, as shown in Figure 5-22. What is the value off the Iterations
Iteration indicatoror after
ter running

on

on
this VI?

ist um

ist um
Figure 5-22. What is the Value off the
e Iterations Indicator?
I or?
r?

r D str

r D str
t fo l In

t fo l In
3. Which of the following custom m control settin
setting
settings defines
nes the data type oof all instances of a control
but allows for different colors and font styles?
sty
a. Control
b. Type Definition
efinition
ion
c. Strict Type Definition
No na

No na
trol
d. Cluster control

nput data representing


4. You have input represe
represen le: X Position,
a circle: Po Y Position, and Radius. In the future, you
ed too modify your
might need you data to include
nclude the co
color of the circle.
tio

tio
What data
ata structure sh ou use to represent
should you represe the circle in your application?
hree separate controls
a. Three c forr the two pos
positions and the radius.
b.. A cluster con
containing all o
of the data.
Na

aar
d
e. An array
c
c. A custom control
on containing
d. A type definition
containing
taining a ccluster.
ontaining a cluster.
th three element
with elements.
c
Na
National Instruments | 5-23
LabVIEW Core 1 Course Manual Lesson 5 Creating and Leveraging Data Structures

Self-Review: Quiz Answers 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.
1. You can create an array of arrays. plication?
catio
What data structure should you use to represent the circle in your application?

uti ts

uti ts
a. True a. Three separate controls for the two positions and the radius.
b. False b. A cluster containing all of the data.
You cannot drag an array data type into an array shell. However,
ever, create
r, you can cr
c c. A custom control containing a cluster.

rib en

rib en
two-dimensional arrays. d. A type definition containing a cluster.

on

on
2. You have two input arrays wired to a For Loop. Auto-indexing
xing is enabled
ndexing enab on both tunnels.
enabl unnels. One e. An array with three elements.
array has 10 elements, the second array has five elements.
ments.s. A value oof 7 is wired
d to the Cou
Count

ist um

ist um
ue of the Iterations
terminal, as shown in Figure 5-23. What is the value Iterat dicator after running
indicator runn
run
this VI?
Figure 5-23. What is the value
ue of the Iterations
Iterati indicator?
icator?
or?
r D str

r D str
t fo l In

t fo l In
Value of Iterations = 4
LabVIEW does not exceedd the arr array size. This protect against programming error.
his helps to prot
LabVIEW mathematical al functions work the
atical wayif you wire a 10 element array to the
he same wayi
No na

No na
d function,
x input of the Add ction, and
and a 5 element
ent
nt array to th
the y input of the Add function, the output
is a 5 element array.
y.
Although thehe for loop runs 5 times,, the iterations
iter
iterati are zero based, therefore the value of the
Iterations indicators
cators is 4.
tio

tio
3. Which h of the following custom settings defines the data type of all instances of a control
m control settin
setting
but allows different colors
lows for diffe
differ rss and font styles?
style
styl
a. Control
b. Type Definition
Defin
Defi
Na

c. Strict Type
d. Cluster
Ty Definition
finition
Clust control
ol
ion
Na
National Instruments | 5-25 5-26 | ni.com
LabVIEW Core 1 Course Manual Lesson 5 Creating and Leveraging Data Structures

Notes Notes

uti ts

uti ts
rib en

rib en
on

on
ist um

ist um
r D str

r D str
t fo l In

t fo l In
No na

No na
tio

tio
Na

Na
National Instruments | 5-27 5-28 | ni.com
Lesson 6 Managing File and Hardware Resources

Managing File and Hardware


6 A. Understanding Hardware and Software Resources
A resource is an addressable file, hardware device, object, or network connection
nnection
ctio available on the
system. The system identifies resources using paths, names, ports or other identifiers.
her iden tifiers Using these
dentifiers.

uti ts

uti ts
Resources identifiers and the VIs and functions that LabVIEW provides, you can
access those resources.
an program your
you system to

rib en

rib en
You have learned how to acquire data and how to display it, but storage of youry dataa is usually a Accessing Resources in LabVIEW
A typical resource operation involves the following operations
ions as shown in Figuree 6-1::

on

on
very important part of any project. You have also learned how to o set up yyo dwaree and
your hardware
configure it in the Measurement & Automation Explorer. r. In this lesson, you learn
arn about storin
storing 1. Creating a resource.
data, programming a basic DAQ application using the DAQmx AQmx API, and a controlling
trolling stand-alone
stand-alo
stand-al

ist um

ist um
instruments with the VISA API and instrument drivers rs inn LabVIEW
LabVIEW. 2. Reading and writing to a resource.
3. Closing the resource.
Topics 4. Checking for errors from the resource.

A. Understanding Hardware and Software Resources


ource Figure 6-1. typical
pical
cal Resource O
Operation
on
r D str

r D str
B. File I/O
AQ System
C. Acquiring Measurements with a DAQ
1 2 3 4
D. Controlling Instruments
t fo l In

t fo l In
1 Open, Initialize or create resourceLabVIEW
ceLabVIEW creates a reference
eference number
num (refnum) as a unique
identifier for the resource
2 Read/Write to resource
3 Close resourceThe refnum m beco
becomes obsolete
4 Check for errorsDisplayy any errors from the resource
No na

No na
Tip The function
ction or VI nnames associated
ciated with ccr
creating a resource generally include one
ollowing
wing verbs: oopen, initialize,
of the following nitial or creat
create. The function or VI that creates the
rce takes
resource kes a resource
resou pathh or device
dev name as an input and then creates a unique
ntifier
er to the reso
identifier resource.
tio

tio
Reference
ence
nce Numb
Numbers (Refnums)
Refnums)
A reference
erencee number, oor refnum,
m, is a unique ididentifier for a resource. When you open a file, device,
etwork
ork connection,
or network connecti LabVIEW VIEW ccreatestes
es a refnum associated with that file, device, or network
Na

Na
onnection.
nnection. All op
connection. operationss youu perform on open files, devices, or network connections use the
refnums to identify
ident eachh object.
iden
example, use a refnum
without clos
bject. Use a refnum
m control to mmod
r control to pass a refnum into or out of a VI. For
modify the contents of the file that a refnum is referencing
closing andd reopening the file.

Because a refnum iss a temporar


te
f

mporar pointer to an open resource, it is valid only for the period during
temporary
pen. IIf you close the resource, LabVIEW disassociates the refnum from the
which the resource is open.
resource, and the refnum becomes obsolete. If you open the resource again, LabVIEW creates a

National Instruments | 6-1 6-2 | ni.com


LabVIEW Core 1 Course Manual Lesson 6 Managing File and Hardware Resources

new refnum that is different from the first refnum. LabVIEW allocates memory for a resource that B. File I/O
is associated with a refnum. Close the refnum to release the resource from memory.
File I/O operations pass data to and from files. Use the File I/O VIs and functions
ctio to handle all
LabVIEW remembers information associated with each refnum, such ass thee current location for aspects of file I/O.

tio s

uti ts
reading from or writing to the object and the degree of user access, so you can can perfor
perform concurrent
ject multiple tim
but independent operations on a single resource. If a VI opens an object times, each open
Understanding File I/O

ibu nt
operation returns a different refnum. LabVIEW automatically closes oses refnums for you when a VI
efnums
f ums as soon as you are ffinished
finishes running, but it is a good programming practice to close refnums

rib en
A typical file I/O operation involves the following process as shown
hown
n in Figure 6-3.
with them to most efficiently use memory and other resources. Close ose refnums
refnum in the opposite site ord
order
1. You create or open a file. After the file opens, a unique identifier
fierr called a refnum
entifie m represents
presents the
that you opened them. For example, if you obtain a refnum to objectbject A and invokee a method on

on
str me
file.
object A to obtain a refnum to object B, close the refnum too object
bject B first aand thenn close
ose the refnum
refnu
to object A. 2. The File I/O VI or function reads from or writes to the file.

ist um
3. You close the file.
Examples of Refnum APIs
Figure 6-3. Steps in a Typical
cal File I/O Operation
O on
When interfacing with a DAQ device using the DAQmx Qmx driver A
API, thee reference
ference is ref
re
referred to as

Di tru irtual
al channels w
a task. A task is a collection of one or more virtual ming,
with timing,
properties. Conceptually, a task represents a measurement oor generation
ration
g, triggering,
triggering and other
on you want to perform.

r D str
1 2 3 4

When controlling an instrument using thee VISA API, the


th reference
nce is referred to
t as a VISA session.
The VISA session is maintained by thee VISASA resou
resourc trol.
resource name control.
s
1 Open File 3 Close File
rent APIs and tth
Figure 6-2 illustrates several different ums
ms they use to access
the refnums a resources. 2 Read/Write File 4 Checkk for Error
Errors
t fo l In

t fo l In
Figure
ure 6-2. Example
Ex
Exa Refnum
num Wiring
File Formats
LabVIEW can use or create
atee the following
fol file formats:
rmats:
mats: Binary, ASCII,
A LVM, and TDMS.
BinaryBinary files underlying file
les are the under ile
le format of all oother file formats.
format
No na

No na
ASCIIAn ASCII CII filee is a specific
spec type of binary file
fil that
t is a standard used by most
programs. It consists
sts of a series
onsists serie of ASCII
serie C codes. ASCII files are also called text files.
des. ASC
LVMThe LabVIEW VIEW meameasurement ent data file (.lvm) is a tab-delimited text file you can open
eadsheet
sheet application
with a spreadsheet applica t-editing application.
or a text-editing ap The .lvm file includes information
tio

tio
he data, such as the
about the t datee andd time the data
da was generated. This file format is a specific
cre
type of ASCII file created forr LabVIEW.
DMS This file format
SThis
TDMSThis f pecific type
is a specific typ of binary file created for National Instruments
ducts. It actually
products. actua consists
sists
ists of
o two
woo separate
sep
sepa filesa binary file that contains data and stores
properties abo
abou ata, and a bbi
about the data, binary index file that provides consolidated information on all
Na

Na attribute and pointers


the attributes

course you learn


cours
In this course,
fro another
the file from
to perform random
earn
inters
ers in the binary

arn about creating


creat
creat
her application, if
bin file.

text (ASCII) files. Use text files when you want to access
i disk space and file I/O speed are not crucial, if you do not need
m access read oor writes, and if numeric precision is not important.

Le
You used an LVM file in Lesson 1, Navigating LabVIEW. To learn more about binary and TDMS
files, refer to the LabVIEW Help or the LabVIEW Core 2 course.

National Instruments | 6-3 6-4 | ni.com


LabVIEW Core 1 Course Manual Lesson 6 Managing File and Hardware Resources

Understanding High-Level File I/O To avoid opening and closing the same file, you need to pass a refnum to the file into the loop.
When you open a file, device, or network connection, LabVIEW creates a refnum associated with
Some File I/O VIs perform all three steps of a file I/O processopen, read/write, d/wri and close. If a pen file
that file, device, or network connection. All operations you perform on open files, devices, or
VI performs all three steps, it is referred to as a high-level VI. However,, these ese VIs mmay not be as network connections use the refnums to identify each object.
efficient as the low-level VIs and functions designed for individual parts process. If you are
rtss of the proces
proce

uti ts

uti ts
g too a file in a sin
writing to a file in a loop, use low-level file I/O VIs. If you are writing single operation, The examples in Figure 6-4 and Figure 6-5 show the advantages of usingusin
ing
g disk streaming.
stream In
you can use the high-level file I/O VIs instead. on off the loop. Figure
Figure 6-4, the VI must open and close the file during each iteration F 6-5 uses
disk streaming to reduce the number of times the VI must interact withh the operating
opera
operati system em to open

rib en

rib en
LabVIEW includes the following high-level file I/O VIs: gins and closing it afterr thee loop
and close the file. By opening the file once before the loop begins loo
completes, you save two file operations on each iteration of the loop.
Write to Spreadsheet FileConverts a 2D or 1D array y of doubl
double-prec
e-prec
double-precision umbers
numbersers to a text

on

on
pends
string and writes the string to a new ASCII file or appends ds the string to an existing
xisting
ing file. You
Yo Figure 6-4. Non-Disk Streaming
ming
g Example
also can transpose the data. The VI opens or createss thee file before
befor writing g to it and closes it

ist um

ist um
afterwards. You can use this VI to create a text filee readable
eadable by m readsheet
eadsheet applications.
most spreadsheet applic
applica
Read From Spreadsheet FileReads a specified fied number of li
lines or rows
ws from a num
numeric text
file beginning at a specified character offset andd converts the
th data too a 2D double-p
double-precision
fore reading from it and closes
array of numbers. The VI opens the file before es it afterwards.
af
afterwa
fterwards.
terwa You can
ed
d in text forma
use this VI to read a spreadsheet file saved format.
r D str

r D str
Write to Measurement FileAn Express press
ss VI that wri
wr
writes dataa to a text-based measurement file
(.lvm) or a binary measurement filee (.tdms
tdms) form
format. You u can specify the save method, file
format (.lvm or .tdms), header type, and delim
delimi
delimiter.
Read from Measurement FileAn eAnAn Express VI that reads
eads data from a text-based
t fo l In

t fo l In
measurement file (.lvm) or a binary measure
measurement file
ile (.tdms
.tdm ) form
format. You can specify the file Figure
gure 6-5. Disk Streaming
ming Example
nt size.
name, file format, and segment

Tip Avoid placing


cingg the hi
high-level VIs in loops,
loops, because the VIs perform open and close
ch time
operations each ime they run
run.
No na

No na
Understanding
ding
ng Low-Level
Low-L el FFile
e I/O
Low-level file I/O
/O VIs
Is and func
functions each
ach perf
perform only one piece of the file I/O process. For
re is one function
example, there functio to open
en ann ASCII file
file, one function to read an ASCII file, and one
tio

tio
function to close an ASCI
ASCII file. Use
se low-level
w-level func
functions when file I/O is occurring within a loop.

Diskk Streaming
treaming with Low-Level
ow-Level
w-Level Functions
You also o can use Fil
File I/O functions
unctions
nction for disk streaming operations, which save memory resources LabVIEW
bVIEW
VIEW Data
Da Directory
Direc
irec ory
ry
Na

byy reducing the nu


the file. Disk str
operations, fo

ng a path
Wiring
number off times

p control
mes the fun

ple, within a lo
for example,

trol or a constant
loo
function interacts with the operating system to open and close
streamingg is a technique ffor keeping files open while you perform multiple write
loop.

constan to the Write to Text File function, the Write to Binary File
const
te To Spreadsheet
function, or the Write Sprea File VI adds the overhead of opening and closing the file
Na
You
ou can use the default
a .lvm
as lvmm or
o .tx
de

W LabVIEW
default, the Write abVIEW
IEW Data directory to store the data files LabVIEW generates, such
LabVIEW
abVIEW
.txt files. LabVIEW
opera
oper
for your operating
VIEW installs
instal the LabVIEW Data directory in the default file directory
stem to help yo
system you organize and locate the data files LabVIEW generates. By
VIEW Measurement
Measu
ctory, and the Read LabVIEW
directory,
File Express VI stores the .lvm files it generates in this
LabVIE Measurement File Express VI reads from this directory. The
tory constant
Default Data Directory constan and the Application:Default:Data Directory property also return
each time the function or VI eexecutes. VIs can be more efficient if you avoid opening and closing the LabVIEW Data directory
rector by default.
rectory
the same files frequently.

National Instruments | 6-5 6-6 | ni.com


LabVIEW Core 1 Course Manual Lesson 6 Managing File and Hardware Resources

Select ToolsOptions and select Paths from the Category list to specify a different default data Using a Terminal Block and Cable
directory. The default data directory differs from the default directory, which is the directory you
ocumen
specify for new VIs, custom controls, VI templates, or other LabVIEW documentsume you create. A terminal block provides a place to connect signals. It consists of screw or spr
spring terminals for
connecting signals and a connector for attaching a cable to connect the terminal
minal block
blo to a DAQ
device. Terminal blocks have 100, 68, or 50 terminals. The type of terminal
minal block you
rminal yo should

uti ts

uti ts
C. Acquiring Measurements with a DAQ System
ystem choose depends on two factorsthe device and the number of signals als you are meas
measuring.
A terminal block with 68 terminals offers more ground terminals to connect
onnect a sig
signal to than a
A data acquisition (DAQ) system uses a data acquisition device to passass a conditi
conditioned electrical
vents the need
terminal block with 50 terminals. Having more ground terminals prevents ne
nee to overlap
erla wires

rib en

rib en
ou can
signal to a computer for software analysis and data logging. You n choose a data acquisition
cquisiti
ween
to reach a ground terminal, which can cause interference between n the signals.
signals
he computer US
device that uses a PCI bus, a PCI Express bus, a PXI bus, or the EEE 1394 por
USB or IEEE port.

on

on
on system
This section explains the hardware used in a data acquisition stem and how
h to configure
gure the Terminal blocks can be shielded or non-shielded. Shieldedd terminal
minal blocks
block offer better
er protection
devices. res, such as cold
against noise. Some terminal blocks contain extra features, on compensation
cold-junction ompensation
compensation,

ist um

ist um
e.
that are necessary to properly measure a thermocouple.
warea
ea terminal
A typical DAQ system has three basic types of hardwarea termina block,
k, a cable, and a DAQ
D
device, as shown in Figure 6-6. ck too the DAQ ddevice. Cables
A cable transports the signal from the terminal block bles come in 1100-, 68-,
Figure 6-6. Typical
pical
al DAQ Syst
Syste
System and 50-pin configurations. Choose a configurationon depending on o the terminal
rminal
nal block and the DAQ
ocks,
device you are using. Cables, like terminal blocks,s, are shielde on-shielded.
hielded.
shielded or non-shielded.
2 4
r D str

r D str
Refer to the DAQ section of the National Instruments
struments cata
cat
catalog or to ni.com/pro
ni.com/products for more
3 inall blocks and cables.
information about specific types of terminal

NATIONAL
INSTRUMENTS BNC-2120
t fo l In

t fo l In
NATIONAL
INSTRUMENTS
Figure 6-7 shows the BNC-2120,, which can be uused to complete
mplete the ex
eexercises in this course.
No na

No na
5

1
tio

tio
1 Signal 4 DAQ Device
2 Terminal Block
al Bloc 5 Computer
3 Cable
e
Na

After
fter you have converted

mputer into
computer
co
conditioning, you
d a physical phenomenon
y needd to acquire that
cable, a DAQ device,
in a measurement
phe
ph into a measurable signal with or without signal
that signal. To acquire a signal, you need a terminal block, a
e, and a compute
comput
computer. This hardware combination can transform a standard
easurement and automation system.
Na
National Instruments | 6-7 6-8 | ni.com
LabVIEW Core 1 Course Manual Lesson 6 Managing File and Hardware Resources

Figure 6-7. BNC-2120 Using DAQ Devices


ANALOG INPUTS NATIONAL Most DAQ devices have four standard elementsanalog input, analog output,
utput, digital I/O, and
1 + Floating Ground Ref. + INSTRUMENTS
_ Source (FS) Source (GS)
_
counters.
AI 3
! BNC-2120 PWR
24
4

uti ts

uti ts
1 RES BNC
TIMING I/O
2
2 3
PFI 0 / P1.0
You can transfer the signal you measure with the DAQ device to the computer
mputer throug
through a variety of
4 23
23 tth PCI or PCI
different bus structures. For example, you can use a DAQ device that plugs into the
3 1. RES+
2. AI GND Express bus of a computer, a DAQ device connected to the PCMCIACIAA socket of a laptop,, or
o a DAQ

rib en

rib en
3. AI SENSE
4 4. RES-

BNC Temp.
BNC
Thermo Quadrature
Encoder
n usee PXI/CompactPCI
device connected to the USB port of a computer. You also can PXI/Comp to create a
Ref. couple
96 Pulses/Rev 22
5 portable, versatile, and rugged measurement system.

on

on
6
PULSES

UP /DN
21 If you do not have a DAQ device, you can simulate one in Meas
Measuremen
uremen & Automation
Measurement utomation
ation Explor
Explo
Explorer
AI 0 AI 1

ist um

ist um
FS GS FS GS PFI 1 / P1.1

PFI 2 / P1.2
(MAX) to complete your software testing. You learn to simulate
mulate a devi
dev he Simulating a D
device in the DAQ
PFI 3 / P1.3 Device section of this lesson.
PFI 4 / P1.4

PFI 5 / P1.5

FS
AI 2
GS FS
AI 3
GS
PFI 6 / P1.6
PF Refer to the DAQ section of the NI catalog or to ni.com/prod
ni.com/products
.com/prod for
or more informa
information about
7 PFI 7 / P1.7
P

PFI 8 / P2.0
20 specific types of DAQ devices.
8 PFI 9 / P2.1
r D str

r D str
PFI 12 / P2.4

FS
AI 4
GS FS
AI 5
G
GS
PFI 13 / P2.5

PFI 14 / P2.6
Analog Input
+5 V

D GND
Analog input is the process of measuring
ing an analog si
signal and
nd transferring
transferring th
the measurement to a
orage.
ge. An analog
computer for analysis, display or storage. analo signall is a signal that
that varies
v continuously.
AI 6 AI 7 EFINED
USER-DEFINED
FS GS FS GS
LS*
SIGNALS*
Analog input is most commonly used d to measure voltagee or current. You can use many types of
t fo l In

t fo l In
ANALOG OUTPUTS 19 devices to perform analog input, such as multifu
multifun
multifunction DAQ Q (MIO) devdevices, high-speed digitizers,
USER 1
18 Dynamic Si
digital multimeters (DMMs) and Dynamic Sig cquisition
sition (DSA)
Signal Acquisition (DSA devices.
9 AO
R2
USER

AO 0 AO 1

FU
FUNCTION GENERATOR *For BNC connectio
connections, wire
Acquiring an analog signal al with a ccomputer requires
uires
es a process knknown as analog-to-digital
anyT
anyTiming I/O or Digital I/O
Frequency Selection
Freq terminals here.
screw te
conversion, which takess an electrical si d translates it in
signal and into digital data so that a computer can
10 DIGITAL I/O
17 digital
al converter
process it. Analog-to-digital converter (ADCs)
converters Cs) are circuit co
com
components that convert a voltage level
No na

No na
0.1-10 kHz 1-100 kHz 00 kHz
13-1000 P0.7

11
1
P0.6
into a series of ones andd zeroes.
P0.5

P
P0.4
12
Sine/Triangle quare Wave
TTL Square W
P0.3
16 ADCs sample the he analog
alog signal on eachh rising
ing or falling edge of a sample clock. In each cycle, the
P0.2
13
13 ADC takes a snapshot
pshot of the aanalog signal, l, so th
that th
the signal can be measured and converted into
P0.1

14
4
tio

tio
P0.0

D GND
lue. A sample cclo
a digital value. ntrols
clock controlsls the rate at which samples of the input signal are taken.
15 O
LO HI
mplitude Adjust
Amplitude
LO HI
Frequency Adjust
Because the incoming, or unknown wn signal is a real
rre world signal with infinite precision, the ADC
imates
ates the signal
approximates signa with fixed
xedd precision. A After the ADC obtains this approximation, the
1 RES/BNC
BNC Switch (AI
( 3) 13 Sine/Triangle Waveform Switch oximation
mation can be converted
approximation rted to a series ofo digital values. Some conversion methods do not
2 Resistor
istor Measurement
Measure Screw
ew Terminals
T 14 Frequency Adjust Knob uire this step, because
require be he conversion
the convers
conv ge
generates a digital value directly as the ADC reaches the
3 Thermocouple Input Connector
ector 15 Amplitude Adjust Knob
Na

4
5
6
7
8
9
Temperature Reference
BNC/Temp. Ref. Switch (AI 0)
BNC/The
BNC/Thermocouple
Analog Input

Analog
I BNC
FS/GS Switchess
e Switch (AI 1)
C Connectors

l Output BNC Connecto


Connector
16
17
18
19
20
21
Digital I/O Screw Terminals
Digital I/O LEDs
User-Defined Screw Terminals
User-Defined BNC Connectors
Timing I/O Screw Terminals
Quadrature Encoder Screw Terminals
Na
pproximation.
proximation.
approximation.

Analog Output
Analog
put
g oou
output is the
he process of ggenerating electrical signals from your computer. Analog output is
generated by performingming digita
digital-to-analog (D/A) conversions. The available analog output types
10 Frequency Range Selectio
Selection Switch 22 Quadrature Encoder Knob
11 Sine/Triangle BNC Connector
nne 23 Timing I/O BNC Connector for a task are voltage andd current.
cu
cur To perform a voltage or current task, a compatible device must
12 TTL Square Wave BNC Connector 24 Power Indicator LED be installed that can generate that form of signal.

National Instruments | 6-9 6-10 | ni.com


LabVIEW Core 1 Course Manual Lesson 6 Managing File and Hardware Resources

Digital-to-analog conversion is the opposite of analog-to-digital conversion. In digital-to-analog Using DAQ Software
conversion, the computer generates the data. The data might have been acquired earlier using
digital
gita
analog input or may have been generated by software on the computer. A digital-to-analog National Instruments data acquisition devices have a driver engine that communicates
mmun between the
converter (DAC) accepts this data and uses it to vary the voltage on an output
put pin ov
over time. The device and the application software. You can use LabVIEW to communicate icate
te with these
t driver
engines. NI-DAQmx contains VIs, functions, and development tools for orr controlling measurement
controlling m

uti ts

uti ts
DAC generates an analog signal that the DAC can send to other devicesces
es or circuits.
devices. Refer to Programming with DAQ in LabVIEW for more information
formation
mation about programming
A DAC has an update clock that tells the DAC when to generate a new w value. The
Th function of the with DAQmx.
C. At each cycle
update clock is similar to the function of the sample clock for an ADC. c thee clock,
clo the

rib en

rib en
DAC converts a digital value to an analog voltage and creates an output as a vvo n a pin. Wh
voltage on When on devices.
In addition, you can use MAX to configure your data acquisition devices. In th on, you llearn
this section,
used with a high speed clock, the DAC can create a signal that appears to vvary constantly
nstantly
ntly and about the driver engines and about using MAX to configure yourur da
data
ta acqu
acqui
acquisition device.
ce.

on

on
smoothly.
DAQ Hardware Configuration

ist um

ist um
Digital I/O Before using a data acquisition device, you must confirm
nfirm
m that the so
software can
n communicat
communicate with
Digital signals are electrical signals that transfer digitalal data over
ove a wire. e. These
hese signals typically
t the device by configuring the devices. The devicess are already configured
con
co d for
or the comput
compute
computers in this
have only two stateson and off, also known as high high and low, or 1 and nd 0. When sendi
sending a digital class.
age to the wire aand the receiver
signal across a wire, the sender applies a voltage iver uses th
the voltage level
to determine the value being sent. The voltage age
ge ranges for each
ea digitalital value depend
depen on the voltage Windows
r D str

r D str
level standard being used. Digital signalss have ve many uses;
use the simplest
implest application
applicat
applic of a digital The Windows Configuration Manager keeps eepss track of all the hardware
rdware installed
installe in the computer,
al orr finite state devices
signal is controlling or measuring digital d s such as switche
such switches and LEDs. Digital including National Instruments DAQ devices.ces. If you hhave a Plug
ug & Play
Play (PnP
(PnP) device, such as an
signals also can transfer data; you cann use
se them
them to program
pr
p ices or comm
devices communicate between nfiguration Manager
E Series MIO device, the Windows Configuration M r automatically
tomatically detects
d and configures
gital
al signals as cclocks orr triggers to cont
devices. In addition, you can use digital co nt or synchronize other
control the device. If you have a non-PnP device,
ce, or legacy device,, you mustt config
confi
configure the device manually
t fo l In

t fo l In
measurements. using the Add New Hardware option in the W Wi
Windows Control
ontrol Panel.
You can use the digital lines in a DAQQ devic quire a digital va
device to acquire value. This acquisition is based You can verify the Windowss Configuration
C ation by accessing
essing the Device
Devic Manager. You can see Data
Dev
on software timing. On somemee devic nfigure
figure the
devices, you can configure the lines iindividually to either measure or Acquisition Devices, which ichh lists all
al DAQ devices es installed in the computer. Double-click a
generate digital samples.. Each
ch line cor
corresponds to a channel in the task. DAQ device to display a dialogalog box with
w tabbed edd pages. The General
G
Ge tab displays overall
information regardingg the device. The Driverr tab specifies the th driver version and location for the
No na

No na
al port
You can use the digital t(s)
(s) in a DA
port(s) cee to acquire
DAQ device ac re a ddigital value from a collection of digital
DAQ device. The Details contai additional
conta
ils tab contains onal information
informati about hardware configuration. The
informa
tion is based on software
lines. This acquisition re timing.
ng. You can
cca configure the ports individually to ecifies
es the system resources
Resources tab specifies rces to thee device
devic such as interrupt levels, DMA, and base
either measure orr generate
nerate digit
digita les. Eac
digital samples. Ea
Each portrt co
corresponds to a channel in the task. ware-configurab
-configurab devices.
address for software-configurable ices.

Counters
ers
tio

tio
Measurement
rement
ement & Au
Automation
A mation Explorer
Explo
A counter
er is a digital tim
timing device.
vice.
ce. You typical
typi
typically
ca use counters for event counting, frequency MAX establishes
tablishes
ablishes all device
dev
d and channel
channel config
configu
configuration parameters. After installing a DAQ device
urement,
ent, period measurement,
measurement, m t, position
position m
measurement, and pulse generation. in the computer,
puter, you mmust run tthis configurat
configur
configuration utility. MAX reads the information the Device
nager
Manager er records in the Windows
ndows
dows R stry
Registrytry aand assigns a logical device number to each DAQ
hen you configu
When unter
configure a counterer for sim
simple event counting, the counter increments when an active
Na

edge
ge is received on the source.
must be armed or started.
ource.
rce. In order for the counter to increment on an active edge, the counter
ed. A counter
resolution of the counter.
unter.
counter hhas a fixed number it can count to as determined by the
nter. For examp
example, a 24-bit counter can count to:

2(Cou
(Counter Resolution) 1 = 224 1 = 16,777,215
Navice. Use the de
device. dev

followin window
The following
onfiguratio
configuration.
mberr to refer tto the device in LabVIEW. Access MAX by double-clicking
device number
the icon on the ddesktop or selecting
electing Too
w is the primary
T oo
ToolsMeasurement & Automation Explorer in LabVIEW.
prima MAX window. MAX is also the means for SCXI and SCC

When a 24-bit counter reaches


ch the value of 16,777,215, it has reached the terminal count. The next
active edge forces the counter to roll over and start at 0.

National Instruments | 6-11 6-12 | ni.com


LabVIEW Core 1 Course Manual Lesson 6 Managing File and Hardware Resources

Figure 6-8. The Primary MAX Window DAQmx Name Controls


The DAQmx Name Controls palette includes controls for the task name, channel
hann name, physical
channel, terminal, scale name, device name, and switch. You can also create
reatee these controls by
right-clicking the corresponding input terminal on a DAQmx VI and selecting
lecting Creat
CreateControl.
Crea

uti ts

uti ts
For more information on these controls, refer to the NI-DAQmx Help.
p.
1: AT-MIO-64E-3 Figure 6-9. DAQmx Name Controls Palette
ette

rib en

rib en
on

on
ist um

ist um
r D str

r D str
DAQmx - Data Acquisition VIs
Use the NI-DAQmx VIs with NI-DAQ Q hardware
rdware devices
devic to develop
devel
velop
op instrumentation,
instrume acquisition,
and control applications. Refer to thee DAQ
AQ Getting SStarted Guide
ide or the NI
NI-DAQ Readme for a
-DAQmx
AQmx suppo
complete listing of devices that NI-DAQmx supports.
The device parameters that you can
an set using the
the cconfiguration
ration
ation utility dep
depend on the device. MAX
t fo l In

t fo l In
confi
configu
saves the logical device number and the configuration meters in the
parameters th Windows Registry. includ the following
The DAQmx - Data Acquisition palette includes owing consta
constants and VIs.
The plug and play capability
y of Windows
ty ws automatically
aau ically
ically detects and
a configures switchless DAQ
CI-6024E,
6024E, when you install
devices, such as the NI PCI-6024E, nstall
ll a device in the computer. Constants
DAQmx Task Name me ConstantLists
ConstantLi
onstantLi all tasksasks you create aand save using the DAQ Assistant.
onstant
Right-click the constantnt and selec
selec I/O Name
select ame
me Filtering fro
from the shortcut menu to limit the tasks
No na

No na
Simulating a DAQ Device
Dev splays
the constant displaysys and to lim
limit what you can enter iin the constant.
You can create NI-DAQmx
I-DAQmx
AQmx simul
simulated
simu devices
eviceses in NI-DA
NI-DAQmx 7.4 or later. Using NI-DAQmx DAQmx Global obal Channel ConstantLists
Co
Con Lists
sts all
al global
bal channels you create and save by using the
ces, you can try N
simulated devices, ductss in you
NI products your application without the hardware. When you stant.
DAQ Assistant. nt. Click and select Browse
wse to select
sele multiple channels. Right-click the constant
yo can import
later acquire the hardware, you ort the NI-DAQmx
NI-D
NI simulated device configuration to the ct I/O Name Filtering
and select Filt rom the shortcut
from shortcu menu to limit the channels the constant
tio

tio
evice
vice using the MAX
physical device M ortable Configuration
Portable Configur
Configur Wizard. With NI-DAQmx simulated yss and to limit what
displays w you u can enter in the constant.
ou also can export
devices, you exp a physical
hysi
ysical
cal device configuration
cco onto a system that does not have the
al device installed.
physical installe
install Then, using
sing the NI-DAQmx
NI-
NI-DD simulated device, you can work on your
ications
ons on a port
applications por stem and
portable system d upon rreturning to the original system, you can easily import VIs
ur application work.
your w DAQmx CreaCreate Virtuall Channel
Channe V VICreates
C a virtual channel or set of virtual channels and
Na

Programming
Program g with DAQ
Youu already
DA in LabVIEW
alrea have an understanding
in learning to uuse LabVIEW to develop a data acquisition application.
Now you can begin
understandin of transducers, signals, DAQ device configuration, and MAX.
Na adds them to a task. Thee instances of
su as analog
channel, such nalog input, digit
perform such as temperature
to perform,
o this polymorphic VI correspond to the I/O type of the
ddigital
i output, or counter output; the measurement or generation
temperatture measurement, voltage generation, or event counting; and in
some ccases, thee sensor to use, such as a thermocouple or RTD for temperature measurements.
ets the same ssettings that you configure in MAX when creating a virtual channel.
This function sets
softwa packages other than LabVIEW, but this course describes only
NI-DAQmx supports software Use this function if the oop
operator of your program might periodically change the physical
LabVIEW development off DAQ
D applications. channel connection, but not other important settings, such as terminal configuration mode or
the custom scale applied. Use the physical channel pull-down menu to specify the device
number of the DAQ device and the actual physical channel your signal is connected to.

National Instruments | 6-13 6-14 | ni.com


LabVIEW Core 1 Course Manual Lesson 6 Managing File and Hardware Resources

DAQmx Read VIReads samples from the task or channels you specify. The instances of this D. Controlling Instruments
polymorphic VI specify what format of samples to return, whether to read a single sample or
annels.
els Y
multiple samples at once, and whether to read from one or multiple channels. You can select an When you use a PC to automate a test system, you are not limited to the typepe of in
ins
instrument you can
instance by right clicking on the DAQmx Read VI and choose Select Typepe to inclu
include additional control. LabVIEW allows you to control virtually any type of instrumentt including amplifiers,
luding am
amp

tio s

uti ts
configuration options for read operations. analyzers, calibrators, oscilloscopes, power supplies, switches, signal generators,
nerators, sensors,
senso and more.
DAQmx Write VIWrites samples to task or channels you specify. ecify.
fy. The insta
instan
instances of this

ibu nt
polymorphic VI specify the format of the samples to write, whether
ther to write one or multiple You can mix and match instruments from various categories. Thee mostost common categories of

rib en
samples, and whether to write to one or multiple channels. Youu can select an
a instance
ancee by right dular instruments.
instrument interfaces are GPIB, USB, Ethernet, serial, and modular instrument
instrument Additional
tiona types
clicking on the DAQmx Write VI and choose Select Type pe too include aadd
dd
additional nfiguration
configuration rallel
el port, NI-CAN,
of instruments include image acquisition, motion control, parallel NI-C nd other
and her
devices. This course focuses on GPIB.

on
str me
options for write operations
DAQmx Wait Until Done VIWaits for the measurement rement
ment or genera
gener
generation to complete.
mplete. Use tthis derstand properties
When you use PCs to control instruments, you need to understand prop
pro instrumen
of the instrument,

ist um
ete before you stop
VI to ensure that the specified operation is complete s the task. ommand
mand set that
such as the communication protocols to use and the command tha the device
vice expects. Re
Refer to
DAQmx Timing VIConfigures number of samplesmples
es to acquire or generate
erate
ate and creates
creat a buffer the instrument programmers manual or user manuall forr informatio
information aboutt the properties of
o an
phic VI correspond
when needed. The instances of this polymorphic correspo to the he type
ype of timing to use on instrument.

Di tru
the task.
DAQmx Trigger VIConfigures triggering ring
ing for the task nstances
nces of this polymorphic
task. The instances p VI Benefits of Instrument Control
ntrol
trol

r D str
ypee to configur
correspond to the trigger and trigger type configure
configure. LabVIEW makes it easy to control and acquire
cquire
ire da
data
ta from any instrument
nstrument over aany bus. You can
DAQmx Start Task VITransitions ns thee task to the running
ngg stat
statee to begin tthe measurement or automate measurements from several devices, ces, analyze data ass you acquire it, and then log the
s
ired
d for some applications
generation. Using this VI is required a
ap ons and is optional
option for others. results to disk. This automation can savee enormous aamountss of time and mo money. Also, using a
DAQmx Stop Task VIStops the task and retu o the state the tas
returns it to task was in before you used ple tasks and ins
single application to control multiple ntss allows you to consolidate and
instruments
t fo l In

t fo l In
the DAQmx Start Task VI or used
d the DAQm
DAQ
DAQmx Writeite VI with the au
aautostart input set to TRUE. synchronize those tasks.

DAQmx Clear Task VIClears the task. Beforee clearing,aring, this V


VI stops the task, if necessary, implify programming
LabVIEW has many tools that help simplify mming for instru
instrument control, including
rces
ces res
and releases any resources reserved by the task.
k.. You cannot uus
use a task after you clear it unless les,
es, wiz
instrument drivers, examples, wizards, andd Express
sss VIs. These to
tools can help you do more with
you recreate the task. epetitive
itive time-
your time by reducing repetitive time-consumingng
g tasks, leaving
leaving you to focus on developing the
pplication.
cation. You ccan download
unique parts of your application. wnload instrume
instrumen
instrument drivers for almost any instrument
Figure 6-10
6-10.
6-1 DAQmx
mx Data Acquisition
Acquis Palette
No na

No na
free of charge.

GPIB
The ANSI/IEEEEEE Standard 4 48
488.1-1987,
987, also known as General Purpose Interface Bus (GPIB),
tio

tio
describes a standard interf
interface for communication between instruments and controllers from
endors. GPIB instruments
various vendors. i ents
nts offer test an
and manufacturing engineers the widest selection of
rs andd instruments
vendors instrumen for general-purpose
e l-purpose to
l-purpos t specialized vertical market test applications. GPIB
ruments
ents are often used ass stand-
instruments stand
stand-alonenee be
bench-top instruments where measurements are taken by
Na

Na
and.
nd. You can aut
hand.

IEEE 488.1 cco


ANSI/IEEE Standard
hesee measurem
automate these measurements by using a PC to control the GPIB instruments.

nformation aabo
contains information
rd 488.2-1992 ex
bout electrical, mechanical, and functional specifications. The
about
eextends IEEE 488.1 by defining a bus communication protocol,
mmon set of data codes and fformats, and a generic set of common device commands.
a common

parall communication interface with data transfer rates of 1 Mbyte/s and


paralle
GPIB is a digital, 8-bit parallel
higher, using a three-wire handshake. The bus supports one system controller, usually a computer,
and up to 14 additional instruments.

National Instruments | 6-15 6-16 | ni.com


LabVIEW Core 1 Course Manual Lesson 6 Managing File and Hardware Resources

The GPIB protocol categorizes devices as controllers, talkers, or listeners to determine which MAX (Windows: GPIB)
device has active control of the bus. Each device has a unique GPIB primaryy address between 0 Use MAX to configure and test the GPIB interface. MAX interacts with the varvarious diagnostic and
and 30. The Controller defines the communication links, responds to devicesicess that
th request service, configuration tools installed with the driver and also with the Windows Registry
gistry and
a Device
an
sends GPIB commands, and passes/receives control of the bus. Controllers ers instruct TTalkers to talk Manager. The driver-level software is in the form of a DLL and contains functions that
ins alll the funct
func

uti ts

tio s
and to place data on the GPIB. You can address only one device at a timeme to talk. ThThe Controller directly communicate with the GPIB interface. The Instrument I/O VIs and function
functions directly call
addresses the Listener to listen and to read data from the GPIB. You can aaddress several devices to
ddress sev the driver software.

ibu nt
listen.

rib en
Open MAX by double-clicking the icon on the desktop or by selecting
cting Tools
ToolsMeasurement me &
remen
Data Transfer Termination Automation Explorer in LabVIEW. The following example shows interfacee in MAX aft
ws a GPIB iin after

on

n
str me
Termination informs listeners that all data has been transferred.
erred.
ed. You can tterminate
te a GPIB data clicking the Scan For Instruments button on the toolbar.
transfer in the following three ways: Figure 6-11. GPIB Interface in Measurement
ement
ent & Automation
Autom
Automa Explorer
xplorer

ist um
The GPIB includes an End Or Identify (EOI) hardware
are line that can be asserted
dware the last
sserted with th
data byte. This is the preferred method.
Place a specific end-of-string (EOS) characterer at the end of the dataa string
ing itself. Some
So

Di tru
instruments use this method instead of or inn addition
ddition to the
th EOI line
ine assertion.
The listener counts the bytes transferredd by handshaking
handshakin and stops reading when
handsha wh the listener
r D str
reaches a byte count limit. This method
od iss often a default
def termination method because the
mination metho
transfer stops on the logical OR of EOI,I, EOS (i(iff us
used) in conjunction
onjunction with the byte count. As

Ins
he listener
a precaution, the byte count on the stener is often
ofte
off set higher er than the expected
ex byte count so
as not to miss any samples.
t fo l In

Data Transfer Rate


To achieve the high data transfer
ansfer rate that
at the
tth GPIB
B was designed for, you must limit the number
d the physic
of devices on the bus and phys ic distance between
physical een devices
devices.

You can obtain faster data rates


rates with HS488 devices and controllers.
ccon HS488 is an extension to
No na

ntrollers support.
GPIB that most NI controllers supp

Note Refer
efer to the National
N l Instruments
Instrume
trum nts GPIB support Web site at
ni.com/support/gpibsupp.htm
.com/support
m/support bsupp.htm
pp.htmm for more
m information about GPIB.
tio

Configuring
guring
uring a GP
GPIB Instrument
nstrument
strument
The software
ware archite
architec
architecture forr inst
instrument
ment
ent con
co
control using LabVIEW is similar to the architecture for
AQ. Instrument
DAQ. nstrument interfaces
iin es such as a GPIB
G B include a set of drivers. Use MAX to configure the
Na

nterface.
terface.
interface.

Na
t
No
Note Most
No st GPIB driver
drivers are available for download at ni.com/support/gpib/
v ns.htm. Always
versions.htm Alway install the newest version of these drivers unless otherwise
ed in the relea
instructed releas
release notes.
Configure the objects listed
isted iin MAX by right-clicking each item and selecting an option from the
shortcut menu.

National Instruments | 6-17 6-18 | ni.com


LabVIEW Core 1 Course Manual Lesson 6 Managing File and Hardware Resources

Serial The following figure shows a typical character frame encoding the letter m.
Serial communication transmits data between a computer and a peripherall devidevice, such as a Figure 6-13. Character Frame for the Letter m
programmable instrument or another computer. Serial communication uses a transm transmitter to send
data one bit at a time over a single communication line to a receiver. Use
se this method
metho when data Idle Start Data Parity op
Stop Idle

uti ts

uti ts
Bit Bits Bit Bitss
Bit
transfer rates are low or you must transfer data over long distances. Most
ost computers have one or
more serial ports, so you do not need any extra hardware other thanan a cable to connect
con the Space
instrument to the computer or to connect two computers to each h other.
her. Mark

rib en

rib en
Figure 6-12. Serial Instrument Example
ample Bit Time

on

on
1
3 e
Character Frame

ist um

ist um
76.6F

RS-232 uses only two voltage states, called MARK K and


nd SPACE. In I such a two-state codi
codin
coding
2
m number
scheme, the baud rate is identical to the maximum mber of bits of information,
rmation,
tion, includin
including control
bits, that are transmitted per second.

positive. The
MARK is a negative voltage, and SPACE is positive. Th previous
p us illustration
illustration shows
sho how the
sh
r D str

r D str
1 RS-232 Instrument 2 RS-232 Cable 3 Serial Port
idealized signal looks on an oscilloscope.. The
The following is the truth table for RS-232:
RS
You must specify four parameters for serial
eriall communication:
communic the
hee baud
baaud rate of the
tth transmission, the Signal > +3 V = 0
aracter,
ter, the sense
number of data bits that encode a character, sens of the optional
ional parity bit,
b and the number of
ges each transmitted
stop bits. A character frame packages transm haracter
racter as a sing
character single start bit followed by Signal < 3 V = 1
t fo l In

t fo l In
the data bits.
wings
wings between +12 V and 12 V. The ddead area between +3 V and
The output signal level usually swings
w fast data
Baud rate is a measure of how ta mov
move een instrument
moves between nstruments tthat use serial communication.
instruments e
3 V is designed to absorb line noise.

Data bits are transmitted upside down and backwards, wards, which me
means that inverted logic is used and ginning
ing of eeach character
A start bit signals the beginning er frame.
me. It is a tr
transition from negative (MARK)
the order of transmission on iss from least significant
cant
ant bit (LSB) to most significant bit (MSB). To oltage.
to positive (SPACE) voltage. ge. Its durati
dur ati in seconds
duration conds is the rec
reci
reciprocal of the baud rate. If the
tting at 9,600 b
instrument is transmitting ba
baud, the duration of th
the start bit and each subsequent bit is
No na

No na
interpret the data bitss in a character
character ffr ou
frame, youu must read fro
ffrom right to left and read 1 for negative
voltage and 0 for positiveive voltage. about 0.104 ms. Thee entire
ntire character
charact
characte frame of eleven bits w would be transmitted in about 1.146 ms.

An optional parityarity
y bit follows tthe dataa bitss in th
the ch
character frame. The parity bit, if present, also Interpreting thee dataa bits for the
th transmission
mission
ion yields
yiel
y 1101101 (binary) or 6D (hex). An ASCII
follows invertedrted logic. This bbit is included
cluded
ed as a means
mea
mean of error checking. You specify ahead of time ble shows that tth
conversion table he letter
this is the er m.
tio

tio
ity
for the parityty of the transmi
transm
transmission to o be even or odd.
odd If you choose for the parity to be odd, the parity
smission
ssion uses od
This transmission y.. There are five oones among the data bits, already an odd number,
odd parity.
n such a way so the number
bit is set in mber of 1s add up u to make an odd number among the data bits and
ity bit is set tto 0.
so the parity
rity bit.
the parity

hee last part of a character


The ch r frame
fram
ramee co
cons
consists of 1, 1.5, or 2 stop bits that are always represented by a Data
ata Transfe
Transfer Rate
e
Na

negative
gative voltage.
voltage If no further
condition. The transmission
(SPACE) voltage.
vol
vo
her ch
character
aracter are transmitted, the line stays in the negative (MARK)
characters
ission of the next
ne character frame, if any, begins with a start bit of positive
n
Na
Youu can calculate
calculat
calcula the maximum
communicati
communicatio

In thee prev
mum transmission
transm
ng by dividing th
communication setting

ample, there ar
previous example,
rate in characters per second for a given
the baud rate by the bits per character frame.

are a total of eleven bits per character frame. If the transmission rate
9,60
9,6
is set at 9,600 baud, you get 9,600/11 = 872 characters per second. Notice that this is the maximum
character transmission rate. TThe hardware on one end or the other of the serial link might not be
able to reach these rates, for various reasons.

National Instruments | 6-19 6-20 | ni.com


LabVIEW Core 1 Course Manual Lesson 6 Managing File and Hardware Resources

Serial Port Standards Instrument DescriptorExact name of a resource. The descriptor specifies the interface type
(GPIB, USB, TCP/IP, ASRL), the address of the device (logical address or primary address),
The following examples are the most common recommended standards of serial
eria port
p and the VISA session type (INSTR or Event).
communication:

uti ts

uti ts
rce
The instrument descriptor is similar to a telephone number, the resourcece is similar to the person
RS232 (ANSI/EIA-232 Standard) is used for many purposes, such ch as connecting a mouse, phone
with whom you want to speak, and the session is similar to the telephone ne line. Each call uses its
printer, or modem. It also is used with industrial instrumentation.
n. Becaause of iimprovements
Because im in ows the proper syntax for the
own line, and crossing these lines results in an error. Table 6-1 shows
rmance
ance of RS232
line drivers and cables, applications often increase the performance RS2
RS23 beyondond the instrument descriptor for a few different interfaces.

rib en

rib en
distance and speed in the standards list. RS232 is limited to point-to-point
nt-to-point cconnections
ionss between
betw
PC serial ports and devices. Table 6-1. Syntax for Various Instrument
mentt Interfaces

on

on
ectrical
rical signal aas opposed
RS422 (AIA RS422A Standard) uses a differential electrical sed to the Interface Syntax
und
unbalanced (single-ended) signals referenced to ground d with RS232
RS23 rential transmissi
RS232. Differential transmission,

ist um

ist um
which uses two lines each to transmit and receive signals,
nals, results in
i greater
err noise immuni
immunit
immunity and Asynchronous serial ASRL[device][::INSTR]
[::INSTR]
longer transmission distances as compared to RS232.32.
GPIB GPIB[device
ce]::prim
primary addresss[::seconda
secondary
RS485 (EIA-485 Standard) is a variation of RS422 22 that allow
allows you to connect
onnect up to 332 devices address][::INSTR]
[::INSTR
lectrical
rical characteristics
to a single port and define the necessary electrical characte
charact to ensure adequ
adequate signal
voltages under maximum load. With thiss eenhanced
nhanced mult
multidrop capability,
ility, you ca
can create VXI instrument through embedded VXI[devic
device]::
::VVXI logical address
ddress[::INSTR]
::I
r D str

r D str
gle RS485 serial
networks of devices connected to a single seria port. Thehe noise immunity
immuni and multidrop or MXIbus controller
oice in industrial
capability make RS485 an attractive choice indus pplications that require
applications re many
distributed devices networked to a PC or other controller
con
c forr data collection
collecti and other GPIB-VXI controller GPIB-VXI[device][::
[::GPIB-VXI primary
operations. address]
]::VXI logical
al address[
[::INSTR]
t fo l In

t fo l In
instead of the instrument
You can use an alias you assign in MAX instead strument descriptor.
des
desc
Instrument Control Programm
Program
Programming
g
The most commonly used VISA IS communication
mmunica nctions
ons are the V
functions VISA Write and VISA Read
VISA is a high-level API that
hat ca
calls low-level
w-lev drivers.
w-leve ers. VISA can control
cco instruments over GPIB,
ntss requir
functions. Most instruments require you to t send information
nformation
formation in ththe form of a command or query
USB, Ethernet, serial, andd other
her interfaces
inter
inter akes
es the appropriate
as it makes appropr driver calls depending on the
rmation
ation back from the instrument.
before you can read information inst
nstrument.
rument. Ther
Therefore, the VISA Write function is
d. When debugg
type of instrument used. debugging VISA SAA problems,
problems, rerem
remember that an apparent VISA
usually followed by a VISA A Read funcffunction.
unc he VISA Write and
The a VISA Read functions work with
problem could be an installation
llation prob
pro
problem with th
h one of the drivers
dri that VISA calls.
No na

No na
ent communicati
any type of instrument communication and are re the
the same w wh
whether you are doing GPIB or serial
In LabVIEW, VISA SA iss a single lib
library off func
functionss you uuse to communicate with a variety of communication. However,ver, because serial communication
co unication requires you to configure extra
terfaces
ces that any instrument
different I/O interfaces mentt may
ma pprovide.
d Because of this, you do not need to use parameters, you mustt start the se
sserial port
rt commu
omm ttio
communication io with the VISA Configure Serial Port VI.
separate I/O palettes
ttes to progra nstrument.
ment. For
program an instrument. Fo eexample, some devices offer multiple interface
tio

tio
types such as Ethernet, US USB
USB, and GPIB B on the same instrument. If the LabVIEW instrument driver Using Instrument
nstrumen Drivers
ivers
ten with functio
were written hee Instrument II/OGPIB palette, those instrument driver VIs
functions on the
would nott work for the instrument nt with the USB
USB interface. VISA solves this problem by providing Imaginee the
he following scenario.
sc You wrote a LabVIEW
La VI that communicates with a specific
gle set of functio
a single function
functions that work for any type
typ of interface. Therefore, many LabVIEW instrument oscope
oscilloscopepe in your la ort tely, the os
lab. Unfortunately, oscilloscope no longer works, and you must replace it.
vers use VISA aas the I/O
drivers O language
langua
language. wever,
However,er, this particular
partic cilloscop
llosc
oscilloscope is no longer made. You found a different brand of
Na

VISA Prog
The

Programming
ming Terminology
he following
Termin
Termi
followi terminology
so
minology is simil
similar to that used for instrument driver VIs:
ny instrument in the system, including serial and parallel ports.
ResourceAny
Na
scilloscope
cilloscope that yyou want
oscilloscope
You must rewrit

When you use


efore,
rewrite your VI.

u an instrument
nstrument
nt to purchase, but your VI no longer works with the new oscilloscope.

trument driver,
driver the driver contains the code specific to the instrument.
efore if you change instrum
Therefore, instrume
instruments, you must replace only the instrument driver VIs with the
instrument driver VIs for the ne
new instrument, which greatly reduces your redevelopment time.
SessionYou mustt open a VISA session to a resource to communicate with it, similar to a Instrument drivers help make test applications easier to maintain because the drivers contain all the
communication channel. When you open a session to a resource, LabVIEW returns a VISA I/O for an instrument in one library, separate from other code. When you upgrade hardware,
session number, which is a unique refnum to that instrument. You must use the session number upgrading the application is easier because the instrument driver contains all the code specific to
in all subsequent VISA functions. that instrument.

National Instruments | 6-21 6-22 | ni.com


LabVIEW Core 1 Course Manual Lesson 6 Managing File and Hardware Resources

Understanding Instrument Drivers The VIs in an instrument driver are organized into six categories. These categories are summarized
in the following table.
A LabVIEW Plug and Play instrument driver is a set of VIs that control a programmable
prog
instrument. Each VI corresponds to an instrument operation, such as configuring,
guring, triggering, and
nfiguring,
reading measurements from the instrument. Instrument drivers help users ers get started using
sers Category Description

tio s

uti ts
instruments from a PC and saves them development time and cost because ause users do not need to
ecause
Initialize The Initialize VI establishes communicationtion with the
th instrument
ource,
learn the programming protocol for each instrument. With open-source, ce, well-doc
well-docu
well-documented

ibu nt
lled.
and is the first instrument driver VI called.
instrument drivers, you can customize their operation for better performance.
formance. A modular ar design

rib en
makes the driver easier to customize. Configure Configure VIs are software routines
es that config
configure the instrument
trum
fter calling these VIs, the
to perform specific operations. After

on
str me
Locating Instrument Drivers asurements or stimulatee a system.
instrument is ready to take measurements system
You can locate most LabVIEW Plug and Play instrument ent drivers in the
th Instrument
ment Driver Finder.
F
Fin Action/Status Action/Status VIs commandd the instrument
instrum to carry out an action
ac

ist um
bVIEW by se
You can access the Instrument Driver Finder within LabVIEW g Tools
selecting igger) or obtain
(for example, arming a trigger) ob rrent status oof the
the current
InstrumentationFind Instrument Drivers or HelpFind
elpFind
Find Instru river . The IIns
Instrument Drivers
Drivers. Instrument instrument or pending operations.
nstrument
rument Driv
Driver Finder pulls drivers from NIs extensive Instrument workk that can be found at
Driver Network

Di tru
ni.com\idnet. When you install an instrument
added to the NI Example Finder.
ent driver, an example
ex program
gram using the
th driver is Data
Utility
The data VIs transfer
Utility VIs perform
er data to or from the instrument.
rform a va
variety
riety of auxiliary
trument.
ry opera
operations,
tions such as reset

r D str
and self-test.
Example Instrument Driver VI
Close The close VII terminate
terminates the software
re connectio
connection to the instrument.
s
The block diagram in Figure 6-14 initializes
itializes
lizes the Agilent
Ag
Agil 34401401 digital multi
mult
multimeter
i (DMM), uses a he last instrument
This is the instru driver VI called
called.
olution
ion and range
configuration VI to choose the resolution range, selectt the
he function, an
and enable or disable auto
l In

t fo l In
ngle measurement,
range, uses a data VI to read a single measureme closes sess the instrumen
instrum
instrument, and checks the error
status. Every application that uses an instrume
instrumen
instrument driverr hass a similar
similar se
sequence of events: Initialize,
Configure, Read Data, and Clo
Close.
Figure 6-14. Agile
Agilent 34401 DMM
MM Instrument Driver Example
No na

No na
tio

tio
Na

Na
t

This is an exam
example program
gramm that is available
ava in the NI Example Finder when you install the
LabVIEW Pl Plu
Plug and Play instrument driver for the Agilent 34401 DMM.

pro
Many programmable able instruments
instrumen have a large number of functions and modes. With this
essary to pprovide a consistent design model that aids both instrument driver
complexity, it is necessary
developers as well as end d us
use
users who develop instrument control applications.

National Instruments | 6-23 6-24 | ni.com


LabVIEW Core 1 Course Manual

Self-Review: Quiz
1. After opening a file, which output does the Open/Create/Replace Filee function
unction return?

uti ts

uti ts
a. File path
b. File name
c. Refnum out

rib en

rib en
d. Task out

on

on
ist um

ist um
2. What is Measurement & Automation Explorer (MAX)?
MAX)?
X)?
a. A tool to configure and test DAQ devices
b. A tool to test instrument communication
n
c. A configurable Express VI
r D str

r D str
d. A window to view LabVIEW project
ectt files

nefits
ts of instrument
3. Which of the following are benefits instrum control?
ntrol?
rol?
t fo l In

t fo l In
a. Automate processes
b. Save time
c. One platform for multiple tasks
tiple ta
d. Limited to only instrumentt
y onee type of ins
No na

No na
4. VISA is a high-level
h-level API that
th callss low-level
w-le drivers.
d
a. True
tio

tio
alse
b. False
Na

Na
National Instruments | 6-25
LabVIEW Core 1 Course Manual Lesson 6 Managing File and Hardware Resources

Self-Review: Quiz Answers Notes


1. After opening a file, which output does the Open/Create/Replace Filee function
unction return?

uti ts

uti ts
a. File path
b. File name
c. Refnum out

rib en

rib en
d. Task out

on

on
ist um

ist um
2. What is Measurement & Automation Explorer (MAX)?
MAX)?
X)?
a. A tool to configure and test DAQ devicess
b. A tool to test instrument communication
ion
c. A configurable Express VI
r D str

r D str
d. A window to view LabVIEW project
ectt files

nefits
ts of instrument
3. Which of the following are benefits instrum control?
ntrol?
rol?
t fo l In

t fo l In
a. Automate processes
b. Save time
c. One platform forr multiple
ultiple tasks
d. Limited to only instrumentt
y onee type of ins
No na

No na
4. VISA is a high-level
h-level API that
th callss low-level
w-le drivers.
d
a. Truee
tio

tio
alse
b. False
Na

Na
National Instruments | 6-27 6-28 | ni.com
Lesson 7 Using Sequential and State Machine Algorithms

Using Sequential and State


7 A. Using Sequential Programming
Many of the VIs you write in LabVIEW accomplish sequential tasks. How ow you pprogram these
sequential tasks can be very different. Consider the block diagram in Figure this block
iguree 7-1. In th

uti ts

tio s
Machine Algorithms ff the
voltage signal is acquired again, and the user is prompted to turn off he power. Ho
po
diagram, a voltage signal is acquired, a dialog box prompts the user to turn on the power, the
However, in this

ibu nt
utionn order of th
example, there is nothing in the block diagram to force the execution these events. Any

rib en
one of these events could happen first.
The first step in developing a LabVIEW application is to explore
ore the architect
architec
architectures that
at exist
ist with
within
Figure 7-1. Unsequenced Tasks
ks

on

n
sful so
LabVIEW. Architectures are essential for creating a successful oftware
ftware de
software des he most
design. The ost common

str me
architectures are usually grouped into design patterns.

ist um
ier to recognize when a design pattern has
As a design pattern gains acceptance, it becomes easier h
velopers
opers read aan
been used. This recognition helps you and other developers n modify
and ify
y VIs that ar
are bbased on
design patterns.

Di tru
There are many design patterns for LabVIEW W VIs. Most applications
app ns use
se at least oon
one design
te Machine d
pattern. In this course, you explore the State desig ern. Learn more about design
design pattern.
r D str
patterns in the LabVIEW Core 2 course.

s
Topics In LabVIEW, you can complete sequential
uential
ntial tasks by placingg each
ch task in a separate
s subVI, and
wiring the subVIs in the order you wantnt them to exexecute using
ing the error cl
cluster wires. However, in
t fo l In

l In
A. Using Sequential Programming
ing
ng kss have a error cluster. Using
k
this example, only two of the tasks ing the
the error clusters, you can force the
B. Using State Programming ssistants,
sistants, bu
execution order of the two DAQ Assistants, bbut not the
he One Button
Button DDialog functions, as shown in
Figure 7-2.
C. State Machines
Figure 7-
7-2. Partially
ally Sequenced T
Tasks
No na

No na
tio

tio
Na

Na
t
You can use a Sequence
nce structure to force the order of operations of block diagram objects. A
equence
quenc structure
Sequence st contains one or more subdiagrams, or frames, that execute in sequential order;
a framee cannot
c gin execution until
begin u everything in the previous frame has completed execution.
Figure 7-3 shows an examp
example oof this VI using a Sequence structure to force execution order.

National Instruments | 7-1 7-2 | ni.com


LabVIEW Core 1 Course Manual Lesson 7 Using Sequential and State Machine Algorithms

Figure 7-3. Tasks Sequenced with a Sequence Structure Use Sequence structures sparingly because they do not enforce error checking and will continue to
go through a sequence even after errors are detected. Rely on data flow rather than sequence
structures to control the order of execution.

uti ts

uti ts
Figure 7-5. Tasks Sequenced with an Error Cluster and Case Structure
Structures

rib en

rib en
on

on
ist um

ist um
B. Using State Programming
To take advantage of the inherent parallelism inn LabVIEW,
abVIEW, avoidav overusing
erusingg Sequence structures.
xecution,
ution, but prohibit
Sequence structures guarantee the order of execution, pr lel operations.
parallel operatio
operation Another Although a Sequence structure and sequentially
ly wired subVIs both accomplish
ccomplish
mplish the tas
ttask, often your
att you cannot st
negative to using Sequence structures is that stop the execution part wway through the VIs require more complex programming:
r D str

r D str
sequence. A good way to use Sequence structures
ctures for th
thi mple is shown iin Figure 7-4.
this example What if you must change the order off the
he sequence?
Figure 7-4. Tasks Sequenced
ced with Sequence
Sequen
Seque Structures
uctures
ures and an Error
E Cluster n the sequence
What if you must repeat an item in sequence m ften than the othe
more often oth
other items?
encee execute
What if some items in the sequence execute on n certain
only when rtain conditi
ndit
conditions are met?
t fo l In

t fo l In
What if you must stop the program immediately, rather
ogram immedia atherr than waiting
waitin until the end of the
sequence?

Although your program may not hav have any of the above
ha bove requirements, there is always the possibility
ove requiremen
that the program must bee modified
modifi
odified the future.. For this reas
ed in tth reason,
reason a state programming architecture
is a good choice, evenn if a sequential programming
p mming structure would be sufficient.
No na

No na
C. State Machines
achines
chines
The state machine
chinee design pat
patt
pattern is a common
mmon an and vvery useful design pattern for LabVIEW. You
tio

tio
The best wayay to write this VI,
V however,
wever, is to enclose
enclo the One Button Dialog functions in a Case d
can use the state machine design pattern to implement
im
implem
mplement
lem any algorithm that th can be explicitly
structure, and wire the err ster
er to the case se
error cluster sselector. describedd by a state diagram
diagr or flowchart.
owchart. A ststat
a machine usually implements a moderately
state
ex decision-making
complex decision-maki
decision-mak thm,
m, such as a diagnostic routine or a process monitor.
algorithm,

tate machine,
A state machine, wh
which is more re precis
pr
precisely de
ddefined as a finite state machine, consists of a set of states
Na

Na
nd
andd a transition function

machin
forr each state
LabVIEW
fu
The two most ccommon finite
Mealy machi orms
machine performs
thatt maps to the

rms an action
mac
acti n ffo
th next state. Finite state machines have many variations.
ite state machines are the Mealy machine and the Moore machine. A
for each transition. A Moore machine performs a specific action
ssta in thee state transition diagram. The state machine design pattern template in
EW implements
ments any algoalgor
algorithm described by a Moore machine.

National Instruments | 7-3 7-4 | ni.com


LabVIEW Core 1 Course Manual Lesson 7 Using Sequential and State Machine Algorithms

Applying State Machines Figure 7-6 shows the basic structure of a state machine implemented in LabVIEW for a
temperature data acquisition system.
Use state machines in applications where distinguishable states exist. Eachh state can lead to one or
put or in-sta
multiple states or end the process flow. A state machine relies on user input in-state calculation Figure 7-6. Basic Infrastructure of a LabVIEW State Machine
chin
to determine which state to go to next. Many applications require an initialization
nitia
itialization state, followed
lization st
sta

uti ts

uti ts
by a default state, where many different actions can be performed. The actions perfo
performed can
1
depend on previous and current inputs and states. A shutdown state te commonly
ommonly pe performs clean up
actions.

rib en

rib en
2
State
State machines are commonly used to create user interfaces.. In a user interface,
interf fferent
ent user
different Functionality Transition
nsi

on

on
ode
Code
gments.
nts. Each pr
actions send the user interface into different processing segments. pro
processingg segment
gment acts aas Code
nother
a state in the state machine. Each segment can lead to another er segment for further
ther processing oor 3

ist um

ist um
ation,
n, the state machine
wait for another user action. In a user interface application, m e constantly monitors
mon
mo
the user for the next action to take.

Process testing is another common application of thehe state machine


mach design sign pattern. For
Fo a process
ocess.
s. Depending
test, a state represents each segment of the process. Dependin on thee result
sult of each states
s test, a
pen
en continually, resulting
different state might be called. This can happen ng in an in-depth analysis of the 1 While Loop 2 Shift Register 3 Case
e Structure
r D str

r D str
process you are testing.
The flow of the state transition diagram is im
implemented
mplemented
plemented by the While Loop.
Loop.
L p. The
T individual states
The advantage of using a state machinee is that
hat after you
y have created
edd a state transition
tra diagram, you ucture.
ure. A shift re
are represented by cases in the Case structure. register on the While Loo
Loop keeps track of the
can create LabVIEW VIs easily. current state and communicates the currenentt state to the
current t Casee structure
ucture input.
input
t fo l In

t fo l In
State Machine Infrastructure
structur
structure Controlling State Machines
achines
Translating the state transition
ion
on ddiagram into a LabVIEW
VIEW block di
diag
diagram requires the following The best method for controlling
ling
in the initialization
tializa
ializ andd transition of state
st machines is the enumerated
infrastructure components: s: type control. Enums are widely ely use
us ctors
ors in state ma
used as case selectors machines. However, if the user
attempts to add or deletee a state from tthe
th enumerated
erated
er ated type co
cont
control, the remaining wires that are
ually executes
ntinually
While LoopContinually execute the various
arious states
state connected to the copieses of this enumerated
enume
enumer ype
pe control break
type break. This is one of the most common
No na

No na
ontains a case
Contains
Case StructureContains ca for eachh state and the
t code to execute for each state lementing
menting state m
obstacles when implementing machines with enumerated
enume
enumera type controls. One solution to this
Shift RegisterContains
erContains state transition
Contains sta n information
sition matio ate a type defined enumerated
problem is to create merat type pe control.
cont This causes all the enumerated type
control copies too automatically
omatically uupdate if you
ou add or remove a state.
State Functionality nts the
lements
onality CodeImplements
ctionality Cod
Code th function
fun of the state
tio

tio
Transition CodeDete
De s the next state in
ion CodeDetermines
Cod i the sequence
Transitioning
tioning
oning State
Sta Machines
There are
re many ways to t control what
wh
hat
at case a Case
Cas structure executes in a state machine. Choose the
od that
method at best suits the function
cti andd complexity
comp
com of your state machine. Of the methods to
plement
ent transitio
implement atee ma
transitions in state machi
machines, thh most common and easy to use is the single Case
the
Na

Na
tructure
ucture transitio
structure transition code, which
method provides
provide for thee most
other methods
em.
them.
moost
ich can be uused to transition between any number of states. This
st scalable, readable, and maintainable state machine architecture. The
method can bee useful in specific
speci
spec situations, and it is important for you to be familiar with

National Instruments | 7-5 7-6 | ni.com


LabVIEW Core 1 Course Manual Lesson 7 Using Sequential and State Machine Algorithms

Default Transition Transition Among Two or More States


For the default transition, no code is needed to determine the next state, because
ecaus there is only one Create a more scalable architecture by using one of the following methodss to transition
t among
possible state that occurs next. Figure 7-7 shows a design pattern that uses default transition
es a de
defau states.
implemented for a temperature data acquisition system.

uti ts

uti ts
Case StructureUse a Case structure instead of the Select function
on for the transition
ion trans
tran code.
Figure 7-7. Single Default Transition
n Figure 7-9 shows the Case structure transition implemented forr a temperat
emperature
ture ddata acquisition
temperature
system.

rib en

rib en
Figure 7-9. Case Structure Transition
tion
n Code

on

on
ist um

ist um
Transition Between Two States
ess
r D str

r D str
The following method involves making a decision
ecision on a transition
on between
between tw
two states. There are
complish
plish this. Figure
several patterns commonly used to accomplish F -8 shows
7-8 show the Select
Sel function used to
transition between two states. One advantage to using a Case structure
ucture
ure is that the
th code iss self-documenting.
self-documenti
f-documenti Because each case
nds to an item in the enum,
in the Case structure corresponds um, it is easy to read and understand the
t fo l In

t fo l In
Figure
e 7-8. Select Function
Fu Transition
ansition Cod
Code code. A Case structure also is scalable. As the th application
cation
ion grows, you
y can add more transitions
to a particular state by adding more cases to the Case ase structure for that state. A disadvantage to
using a Case structure iss th ll the ccode is visible at onc
that not all once. Because of the nature of the
ot possible
Case structure, it is not possibl to see at a glance
ance
nce the complete
comple functionality of the transition
code.
yIff you need more
Transition ArrayIf m b visible than a Case structure allows,
of the code to be
No na

No na
you can create a transition
ansition array
arra for all the transitions
ransitions that
t can take place.
Figure 7-10 shows
ws the trans
transit ray imple
transition array mp ted
ed for a temperature data acquisition system.
implemented
Figure
F
Fig
ig 7-10.
10. Transition A
Array Transition Code
tio

tio
This method
thod
od works well
we if you know
now
ow that the ind
individual state always transitions between two states.
ver, this
However, his method limits the
th scalability
alability of
o the application. If you need to modify the state to
nsition
on among more
transition mo than n two sstat
states, this
his solution would not work and would require a major
Na

odification of th
modification tion code.
the transition

Na Decision Making Code

National Instruments | 7-7 7-8 | ni.com


LabVIEW Core 1 Course Manual Lesson 7 Using Sequential and State Machine Algorithms

In this example, the decision making code provides the index that describes the next state. For Figures 7-12 through 7-15 illustrate the states of the state machine that implements the state
example, if the code should progress to the Error Handler state next, the decision making code transition diagram detailed in Figure 7-11.
his desig
outputs the number 1 to the index input of the Index Array function. This des
design pattern makes
his pattern
the transition code scalable and easy to read. One disadvantage of this attern is th
tthat you must Figure 7-12. Acquisition State

uti ts

tio s
use caution when developing the transition code because the array y is zero-indexe
zero-indexed.

ibu nt
Case Study: Course Project

rib en
The course project acquires a temperature every half second, analyzes
alyzes each ttemperature
ature to
rts thee user if th
determine if the temperature is too high or too low, and alerts tthere is a danger
ger of
o

on

str me
ing occurs
heatstroke or freeze. The program logs the data if a warning occurs.. If the user hasas not clicked the
th
ws the
stop button, the entire process repeats. Figure 7-11 shows he state
stat
st e tran
transi agram for the cou
transition diagram course

ist um
project.
Figure 7-11. State Transition Diagram
am for the C
Course Project
oject

Di tru
Figure 7-13.
13. Analysis
Analys State
S
r D str
Initialize

for Ins
t fo l In

Acquistion
Ac istion

Time Elapsed
psed = TRUE
and

l
Stop
op = FALSE
No na

No na
Warning
Wa ning = TRUE
Analysis

Data log
D
Figure
gure 7-14. Data
Dat Log State
tio

tio
Time Elapsed = FALSE
and
Stop = FALSE
Time
Check
Warning
Warnin = FALSE
Na

Stop = TRUE
Na
National Instruments | 7-9 7-10 | ni.com
Na
tio
No na
t fo l In
r D str
Figure 7-15. Time Check State

ist um
rib en
uti ts
on

National Instruments | 7-11


LabVIEW Core 1 Course Manual

Na
tio
No na
t fo l In
r D str
ist um
rib en
uti ts
on
LabVIEW Core 1 Course Manual

Self-Review: Quiz
1. When using a Sequence structure, you can stop the execution in the middle
ddle of a sequence.

uti ts

uti ts
a. True
b. False

rib en

rib en
achinee instead
2. Which of the following are benefits of using a state machine instead of a sequential
uential
al structure
structure?

on

on
a. You can change the order of the sequence.

ist um

ist um
ce.
b. You can repeat individual items in the sequence.
c. You can set conditions to determine when an item
tem in the se
sequencee should
hould execu
execute
execute.

r D str n thee sequence


d. You can stop the program at any point in sequence.

r D str
t fo l In

t fo l In
No na

No na
tio

tio
Na

Na
National Instruments | 7-13
LabVIEW Core 1 Course Manual Lesson 7 Using Sequential and State Machine Algorithms

Self-Review: Quiz Answers Notes


1. When using a Sequence structure, you can stop the execution in the middle
ddle of a sequence.

uti ts

uti ts
a. True
b. False

rib en

rib en
achinee instead
2. Which of the following are benefits of using a state machine instead of a sequential
uential
al structure
structure?

on

on
a. You can change the order of the sequence.

ist um

ist um
uence.
ce.
b. You can repeat individual items in the sequence.
n an
c. You can set conditions to determine when n item in th ence
nce should execute.
the sequence ex
exe

r D str nt in
d. You can stop the program at any point n the seque
sequen
sequence.

r D str
t fo l In

t fo l In
No na

No na
tio

tio
Na

Na
National Instruments | 7-15 7-16 | ni.com
Lesson 8 Solving Dataflow Challenges with Variables

Solving Dataflow Challenges with


h
8 A. Communicating Between Parallel Loops
In this course, parallelism refers to executing multiple tasks at the same time.
me. Consider
Consi
Con the example
of creating and displaying two sine waves at different frequencies. Using parallelism,
arallelism you place
ng parallelism

uti ts

uti ts
Variables one sine wave in a loop, and the second sine wave in a different loop..

A challenge in programming parallel tasks is passing data among ltiple loops without creating
g multiple

rib en

rib en
re, the
a data dependency. For example, if you pass the data using a wire, he loops are no longer
ger pa
parallel.
LabVIEW is a dataflow language. As such, you generally usee dataflow
ataflow desig
desi
design principles
cipless in In the multiple sine wave example, you may want to share a single
gle stop memech
mechanism between
ween th
the
loops, as shown in Figure 8-1.

on

on
developing your code. However, in a few situations, such ass communicati
mmunicat n between
communicating een two
wo parallel
loops, you must break the dataflow execution model by y passing
assing inform
information between
ween locations
locatio
location
in the code that you cannot connect with a wire. Figure 8-1. Parallel Loops
s Front
ront Panel

ist um

ist um
In this lesson you learn about variables, in general, andd local variables,
variab
varia pecifically,
cifically, to handle
specifically, han
special use cases where the dataflow execution model does not w work. Youou also
lso learn abo
ab
about the
programming issues involved when using variablesables
es and how to t overcome
ome these challenges.
challe

he LabVIEW ddataflow
Because variables are not inherently part of the w execution
ecution model,
mod
mode use variables
r D str

r D str
he code
carefully. Misusing variables can make the ode hard to rread, lead
ad
d to unexpec
unexpected behavior in VIs,
and slow performance.

Topics
t fo l In

t fo l In
A. Communicating Between Parallel
allel
llel Loops
d Read
B. Writing to Controls and Rea om
m IIndicators
Reading from ors
C. Variables
D. Race Conditions
No na

No na
Examine what happens
penss when you tr
try
t to share data among parallel loops with a wire using those
s.
different methods.

Method
d 1 (Incorrect)
(Incorre
tio

tio
Place the Stop Button te terminal outside
utside of both lloops and wire it to each conditional terminal, as
shown in Figure 8-2. TheT Loop controlontrol
ntrol is a data
da input to both loops, therefore the Stop Button
dat
inal is read only once, before
terminal efore either
her
er Wh
W
While Loop begins executing. If False is passed to the
ops,
ps, the While Loops
loops, L
Lo runn indefinitel
ndefin
indefinitely. Cl
Clicking the Stop button does not stop the VI because the
Na

Na
utton
tton click is not
button no read during ng the iteration
iterat of either loop.

National Instruments | 8-1 8-2 | ni.com


LabVIEW Core 1 Course Manual Lesson 8 Solving Dataflow Challenges with Variables

Figure 8-2. Parallel Loops Method 1 Example B. Writing to Controls and Reading from Indicators
In addition to communicating between two simultaneously running loops,, there
ere ar
are other dataflow
challenges that can be overcome with local variables.

uti ts

tio s
You can use a local variable to update a single front panel indicatorr from
om more than one location

ibu nt
on the block diagram. For example, if you have a VI with two Whileile Loops,
Loops, you can
c update a front

rib en
panel indicator to display which loop is currently executing.

With a local variable, you can write to or read from a control ol or indicator oon the front
ront panel. In

on

n
str me
effect, with a local variable you can access a front panel objectct as both an input and an output. FFo
For
ou can clear the
example, if the user interface requires users to log in, you th Login and Password

ist um
riable
prompts each time a new user logs in. Use a local variable le to read from
fro the Login and Passw
Pass
Password
Method 2 (Incorrect) pty strings to these
string controls when a user logs in and to write empty the controls
trools
ls when the u
us
user logs
Move the Stop Button terminal inside Loop 1 so that hat it is read in each
e iteration
ation
on of L
Loopp 1, as shown out.
in the following block diagram. Although Loopp 1 terminates properly, ppr , Loopp 2 does not
no execute

Di tru
until it receives all its data inputs. Loop 1 doess not
ot pa
ppass
sss data oout of the
he loopop until the loop stops, so C. Variables
Loop 2 must wait for the final value of the Stop Button av
top Button, availablee only after LooLoop 1 finishes.
r D str
allel.
Therefore, the loops do not execute in parallel. l. Also, Lo
Loopop 2 executes
cutes
tes for only one
o iteration because In LabVIEW, the flow of data rather than n the
he sequential order of commands d det
determines the
its conditional terminal receives a True value lue from the Stop Button utton switch in Loop 1. ments.
execution order of block diagram elements. s. Theref
Therefore
fore you can
Therefore, an
n create block
block ddiagrams that have

s
simultaneous operations. For example, le, you can run ttwo Forr Loops
ops simultan
simultaneously and display the
Figure 8-3.
3. Parallel Loop
Loops Method
hod 2 Example
results on the front panel, as shownn in
n Figure 8-4.
t fo l In

l In
Figure 8-4. Displaying
ng the Results
Resu
Result of Two
wo For
or Loops on the Front Panel
No na

No na
tio

tio
Method
d 3 (Solution)
(Solutio
(Solut
If you could
ould
uld read the value
val of thehe loop control from
f a file, you would no longer have a dataflow
dency
dependency y between thetth loops,
s, as each loo
loop ccan independently access the file. In addition, reading
and writing
ting to files ccan be time
ime
me con
c ming,
ng at least in processor time.
consuming,
Na

Na
t
Another
other way to accomplish
a lish the taskk of communicating
cco between parallel loops is to find the location
where the loo
loop control
ol data is stored ini memory and read that memory location directly. A local
variable
ariable allows
allo you to do this by reading
re from the same front panel control in more than one
ion on
location o the diagram.
agram. Later ini this lesson you learn how to create and use a local variable that In LabVIEW,
bVIE
VI the flow of data ra
rather than the sequential order of commands determines the
ween two parallel
communicates between par loops. ock di
execution order of block diagra
diagram elements. Therefore, you can create block diagrams that have
simultaneous operations. For example, you can run two For Loops simultaneously and display the
results on the front panel, as shown in the following block diagram. However, if you use wires to
pass data between parallel loops, they no longer operate in parallel. Parallel loop operations can be

National Instruments | 8-3 8-4 | ni.com


LabVIEW Core 1 Course Manual Lesson 8 Solving Dataflow Challenges with Variables

two parallel loops on the same block diagram without any data flow dependency, or two loops in You also can select a local variable from the Functions palette and place it on the block diagram.
separate VIs that are called at the same time. The local variable node is not yet associated with a control or indicator.

ecause
use of the wire between
The block diagram in Figure 8-5 does not run the two loops in parallel because

uti ts

uti ts
the two subVIs.
variabl node and
To associate a local variable with a control or indicator, right-click the local variable
Figure 8-5. Data Dependency Imposed by Wire select Select Item from the shortcut menu. The expanded shortcut ut menu
enu lists all the
t front panel
objects that have owned labels.

rib en

rib en
LabVIEW uses owned labels to associate local variables withh front
nt panel objects,
obj soo label
bel the front

on

on
ls.
panel controls and indicators with descriptive owned labels.

ist um

ist um
Reading and Writing to Variables
After you create a variable, you can read data from
m a variab
variable
ariable
le or w
write dataa to it. By defa
defau
default, a new
The wire creates a data dependency, because the second
cond loop do
does not start until the first
firs loop rks as an indicat
variable receives data. This kind of variable works indicator and is a write local oor global.
finishes and passes the data through its tunnel. To make the two loops run concurrently,
ncurrently remove the When you write new data to the local or globalal variable,
ariable, the aassociated
ed front panel cocontrol or
wire. To pass data between the subVIs, use anotherher technique,
techniqu suchh as a variable. indicator updates to the new data.
r D str

r D str
In LabVIEW, variables are block diagram m elements
ements that aallow youou to access or sto
store data in another havee as a data source.
You also can configure a variable to behave so va
v
Right-click the variable and select
location. The actual location of the dataa varies
aries depend
depending on the he type of the vvariable. Local Change To Read from the shortcut menu enu to configur ariable
able to behave as a control. When
configure the variable
ntrols
ols and
variables store data in front panel controls and indic
indica
indicators. Globalal variables
variables aand single-process this node executes, the VI reads the dataa in the
the asso
associated frontt panel contr
control or indicator.
al repositories
shared variables store data in special repositorie
epositoriess that
th you can access from multiple
m VIs. Functional
t fo l In

t fo l In
hile Loop shift registers.
global variables store data in While rre s. Regardless ofo wwhere the variable stores To change the variable to receivee data from the bblock diagram
iagram
ram rather than
tha
th provide data, right-click
rcumvent
cumvent no
data, all variables allow you to circumvent nor
normal data ata flow by passing
passin
passi data from one place to the variable and select Change To o Write fro
from the shortcut
hortcut
cut menu.
another without connecting theth two places
laces
aces with
w a wire. For this reason,
rreas variables are useful in
parallel architectures, but also
so have
hav certain drawbacks,
backs,
acks, such as ra
race conditions. On the block diagram, you u can dis
dist
distinguish read variables
riables from wrw
write variables the same way you
distinguish controls fromm indicators
dicators.. A read variable
indicators. able has a thick bborder similar to a control. A write
rder similar to an indicator.
variable has a thin border tor.
Local VariablesUsing
lesUsing
Usin Variables
riables in a Single VI
No na

No na
Local variables transfer
ansfer
er data withi
within a single
gle VI. Local Variable
ble Example
In LabVIEW, youu read data from
fro
f or write data to a front
f panel object using its block diagram In the Communicating
nicating
ating Between
Betwe Parallelllel Loops
oops sect
section of this lesson, you saw an example of a VI
terminal. However,
owever, a front panel
p object
bject has only one
on block diagram terminal, and your application rallel loops. The front panel
that used parallel anell contained a single switch that stopped the data generation
tio

tio
might needd to access the ddata in that
hat terminal
erminal from
fr more than one location. displayed onn two graphs. On O the block diagram, thetth data for each chart is generated within an
uall While Loop to allow for
individual or separate timing
tim of each loop. The Loop Control terminal
Local and global variables
varia pass information
formation bbetween locations in the application that you cannot
formatio stoppeded bothth While Lo
Loops. In this example
example, th
the two loops must share the switch to stop both loops
nect with a wire. Use local
connect cal
al variables
varia
va s to aaccess front panel objects from more than one location at thee same
me time.
Us global variables
in a single VI. Use iables to access and pass data among several VIs.
Na

Use a Feedb
Feedbac
Feedback Node to store data fr

Creating
eatin
atin Local
cal Variables
Variable
Variab
from a previous VI or loop execution.
Na
Forr both charts tto updatee as expected, th
Whi Loops to pass the Stop
between While
the While Loops must operate in parallel. Connecting a wire
St Button data makes the While Loops execute serially, rather

Right-click an existing
g front ppanel object or block diagram terminal and select CreateLocal
Variable from the shortcututt menu
m to create a local variable. A local variable icon for the object
appears on the block diagram.

National Instruments | 8-5 8-6 | ni.com


LabVIEW Core 1 Course Manual Lesson 8 Solving Dataflow Challenges with Variables

than in parallel. Figure 8-6 shows a block diagram of this VI using a local variable to pass the Stop Use a global variable to share data among VIs on the same computer, especially if you do not use
Button data. 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.
Figure 8-6. Local Variable Used to Stop Parallel Loops
ps

uti ts

uti ts
Creating Global Variables
Use global variables to access and pass data among several VIs that hat run
un simultan
simultane
simultaneously. Global
variables are built-in LabVIEW objects. When you create a global bal variable, LabVIEW
Lab
La

rib en

rib en
automatically creates a special global VI, which has a front panel anell but no blo
bloc am. Add
block diagram.
controls and indicators to the front panel of the global VI to o define
ine the data types of the
he global

on

on
ner from which sseveral VIss can acce
variables it contains. In effect, this front panel is a container access
data.

ist um

ist um
Loop 2 reads a local variable associated with the Stop Button Wh
top Button. When you set et the button to False multaneously.
aneously. Each
For example, suppose you have two VIs running simultaneously. E VI contains
tains a While Loop
on the front panel, the terminal in Loop 1 writes a False
se value to the Stop
op Button local
cal vvariable rst VI contain
and writes data points to a waveform chart. The first contains a Boolean
eann control to ter
te
terminate
and to the conditional terminal in Loop 1. Loopp 2 reads the Sto
Stop Buttonon local
cal variable and writes minate
both VIs. You must use a global variable to terminate te both
bbotth loops
loop with a single
gle Boolean control. If
nal. Thus, the lo
a False value to the Loop 2 conditional terminal. n in parallel and terminate
loops run thinn the same V
both loops were on a single block diagram within VI, you could
d use a loc
local variable to
simultaneously when you turn off a single front
ont panel sswit
switch. terminate the loops.
r D str

r D str
With a local variable, you can write to orr read
ad from a control
con ndicator on the front
or indicator f panel. Writing ionss palette and place itt on the block diagram.
Select a global variable from the Functions di
d
ng dataa to any other
to a local variable is similar to passing ot
o minal.
al. However, with a local variable
terminal.
ntroll or read fr
you can write to it even if it is a control fro
o it even
from en iff it is an indi
iindicator.
nd In effect, with a
local variable, you can access a front pane
panel objec
obje th an input and an
object as both a output.
t fo l In

t fo l In
Double-click the global variable node to display the front
nt panel
anel of the ggl
global VI. Place controls and
qui
uires
For example, if the user interface requiresres use og in,, you can cle
users to log clear the Login and Password me way y
indicators on this front panel the same yo
you do onn a standard fron
front panel.
prompts each time a new user er log
lo
logs in. Usee a local variable to read from the Login and Password
serr logss in and
string controls when a user an to write empty
empty strings to these controls when the user logs LabVIEW uses owned labels bels to iden
ide
identify global variables,
ables, so labe
label the front panel controls and
out. tive owned labe
indicators with descriptive labels.
No na

No na
eral single variab
You can create several variable global VIs, each wi
with one front panel object, or if you want
Global and
d Shared VariablesUsing
V able Usin
Usi Variables Among VIs ariables
bles together,
to group similar variables together you can
an create
cr glo variable VI with multiple front panel
one global
objects.
You also can use variables to access
a and pass
ass data
data among
a several VIs that run simultaneously. A
local variablee shares
ares data wit
within a VI. A global va varia
variable also shares data, but it shares data among A global VII with multiple objects
o ore efficient
is more efficien because you can group related variables
tio

tio
multiple VIs. s. For example,
example suppose se you have two VIs running simultaneously. Each VI contains a together. Thee block diagra
diagram of a VI can include several global variable nodes that are associated
While Loopoop
op and writes data
d points ntss to a waveform
wavefor chart. The first VI contains a Boolean control to ntrols
rols and indic
with controls indica
indicators on thee front panel of a global VI. You place global VIs on other VIs
nate both VIs. Yo
terminate You can use a global varivaria
variable to terminate both loops with a single Boolean ame way you place
the same pla subVIsVIs on other
her VIs.
VIs
V Each time you place a new global variable node on
rol. If both loop
control. loops were onn a ssin
single block
loc diagram within the same VI, you could use a local lock diagram, La
a block LabVIEW W creat
creates a new
w gglobal VI associated only with that global variable node
ariable
riable to terminate
variable termin
termina the loops.
oops.
ps.
Na

You also can use


shared variab
u a single-process

twork A shared
twork.
a network.
gle-processs shared
gle-proces
milar
ilar to a local
variable is similar
shar variable in the same way you use a global variable. A
sh
local vvariable or a global variable, but allows you to share data across
ed variable ccan be single-process or network-published. Although
varia
network-published shared variables are beyond the scope of this course, by using the
Na
ndd copies of it.
and

single-process shared variable


ariab you can later change to a network-published shared variable.
variable,

National Instruments | 8-7 8-8 | ni.com


LabVIEW Core 1 Course Manual Lesson 8 Solving Dataflow Challenges with Variables

Figure 8-7 shows a global VI front panel window with a numeric, a string, and a cluster containing Creating Single-Process Shared Variables
a numeric and a Boolean control. The toolbar does not show the Run, Stop, p, or related buttons as
You must use a project file to use a shared variable. To create a single-process
cess shared variable,
a normal front panel window.
right-click My Computer in the Project Explorer window and select NewVari
NewVariable.
wV The
Shared Variable Properties dialog box appears, as shown in Figure 8-8.

uti ts

uti ts
Figure 8-7. Global VI Front Panel Window
w
Figure 8-8. Shared Variable Properties Dialog
alog
g Box

rib en

rib en
on

on
ist um

ist um
r D str

r D str
After you finish placing objects on the global al VI front
fron panel, savee it and retur
return to the block diagram
electt the object in
of the original VI. You must then select i the global
al VI
V thatat yo
you want to access. Click
the global variable node and select ct a front panel object
o rom
m the shortcut
from shortc t menu. The shortcut menu
t fo l In

t fo l In
lists all the front panel objects in the global VI tthat havee owned
wned labels. You also can right-click the
global variable node and select a front nt panel object fromm the Select Item shortcut menu.

rating tool or
You also can use the Operating o Labeling tool
ool to click the gglobal variable node and select the
m thee shortcut m
front panel object from me
menu. Under Variable Type, select ect Single PProcess. Give the variable
Pr variab a name and a data type. After you
iable, it auto
create the shared variable, automati
ma
automatically ppears in a ne
appears new library in your project file. Save the
No na

No na
If you want to use this global variab
vari ab in other VIs, select the
variable th Select a VI option on the Functions d additional
library. You can add dditional shar
sha
shared variabless to this lib
libr
library as needed. You can drag and drop
lt, the
palette. By default, he global va
var
variable is assoc
oc
associated with the first front panel object with an owned m the listing in tth
the variable from the Project Explorerr win
ect Ex
Exp wi
window directly to the block diagram. Use
label that you placeded in the gglob
global VI. Right-click
ht-c th
the global variable node you placed on the block enu to switch between
the short-cut menu be writing
ting or re
reading. Use the error clusters on the variable to
diagram and select ct a frontt pan
pa ect from the Sele
panel object Select Item shortcut menu to associate the global
S impose data flow..
tio

tio
ith
variable withth the data from another er front panel ob
obj
object.
Initializing
alizing
zing Variables
Va
Varia s
To initialize
nitialize
lize a local or
o globall variable,
varia , verify
verif that the variable contains known data values before
thee VI runs. Otherwise,
Othe
Otherw thee variables
variab m h contain data that causes the VI to behave incorrectly.
might
Na

Na
If the variable re
value to the va
relies on a computation
var
variable before
action in parallel
par th
with
omputation rresult for the initial value, make sure LabVIEW writes the
eforee iit attempts
temp to access the variable for any other action. Wiring the write
h the rest off the VI can cause a race condition.

National Instruments | 8-9 8-10 | ni.com


LabVIEW Core 1 Course Manual Lesson 8 Solving Dataflow Challenges with Variables

To make sure it executes first, you can isolate the code that writes the initial value for the variable In the state shown in Figure 8-10, the east and west traffic has a green light, while the north and
to the first frame of a sequence structure or to a subVI and wire the subVI to execute first in the south traffic has a red light. This stage waits for 4 seconds, as shown by the Wait (ms) function.
data flow of the block diagram, as shown in Figure 8-9.
Figure 8-10. Too Many Variables Used
Figure 8-9. Initializing Variables

uti ts

uti ts
rib en

rib en
on

on
ist um
If you do not initialize the variable before the VII reads
ads the varia
variable forr the first time, th
tthe variable
ont panel object
contains the default value of the associated front objec
object.
r D str
Avoiding Programming Issues
ssues
ues Inherent
Inhe nt with Variables
Varia
Vari
Local and global variables are advanced
ced LabVIEW
abVIEW cconcepts.s. They
hey are inher
inherently not part of the
LabVIEW dataflow execution model. el. Some of the
the pprogramming
mming
ng issues wit
w
with variables include the
following:
t fo l In

Make the block diagram codee hard to read


read use variables bre
readBecause break the dataflow model, you

ist
w the flow
cannot use wires to follow w of d
da
data.
ehavior
vior in VIsUsing vari
Lead to unexpected behavior iables
ables instead of a connector pane or using
variables
variables to access values
es in each ffr
frame of a sequence stru
struct
structure is a bad practice and can cause

t fo l
vior in
unexpected behavior n VIs.
No na

No na
rD
anceOverusing
Overusing local and global
Slow performanceOverusing obal variab
varia
variables, such as using them to avoid long The example shown n in Figure 8-11 accomplishes hes the same
am task but more efficiently and using a
diagra
diagr or using
wires across the block diagram sing the
th stea of data flow, slows performance.
stead
them instead better design. Noticetice that this example
exa iss much
muc easier
sier
ier to read and understand than the previous
example, mostlyy by reducing variable
va plac the indicators in the While Loop outside the
use. By placing
Figure 8-10 and Figure 8-11 illustrate te two
wo ways to pprogram the same example. Figure 8-10 Case structure,e, the
he indicators can update
date after every
ev state without using a variable. This example
tio

tio
var
va
illustrates a poor use of variables 8-1 illustrates a more optimal design. The
while Figure 8-11 cult
ult to modify for
is less difficult fo furtherr functionality, ssu
such as adding left turn signals, than the previous
ming example is a traffic
programming icc light applicat
applicati
application implemented as a state machine. Each state example.
updatess the
he lights for th
tthe next stagegee of the light
ligh sequence.
Na

Na
National Instruments | 8-11 8-12 | ni.com
LabVIEW Core 1 Course Manual Lesson 8 Solving Dataflow Challenges with Variables

Figure 8-11. Reduced Variables readers or monitors for a shared resource. However, try to use only one writer or controller for a
shared resource to avoid race conditions.

Properly Sequencing Instructions

uti ts

uti ts
Code in which data flow is not properly used to control the execution on order
rder can cau
cause some race
conditions. When a data dependency is not established, LabVIEW W cann schedule ta
tasks in any order,

rib en

rib en
end upon each oother. Consi
which creates the possibility for race conditions if the tasks depend Consider the
example in Figure 8-12.

on

on
Figure 8-12. Simple Race Condition
ndition

ist um

ist um
r D str

r D str
D. Race Conditions The code in this example has four possible
siblee outcomes, depending
ding
ng on the order in which the
operations execute.
A race condition occurs when the timing
iming
ng of events or the scheduling
cheduling
heduling of task
tasks unintentionally affects
t fo l In

t fo l In
ditions are a common
an output or data value. Race conditions com
co blem for programs
problem pro
prog that execute multiple Outcome 1: Value = (Value
Value 5) + 2
ween them using variables.
tasks in parallel and share data between able
1. Terminal reads Value.
ult to identify
Race conditions are difficult iden
ide and debug,ug, because the ooutcome depends upon the order 2. Value 5 is stored in Value.
ue.
in which the operating system
em execute uled
executes scheduledled tasks and tthe timing of external events. Often,
3. Local variable readss Value
alue 5.
ition can return the same
code with a race condition mee re
rresult
sult thousan
thousands of times in testing, but still be
No na

No na
g different
capable of returning fferent result at any time.
mee 4. (Value 5) + 2 is stored Value.
ored in Valu
Value

o avoid
The best way to d race cond
conditions is byy using
us the ffollowing techniques: Outcome 2: Value = ((Value
(V e + 2) 5
ng and
Controlling nd limiting shared
s resources.
ources. 1. Local variable
riablee reads Value.
Val
Valu
tio

tio
Properly instructions
rlyy sequencing in ons by specifying
specifyin an execution order. 2. Value + 2 is stored in Value.
ducing
cing the use of
Reducing o variables.
es rminal
nal reads Value
3. Terminal Valu
Va + 2.
lue + 2) 5 iis stored
4. (Value d in Valu
Va
Value.
Controlling
ontrolling and Limiting
imiting Shared
S Resources
Na

Race conditions are most


A resource is any entity
thee most common
com
includee fi
ost common when
tity
hared
shared
whe two tasks have both read and write access to a resource.
whe
ity that is shared
share between the processes. When dealing with race conditions,
d resources are data storage, such as variables. Other examples of resources
files and references
eferences to hardware
ha
h resources.
Na
Outcome 3

2. Local
3: Value
1.. Terminal
ue = Value 5
Termina reads Value.
lue.
cal variablee reads Value.
ocal
3. Value + 2 is stored Value.
d in Va
Valu
cee fr
When you alter a resource from multiple locations, you introduce the possibility of a race
condition. Therefore, an ideal way to avoid race conditions is to minimize shared resources and the 4. Value 5 is stored in Value.
number of writers to the remaining shared resources. In general, it is not harmful to have multiple

National Instruments | 8-13 8-14 | ni.com


LabVIEW Core 1 Course Manual

Outcome 4: Value = Value + 2


1. Terminal reads Value.
2. Local variable reads Value.

uti ts

uti ts
3. Value 5 is stored in Value.
4. Value + 2 is stored in Value.

rib en

rib en
enerally
rally behaves
Although this code is considered a race condition, the code generally beha andomly
mly than
less randomly t
the first race condition example because LabVIEW usually assigns gns a consis der to the
consistent order

on

on
operations. However, you should avoid situations such as this one becaus rder and
because the order nd the
uld change
behavior of the VI can vary. For example, the order could hange when running ng thee VI under

ist um

ist um
wer version of L
different conditions or when upgrading the VI to a newer EW.
LabVIEW.W. Fortunately,
Fortunately race
ntrolliing
ng the dat
conditions of this nature are easily remedied by controlling data flow.

r D str

r D str
t fo l In

t fo l In
No na

No na
tio

tio
Na

Na
National Instruments | 8-15
LabVIEW Core 1 Course Manual

Self-Review: Quiz
1. You should use variables in your VI whenever possible.

uti ts

uti ts
a. True
b. False

rib en

rib en
ters and
2. When controlling resources, which combination of writers nd readers
reader reducess the chance of

on

on
race conditions?

ist um

ist um
a. One writer, one reader
b. One writer, multiple readers
c. Multiple writers, one reader
d. Multiple writers, multiple readers
r D str

r D str
t fo l In

t fo l In
No na

No na
tio

tio
Na

Na
National Instruments | 8-17
LabVIEW Core 1 Course Manual Lesson 8 Solving Dataflow Challenges with Variables

Self-Review: Quiz Answers Notes


1. You should use variables in your VI whenever possible.

uti ts

uti ts
a. True
b. False
You should use variables only when necessary. Use wiress to transfer dat
da ev
data whenever

rib en

rib en
possible.

on

on
ist um

ist um
2. When controlling resources, which combination off writers
riters and re
rea duces the chan
readers reduces chanc
chance of
race conditions?
a. One writer, one reader
b. One writer, multiple readers
c. Multiple writers, one reader
r D str

r D str
d. Multiple writers, multiple readers
t fo l In

t fo l In
No na

No na
tio

tio
Na

Na
National Instruments | 8-19 8-20 | ni.com
Appendix A Additional Information and Resources

Additional Information and


A Other National Instruments Training Courses
National Instruments offers several training courses for LabVIEW users. These ese ccourses continue
the training you received here and expand it to other areas. Visit ni.com/training
trainin to purchase
om/training

uti ts

uti ts
Resources cations
tions around tth
course materials or sign up for instructor-led, hands-on courses at locations the world.

National Instruments Certification

rib en

rib en
This appendix contains additional information about National
al Instruments
nstruments technical
tte l support
port Earning an NI certification acknowledges your expertise in working king with NI
N products
cts and

on

on
options and LabVIEW resources. c
technologies. The measurement and automation industry, your employer, clients, and peers
recognize your NI certification credential as a symbol of the skills and knowledge
kn ge you
ou have gained
gain
National Instruments Technical Support
pport Options
Op
O ns through experience. Visit ni.com/training for more re information
nformation aabout thee NI certification
certificatio
certificati

ist um

ist um
program.
Log in to your National Instruments ni.com Userr Profile
ofile to get ppersonalized
lized
ed access to your
y
services. Visit the following sections of ni.com forr technical support
su and professional services: LabVIEW Resources
SupportTechnical support at ni.com/support
pport inclu
support includes the following
lowing resources:
reso
resou
This section describes how you can receive more information
informati regarding
arding
ng LabVIEW.
LabVIEW
Self-Help Technical ResourcesFor or answers aand solutions,
For ons, visit ni.co
ni.com/support for
r D str

r D str
earchable
hable Know
software drivers and updates, a searchable Knowl
KnowledgeBase,ase, product manuals,
man
m step-by-step
andss of example
troubleshooting wizards, thousands exampl programs,
ams,
ms, tutorials, application
ap notes, NI Community
n. Registered
instrument drivers, and so on. egistered use
us eive access to
users also receive t the NI Discussion NI Community is an on-line communitynity that unites
unites users
u from
om around the w world to discuss, share,
Forums at ni.com/forums ms. NI Applications
Applicati Engineers
gineer
neerss make sure
sur every question
su and learn about LabVIEW. Visit thee NI Community to askk questions,
stions, get ideas,
id
i and share code for
t fo l In

t fo l In
submitted online receivess an answe
answer. om/community for more
LabVIEW projects. Go to ni.com/community ore information.
information
Standard Service Program m Membe
Member
MembershipThisThis is program entitles
e members to direct
ation Engineers
ations
access to NI Applications eers via phone
on and
one nd email fo
ffor one-to-one technical support, LabVIEW Books
ve access
as well as exclusive cess to
t self-paced onlinene training modules
m at Many books have been writtenen abou
about LabVIEW programming
ramming anand applications. The National
ni.com/self-paced-training
-paced-train
ced-train . All
ll customers auaut
automatically receive a one-year ntains
ns a list of all
Instruments Web site contains a the LabVIEW
abbVIEW
VIEW books aand links to places to purchase these
S
membership in the Standard Service Progr (SSP)
Program SSP with the purchase of most software books. Visit http://zone.ni.com/devzone/cda/tut/p/id/5389
/zone.ni.com
e.ni.com one/cda/tu
one/cda/tut/ for more information.
No na

No na
nd bundles
products and undles inclu
includ eloper Suite
including NI Developer uit NI also offers flexible extended
Suite.
ons that guarantee
contract options gua
guar S
SS benefits
your SSP nefit are available without interruption for as
long as youu need them.
them Visit ni.com/ssp
i.com/ssp
om for more information.
For information about otherr technical
nformation ab
abou support options in your area, visit
hnical supp
suppo
tio

tio
com/service or contact
ni.com/services
.com/service ontact your local
loc office at ni.com/contact.
System
stemm IntegrationIf
Integratio
Integration youu have time con
constraints, limited in-house technical resources, or
other
therr project challenges,
cha
chal National
Nati al Instruments
Instrum
Instru Alliance Partner members can help. The NI
ance Partne
Alliance Partners joins system
ystem int at
integrators, consultants, and hardware vendors to provide
Na

comprehensiv service
comprehensive

visit ni.

You also
ce and expertise
assistance ffor application
ication
liance.
ni.com/alliance
lliance

so can visit the Worldwid


expertis to customers. The program ensures qualified, specialized
on and system
sy
syste development. To learn more, call your local NI office or

Worldwide Offices section of ni.com/niglobal to access the branch


Na
office Web sites, whichch prov
provi d up-to-date contact information, support phone numbers, email
provide
ent
addresses, and current events.

National Instruments | A-1 A-2 | ni.com


Glossary

Glossary
C
channel 1. PhysicalA terminal or pin at which you can measure m
mea or generate
A an analog or digital signal. A single physicall channel
annel can iinclude more

uti ts

uti ts
erential
ential analog in
than one terminal, as in the case of a differential iinput channel
automatic scaling Ability of scales to adjust to the range of plotted
otted values
values. On graph or a digital port of eight lines. A counter also can be a physical
ph channel,
scales, autoscaling determines maximum and minimuminimum scale values. although the counter name is not the namee of the term terminal where the

rib en

rib en
counter measures or generates the digital al signal.
B perty settings
2. VirtualA collection of property se tings tha nclude
that can includede a name,

on

on
minal
a physical channel, input terminal al connection
connections, the typeype of
block diagram Pictorial description or representation
tation of a pr
program or algorithm. TThe
measurement or generation, and scaling inf info on. You can defin
information. defi
define
cutab icons
block diagram consists of executable icon called nodes and wires
wire that

ist um

ist um
NI-DAQmx virtual channels els outside a tas bal)
al) or inside a tta
task (global) task
carry data between the nodes.s. The bl ock diagram is the source co
block code for
tual channels
(local). Configuring virtual channels is optionalal in Traditional
the VI. The block diagram resides iin the
th block diagram window
wind of the
NI-DAQ (Legacy) and d earlier
rlier version
versio but is integral
versions, ntegral to ev
eve
every
VI.
ake in NI-DAQ
measurement you take NI-DAQm
NI-DAQmx. In Traditionalitional NI-D
NI-DAQ
Boolean controls and o manipulat
Front panel objects to ay Boolean (TRUE or
manipulate and display nfigure
ure virtual channels
(Legacy), you configure c s in MAX. In NI-DAQmx,
N
NI
indicators FALSE) data. ure
re virtual cchann
you can configure her inn MAX or in your program,
channels either
r D str

r D str
figure channels
and you can configure chann
channe as part art of a task or separately.
s
broken Run button laces the Ru
Button that replaces n when a VI ca
Run button cannot run because of
errors. 3. SwitchAA switch chan resents any conn
channel represents connection point on a
an be made up
switch. It can u of onee or more signal wires (commonly one,
broken VI nnot run bec
VI that cannot rrors; sign
because of errors; signified by a broken arrow in the two, orr four),
ur), dependi hee switch
depending on the switch topolo
topology. A virtual channel
t fo l In

t fo l In
en Run button
broken button. ot be created with
cannot wi a switch
w itch
h channel.
channel. Sw
Switch channels may be used
n the NI-DA
only in NI-DAQmx Switch tch functions and VIs.

checkbox Small square bbox in a dialog box whi


which you can select or clear.
Checkboxe
Checkbox ally
Checkboxes generallylly are associate
associated with multiple options that you
can set. Yo
You can select
elect more than one checkbox.
No na

No na
al
conditional terminal Termin of a While
Terminal W Loop that
Loop tha contains a Boolean value that
dete
deter
determines if thee V form another iteration.
VI performs
Context Help ndow
p window W
Window w thatt displays basic
ba information about LabVIEW objects when
tio

tio
o
you move the cursor over each object. Objects with context help
rmation
mation include VIs, functions, constants, structures, palettes,
information
erties,
ties, method
properties, methods, events, and dialog box components.
trol
control pan object
Front panel obj
bj for entering data to a VI interactively or to a subVI
Na

Na pal
pale
Controls palette

current VI
programma
programmat
programmatically,
Palette tth
objects
objects.

VI w
such as a knob, push button, or dial.
that contains front panel controls, indicators, and decorative

whose front panel, block diagram, or Icon Editor is the active


w
window.

National Instruments | G-1 G-2 | ni.com


LabVIEW Core 1 Course Manual Glossary

D E
DAQ See data acquisition (DAQ). Error list window Window that displays errors and warnings occurring
curring
rin in a VI and in
some cases recommends how to correct the errors.
or

uti ts

uti ts
DAQ Assistant asurement
urement tasks,
A graphical interface for configuring measurement tasks channels,
and scales. error message lfunction
ction or of an unacceptable
Indication of a software or hardware malfunction
data entry attempt.
DAQ device A device that acquires or generates dataa and can contain
con
co ul
multiple

rib en

rib en
channels and conversion devices. DAQAQ devices ininclude plug-in
g-in Express VI A subVI designed to aid in commonn measurement ttasks. You confi
configure
AQP
devices, PCMCIA cards, and DAQPad Pad
ad devices, which connect
nect to a ation dialog box.
an Express VI using a configuration box

on

on
computer USB or IEEE 1394 port.. SCXI
SCXI modules
modu are considered
mod sidered DAQ
devices.
F

ist um

ist um
data acquisition ring analog or di
1. Acquiring and measuring lectrical
trical signals from
digital electrical f
For Loop Iterative loop structure thatt executes its
it subdiagram
agram
gram a set number
numb
num of
(DAQ) ansducers,
ducers, and tte
sensors, acquisition transducers, bess or fixtures.
test probes
ext-based
ased code:
times. Equivalent to text-based code For i = 0 to n 1, 1 do....
og or digital
2. Generating analog digi l elec
ele ignals.
ls.
electrical signals.
front panel terface
ace of a VI
Interactive user interface VI. Front panelel appearance
appearan imitates
data flow ystem
stem that consists
Programming system consi
consi of executable
xecutable
able nodes that execute ments,
ents, such as os
physical instruments, copess and multim
oscilloscopes multimeters.
r D str

r D str
ey receive all required
only when they req
re nput data. The nodes
input n produce
omatically when
output data automatically w eyy execute. LabVIEW
they LabV
Lab is a dataflow function cution
ion element, comparable
Built-in execution rable to an ope
opera
operator, function,
he movement
system. The ovement of
o data through
hrough
ugh the node
nodes determines the ent inn a text-based
or statement text-base
text-ba ramming
ming language.
programming langua
on order of the VIs
execution V and functions
nctions on the
th block diagram.
Functions palette Palettee that
at contains VIs,
V functions,
ctions,
ions, block dia
diagram structures,
t fo l In

t fo l In
data type mat for informat
Format information. In LabVIEW,
bVIEW, accacce
acceptable data types for most and constants.
VIs andd functions are numeric,
meric,
ic, array,
array, string,
stri Boolean, path, refnum,
enu
enum
enumeration,n, w m, and cluster.
waveform, G
default Preset valu
value. Many VI inputs use
use a default value if you do not specify General Purpose GPIB. Syn
Synonymous uss with HP-IB. T
Th
The standard bus used for controlling
a value
value. Interface Bus electroni instruments
electronic ments with a computer.
com Also called IEEE 488 bus
No na

No na
device An instrument
ins nt or
o controller
ntroller y
yo
you can access as a single entity that because
ecaus it is definedd by ANSI/IEEE
ANSI/
ANSI/I Standards 488-1978, 488.1-1987,
contr
con
controls or monitor
ito real-world
monitors -wo
wo I/O points. A device often is connected and 4488.2-1992.
992.
to a host computer
puter throu
through some type of communication network. graph 2 display
2D ay of one or mo
more plots. A graph receives and plots data as a
SSee also
o DAQ
AQ device anand measurement device.
tio

tio
block.
drag To usee the cursor on the screen to select, move, copy, or delete objects.
I
driverr Softw e that
Software hat controls
ccon a specific hardware device, such as a DAQ
devic
device. I/O
O Input/Output.
Input/Outp
nput/O The transfer of data to or from a computer system
Na

ty
dynamic data type Data type uused by Express VIs that includes the data associated with a
signal aan
the nam
and attributes that provide information about the signal, such as
name of the signal or the date and time LabVIEW acquired the
data Attributes specify how the signal appears on a graph or chart.
data.
Na
on
n
icon
indicator
involving communications
data acq
acqui
Graphi
cco channels, operator input devices, and/or
acquisition and control interfaces.
Graphical representation of a node on a block diagram.
Fro panel object that displays output, such as a graph or LED.
Front
instrument driver A set of high-level functions that control and communicate with
instrument hardware in a system.

National Instruments | G-3 G-4 | ni.com


LabVIEW Core 1 Course Manual Glossary

Instrument I/O Add-on launched from the Instrument I/O Assistant Express VI that NI-DAQmx The latest NI-DAQ driver with new VIs, functions, and development
Assistant communicates with message-based instruments an
and graphically parses tools for controlling measurement devices. Thee adadvantages of
the response. NI-DAQmx over earlier versions of NI-DAQ Q include
clu the DAQ
asurement
ement tasks
Assistant for configuring channels and measurement tas
task for your

uti ts

uti ts
device for use in LabVIEW, LabWindowss/CVI, and M Measurement
L Studio; NI-DAQmx simulation for most st supported
upported dev
devices for testing
label Text object used to name or describee objects
jects or reg
regi
regions on th
the front and modifying applications without plugging
gging in hard
hardware; and a

rib en

rib en
panel or block diagram. ating DAQ appli
simpler, more intuitive API for creating applications using
g fewer
rsions
ons of NI-DAQ.
functions and VIs than earlier versions NI-DA

on

on
LabVIEW Laboratory Virtual Instrument Engineering
neering W
Wo
Workbench.ch. LabVIEW
abVIEW is
nguage
age that uses icons instead
a graphical programming language ead of lines oof node Program execution element. Node dess are analo
Nodes analogous too statements,
atements,
text to create programs. ubroutin
outiness in te
operators, functions, and subroutines tex d programmin
text-based programming

ist um

ist um
agram,
am, nodes
languages. On a block diagram, node in unctio
nctions,
ns, structu
include functions, structures,
LED Light-emitting diode. and subVIs.
legend hartt owns to di
Object a graph or chart dis
display thee names
mes and plo
plot styles of numeric controls and manipulate aand display
Front panel objects to manipulate play numeric dat
data.
h orr chart.
plots on that graph indicators
r D str

r D str
M O
MAX See Measurement
surement
ement & Aut
Au
Automation
on Explorer.
xplorer. object Generic term
m for any ite
item on thee front
ont panel or block diagram,
ing controls, ind
including indicators,, structures, nodes,
nod wires, and imported
Measurement & The standard National Instruments
tandard Nation
Nationa mentss hardware
ument hardwa configuration and
t fo l In

t fo l In
ures.
res.
pictures.
Automation Explorer nostic
ostic environm
diagnostic enviro or Windows.
environment for
Operating tool nter da
Tool to enter data into controls
ontrols
ols or to ope
operate them.
measurement device ess ssuch as the
DAQ devices he E Series mu
mul
multifunction I/O (MIO) devices,
SCXI
CXI sig oning
ning modules, and
signal conditioning a switch modules.
P
menu bar Horizon bar that
Horizonta
Horizontal at lists the names
name of the main menus of an application.
No na

No na
The
he me
menu bar appearsears below ththe title bar of a window. Each palette Displays
Display objects orr tools you can
ca use to build the front panel or block
applic m
application has a menu th is distinct for that application, although
bar that diagra
diagram.
som
some menusus and
nd commands
com are common to many applications.
plot G
Gr
Graphicall representation
resen of an array of data shown either on a graph or
a chart.
tio

tio
N
ingg tool
Positioning Tooll to move and re
resize objects.
NI-DAQ
AQ Driverr software included
in with all NI DAQ devices and signal
condit
ondi ngg com
conditioning co
components. NI-DAQ is an extensive library of VIs and ect
project A co ion
on of L
collection LabVIEW files and files not specific to LabVIEW that
ANSI C fu functions you can call from an application development you can
ca use
u to create build specifications and deploy or download files
Na

environmen
environment (ADE), such as LabVIEW, to program an NI
measurement device, such as the M Series multifunction I/O (MIO)
measure
measurem
DAQ d de
devices, signal conditioning modules, and switch modules. Na
Project Exp
indow
ndow
window
Expl
Explorer

Properties dialog
to targets.
Window in which you can create and edit LabVIEW projects.

Dia
Di
Dialog boxes accessed from the shortcut menu of a control or indicator
boxes tthat you can use to configure how the control or indicator appears in
th
the front panel window.

National Instruments | G-5 G-6 | ni.com


LabVIEW Core 1 Course Manual Glossary

pull-down menus Menus accessed from a menu bar. Pull-down menu items are usually Traditional NI-DAQ An older driver with outdated APIs for developing data acquisition,
general in nature. (Legacy) instrumentation, and control applications for older
lde National
raditiona
itio NI-DAQ
Instruments DAQ devices. You should use Traditional
PXI PCI eXtensions for Instrumentation. A modular,
dular, computer-based
r, comput
compute fer too the NI-D
(Legacy) only in certain circumstances. Refer NI-DAQ Readme

uti ts

uti ts
instrumentation platform. for more information about when to use Traditional
aditional NI-D
NI-DAQ
ported devices,
(Legacy), including a complete list of supported devic operating
S systems, and application software andd language
anguage versions.
vers

rib en

rib en
sample Single analog or digital input or output
put data poi
poin
point.
V

on

on
scale Part of graph, chart, and somee numeric
umeric controls
contr and indicators
icators that
tha
VI See virtual instrument (VI).
contains a series of marks or points
oints at kno
know vals to denote units
known intervals uun

ist um

ist um
of measure. virtual instrument (VI) Program in LabVIEW that
at models the appearance
ap ncee and function of a
physical instrument.
shortcut menu ht-clicki
icking
ng an oobject. Menu
Menu accessed by right-clicking nu items pert
perta
pertain to that
object specifically.
W
string Representation off a value as tex
text.
r D str

r D str
waveform Multiple voltage
age readings tak
taken at a specific sampling
samplin rate.
structure ntroll element, su
Program control such as a Flat Sequence sstructure, Stacked
Sequence structure,
cture, Case sstructure,
re, For Loop, Wh
While Loop, or Timed waveform chart Indicator that plots
plots data ppoints att a certain
rtain rate.
Loop.
While Loop Loop structure
cture thatt rep
repeats a section
ection of code uuntil a condition occurs.
t fo l In

t fo l In
subpalette tte
te that you access
Palette acce
acces from another
anot
other
ther palette that
t is above the subpalette
rarchy.
in hierarchy. wire Data path betwee
between nodes.

subVI VI us h block diagram


he
used on the iagram of anot
anoth
another VI. Comparable to a Wiring tool Tool to define
Too nee ddata paths
ths terminals.
hs between term
ter
subroutin
brouti
subroutine.
No na

No na
T
task A collection
co
c n of one
on or more
re channels, timing, triggering, and other
pr
p
propertiess in NI-DAQm
NI-DA
NI-DAQmx. A task represents a measurement or
tion you want to perform.
generation
tio

tio
templatee VI hat
at contains common
VI that com controls and indicators from which you can
build multiple VIs that perform similar functions. Access template VIs
from
rom tthe New
w ddialog box.
ew
Na

erminal
mina
terminal
tip strip

tool
Object or region

Small yye
re on a node through which data pass.
yellow text banners that identify the terminal name and make it
easier to identify terminals for wiring.

Spe
Special cursor to perform specific operations.
Na
toolbar Bar that contains command buttons to run and debug VIs.

National Instruments | G-7 G-8 | ni.com

Você também pode gostar