LabVIEWBasics I
LabVIEWBasics I
Copyright
© 1993–2005 National Instruments Corporation. All rights reserved.
Under the copyright laws, this publication may not be reproduced or transmitted in any form, electronic or mechanical, including
photocopying, recording, storing in an information retrieval system, or translating, in whole or in part, without the prior written consent
of National Instruments Corporation.
In regards to components used in USI (Xerces C++, ICU, and HDF5), the following copyrights apply. For a listing of the conditions and
disclaimers, refer to the USICopyrights.chm.
This product includes software developed by the Apache Software Foundation (http:/www.apache.org/).
Copyright © 1999 The Apache Software Foundation. All rights reserved.
Copyright © 1995–2003 International Business Machines Corporation and others. All rights reserved.
NCSA HDF5 (Hierarchical Data Format 5) Software Library and Utilities
Copyright 1998, 1999, 2000, 2001, 2003 by the Board of Trustees of the University of Illinois. All rights reserved.
Trademarks
National Instruments, NI, ni.com, and LabVIEW are trademarks of National Instruments Corporation. Refer to the Terms of Use section
on ni.com/legal for more information about National Instruments trademarks.
Other product and company names mentioned herein are trademarks or trade names of their respective companies.
Members of the National Instruments Alliance Partner Program are business entities independent from National Instruments and have
no agency, partnership, or joint-venture relationship with National Instruments.
Patents
For patents covering National Instruments products, refer to the appropriate location: Help»Patents in your software,
the patents.txt file on your CD, or ni.com/legal/patents.
Worldwide Technical Support and Product Information
ni.com
Worldwide Offices
Australia 1800 300 800, Austria 43 0 662 45 79 90 0, Belgium 32 0 2 757 00 20, Brazil 55 11 3262 3599, Canada 800 433 3488,
China 86 21 6555 7838, Czech Republic 420 224 235 774, Denmark 45 45 76 26 00, Finland 385 0 9 725 725 11,
France 33 0 1 48 14 24 24, Germany 49 0 89 741 31 30, India 91 80 51190000, Israel 972 0 3 6393737, Italy 39 02 413091,
Japan 81 3 5472 2970, Korea 82 02 3451 3400, Lebanon 961 0 1 33 28 28, Malaysia 1800 887710, Mexico 01 800 010 0793,
Netherlands 31 0 348 433 466, New Zealand 0800 553 322, Norway 47 0 66 90 76 60, Poland 48 22 3390150,
Portugal 351 210 311 210, Russia 7 095 783 68 51, Singapore 1800 226 5886, Slovenia 386 3 425 4200,
South Africa 27 0 11 805 8197, Spain 34 91 640 0085, Sweden 46 0 8 587 895 00, Switzerland 41 56 200 51 51,
Taiwan 886 02 2377 2222, Thailand 662 278 6777, United Kingdom 44 0 1635 523545
For further support information, refer to the Additional Information and Resources appendix. To comment on National Instruments
documentation, refer to the National Instruments Web site at ni.com/info and enter the info code feedback.
Contents
Student Guide
A. About This Manual ...............................................................................................viii
B. What You Need to Get Started .............................................................................viii
C. Installing the Course Software..............................................................................ix
D. Course Goals.........................................................................................................x
E. Course Conventions ..............................................................................................x
Lesson 1
Problem Solving
A. Software Development Method ............................................................................1-2
B. Scenario ................................................................................................................1-2
C. Design ...................................................................................................................1-2
D. Implementation .....................................................................................................1-7
E. Testing ..................................................................................................................1-8
F. Maintenance..........................................................................................................1-8
Exercise 1-1 Software Development Method........................................................1-9
Exercise 1-2 Project: State Transition Diagram ....................................................1-11
G. Project ...................................................................................................................1-14
Lesson 2
Navigating LabVIEW
A. Virtual Instruments (VIs)......................................................................................2-2
B. Parts of a VI ..........................................................................................................2-2
C. Starting a VI..........................................................................................................2-4
D. Project Explorer ....................................................................................................2-8
E. Front Panel ............................................................................................................2-12
F. Block Diagram ......................................................................................................2-18
Exercise 2-1 Concept: Exploring a VI...................................................................2-25
G. Searching for Controls, VIs, and Functions..........................................................2-26
Exercise 2-2 Concept: Navigating Palettes ...........................................................2-28
H. Selecting a Tool ....................................................................................................2-29
Exercise 2-3 Concept: Selecting a Tool ................................................................2-35
I. Dataflow................................................................................................................2-39
Exercise 2-4 Concept: Dataflow............................................................................2-41
J. Building a Simple VI ............................................................................................2-42
Exercise 2-5 Simple AAP VI.................................................................................2-46
K. LabVIEW Help Utilities .......................................................................................2-57
Exercise 2-6 Concept: Using Help ........................................................................2-61
Lesson 3
Implementing a VI
A. Front Panel Design................................................................................................3-2
Exercise 3-1 Project: Weather Station UI VI ........................................................3-9
B. Block Diagram Terminals.....................................................................................3-14
C. Documenting Code ...............................................................................................3-22
Exercise 3-2 Project: Determine Warnings VI ......................................................3-25
D. While Loops..........................................................................................................3-32
Exercise 3-3 Auto Match VI..................................................................................3-35
E. For Loops ..............................................................................................................3-41
Exercise 3-4 Concept: While Loops versus For Loops .........................................3-44
F. Timing a VI...........................................................................................................3-47
G. Iterative Data Transfer ..........................................................................................3-48
Exercise 3-5 Average Temperature VI..................................................................3-51
H. Plotting Data .........................................................................................................3-55
Exercise 3-6 Temperature Multiplot VI ................................................................3-61
I. Case Structures .....................................................................................................3-66
Exercise 3-7 Project: Determine Warnings VI ......................................................3-71
J. Formula Nodes......................................................................................................3-78
Exercise 3-8 Optional: Square Root VI.................................................................3-80
Exercise 3-9 Optional: Determine Warnings Challenge VI .................................3-84
Exercise 3-10 Optional: Determine More Warnings VI..........................................3-87
Lesson 4
Relating Data
A. Arrays....................................................................................................................4-2
Exercise 4-1 Concept: Manipulating Arrays .........................................................4-8
B. Clusters .................................................................................................................4-15
Exercise 4-2 Concept: Clusters..............................................................................4-21
Exercise 4-3 Project: Weather Station UI VI ........................................................4-26
C. Type Definitions ...................................................................................................4-29
Exercise 4-4 Project: Weather Station CTL ..........................................................4-33
Lesson 5
Debugging VIs
A. Correcting Broken VIs..........................................................................................5-2
B. Debugging Techniques .........................................................................................5-4
C. Undefined or Unexpected Data.............................................................................5-11
D. Error Checking and Error Handling......................................................................5-12
Exercise 5-1 Concept: Debugging.........................................................................5-16
Lesson 6
Developing Modular Applications
A. What is Modularity? .............................................................................................6-2
B. Icon and Connector Pane ......................................................................................6-4
C. Using SubVIs ........................................................................................................6-9
Exercise 6-1 Project: Determine Warnings VI ......................................................6-11
Self-Review: Quiz.......................................................................................................6-17
Self-Review: Quiz Answers........................................................................................6-19
Lesson 7
Measurement Fundamentals
A. Computer-Based Measurement Systems ..............................................................7-2
B. Measurement Concepts.........................................................................................7-4
C. Increasing Measurement Quality ..........................................................................7-12
Exercise 7-1 Concepts: Measurement Fundamentals............................................7-18
Lesson 8
Data Acquisition
A. Hardware...............................................................................................................8-2
B. Software Architecture ...........................................................................................8-5
C. Simulating a DAQ Device ....................................................................................8-8
Exercise 8-1 Concept: MAX ...............................................................................8-9
D. Analog Input .........................................................................................................8-15
Exercise 8-2 Triggered Analog Input VI ..............................................................8-17
E. Analog Output.......................................................................................................8-22
F. Counters ................................................................................................................8-23
Exercise 8-3 Count Events VI ..............................................................................8-25
G. Digital I/O .............................................................................................................8-28
Exercise 8-4 Optional: Digital Count VI ..............................................................8-29
Self-Review: Quiz.......................................................................................................8-33
Lesson 9
Instrument Control
A. Instrument Control ................................................................................................9-2
B. GPIB .....................................................................................................................9-2
C. Serial Port Communication...................................................................................9-3
D. Using Other Interfaces ..........................................................................................9-6
E. Software Architecture ...........................................................................................9-7
Exercise 9-1 Concept: GPIB Configuration with MAX .......................................9-9
Lesson 10
Analyzing and Storing Measurement Data
A. Analyzing and Processing Numeric Data .............................................................10-2
Exercise 10-1 Concept: Analysis Types..................................................................10-7
B. Reading and Writing Data to File .........................................................................10-9
Exercise 10-2 Optional: Read VCard VI.................................................................10-13
Self-Review: Quiz Answers........................................................................................10-29
Lesson 11
Common Design Techniques and Patterns
A. Sequential Programming.......................................................................................11-2
B. State Programming ...............................................................................................11-4
C. State Machines ......................................................................................................11-5
Exercise 11-1 Project: Temperature Weather Station .............................................11-12
D. Parallelism ............................................................................................................11-28
Summary .....................................................................................................................11-29
Appendix A
Additional Information and Resources
Index
Course Evaluation
Thank you for purchasing the LabVIEW Basics I: Introduction course kit.
You can begin developing an application soon after you complete the
exercises in this manual. This course manual and the accompanying
software are used in the three-day, hands-on LabVIEW Basics I:
Introduction course.
You can apply the full purchase of this course kit toward the corresponding
course registration fee if you register within 90 days of purchasing the kit.
Visit ni.com/training for online course schedules, syllabi, training
centers, and class registration.
Note For course manual updates and corrections, refer to ni.com/info and enter the
info code rdlvce.
Courses
Certifications
Hardware-Based Courses:
• Data Acquisition and Signal Conditioning • Modular Instruments • Instrument Control • Machine Vision
• Motion Control • LabVIEW Real-Time
*Core courses are strongly recommended to realize maximum productivity gains when using LabVIEW.
The course manual is divided into lessons, each covering a topic or a set
of topics. Each lesson consists of the following:
• An introduction that describes the purpose of the lesson and what
you will learn
• A description of the topics in the lesson
• A set of exercises to reinforce those topics
Some lessons include optional and challenge exercise sections or a set
of additional exercises to complete if time permits.
• A summary that outlines important concepts and skills taught in
the lesson
If you do not have this hardware, you still can complete the exercises.
Alternate instructions are provided for completing the exercises without
hardware. Exercises that explicitly require hardware are indicated with an
icon, shown at left. You also can substitute other hardware for those
previously mentioned. For example, you can use a GPIB instrument in place
of the NI Instrument Simulator, or another National Instruments DAQ
device connected to a signal source, such as a function generator.
❑ GPIB interface
❑ A serial cable
❑ A GPIB cable
Filename Description
Exercises Folder for saving VIs created during the course and
for completing certain course exercises; also
includes subVIs necessary for some exercises and
zip file (nidevsim.zip) containing the LabVIEW
instrument driver for the NI Instrument Simulator
Solutions Folder containing the solutions to all the course
exercises
D. Course Goals
This course prepares you to do the following:
• Understand front panels, block diagrams, icons, and connector panes
• Use the programming structures and data types that exist in LabVIEW
• Use various editing and debugging techniques
• Create and save VIs so you can use them as subVIs
• Display and log data
• Create applications that use plug-in DAQ devices
• Create applications that use serial port and GPIB instruments
E. Course Conventions
The following conventions appear in this course manual:
» The » symbol leads you through nested menu items and dialog box options
to a final action. The sequence File»Page Setup»Options directs you to pull
down the File menu, select the Page Setup item, and select Options from
the last dialog box.
bold Bold text denotes items that you must select or click in the software, such as
menu items and dialog box options. Bold text also denotes parameter names,
controls and buttons on the front panel, dialog boxes, sections of dialog
boxes, menu names, and palette names.
monospace Text in this font denotes text or characters that you should enter from the
keyboard, sections of code, programming examples, and syntax examples.
This font is also used for the proper names of disk drives, paths, directories,
programs, subprograms, subroutines, device names, functions, operations,
variables, filenames and extensions, and code excerpts.
monospace bold Text in this font denotes the messages and responses that the computer
automatically prints to the screen. This font also emphasizes lines of code
that are different from the other examples.
Platform Text in this font denotes a specific platform and indicates that the text
following it applies only to that platform.
The following lesson outlines a software development strategy you can use
to solve your measurement and analysis needs.
Topics
A. Software Development Method
B. Scenario
C. Design
D. Implementation
E. Testing
F. Maintenance
G. Project
B. Scenario
During this stage of the software development method, you define what
your problem is so that you can approach it with all the necessary factors
identified. You can remove extraneous factors during this phase and focus
on the core problem that you must solve. How you identify the problem
initially can save you time while you design and implement a solution.
C. Design
After you determine the scope of the problem, you can design a solution by
analyzing the problem. Part of analyzing the solution is identifying the
inputs and outputs of the software, as well as any additional requirements.
After you define the inputs and outputs, you can design an algorithm,
flowchart and/or state transition diagram to help you arrive at a software
solution.
Furnace Example—Inputs for the furnace software are the cure time
(seconds), the necessary cure temperature (degrees Kelvin), and the furnace
temperature (degrees Kelvin).
Designing a Flowchart
A flowchart displays the steps for solving the problem. Flowcharts are
useful because you can follow more complex processes of an algorithm in a
visual way. For example, you can see if a specific step has two different
paths to the end solution and you can plan your code accordingly.
The start of the program is signified with a solid circle, as shown at left.
The end of the program is signified with a targeted circle, as shown at left.
Furnace Example—You can also use a state transition diagram for this
example. Figure 1-2 shows the furnace example redesigned as a state
transition diagram. Both the flowchart and the state transition diagram are
valid ways to design a VI, but may lead to a different programming solution.
Legend
T = Current Temperature
X = Desired Temperature
T=Y Y = Exterior Temperature
A = Current Time
Compare B = Cure Time
Temperatures
A<B
T=Y
Acquire
Oven
Temperature
T >= X
Check Time
A >= B
D. Implementation
In the implementation stage, you create code for your algorithm or
flowchart. When writing code in a text-based language, the algorithm
elegantly translates into each line of code, depending on the level of detail
shown in the algorithm. Because LabVIEW is a graphical programming
language, the flowchart works much the same way. Refer to Lesson 11,
Common Design Techniques and Patterns for more information about
implementing LabVIEW VIs from a flowchart or state transition diagram.
E. Testing
Testing and verifying is an important part of the software development
method. Make sure to test your implementation with data that is both logical
and illogical for the solution you created. Testing logical data verifies that
the inputs produce the expected result. By testing illogical data, you can test
to see if the code has effective error handling.
F. Maintenance
Maintenance is the ongoing process of resolving programming errors
adding parallel construction changes to the original solution for a problem.
Furnace Example—After writing this code, you may discover that the
customer wants to add a temperature sensor to another area of the oven to
add redundancy to the system. Adding features to the program is easier if
you plan for scalability in your software from the beginning.
Scenario
You are responsible for displaying the time until arrival for airplanes at an
airport. You receive this information in seconds, but must display it as a
combination of hours/minutes/seconds.
Design
What inputs are you given?
What is the relationship/conversion between the inputs and outputs? Use the
Windows calculator to help you determine the relationship.
Implementation
During this stage, you implement the program from the algorithm or
flowchart. For this exercise, skip this stage. Refer to Exercise 2-1 to see an
implementation of a solution to this problem.
Testing
Use a set of known values to test the algorithm or flowchart you designed.
Input Output
Maintenance
If a test value set has failed, return to the design phase and check for errors.
Scenario
Design a state transition diagram for a program that does the following:
1. Acquires a temperature every half a second
2. Analyzes each temperature to determine if the temperature is too high or
too low
3. Alerts the user if there is a danger of heat stroke or freeze
4. Displays the data to the user
5. Logs the data if a warning occurs
6. If the user does not stop the program, the entire process repeats
Design
In the design stage, you determine the inputs and outputs. Design a state
transition diagram utilizing the inputs to achieve the required outputs.
Inputs
• Current Temperature (T)
• High Temperature Limit (X)
• Low Temperature Limit (Y)
• Stop
Outputs
• Warning Levels: Heatstroke Warning, No Warning, Freeze Warning
• Current Temperature Display
• Data Log File
Note You do not complete the Implementation, Testing and Maintenance stages in this
exercise because the goal of the exercise is to complete only the design.
G. Project
Throughout this course, the course project illustrates concepts. In
Exercise 1-2, you designed the state transition diagram for the course
project. The diagram you designed is just one potential design among many.
For this course, one state transition diagram, shown in Figure 1-3, is chosen
so that all students may follow the same instruction set. This state transition
diagram is chosen because it successfully solves the problem and it has parts
that can be effectively used to demonstrate course concepts. However, it
may not be the best solution to the problem.
Initialize
Acquisition
Time Elapsed=TRUE
and
Stop=False
Warning=TRUE
Analysis
Datalog
Time Elapsed=FALSE
and
Stop=FALSE
Time Check
Warning=FALSE
Stop=TRUE
Initialize
Time Elapsed=TRUE
Acquisition
Time Elapsed=FALSE
Time Check
T>X? Y<T<X?
T<Y?
Heatstroke
Freeze Warning No Warning
Warning
Stop=False
Stop
Stop=TRUE
Self-Review: Quiz
Match each step of the described software development method to the
correct description of the step.
Notes
Topics
A. Virtual Instruments (VIs)
B. Starting a VI
C. Parts of a VI
D. Project Explorer
E. Front Panel
F. Block Diagram
G. Searching for Controls, VIs, and Functions
H. Selecting a Tool
I. Dataflow
J. Building a Simple VI
K. LabVIEW Help Utilities
B. Parts of a VI
LabVIEW VIs contain three main components—the front panel, the block
diagram, and the icon/connector pane.
Front Panel
The front panel is the user interface for the VI. Figure 2-1 shows an example
of a front panel. You build the front panel with controls and indicators,
which are the interactive input and output terminals of the VI, respectively.
Block Diagram
After you build the front panel, you add code using graphical
representations of functions to control the front panel objects. Figure 2-2
shows an example of a block diagram. The block diagram contains this
graphical source code. Front panel objects appear as terminals on the block
diagram.
Icon/Connector Pane
You can use a VI as a subVI. A subVI is a VI that is used inside of another
VI, similar to a function in a text-based programming language. To use a VI
as a subVI, it must have an icon and a connector pane.
Every VI displays an icon, shown at left, in the upper right corner of the
Default Icon front panel and block diagram windows. An icon is a graphical
representation of a VI. The icon can contain both text and images. If you use
a VI as a subVI, the icon identifies the subVI on the block diagram of the
VI. The default icon contains a number that indicates how many new VIs
you opened after launching LabVIEW.
C. Starting a VI
When you launch LabVIEW, the Getting Started window appears. Use this
window to create new VIs and projects, select among the most recently
opened LabVIEW files, find examples, and search the LabVIEW Help. You
also can access information and resources to help you learn about
LabVIEW, such as specific manuals, help topics, and resources at ni.com/
manuals.
The Getting Started window disappears when you open an existing file or
create a new file. You can display the window by selecting View»Getting
Started Window.
To open a new, blank VI that is not associated with a project, select the
Blank VI option on the Getting Started window.
Opening an Existing VI
Select the Browse option in the Getting Started window to navigate to and
open an existing VI.
Tip The VIs you edit in this course are located in the
C:\Exercises\LabVIEW Basics I directory.
As the VI loads, a status dialog box similar to the following example might
appear.
The Loading section lists the subVIs of the VI as they load into memory
and shows the number of subVIs loaded into memory so far. You can cancel
the load at any time by clicking the Stop button.
You can have LabVIEW ignore a subVI by clicking the Ignore SubVI
button, or you can click the Browse button to search for the missing subVI.
Saving a VI
To save a new VI, select File»Save. If you already saved your VI, select
File»Save As to access the Save As dialog box. From the Save As dialog
box, you can create a copy of the VI, or delete the original VI and replace it
with the new one.
D. Project Explorer
Use projects to group together LabVIEW files and non-LabVIEW files,
create build specifications, and deploy or download files to targets. When
you save a project, LabVIEW creates a project file (.lvproj), which
includes references to files in the project, configuration information, build
information, deployment information, and so on.
You must use a project to build applications and shared libraries. You also
must use a project to work with an RT, FPGA, or PDA target. Refer to the
specific module documentation for more information about using projects
with the LabVIEW Real-Time, FPGA, and PDA modules.
When you add another target to the project, LabVIEW creates an additional
item in the Project Explorer window to represent the target. Each target
also includes Dependencies and Build Specifications. You can add files
under each target.
1 2 3
7 6 5 4
Project-Related Toolbars
Use the Standard, Project, Build Specifications, and Source Control
toolbar buttons to perform operations in a LabVIEW project. The toolbars
are available at the top of the Project Explorer window, as shown in
Figure 2-7. You might need to expand the Project Explorer window to
view all of the toolbars.
Tip The Source Control toolbar is only available if you have Source Control
configured in LabVIEW.
You can add items to the Source of a project in the following ways:
1. Right-click Source and select Add»File from the shortcut menu to add
a file. You also can select Source and then select Project»Add To
Project»Add File to add a file.
2. Right-click Source and select Add»Folder from the shortcut menu to
add a folder. You also can select Source and then select Project»Add
To Project»Add Folder to add a folder. Selecting a folder on disk adds
contents of the entire folder, including files and contents of subfolders.
Note After you add a folder on disk to a project, LabVIEW does not automatically
update the folder in the project if you make changes to the folder on disk.
3. Right-click Source and select New»VI from the shortcut menu to add a
new, blank VI. You also can select File»New VI or Project»Add To
Project»New VI to add a new, blank VI
4. Select the VI icon in the upper right corner of a front panel or block
diagram window and drag the icon to Source.
5. Windows Select an item or folder from the file system on your computer
and drag it to Source.
You also can add new LabVIEW files to a project from the New dialog box.
Select File»New or Project»Add To Project»New to display the New
dialog box. In the New dialog box, select the item you want to add and place
a checkmark in the Add to project checkbox.
Note Removing an item from a project does not delete the item on disk.
You can arrange items in a folder. Right-click a folder and select Arrange
By»Name from the shortcut menu to arrange items in alphabetical order.
Right-click a folder and select Arrange By»Type from the shortcut menu
to arrange items by file type.
Right-click the project and select View»Full Paths from the shortcut menu
to view where files that a project references are saved on disk.
Use the Project File Information dialog box to view where files that a
project references are located on disk and in the Project Explorer window.
Select Project»File Information to display the Project File Information
dialog box. You also can right-click the project and select View»File
Information from the shortcut menu to display the Project File
Information dialog box.
Saving a Project
You can save a LabVIEW project in the following ways:
• Select File»Save Project.
• Select Project»Save Project.
• Right-click the project and select Save from the shortcut menu.
• Click the Save Project button on the Project toolbar.
You must save new, unsaved files in a project before you can save the
project. When you save a project, LabVIEW does not save dependencies as
part of the project file.
Note Make a backup copy of a project when you prepare to make major revisions to the
project.
E. Front Panel
When you open a new or existing VI, the front panel of the VI appears. The
front panel is the user interface for the VI. Figure 2-8 shows an example of
a front panel.
1
3
The user can change the input value for the Number of Measurements and
Delay(sec). The user can see the value generated by the VI on the
Temperature Graph. The VI generates the values for the indicators based
on the code created on the block diagram. You learn about the block
diagram in the next section.
Every control or indicator has 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.
1 2
indicators to display text to the user. The most common string objects are
tables and text entry boxes as shown in Figure 2-11.
Controls Palette
The Controls palette contains the controls and indicators you use to create
the front panel. You access the Controls palette from the front panel by
selecting View»Controls Palette. The Controls palette is broken into
various categories; you can expose some or all of these categories to suit
your needs. Figure 2-12 shows a Controls palette with all of the categories
exposed and the Modern category expanded. During this course, you work
exclusively in the Modern category.
Shortcut Menus
All LabVIEW objects have associated shortcut menus. As you create a VI,
use the shortcut menu items to change the appearance or behavior of front
panel and block diagram objects. To access the shortcut menu, right-click
the object.
Click the Run button to run a VI. LabVIEW compiles the VI, if necessary.
You can run a VI if the Run button appears as a solid white arrow, shown at
left. The solid white arrow also indicates you can use the VI as a subVI if
you create a connector pane for the VI.
While the VI runs, the Run button appears as shown at left if the VI is a top-
level VI, meaning it has no callers and therefore is not a subVI.
If the VI that is running is a subVI, the Run button appears as shown at left.
The Run button appears broken, shown at left, when the VI you are creating
or editing contains errors. If the Run button still appears broken after you
finish wiring the block diagram, the VI is broken and cannot run. Click this
button to display the Error list window, which lists all errors and warnings.
Click the Run Continuously button, shown at left, to run the VI until you
abort or pause execution. You also can click the button again to disable
continuous running.
While the VI runs, the Abort Execution button, shown at left, appears.
Click this button to stop the VI immediately if there is no other way to stop
the VI. If more than one running top-level VI uses the VI, the button is
dimmed.
Caution The Abort Execution button stops the VI immediately, before the VI finishes
the current iteration. Aborting a VI that uses external resources, such as external
hardware, might leave the resources in an unknown state by not resetting or releasing
them properly. Design VIs with a stop button to avoid this problem.
Click the Pause button, shown at left, to pause a running VI. When you
click the Pause button, LabVIEW highlights on the block diagram the
location where you paused execution, and the Pause button appears red.
Click the Pause button again to continue running the VI.
Select the Text Settings pull-down menu, shown at left, to change the font
settings for the selected portions of the VI, including size, style, and color.
Select the Align Objects pull-down menu, shown at left, to align objects
along axes, including vertical, top edge, left, and so on.
Select the Resize Objects pull-down menu, shown at left, to resize multiple
front panel objects to the same size.
Select the Reorder pull-down menu, shown at left, when you have objects
that overlap each other and you want to define which one is in front or back
of another. Select one of the objects with the Positioning tool and then select
from Move Forward, Move Backward, Move To Front, and Move To
Back.
Select the Show Context Help Window button, shown at left, to toggle the
display of the Context Help window.
Type appears to remind you that a new value is available to replace an old
value. The Enter button disappears when you click it, press the <Enter> key
or click the front panel or block diagram workspace.
F. Block Diagram
Block diagram objects include terminals, subVIs, functions, constants,
structures, and wires, which transfer data among other block diagram
objects.
4 3 2 1
Terminals
Front panel objects appear as terminals on the block diagram.Terminals are
entry and exit ports that exchange information between the front panel and
block diagram. Terminals are analogous to parameters and constants in text-
based programming languages. Types of terminals include control or
indicator terminals and node terminals. Control and indicator terminals
belong to front panel controls and indicators. Data you enter into the front
panel controls (a and b in the previous figure) enter the block diagram
through the control terminals. The data then enter the Add and Subtract
functions. When the Add and Subtract functions complete their
calculations, they produce new data values. The data values flow to the
indicator terminals, where they update the front panel indicators (a+b and a-
b in the previous figure).
The terminals in Figure 2-15 belong to four front panel controls and
indicators. The connector panes of the Add and Subtract functions, shown
at left, have three node terminals. To display the terminals of the function
on the block diagram, right-click the function node and select Visible
Items»Terminals from the shortcut menu.
The terminals represent the data type of the control or indicator. You can
configure front panel controls or indicators to appear as icon or data type
terminals on the block diagram. By default, front panel objects appear as
icon terminals. For example, a knob icon terminal, shown as follows,
represents a knob on the front panel.
The DBL at the bottom of the terminal represents a data type of double-
precision, floating-point numeric. A DBL terminal, shown as follows,
represents a double-precision, floating-point numeric control.
Functions
Functions are the fundamental operating elements of LabVIEW. Functions
do not have front panels or block diagrams but do have connector panes.
Double-clicking a function only selects the function. A function has a pale
yellow background on its icon.
SubVIs
SubVIs are VIs that you build to use inside of another VI or that you access
on the Functions palette.
wires, front panel icons, functions, possibly subVIs, and other LabVIEW
objects. The upper right corner of the front panel and block diagram displays
the icon for the VI. This is the icon that appears when you place the VI on a
block diagram as a subVI.
SubVIs also can be Express VIs. Express VIs are nodes that require minimal
wiring because you configure them with dialog boxes. Use Express VIs for
common measurement tasks. You can save the configuration of an Express
VI as a subVI. Refer to the Express VIs topic of the LabVIEW Help for more
information about creating a subVI from an Express VI configuration.
LabVIEW uses colored icons to distinguish between Express VIs, and other
VIs on the block diagram. Icons for Express VIs appear on the block
diagram as icons surrounded by a blue field whereas subVI icons have a
yellow field.
You can resize the expandable node to make wiring even easier, but it also
takes a large amount of space on the block diagram. Complete the following
steps to resize a node on the block diagram.
1. Move the Positioning tool over the node. Resizing handles appear at the
top and bottom of the node.
2. Move the cursor over a resizing handle to change the cursor to the
resizing cursor.
3. Use the resizing cursor to drag the border of the node down to display
additional terminals.
4. Release the mouse button.
To cancel a resizing operation, drag the node border past the block diagram
window before you release the mouse button.
Note If you display a subVI or Express VI as an expandable node, you cannot display
the terminals for that node and you cannot enable database access for that node.
Wires
You transfer data among block diagram objects through wires. In Figure,
wires connect the control and indicator terminals to the Add and Subtract
function. Each wire has a single data source, but you can wire it to many VIs
and functions that read the data. Wires are different colors, styles, and
thicknesses, depending on their data types.
A broken wire appears as a dashed black line with a red X in the middle, as
shown at left. Broken wires occur for a variety of reasons, such as when you
try to wire two objects with incompatible data types.
Boolean Green
String Pink
the wires must be correct. You must connect the wires to only one input and
at least one output. For example, you cannot wire two indicators together.
The components that determine wiring compatibility include the data type
of the control and/or the indicator and the data type of the terminal.
Data Types
Data types indicate what objects, inputs, and outputs you can wire together.
For example, if a switch has a green border, you can wire a switch to any
input with a green label on an Express VI. If a knob has an orange border,
you can wire a knob to any input with an orange label. However, you cannot
wire an orange knob to an input with a green label. Notice the wires are the
same color as the terminal.
Toggle automatic wiring by pressing the space bar while you move an
object using the Positioning tool.
By default, automatic wiring is enabled when you select an object from the
Functions palette or when you copy an object already on the block diagram
by pressing the <Ctrl> key and dragging the object. Automatic wiring is
disabled by default when you use the Positioning tool to move an object
already on the block diagram.
Functions Palette
The Functions palette contains the VIs, functions and constants you use to
create the block diagram. You access the Functions palette from the block
diagram by selecting View»Functions Palette. The Functions palette is
broken into various categories; you can show and hide categories to suit
your needs. Figure 2-17 shows a Functions palette with all of the categories
exposed and the Programming category expanded. During this course, you
work mostly in the Programming category, but you also use other
categories, or subpalettes.
To view or hide categories, select the View button on the palette, and select
or deselect in the Always Visible Categories option. You learn more about
using the Functions palette in Exercise 2-2.
Notice the flow of data through the block diagram. Click the button again to
disable execution highlighting.
Click the Retain Wire Values button, shown at left, to save the wire values
at each point in the flow of execution so that when you place a probe on the
wire, you can immediately retain the most recent value of the data that
passed through the wire. You must successfully run the VI at least once
before you are able to retain the wire values.
Click the Step Into button, shown at left, to open a node and pause. When
you click the Step Into button again, it executes the first action and pauses
at the next action of the subVI or structure. You also can press <Ctrl> and
down arrow keys. Single-stepping through a VI steps through the VI node
by node. Each node blinks to denote when it is ready to execute. By stepping
into the node, you are ready to single-step inside the node.
Click the Step Over button, shown at left, to execute a node and pause at
the next node. You also can press <Ctrl> and right arrow keys. By stepping
over the node, you execute the node without single-stepping through the
node.
Click the Step Out button, shown at left, to finish executing the current
node and pause. When the VI finishes executing, the Step Out button
becomes dimmed. You also can press <Ctrl> and up arrow keys.
By stepping out of a node, you complete single-stepping through the node
and navigate to the next node.
Description
You received a VI from an employee that can convert seconds into a
combination of hours/minutes/seconds. You must evaluate this VI to see if
it works as expected and can display the remaining time until the plane
arrives.
❑ For each input, compare the given outputs to the outputs listed in
Table 2-1. If the VI works correctly, they should match.
Input Output
0 seconds 0 hours, 0 minutes, 0 seconds
60 seconds 0 hours, 1 minute, 0 seconds
3600 seconds 1 hour, 0 minutes, 0 seconds
3665 seconds 1 hour, 1 minutes, 5 seconds
Until you are familiar with the location of VIs and functions, search for the
function or VI using the Search button. For example, if you want to find the
Random Number function, click the Search button on the Functions palette
toolbar and start typing Random Number in the text box at the top of the
palette. LabVIEW lists all matching items that either start with or contain
the text you typed. You can click one of the search results and drag it to the
block diagram, as shown in Figure 2-18.
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 and select Add Item to Favorites, as shown
in Figure 2-19.
Description
1. Open Navigating Palettes.exe in the C:\Exercises\LabVIEW
Basics I\Navigating Palettes directory.
3. Using the instructions given in the simulation, place the DAQ Assistant
Express VI in the Favorites category of the Functions palette.
H. Selecting a Tool
You can create, modify and debug VIs using the tools provided by
LabVIEW. A tool is a special operating mode of the mouse cursor. The
operating mode of the cursor corresponds to the icon of the tool selected.
LabVIEW chooses which tool to select based on the current location of the
mouse.
Tip You can manually choose the tool you need by selecting it on the Tools palette.
Select View»Tools Palette to display the Tools palette.
Operating Tool
When the mouse cursor changes to the icon shown at left, it is using the
Operating tool. The Operating tool changes the values of a control. For
example, in Figure 2-21 the Operating tool moves the pointer on the
Horizontal Pointer Slide. When the mouse hovers over the pointer, the
cursor automatically accesses the Operating tool.
The Operating tool is mostly used on the front panel, but you also can use
the Operating tool on the block diagram to operate increment/decrement
buttons.
Positioning Tool
When the mouse cursor is an arrow, shown at left, the Positioning tool is
functioning. The Positioning tool selects or resizes objects. For example, in
Figure 2-22 the Positioning tool selects the Number of Measurements
numeric control. After selecting an object, you can move, copy, or delete the
object. When the mouse hovers over the edge of an object, the cursor
automatically accesses the Positioning tool.
If the mouse hovers over a resizing node of an object, the cursor mode
changes to show that you can resize the object, as shown in Figure 2-23.
Notice that the cursor is hovering over a corner of the XY Graph at a resizing
node, and the cursor mode changes to a double-sided arrow.
You can use the Positioning tool on both the front panel and the block
diagram.
Labeling Tool
When the mouse cursor changes to the icon shown at left, the Labeling tool
is in operation. Use the Labeling tool to enter text in a control, to edit text,
and to create free labels. For example, in Figure 2-24 the Labeling tool
enters text in the Number of Measurements numeric control. When the
mouse hovers over the interior of the control, the cursor automatically
accesses the Labeling tool. Click once to place a cursor inside the control.
Then. double-click to select the current text.
When you are not in a specific area of a front panel or block diagram that
accesses a certain mouse mode, the cursor appears as cross-hairs. When the
cross-hairs mode is active, you can double-click to access the Labeling tool
and create a free label.
Wiring Tool
When the mouse cursor changes to the icon shown at left, the Wiring tool is
in operation. Use the Wiring tool to wire objects together on the block
diagram. For example, in Figure the Wiring tool wires the Number of
Measurements terminal to the count terminal of the For Loop. When the
mouse hovers over the exit or entry point of a terminal or over a wire, the
cursor automatically accesses the Wiring tool.
The Wiring tool works mainly with the block diagram and when you create
a connector pane on the front panel.
The top item in the Tools palette, shown at left, is the Automatic Tool
Selection. When this is selected, LabVIEW automatically chooses a tool
based on the location of your cursor. You can turn off Auto tool by
deselecting the item, or by selecting another item in the palette. There are
some additional tools on the palette, as described below:
Use the Object Shortcut Menu tool, shown at left, to access an object
shortcut menu with the left mouse button.
Use the Scrolling tool, shown at left, to scroll through windows without
using scrollbars.
Use the Breakpoint tool, shown at left, to set breakpoints on VIs, functions,
nodes, wires, and structures to pause execution at that location.
Use the Probe tool, shown at left, to create probes on wires on the block
diagram. Use the Probe tool to check intermediate values in a VI that
produces questionable or unexpected results.
Use the Color Copy tool, shown at left, to copy colors for pasting with the
Coloring tool.
Use the Coloring tool, shown at left, to color an object. The Coloring tool
also displays the current foreground and background color settings.
Description
During this exercise, you complete tasks in a partially built front panel and
block diagram. These tasks give you experience in using the Auto tool.
❑ Open LabVIEW.
❑ Select File»Open.
Figure 2-27 shows an example of the front panel as it appears after your
modifications. You increase the size of the waveform graph, rename the
numeric control, change the value of the numeric control, and move the
pointer on the horizontal pointer slide.
❑ Move the cursor to the middle left resizing node until the cursor
changes to a double arrow, as shown in Figure 2-28.
❑ Drag the repositioning point until the Waveform Graph is the size
you want.
❑ When the cursor changes to the Labeling tool icon, as shown at left,
press the mouse button.
5. Change the value of the pointer on the horizontal pointer slide using the
Operating tool.
❑ When the cursor changes to the Operating tool icon, as shown at left,
press the mouse button and drag to the value you want.
Figure 2-28 shows an example of the block diagram as it appears after your
modifications. You move the Number of Measurements terminal and wire
the terminal to the count terminal of the For Loop.
❑ Move the cursor in the terminal until the cursor changes to an arrow,
as shown at left.
❑ Move the cursor to the right of the terminal, stopping when the
cursor changes to a wiring spool, as shown at left.
❑ Move the cursor to the count (N) terminal, shown at left, of the For
Loop.
10. Try moving other objects, deleting wires and rewiring them, and wiring
object and wires together until you are comfortable with using these
tools.
11. Change the value of the Delay (sec) control to something greater than
zero (0).
12. Click the Run button, shown at left, to run the VI.
The time required to execute this VI is equivalent to Number of
Measurements times Delay (Sec). Once the VI is finished executing, the
data is displayed on the Temperature Graph.
13. Select File»Close to close the VI. You do not need to save the VI.
14. Click the Don’t Save All button to save changes before closing.
I. Dataflow
LabVIEW follows a dataflow model for running VIs. A block diagram node
executes when it receives all required inputs. When a node executes, it
produces output data and passes the data to the next node in the dataflow
path. The movement of data through the nodes determines the execution
order of the VIs and functions on the block diagram.
In Figure 2-30, consider which code segment would execute first—the Add,
Random Number, or Divide function. You cannot know because inputs to
the Add and Divide functions are available at the same time, and the
Random Number function has no inputs. In a situation where one code
segment must execute before another, and no data dependency exists
between the functions, use other programming methods, such as error
clusters, to force the order of execution. Refer to Lesson 4, Relating Data,
for more information about error clusters.
Description
1. Open the Dataflow.exe simulation from the
C:\Exercises\LabVIEW Basics I\Dataflow directory.
J. Building a Simple VI
Most LabVIEW VIs have three main tasks: acquiring some sort of data,
analyzing the acquired data, and presenting the result. When each of these
parts are simple, you can complete the entire VI using very few objects on
the block diagram. Express VIs are designed specifically for completing
common, frequently used operations. In this section, you learn about some
Express VIs in each of these categories: acquire, analyze, and present. Then
you learn to build a simple VI using these three parts, as shown in Figure 2-
31.
Figure 2-31. Acquire, Analyze and Present Example Front Panel and Block Diagram
On the Functions palette, the Express VIs are grouped together in the
Express category. Express VIs use the dynamic data type to pass data
between Express VIs.
Acquire
Express VIs used for the Acquire task include the following: DAQ
Assistant, Instrument I/O Assistant, Simulate Signal, and Read from
Measurement File.
DAQ Assistant
The DAQ Assistant acquires data through a data acquisition board.You must
use this Express VI frequently throughout this course. Refer to Lesson 8,
Navigating LabVIEW, for more information about the DAQ Assistant. Until
you learn more about data acquisition, you only use one channel of the data
acquisition board, CH0. This channel is connected to a temperature sensor
on the DAQ Signal Accessory. You can touch the temperature sensor to
change the temperature the sensor reads.
Simulate Signal
The Simulate Signal Express VI generates simulated data such as a sine
wave.
Analyze
Express VIs used for the Analyze task include the following: amplitude and
level measurements, statistics, tone measurements, and so on.
Statistics
The Statistics Express VI calculates statistical data from a waveform. This
includes mean, sum, standard deviation, and extreme values.
Spectral Measurements
The Spectral Measurements Express VI performs spectral measurement on
a waveform, such as magnitude and power spectral density.
Tone Measurements
The Tone Measurements Express VI searches for a single tone with the
highest frequency or highest amplitude. It also finds the frequency and
amplitude of a single tone.
Filter
The Filter Express VI processes a signal through filters and windows. Filters
used include the following: Highpass, Lowpass, Bandpass, Bandstop, and
Smoothing. Windows used include Butterworth, Chebyshev, Inverse
Chebyshev, Elliptical, and Bessel.
Present
Present tasks are Express VI that perform a function, such as the Write to
Measurement File Express VI or are indicators that present data on the front
panel of the VI. The most commonly used indicators for this task include the
Waveform Chart, the Waveform Graph, and the XY Graph. Common
Express VIs include the Write to Measurement File, the Build Text, DAQ
Assistant, and the Instrument I/O Assistant. In this case, the DAQ Assistant
and the Instrument I/O Assistant provide output data from the computer to
the DAQ board or an external instrument.
Build Text
The Build Text Express VI creates text, usually for displaying on the front
panel or exporting to a file or instrument. Refer to Lesson 10, Analyzing and
Storing Measurement Data, for more information on creating strings.
Running a VI
After you configure the Express VIs using the dialog boxes, and wire the
Express VIs together, you can run the VI. When you finish building your VI,
click the Run button on the toolbar, shown at left, to execute the VI.
While the VI is running, the Run button icon changes to the one shown at
left. After the execution completes, the Run button icon changes back to its
original state, and the front panel indicators contain data.
If the button still appears broken when you finish wiring the block diagram,
the VI is broken and cannot run.
Generally, this means that a required input is not wired, or a wire is broken.
Press the broken run button to access the Error List dialog box. The Error
List dialog box lists each error and describes the problem. You can double-
click an error to go directly to the error. Refer to Lesson 5, Debugging VIs,
for more information on debugging.
Scenario
You need to acquire a sine wave for 2 seconds, determine and display the
average value, log the data, and display the sine wave on a graph.
Design
The input for this problem is an analog channel of sine wave data. The
outputs include a graph of the sine data and a file logging the data.
Flow Chart
Log Data
Program Architecture—Quiz
1. Acquire: Circle the Express VI that is best suited to acquiring a sine
wave from a data acquisition board.
3. Present: Circle the Express VIs and/or indicators that are best suited to
displaying the data on a graph and logging the data to file.
Implementation
1. Prepare your hardware to generate a sine wave.
Hardware
❑ Find the DAQ Signal Accessory and visually confirm that it is
connected to the DAQ board in your computer.
❑ Set the Frequency Range switch and the Frequency Adjust knob
to their lowest levels.
❑ Skip to step 2.
1 2
No Hardware
❑ Skip this step if you are not using hardware.
2. Open LabVIEW.
❑ Select File»Save.
❑ Click OK.
5. Place a waveform graph on the front panel to display the acquired data.
6. Place a numeric indicator on the front panel to display the average value.
Note The terminals corresponding to the new front panel objects appear on the block
diagram.
Hardware
The sine wave is generated on Analog In Channel 1. Use the DAQ
Assistant Express VI to acquire 2 seconds of data.
Tip Reading 2,000 samples at a rate of 1,000 Hertz retrieves 2 seconds worth of data.
❑ Skip to step 9.
No Hardware
Simulate the acquisition of a 100 Hz sine wave sampled at 1kHz for 2
seconds. Use the Simulate Signal Express VI.
❑ In the Timing section, set the Samples per second (Hz) to 1,000.
9. Determine the average value of the data acquired by using the Statistics
Express VI.
❑ Click OK.
❑ Click OK.
Note Future exercises do not detail the directions for finding specific functions or
controls in the palettes. Use the palette search feature to locate functions and controls.
11. Wire the data from the DAQ Assistant (or Simulate Signal Express VI)
to the Statistics Express VI.
❑ Place the mouse cursor over the data output of the DAQ Assistant
(or Simulate Signal Express VI) at the location where the cursor
changes to the Wiring tool.
❑ Place the mouse cursor over the Signals input of the Statistics
Express VI and click the mouse button to end the wire.
❑ Place the mouse cursor over the data output wire of the DAQ
Assistant (or Simulate Signal Express VI) at the location where the
cursor changes to the Wiring tool.
❑ Place the mouse cursor over the graph indicator and click the mouse
button to end the wire.
13. Wire the Arithmetic Mean output of the Statistics Express VI to the
Average Value numeric indicator.
❑ Place the mouse cursor over the Arithmetic Mean output of the
Statistics Express VI at the location where the cursor changes to the
Wiring tool.
❑ Place the mouse cursor over the Average Value numeric indicator
and click the mouse button to end the wire.
14. Wire the data output to the Signals input of the Write Measurement File
Express VI.
❑ Place the mouse cursor over the data output wire of the DAQ
Assistant (or Simulate Signal Express VI) at the location where the
cursor changes to the Wiring tool.
❑ Place the mouse cursor over the Signals input of the Write
Measurement File Express VI and click the mouse button to end the
wire.
Note Future exercises do not detail the directions for wiring between objects.
Testing
1. Switch to the front panel of the VI.
❑ Use the labeling tool to change the last number on the X Scale of the
waveform graph to .1.
3. Save the VI.
4. Run the VI.
5. Open the front panel of the VI by selecting Window»Show Front
Panel.
The graph indicator should display a sine wave and the Average Value
indicator should display a number around zero. If the VI does not run as
expected, review the implementation steps.
6. Close the VI.
When you move the cursor over front panel and block diagram objects, the
Context Help window displays the icon for subVIs, functions, constants,
controls, and indicators, with wires attached to each terminal. When you
move the cursor over dialog box options, the Context Help window
displays descriptions of those options. In the Context Help window, the
labels of required terminals appear bold, recommended terminals appear as
plain text, and optional terminals appear dimmed. The labels of optional
terminals do not appear if you click the Hide Optional Terminals and Full
Path button, shown as follows, in the Context Help window.
Click the Hide Optional Terminals and Full Path button located on the
lower left corner of the Context Help window to display the optional
terminals of a connector pane and to display the full path to a VI. Optional
terminals are shown by wire stubs, informing you that other connections
exist. The detailed mode displays all terminals, as shown in Figure 2-37.
Click the Lock Context Help button to lock the current contents of the
Context Help window. When the contents are locked, moving the cursor
over another object does not change the contents of the window. To unlock
the window, click the button again. You also can access this option from the
Help menu.
LabVIEW Help
You can access the LabVIEW Help either by clicking the More Help button
in the Context Help window, selecting Help»Search the LabVIEW Help,
or clicking the blue Click here for more help link in the Context Help
window. You also can right-click an object and select Help from the
shortcut menu.
You can access the LabVIEW Help either by clicking the More Help button
in the Context Help window, selecting Help»Search the LabVIEW Help,
or clicking the blue
link in the Context Help window. You also can right-click an object and
select Help.
NI Example Finder
The New dialog box contains many LabVIEW template VIs that you can
use to start building VIs. However, these template VIs are only a subset of
the hundreds of example VIs included with LabVIEW. You can modify any
example VI to fit an application, or you can copy and paste from an example
into a VI that you create.
In addition to the example VIs that ship with LabVIEW, you also can access
hundreds of example VIs on the NI Developer Zone at ni.com/zone.
To search all examples using LabVIEW VIs, use the NI Example Finder.
The NI Example Finder is the gateway to all installed examples and the
examples located on the NI Developer Zone.
Description
This exercise consists of a series of tasks designed to help you become
familiar with the LabVIEW Help tools. Complete the follow steps.
NI Example Finder
1. You have a GPIB board in your computer, and you want to learn how to
communicate with it using LabVIEW. Use the NI Example Finder to
find a VI that communicates with a GPIB board.
❑ Open LabVIEW.
2. You want to learn more about Express VIs, especially their use in
filtering signals. Use the NI Example Finder to find an appropriate VI.
❑ The NI Example Finder should still be open from the previous step.
If not, open the NI Example Finder.
❑ Place your mouse cursor over the Simulate Signal Express VI. The
Context Help window content changes to show information about
the object that your mouse is over.
❑ Move your mouse over another Express VI. Notice the Context
Help window content changes in reference to the location of the
mouse cursor.
❑ Move your mouse over one of the Tone Measurements Express VIs.
4. Anchor the Context Help window so that you can move your mouse
without the contents of the window changing. The Context Help
window should show information about the Simulate Signal Express VI.
❑ To anchor the context help window, select the Lock button in the
lower left corner of the window, shown at left.
Tip If the contents of the window change before you locked the window, avoid passing
your mouse over other objects on the way to the Context Help window. Move the
window closer to the object of interest to view context help for that item.
❑ Move your mouse over another object. Notice the contents of the
window do not change while the lock button is selected.
❑ Replace the text in the "Simulated frequency" Tip box with the
text This is the tip for the control.
❑ Click OK.
❑ Notice that the tool tip that appears matches the text you typed in the
Tip field of the Description and Tip dialog box.
LabVIEW Help
6. Use the LabVIEW Help to learn more information about the Filter
Express VI.
❑ Right-click the Filter Express VI and select Help from the shortcut
menu. This opens the LabVIEW Help topic for the Filter Express VI.
Note To access the LabVIEW Help for this topic, you can also select the Detailed Help
hyperlink in the Context Help window while the Filter Express VI is selected, or click
the question mark icon in the Context Help window.
❑ Explore the topic. For example, what is the purpose of the Phase
Response dialog box option?
❑ Click the Find on the Functions Palette button at the top of the
Help window.
7. Close the Express Filter VI when you finish. Do not save changes.
Self-Review: Quiz
Refer to Figure 2-39 to answer the following quiz questions.
Notes
Topics
A. Front Panel Design
B. Block Diagram Terminals
C. Documenting Code
D. While Loops
E. For Loops
F. Timing a VI
G. Iterative Data Transfer
H. Plotting Data
I. Case Structures
J. Formula Nodes
You can display the outputs of the problem with indicators or log the outputs
to a file. You also can output data to a device using signal generation.
Lessons about data acquisition, signal generation and file logging appear
later in this course.
Labels/Captions
When creating labels for controls and indicators, make sure to label them
clearly. These labels help users identify the function for each control and
indicator. Also, clear labelling helps you document your code in the block
diagram. Control and indicator labels correspond to the names of terminals
on the block diagram.
Captions help you describe a control on the front panel. Captions do not
appear on the block diagram. Using captions allows you to document the
user interface without cluttering the block diagram with long names. For
example, in the Weather Station, you must provide an upper boundary for
the temperature level. If the temperature rises above this level, the Weather
Station indicates a heatstroke warning. You could call this control Upper
Temperature Limit (Celsius). However, this label would occupy
unnecessary space on the block diagram. Instead use a caption for the
control Upper Temperature Limit (Celsius) and use the label to
create a shorter description for the block diagram, such as Upper Temp.
Control/Indicator Options
You can set default values for controls. Figure 3-1 shows a default value of
35 degrees Celsius. By setting a default value, you can assume a reasonable
value for a VI if the user does not set another value during run-time. To set
the default value complete the following steps:
1. Enter the desired value
2. Right-click the control and select Data Operations»Make Current
Value Default from the shortcut menu.
You also can hide and view items on controls and indicators. For example,
in Figure 3-1, you can see both the caption and the label. However, you only
need to see the caption. To hide the label, right-click the control and select
Visible Items»Label as shown in Figure 3-2.
1 2
Using Color
Proper use of color can improve the appearance and functionality of your
front panel. Using too many colors, however, can result in color clashes
that cause the front panels to look too busy and distracting.
When you design the front panel, consider how users interact with the VI
and group controls and indicators logically. If several controls are related,
add a decorative border around them or put them in a cluster.
Centered items are better than random but much less orderly than either left
or right alignment. A band of white space acts as a very strong means of
alignment. Centered items typically have ragged edges and the order is not
as easily noticed.
Do not place front panel objects too closely together. Try to leave some
blank space to make the front panel easier to read. Blank space also prevents
users from accidentally clicking the wrong control or button.
1 2
Avoid placing objects on top of other objects. Placing a label or any other
object over or partially covering a control or indicator slows down screen
updates and can make the control or indicator flicker.
Using too many font styles can make your front panel look busy and
disorganized. Instead, use two or three different sizes of the same font.
Serifs help people to recognize whole words from a distance. If you are
using more than one size of a font, make sure the sizes are noticeably
different. If not, it may look like a mistake. Similarly, if you use two
different fonts, make sure they are distinct.
Design your front panels with larger fonts and more contrast for industrial
operator stations. Glare from lighting or the need to read information from
a distance can make normal fonts difficult to read. Also, remember that
touch screens generally require larger fonts and more spacing between
selection items.
Note If fonts do not exist on a target machine, substituted fonts can cause the user
interface to appear skewed.
System Controls
A common user interface technique is to display dialog boxes at appropriate
times to interact with the user. You can make a VI behave like a dialog box
by selecting File»VI Properties, selecting the Window Appearance
category, and selecting the Dialog option.
Use the system controls and indicators located on the System palette in
dialog boxes you create. Because the system controls change appearance
depending on which platform you run the VI, the appearance of controls in
VIs you create is compatible on all LabVIEW platforms. When you run the
VI on a different platform, the system controls adapt their color and
appearance to match the standard dialog box controls for that platform.
System controls typically ignore all colors except transparent. If you are
integrating a graph or non-system control into the front panel, try to match
them match by hiding some borders or selecting colors similar to the system
colors.
Tab Controls
Physical instruments usually have good user interfaces. Borrow heavily
from their design principles, but use smaller or more efficient controls, such
as ring controls or tab controls, where appropriate. Use tab controls to
overlap front panel controls and indicators in a smaller area.
To add another page to a tab control, right-click a tab and select Add Page
Before or Add Page After from the shortcut menu. Relabel the tabs with
the Labeling tool, and place front panel objects on the appropriate pages.
The terminals for these objects are available on the block diagram, as are
terminals for any other front panel object (except Decorations).
You can wire the enumerated control terminal of the tab control to the
selector of a Case structure to produce cleaner block diagrams. With this
method you associate each page of the tab control with a subdiagram, or
case, in the Case structure. You place the control and indicator terminals
from each page of the tab control—as well as the block diagram nodes
and wires associated with those terminals—into the subdiagrams of the
Case structure.
Decorations
Use the decorations located on the Decorations palette to group or separate
objects on a front panel with boxes, lines, or arrows. These objects are for
decoration only and do not display data.
Menus
Use custom menus to present front panel functionality in an orderly way and
in a relatively small space. Using small amounts of space leaves room on the
front panel for critical controls and indicators, items for beginners, items
needed for productivity, and items that do not fit well into menus. You also
can create keyboard shortcuts for menu items.
To create a run-time shortcut menu for front panel objects, right-click the
front panel object and select Advanced»Run-Time Shortcut Menu»Edit.
To create a custom run-time menu for your VI, select Edit»Run-Time
Menu.
Scenario
You are given the design information for a weather station project that you
must implement. Using the information, create a front panel that will be the
user interface for the Weather Station VI.
Design
Initialize
Acquisition
Time Elapsed=TRUE
and
Stop=False
Warning=TRUE
Analysis
Datalog
Time Elapsed=FALSE
and
Stop=FALSE
Time Check
Warning=FALSE
Stop=TRUE
Implementation
Each input entered and each output displayed must appear on the front
panel. Complete the following instructions to create a front panel similar to
that shown in Figure 3-4. This front panel retrieves the upper and lower
temperature limits and a stop Boolean and displays the warning string and
the temperature history.
Figure 3-4. Front Panel for the Temperature Weather Station Project
Note You modify the behavior and appearance of the waveform chart in another
exercise.
❑ Use the font tools on the front panel toolbar to change the size, color
and font of the indicator.
Tip You can enter text into the Warning indicator to test the fonts that you choose.
❑ Increase the size of the Stop button by selecting a corner of the Stop
button with the selection tool and dragging the area to the desired
size and shape.
9. Add labels and decorations and arrange the objects on the front panel to
increase the usability. Refer to Figure 3-4 for suggestions, or design the
front panel your own way. Tips:
❑ The square around the temperature ranges and the triangles used to
illustrate heatstroke and freeze is available in the Decorations
category of the Controls palette.
❑ Visually group all controls together on the left side of the front
panel.
❑ Visually group all indicators together on the right side of the panel.
The Stop button is the only exception to this rule, as it is generally
placed in the lower right side of the panel.
❑ Use colors where appropriate on the front panel. For example, the
Stop button is usually red, heat is generally associated with red, and
cold is generally associated with blue.
In this algorithm, Base and Height are inputs and Area is an output, as
shown in Figure 3-5.
The constant .5 does not necessarily appear on the front panel, except
possibly as documentation of the algorithm.
1 3 2
Figure 3-6. Area of a Triangle Block Diagram with Icon Terminal View
Notice that the Base (cm) and Height (cm) block diagram terminals have a
different appearance from Area (cm2). There are two distinguishing
characteristics between a control and an indicator on the block diagram. The
first is an arrow on the terminal that indicates the direction of data flow. The
controls have arrows showing the data leaving the terminal, whereas the
indicator 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.
Figure 3-7 shows the same block diagram without using the icon view of the
terminals; however, the same distinguishing characteristics between
controls and indicators exist.
Figure 3-7. Area of a Triangle Block Diagram without Icon Terminal View
Numeric
The numeric data type represents numbers of various types. To change the
representation type of a number, right-clicking the control, indicator, or
constant, and select Representation, as shown in Figure 3-8.
Within the numeric data type, there are the following subcategories of
representation: floating-point numbers, signed integers, unsigned integers,
and complex numbers.
Floating-Point Numbers
Floating-point numbers represent fractional numbers. In LabVIEW,
floating-point numbers are represented with the color orange.
Integers
Integers represent whole numbers. Signed integers can be positive or
negative. Use the unsigned integer datatypes when you know the integer is
always positive. In LabVIEW, integers are represented with the color blue.
Complex Numbers
Complex numbers are represented by two values linked together in
memory: one representing the real part and one representing the imaginary
part. In LabVIEW, since complex numbers are a type of floating-point
number, complex numbers are also represented with the color orange.
Boolean Values
LabVIEW stores Boolean data as 8-bit values. If the 8-bit value is zero, the
Boolean value is FALSE. Any nonzero value represents TRUE. In
LabVIEW, the color green represents Boolean data.
Boolean values also have a mechanical action associated with them. The
two major actions are latch and switch. Latch action is similar to a doorbell,
whereas switch action is similar to a light switch. You can also define when
the switch or latch occurs: when pressed, when released or until released. To
String
A string is a sequence of displayable or non-displayable ASCII characters.
Strings provide a platform-independent format for information and data.
Some of the more common applications of strings include the following:
• Creating simple text messages.
• Passing numeric data as character strings to instruments and then
converting the strings to numeric values.
• Storing numeric data to disk. To store numeric data in an ASCII file, you
must first convert numeric data to strings before writing the data to a
disk file.
• Instructing or prompting the user with dialog boxes.
On the front panel, strings appear as tables, text entry boxes, and labels.
LabVIEW includes built-in VIs and functions you can use to manipulate
strings, including formatting strings, parsing strings, and other editing.
Right-click a string control or indicator on the front panel to select from the
display types shown in the following table. The table also shows an example
message in each display type.
Hex Display Displays the ASCII value of 5468 6572 6520 6172
each character in hex instead 6520 666F 7572 2064
of the character itself. 6973 706C 6179 2074
7970 6573 2E0A 5C20
6973 2061 2062 6163
6B73 6C61 7368 2E
Enumerated Control
An enum (enumerated control, constant or indicator) is a combination of
data types. 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 pairs for a Month variable
are January-0, February-1, and so on through December-11. Figure 3-10
shows an example of these data pairs in the Properties dialog box for an
enumerated control.
1 2 3
Dynamic
The dynamic data type stores the information generated or acquired by an
Express VI. The dynamic data type appears as a dark blue terminal, shown
at left. Most Express VIs accept and/or return the dynamic data type.
You can wire the dynamic data type to any indicator or input that accepts
numeric, waveform, or Boolean data. Wire the dynamic data type to an
indicator that can best present the data. Indicators include graphs, charts,
or numeric indicators.
Most other VIs and functions in LabVIEW do not accept the dynamic data
type. To use a built-in VI or function to analyze or process the data the
dynamic data type includes, you must convert the dynamic data type.
Use the Convert from Dynamic Data Express VI, shown at left, to convert
the dynamic data type to numeric, Boolean, waveform, and array data types
for use with other VIs and functions. When you place the Convert from
Dynamic Data Express VI on the block diagram, the Configure Convert
from Dynamic Data dialog box appears. The Configure Convert from
Dynamic Data dialog box displays options that let you specify how you
want to format the data that the Convert from Dynamic Data Express VI
returns.
open the Configure Convert from Dynamic Data dialog box to control
how the data appears in the array.
C. Documenting Code
Professional developers who maintain and modify VIs know the value of
good documentation. Document the block diagram well to ease future
modification of the code. In addition, document the front panel well to
explain the purpose of the VI and the front panel objects.
VI Properties
Use the Documentation component of the VI Properties dialog box to
create VI descriptions and to link from VIs to HTML files or to compiled
help files. To display VI Properties right-click the VI icon on the front panel
or block diagram and select VI Properties from the shortcut menu or select
File»VI Properties. Then select Documentation from the Categories
drop-down menu. You cannot access this dialog box while a VI runs.
• Help path—Contains the path to the HTML file or to the compiled help
file you want to link to from the Context Help window. If this field is
empty, the blue Click here for more help. link does not appear in the
Context Help window, and the More Help button is dimmed. You also
can use the Help:Document Path property to set the help path
programmatically.
• Browse—Displays a file dialog box to use to navigate to an HTML file
or to a compiled help file to use as the Help path.
Graphical Programming
While the graphical nature of LabVIEW aids in self-documentation of block
diagrams, extra comments are helpful when modifying your VIs in the
future. There are two types of block diagram comments—comments that
describe the function or operation of algorithms and comments that explain
the purpose of data that passes through wires. Both types of comments are
shown in the following block diagram. You can insert standard labels either
with the Labeling tool, or by inserting a free label from the Functions»All
Functions»Decorations subpalette. By default, free labels have a yellow
background color.
• Do not show labels on function and subVI calls because they tend to be
large and unwieldy. A developer looking at the block diagram can find
the name of a function or subVI by using the Context Help window.
• Use small free labels with white backgrounds to label long wires to
identify their use. Labeling wires is useful for wires coming from shift
registers and for long wires that span the entire block diagram.Refer to
the Case Structures section of this lesson for more information about
shift registers.
• Label structures to specify the main functionality of the structure.
• Label constants to specify the nature of the constant.
• Use free labels to document algorithms that you use on the block
diagrams. If you use an algorithm from a book or other reference,
provide the reference information.
Scenario
You must create a portion of a larger project. The lead developer gives you
the inputs of the VI, the algorithm and the expected outputs. Build and
document a VI based on the design given.
Design
Flowchart
Current Temp
No
>=Max Temp?
Yes
Warning Text =
Warning Text =
Heatstroke
No Warning
Warning
Current Temp
No
<= Min Temp?
Yes
Warning
Text = No No
Warning?
Yes
Implementation
Follow the instructions given below to create a front panel similar to
Figure 3-14. This front panel retrieves from the user the current
temperature, the maximum temperature, and the minimum temperature, and
displays to the user the warning string and the warning Boolean LED. This
VI is part of the temperature weather station project you created in the
previous exercise.
❑ Select File»Save.
Tip This subVI could be used for Fahrenheit, Kelvin, or any temperature scale, as long
as all inputs use the same scale. Therefore, it is not necessary to add scale units to the
labels.
❑ Hold down the <Ctrl> key and click and drag the Current Temp
numeric control to create a copy of the control.
❑ Change the label text of the new numeric control to Max Temp.
❑ Hold down the <Ctrl> key and click and drag the Max Temp
numeric control to create a copy of the control.
❑ Change the label text of the new numeric control to Min Temp.
6. Create a string indicator for the warning text.
Tip If you do not want to use the Icon Terminal view on the block diagram, select
Tools»Options, then select Block Diagram from the Category list. Remove the
checkmark from the Place front panel terminals as icons item.
Follow the instructions given below to build a block diagram similar to the
one shown in Figure 3-15.
❑ Wire the Max Temp terminal to the y input terminal of the Greater
Or Equal? function.
❑ Wire the Current Temp terminal to the x input terminal of the Less
Or Equal? function.
❑ Wire the Min Temp terminal to the y input terminal of the Less Or
Equal? function.
11. If the Current Temp is equal to or greater than the Max Temp, generate
a Heatstroke Warning string, otherwise generate a No Warning
string.
❑ Place the Select function on the block diagram to the right of the
Greater Or Equal? function.
❑ Place a string constant on the block diagram to the upper left of the
Select function.
❑ Hold down the <Ctrl> key and click and drag the Heatstroke
Warning string constant to the lower left of the Select function to
create a copy of the constant.
12. If the Current Temp is equal to or less than the Min Temp, generate a
Freeze Warning string, else use the string generated in Step 11.
❑ Create a copy of the Select function and place it to the right of the
Less Or Equal?.
❑ Create a copy of the string constant and place it to the upper right of
the Select function.
❑ Wire the output of the second Select function to the Warning Text
indicator.
❑ Wire the output of the second Select function to the x input terminal
of the Not Equal function.
❑ Wire the output of the Not Equal function to the Warning? Boolean.
15. Document the code using the following suggestions on the front panel.
❑ Create tip strips for each control and indicator stating the purpose of
the object and the units used. To access tip strips, right-click a
control, and select Description and Tip.
Testing
1. Test the VI by inputting a value for Current Temp, Max Temp, and Min
Temp, and running for each set.
Table 3-1 shows the expected Warning Text string and Warning?
Boolean for each set of input values.
What happens if you input a Max Temp value that is less than the Min
Temp? What would you expect to happen? You learn to handle errors
like this one in a Exercise 3-7.
D. While Loops
Similar to a Do Loop or a Repeat-Until Loop in text-based programming
languages, a While Loop, shown as follows, executes a subdiagram until a
condition occurs.
Code
No Repeat (code);
Condition Until Condition met;
Code
met?
End;
Yes
End
1 2 3
The While Loop is located on the Structures palette. Select the While Loop
from the palette then use the cursor to drag a selection rectangle around the
section of the block diagram you want to repeat. When you release the
mouse button, a While Loop boundary encloses the section you selected.
Add block diagram objects to the While Loop by dragging and dropping
them inside the While Loop.
The While Loop executes the subdiagram until the conditional terminal, an
input terminal, receives a specific Boolean value. The default behavior and
appearance of the conditional terminal is Stop if True, shown as follows.
When a conditional terminal is Stop if True, the While Loop executes its
subdiagram until the conditional terminal receives a TRUE value. You can
change the behavior and appearance of the conditional terminal by
right-clicking the terminal or the border of the While Loop and selecting
Continue if True, shown as follows, from the shortcut menu.
The iteration terminal (an output terminal), shown as follows, contains the
number of completed iterations.
The iteration count always starts at zero. During the first iteration, the
iteration terminal returns 0.
In the following block diagram, the While Loop executes until the subVI
output is greater than or equal to 10.00 and the Enable control is True.
The And function returns True only if both inputs are True. Otherwise,
it returns False.
Structure Tunnels
Tunnels feed data into and out of structures. The tunnel appears as a solid
block on the border of the While Loop. The block is the color of the data
type wired to the tunnel. Data pass out of a loop after the loop terminates.
When a tunnel passes data into a loop, the loop executes only after data
arrive at the tunnel.
Only the last value of the iteration terminal displays in the Iterations
indicator.
Scenario
Build a VI that continuously generates random numbers between 0 and 1000
until it generates a number that matches a number selected by the user.
Determine how many random numbers the VI generated before the
matching number.
Design
Flowchart
Generate a
random number No
between 0 and 1
Multiply by 1000
Display Number of
Iterations
Implementation
Open a blank VI and build the following front panel. Modify the controls
and indicators as shown in the following front panel and as described in the
following steps.
2. Set the properties for the Number to Match control so that the default
value is 50, the data range is from 0 to 1000, the increment value is 1,
and the digits of precision is 1.
❑ Set the Minimum value to 0 and select Coerce from the Out of
Range Action pull-down menu.
❑ Set the Maximum value to 1000 and select Coerce from the Out of
Range Action pull-down menu.
❑ Set the Increment value to 1 and select Coerce to Nearest from the
Out of Range Action pull-down menu.
❑ Select the Random Number (0-1) function and place it on the block
diagram. The Random Number (0-1) generates a random number
between 0 and 1.
❑ Select the Multiply function and place it on the block diagram. The
Multiply function multiplies the random number by y to produce
a random number between 0 and y.
❑ Place the Not Equal? function on the block diagram. This function
compares the random number with Number to Match and returns
True if the numbers are not equal; otherwise, it returns False.
9. Repeat the algorithm until the Not Equal? function returns True.
10. Display the number of random numbers generated to the user by adding
one to the iteration terminal value.
❑ Wire the iteration terminal to the border of the While Loop. A blue
tunnel appears on the While Loop border.
Tip Each time the loop executes, the iteration terminal increments by one. Wire the
iteration value to the Increment function because the iteration count starts at 0. The
iteration count passes out of the loop upon completion.
Testing
1. Display the front panel.
❑ Run the VI. LabVIEW coerces the out-of-range value to the nearest
value in the specified data range.
E. For Loops
N=100
i=0
N=100;
i=i+1
i=0;
Code
No Until i=N:
i=N? Code
Repeat (code; i=i+1);
Yes
End;
End
1 2 3
The iteration terminal (an output terminal), shown as follows, contains the
number of completed iterations.
The iteration count always starts at zero. During the first iteration, the
iteration terminal returns 0.
The For Loop differs from the While Loop in that the For Loop executes a
set number of times. A While Loop stops executing the subdiagram only if
the value at the conditional terminal exists.
The following For Loop generates a random number every second for
100 seconds and displays the random numbers in a numeric indicator.
Numeric Conversion
LabVIEW can represent numeric data types as signed or unsigned integers,
floating-point numeric values, or complex numeric values, as discussed in
the LabVIEW Data Types section of this lesson. Normally, when you wire
different representation types to the inputs of a function, the function returns
an output in the larger or wider format. LabVIEW chooses the
representation that uses more bits. If the number of bits is the same,
LabVIEW chooses unsigned over signed. For example, if you wire a DBL
and an I32 to a Multiply function, the result is a DBL, as shown in
Figure 3-22. The 64-bit signed integer is coerced because it uses fewer bits
than the double-precision, floating-point numeric value. The lower input of
the Multiply function shows a grey dot, called a coercion dot, that indicates
a numeric coercion occurred.
1 Coercion Dot
However, the For Loop count terminal works in the opposite manner. If you
wire a double-precision, floating-point numeric value to the 64-bit count
terminal, LabVIEW converts the larger numeric value to a 32-bit signed
integer. Although the conversion is contrary to normal conversion
standards, it is necessary, as a For Loop can only execute an integer number
of times.
1 Coercion Dot
Description
For the following scenarios, decide whether to use a While Loop or a For
Loop.
Scenario 1
Acquire a pressure every second for one minute.
1. If you use a While Loop, what is the condition that you need to stop the
loop?
2. If you use a For Loop, how many iterations does the loop need to run?
Scenario 2
Acquire a pressure until the pressure is 1400 psi.
1. If you use a While Loop, what is the condition that you need to stop the
loop?
2. If you use a For Loop, how many iterations does the loop need to run?
Scenario 3
Acquire a pressure and a temperature until both values are stable for two
minutes.
1. If you use a While Loop, what is the condition that you need to stop the
loop?
2. If you use a For Loop, how many iterations does the loop need to run?
Scenario 4
Output a voltage ramp starting at zero, increasing incremental by 0.5 V
every second, until the output voltage is equal to 5 V.
1. If you use a While Loop, what is the condition that you need to stop the
loop?
2. If you use a For Loop, how many iterations does the loop need to run?
Answers
Scenario 1
Acquire a pressure every second for one minute.
1. While Loop: Time = 1 minute
2. For Loop: 60 iterations
3. Both are possible.
Scenario 2
Acquire a pressure until the pressure is 1400 psi.
1. While Loop: Pressure = 1400 psi
2. For Loop: unknown
3. A While Loop. Without more information, a For Loop is impossible.
Scenario 3
Acquire a pressure and a temperature until both values are stable for two
minutes.
1. While Loop: [(Last Temperature = Previous Temperature) for 2 minutes
or more] AND [(Last Pressure = Previous Pressure) for 2 minutes or
more]
2. For Loop: unknown
3. A While Loop. Without more information, a For Loop is impossible.
Scenario 4
Output a voltage ramp starting at zero, increasing incremental by 0.5 V
every second, until the output voltage is equal to 5 V.
1. While Loop: Voltage = 5 V
2. For Loop: 11 iterations
3. Either one is a good choice.
F. Timing a VI
When a loop finishes executing an iteration, it immediately begins
executing the next iteration, unless it reaches a stop condition. Most often,
you need to control the frequency or timing of the iteration. For example, if
you are acquiring data, and you want to acquire the data once every 10
seconds, you need a way to time the loop iterations so they occur once every
10 seconds.
Even if you do not need the execution to occur at a certain frequency, you
need to provide the processor with time to complete other tasks, such as
processing the user interface. This section introduces some methods for
timing your loops.
Wait Functions
Place a wait function are placed inside a loop to allow a VI to sleep for a set
amount of time. This allows your processor to address other tasks during the
wait time. Wait functions use the operating system millisecond clock.
The Wait (ms) function, shown at left, waits until the millisecond counter
counts to an amount equal to the input you specify. This function guarantees
that the loop execution rate is at least the amount of the input you specify.
Note The Time Delay Express VI behaves similar to the Wait (ms) function with the
addition of built-in error clusters. Refer to Lesson 4, Implementing a VI for more
information about error clusters.
Elapsed Time
In some cases, it is useful to determine how much time elapses after some
point in your VI. The Elapsed Time Express VI, shown at left, indicates the
amount of time that elapses after the specified start time. This VI allows you
to keep track of time while the VI continues to execute. This function does
not provide the processor with time to complete other tasks. You learn more
about this Express VI, as you use it in the Weather Station course project.
Note Feedback Nodes are another method used in LabVIEW for retaining information
from a previous iteration. Refer to the Feedback Node topic in the LabVIEW Help for
more information about feedback nodes.
Use shift registers when you want to pass values from previous iterations
through the loop to the next iteration. A shift register appears as a pair of
terminals, shown as follows, directly opposite each other on the vertical
sides of the loop border.
The terminal on the right side of the loop contains an up arrow and stores
data on the completion of an iteration. LabVIEW transfers the data
connected to the right side of the register to the next iteration. After the loop
executes, the terminal on the right side of the loop returns the last value
stored in the shift register.
Create a shift register by right-clicking the left or right border of a loop and
selecting Add Shift Register from the shortcut menu.
A shift register transfers any data type and automatically changes to the data
type of the first object wired to the shift register. The data you wire to the
terminals of each shift register must be the same type.
You can add more than one shift register to a loop. If you have multiple
operations that use previous iteration values within your loop, use multiple
shift registers to store the data values from those different processes in the
structure, as shown in the following figure.
In the previous figure, the For Loop executes five times, incrementing the
value the shift register carries by one each time. After five iterations of the
For Loop, the shift register passes the final value, 5, to the indicator and the
VI quits. Each time you run the VI, the shift register begins with a value
of 0.
If you do not initialize the shift register, the loop uses the value written to
the shift register when the loop last executed or the default value for the data
type if the loop has never executed.
In the previous figure, the For Loop executes five times, incrementing the
value the shift register carries 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, the shift register
passes the final value, 5, to the indicator, and the VI quits. The next time you
run the VI, the shift register begins with a value of 5, which was the last
value from the previous execution. After five iterations of the For Loop, the
shift register passes the final value, 10, to the indicator. If you run the VI
again, the shift register begins with a value of 10, and so on. Uninitialized
shift registers retain the value of the previous iteration until you close the
VI.
Stacked shift registers can occur only on the left side of the loop because the
right terminal transfers the data generated only from the current iteration to
the next iteration, as shown in the following figure.
If you add another element to the left terminal in the previous figure, values
from the last two iterations carry over to the next iteration, with the most
recent iteration value stored in the top shift register. The bottom terminal
stores the data passed to it from the previous iteration.
Scenario
The Temperature Monitor VI acquires and displays temperature. Modify the
VI to average the last three temperature measurements and display the
running average on the waveform chart.
Design
Figure 3-24 and Figure 3-25 shows the Temperature Monitor VI front panel
and block diagram.
To modify this VI, you need to retain the temperature values from the
previous two iterations, and average the values. Use a shift register with an
additional element to retain data from the previous two iterations. Initialize
the shift register with a reading from the temperature sensor. Chart only the
average temperature.
Implementation
1. Test the VI.
Hardware
❑ Open the Temperature Monitor.vi in the C:\Exercises\
LabVIEW Basics I\Average Temperature directory.
❑ Skip to step 2.
No Hardware
❑ Open Temperature Monitor (Demo).vi in the
C:\Exercises\LabVIEW Basics I\Average Temperature
directory.
2. Stop the VI by changing the state of the Power switch. Notice that the
Power switch immediately switches back to the On state. The
mechanical action of the switch controls this behavior.
❑ Right-click the right or left border of the While Loop and select
Add Shift Register from the shortcut menu to create a shift register.
❑ Right-click the left terminal of the shift register and select Add
Element from the shortcut menu to add an element to the shift
register.
❑ Press the <Ctrl> key while you click the Thermometer VI and drag
it outside the While Loop to create a copy of the subVI.
The Thermometer VI returns one temperature measurement from
the temperature sensor and initializes the left shift registers before
the loop starts.
Testing
1. Run the VI.
H. Plotting Data
You already used charts and graphs to plot simple data. This section
explains more about using and customizing charts and graphs.
Waveform Charts
The waveform chart is a special type of numeric indicator that displays one
or more plots of data typically acquired at a constant rate. Waveform charts
can display single or multiple plots. Figure 3-27 shows the elements of a
multiplot waveform chart. Two plots are displayed: Raw Data and Running
Avg.
6
1
3
5
You can configure how the chart updates to display new data. Right-click
the chart and select Advanced»Update Mode from the shortcut menu to set
the chart update mode. The chart uses the following modes to display data:
• Strip Chart—Shows running data continuously scrolling from left to
right across the chart with old data on the left and new data on the right.
A strip chart is similar to a paper tape strip chart recorder. Strip Chart
is the default update mode.
• Scope Chart—Shows one item of data, such as a pulse or wave,
scrolling partway across the chart from left to right. For each new value,
the chart plots the value to the right of the last value. When the plot
reaches the right border of the plotting area, LabVIEW erases the plot
and begins plotting again from the left border. The retracing display of
a scope chart is similar to an oscilloscope.
• Sweep Chart—Works similarly to a scope chart except it shows the old
data on the right and the new data on the left separated by a vertical line.
LabVIEW does not erase the plot in a sweep chart when the plot reaches
the right border of the plotting area. A sweep chart is similar to an EKG
display.
Figure 3-28 shows an example of each chart update mode. The scope chart
and sweep chart have 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 chart.
Wiring Charts
You can wire a scalar output directly to a waveform chart. The waveform
chart terminal shown in Figure 3-29 matches the input data type.
Waveform charts can display multiple plots together using the Bundle
function located on the Cluster palette. In Figure 3-30, the Bundle function
bundles the outputs of the three VIs to plot on the waveform chart.
The waveform chart terminal changes to match the output of the Bundle
function. To add more plots, use the Positioning tool to resize the Bundle
function. Refer to Lesson 4, Relating Data for more information about
bundles.
Waveform Graphs
VIs with a graph usually collect the data in an array and then plot the data
to the graph.Figure 3-31 shows the elements of a graph.
11 1
4
5 6
10
8 7
The graphs located on the Graph Indicators palette include the waveform
graph and XY graph. The waveform graph plots only single-valued
functions, as in y = f(x), with points evenly distributed along the x-axis,
Resize the plot legend to display multiple plots. Use multiple plots to save
space on the front panel and to make comparisons between plots. XY and
waveform graphs automatically adapt to multiple plots.
Refer to the (Y) Multi Plot 1 graph in the Waveform Graph VI in the
labview\examples\general\graphs\gengraph.llb for an
example of a graph that accepts this data type.
The waveform graph accepts a plot array where the array contains clusters.
Each cluster contains a 1D array that contains the y data. The inner array
describes the points in a plot, and the outer array has one cluster for each
plot. The following front panel shows this array of the y cluster.
Use a plot array instead of a 2D array if the number of elements in each plot
is different. For example, when you sample data from several channels using
different time amounts from each channel, use this data structure instead of
a 2D array because each row of a 2D array must have the same number of
elements. The number of elements in the interior arrays of an array of
clusters can vary. Refer to the (Y) Multi Plot 2 graph in the Waveform Graph
VI in the labview\examples\general\graphs\gengraph.llb for
an example of a graph that accepts this data type.
The waveform graph also accepts the dynamic data type, which is for use
with Express VIs. In addition to the data associated with a signal, the
dynamic data type includes attributes that provide information about the
signal, such as the name of the signal or the date and time the data was
acquired. Attributes specify how the signal appears on the waveform graph.
When the dynamic data type includes multiple channels, the graph displays
a plot for each channel and automatically formats the plot legend and
x-scale time stamp.
The XY graph also accepts an array of points, where a point is a cluster that
contains an x value and a y value. Refer to the (Array of Pts) Single Plot
graph in the XY Graph VI in the labview\examples\general\
graphs\gengraph.llb for an example of a graph that accepts this data
type. The XY graph also accepts an array of complex data, in which the real
part is plotted on the x-axis and the imaginary part is plotted on the y-axis.
Multiplot XY Graphs
The XY graph accepts three data types for displaying multiple plots. The
XY graph accepts an array of plots, where a plot is a cluster that contains an
x array and a y array. Refer to the (X and Y arrays) Multi Plot graph in the
XY Graph VI in the labview\examples\general\graphs\
gengraph.llb for an example of a graph that accepts this data type.
Scenario
Modify the VI from Exercise 3-5 to plot both the current temperature and
the running average on the same chart. In addition, allow the user to examine
a portion of the plot while the data is being acquired.
Design
Figure 3-32 shows the front panel for the existing VI (Average Temperature
VI) and Figure 3-33 shows the block diagram.
To allow the user to examine a portion of the plot while the data is begin
acquired, display the Scale Legend and Graph Palette for the waveform
chart. Also, expand the legend to show additional plots.
To modify the block diagram in Figure 3-33, you must modify the chart
terminal to accept multiple pieces of data. Use a Bundle function to combine
the average temperature and the current temperature into a cluster to pass to
the Temperature History chart terminal.
Modify the block diagram first, then modify the front panel.
Implementation
1. Open Average Temperature.vi in the C:\Exercises\
LabVIEW Basics I\Average Temperature directory. You created
this VI in the previous exercise.
In the steps below, you modify the block diagram similar to that shown in
Figure 3-35.
❑ Wire the output of the Divide function to the top input of the Bundle
function.
In the following steps, modify the front panel similar to the one shown in
Figure 3-34.
❑ Use the Positioning tool to resize the plot legend to two objects,
using the top middle resizing node.
❑ Change the plot type of Current Temp. Use the Operating tool to
select the plot in the plot legend and choose the plots you want.
Tip The order of the plots listed in the plot legend is the same as the order of the items
wired to the Bundle function on the block diagram.
7. Show the Scale Legend and Graph Palette of the Waveform Chart.
Testing
1. Run the VI. Use the tools in the Scale Legend and Graph palette to
examine the data as it is generated.
I. Case Structures
A Case structure, shown as follows, has two or more subdiagrams, or cases.
Only one subdiagram is visible at a time, and the structure executes only one
case at a time. An input value determines which subdiagram executes. The
Case structure is similar to switch statements or if...then...else statements in
text-based programming languages.
The case selector label at the top of the Case structure, shown as follows,
contains the name of the selector value that corresponds to the case in the
center and decrement and increment arrows on each side.
Click the decrement and increment arrows to scroll through the available
cases. You also can click the down arrow next to the case name and select a
case from the pull-down menu.
You must wire an integer, Boolean value, string, or enumerated type value
to the selector terminal. You can position the selector terminal anywhere on
the left border of the Case structure. If the data type of the selector terminal
is Boolean, the structure has a TRUE case and a FALSE case. If the selector
terminal is an integer, string, or enumerated type value, the structure can
have any number of cases.
Specify a default case for the Case structure to handle out-of-range values.
Otherwise, you must explicitly list every possible input value. For example,
if the selector is an integer and you specify cases for 1, 2, and 3, you must
specify a default case to execute if the input value is 4 or any other
unspecified integer value.
Selecting a Case
Figure 3-36 shows a VI that uses a Case structure to execute different code
dependent on whether a user selects degrees Celsius or Fahrenheit for their
desired temperature units. The top block diagram shows the True case in the
foreground. In the middle block diagram, the False case is selected. To
select a case, enter the value in the case selector identifier or use the
Labeling tool to edit the values. After you select another case, that case
appears at the front, as shown in the bottom block diagram of Figure 3-36.
If you enter a selector value that is not the same type as the object wired to
the selector terminal, the value appears red to indicate that you must delete
or edit the value before the structure can execute, and the VI will not run.
Also, because of the possible round-off error inherent in floating-point
arithmetic, you cannot use floating-point numbers as case selector values. If
you wire a floating-point value to the case, LabVIEW rounds the value to
the nearest even integer. If you type a floating-point value in the case
selector label, the value appears red to indicate that you must delete or edit
the value before the structure can execute.
Consider the following example: A Case structure on the block diagram has
an output tunnel, but in at least one of the cases, there is no output value
wired to the tunnel. If you run this case, LabVIEW does not know what
value to place in the output. LabVIEW indicates this error by leaving the
center of the tunnel white. The unwired case might not be the case that is
currently visible on the block diagram.
To correct this error, move to the case(s) that contain(s) the unwired output
tunnel and wire an output to the tunnel. You also can right-click the output
tunnel and select Use Default If Unwired from the shortcut menu to use the
default value for the tunnel data type for all unwired tunnels. When the
output is properly wired in all cases, the output tunnel is a solid color.
Avoid using the Use Default If Unwired option. Using this option does not
document the block diagram well, and can confuse other programmers using
your code. The Use Default If Unwired option also makes debugging your
code difficult. If you choose to use this option, be aware that the default
value used is the default value for the data type that is wired to the tunnel.
For example, if the tunnel is a Boolean data type, the default value is
FALSE. Use the Table 3-3 for assistance.
Examples
In the following examples, the numeric values pass through tunnels to the
Case structure and are either added or subtracted, depending on the value
wired to the selector terminal.
If the Boolean control wired to the selector terminal is True, the VI adds the
numeric values. Otherwise, the VI subtracts the numeric values.
An enumerated type control gives users a list of items from which to select.
The data type of an enumerated type control includes information about the
numeric values and string labels in the control. When you wire an
enumerated type control to the selector terminal of a Case structure, the case
selector displays a case for each item in the enumerated type control. The
Case structure executes the appropriate case subdiagram based on the
current item in the enumerated type control. In the previous block diagram,
if Enum is add, the VI adds the numeric values. If Enum is subtract, the
VI subtracts the numeric values.
Scenario
You created a VI where a user inputs a temperature, a maximum
temperature and a minimum temperature. A warning string is generated
depending on the relationship of the given inputs. However, a situation
could occur that causes the VI to work incorrectly. The user could enter a
maximum temperature that is less than the minimum temperature. Modify
the VI so that a different string is generated to alert the user to the error:
"Upper Limit < Lower Limit." Set the warning Boolean to True to
indicate the error.
Design
Modify the flowchart created for the original Determine Warnings VI as
shown in Figure 3-37.
Output
Min Temp >= Current Temp Current Temp
No No No No Warning and
Max Temp >= Max Temp <= Min Temp
FALSE
Output
Output
Heatstroke
Create Error Freeze Warning
Warning and
and TRUE
TRUE
Output
Upper Limit
< Lower Limit
and TRUE
Implementation
Follow the instructions given below to modify the block diagram similar to
that shown in Figure 3-39. This VI is part of the temperature weather station
project.
Tip To select more than one item press the <Shift> key while you select the items.
❑ While the terminals are still selected, use the left arrow key on the
keyboard to move the controls further to the left of the block
diagram.
❑ While the terminals are still selected, use the right arrow key on the
keyboard to move the controls further to the right of the block
diagram.
❑ Wire the Min Temp output to the x input on the Greater? function.
❑ Wire the Max Temp output to the y input on the Greater? function.
❑ Place a Case structure around the block diagram code, except for the
excluded terminals.
❑ Wire the output of the Greater? function to the case selector of the
Case structure.
5. If the Min Temp is less than the Max Temp, execute the code that
determines the warning string and boolean.
❑ While the True case is visible, right-click the border of the Case
structure, and select Make This Case False from the shortcut menu.
When you create a Case structure around existing code, the code is
automatically placed in the True case.
6. If the Min Temp is greater than the Max Temp, create a custom string
for the Warning Text indicator and set the Warning? indicator to True,
as shown in Figure 3-40.
❑ Select Create»Constant.
❑ Select Create»Constant.
Testing
1. Switch to the front panel of the VI.
3. Test the VI by entering values from Table 3-4 for Current Temp, Max
Temp, and Min Temp, and running for each set.
Table 3-4 shows the expected Warning Text and Warning? Boolean
value for each set of inputs.
J. Formula Nodes
When you want to use a complicated equation in LabVIEW, you do not have
to wire together various arithmetic functions on the block diagram. You can
develop equations in a familiar, mathematical environment and then
integrate the equations into an application.
The Formula Node is a convenient text-based node you can use to perform
mathematical operations on the block diagram. You do not have to access
any external code or applications, and you do not have to wire low-level
arithmetic functions to create equations. In addition to text-based equation
expressions, the Formula Node can accept text-based versions of if
statements, while loops, for loops, and do loops, which are familiar to C
programmers. These programming elements are similar to what you find in
C programming but are not identical.
Formula Nodes are useful for equations that have many variables or are
otherwise complicated and for using existing text-based code. You can copy
and paste the existing text-based code into a Formula Node rather than
recreating it graphically.
Create the input and output terminals of the Formula Node by right-clicking
the border of the node and selecting Add Input or Add Output from the
shortcut menu, then enter the variable for the input or output. Enter the
equation in the structure. Each equation statement must terminate with a
semicolon (;).
You also can use Formula Nodes for decision making. The following block
diagram shows two different ways of using an if-then statement in a
Formula Node. The two structures produce the same result.
The Formula Node can perform many different operations. Refer to the
LabVIEW Help for more information about functions, operations, and
syntax for the Formula Node.
Scenario
Build a VI that calculates the square root of a number the user enters. If the
number is negative, display the following message to the user:
Error... Cannot find the square root of a negative
number.
Design
Flowchart
Display Error
Number>=0? No
Dialog
Yes
Implementation
1. Open a blank VI and build the front panel shown in Figure 3-42.
4. If Number is less than 0, display a dialog box that informs the user of
the error.
❑ Wire the numeric constant to the right edge of the case structure.
❑ Place the Square Root function in the True case. This function
returns the square root of Number.
Testing
1. Display the front panel.
Goal
Modify an existing VI to use the Formula Node or a Case structure to make
a software decision.
Scenario
In the Determine Warnings VI from Exercise 3-2, you used the Select
function to pass a string based on decision. Revise this block diagram to use
either a Formula Node or a Case structure (or a combination of both) to
complete the same purpose.
Design
Flowchart
Figure 3-45 shows the flowchart you used in Exercise 3-2 to create the
Determine Warnings VI.
Current Temp
No
>=Max Temp?
Yes
Warning Text =
Warning Text =
Heatstroke
No Warning
Warning
Current Temp
No
<= Min Temp?
Yes
Warning
Text = No No
Warning?
Yes
Implementation
As part of the challenge, no implementation instructions are given for this
exercise. The VI you should start from is located in the C:\Exercises\
LabVIEW Basics I\Determine Warnings Challenge directory.
If you need assistance, open the solution VIs. The solutions are located in
C:\Solutions\LabVIEW Basics I\Exercise 3-9 directory.
The solution to this exercise is not used in the course project, so you do not
need to add it to the Weather Station.proj file.
Scenario
You have a VI that determines whether a Heatstroke Warning or a Freeze
Warning has occurred, based on temperature input. You must expand this
VI so that it also determines whether a High Wind Warning has occurred
based on a wind speed reading and a maximum wind speed setting. The
warnings must be displayed as a single string. For example, if a Heatstroke
Warning and a High Wind Warning has occurred, the string should read:
Heatstroke and High Wind Warning.
Design
Inputs and Outputs
Flowchart
The flowchart shown in Figure 3-46 was used for the Determine Warnings
VI. In this VI, wind data is not taken. Modify this flowchart to determine the
High Wind Warning as well.
Current Temp
No
>=Max Temp?
Yes
Warning Text =
Warning Text =
Heatstroke
No Warning
Warning
Current Temp
No
<= Min Temp?
Yes
Warning
Text = No No
Warning?
Yes
Min Temp
No
Max Temp
Create Create empty Create "Freeze" Create empty Create "High Create empty
"Heatstroke" string string string string Wind" string string
Output
Upper Limit
Combine strings
< Lower Limit
and TRUE
Combine and
display Warning
Text; determine
and display
Warning?
VI Architecture
There are many ways to write this program. In this exercise, you use case
structures to determine what string to pass, and Concatenate Strings
functions to merge strings together.
Implementation
A portion of this VI has already been built for you. The front panel of the VI
is shown in Figure 3-48. This front panel retrieves from the user the current
temperature, the maximum temperature, the minimum temperature, the
current wind speed and the maximum wind speed and displays to the user
the warning string and the warning Boolean. This VI is not used in the
Weather Station project in this course.
3. Use Figures 3-49 through 3-53 to assist you in building the block
diagram code.
❑ Case structure.
❑ Space constant.
❑ Equal function.
Figure 3-50. True Cases for When Temperature and Wind Warnings Are Not
Generated
Figure 3-52. False Cases for When Wind and Temperature Warnings Are Generated
Testing
1. Test the following values to be sure your VI works as expected.
Min Temp 15 15 15 15 15 15
Current 25 25 25 35 35 35
Wind
Speed
Max Wind 30 30 30 30 30 30
Speed
Warning No Warning Heatstroke Freeze Heatstroke Freeze and High Wind
Text Warning Warning and High High Wind Warning,
Wind Warning
Warning
Self-Review: Quiz
1. Which of the following identifies the control or indicator on the block
diagram?
a. Caption
b. Location
c. Label
d. Value
2. Which of the following structures must run at least one time?
a. While Loop
b. For Loop
3. Which of the following is ONLY available on the block diagram?
a. Control
b. Constant
c. Indicator
d. Connector Pane
4. Which of the following mechanical actions causes a Boolean in the false
state to change to true when you press it and stay true until you release
it and LabVIEW has read the value?
a. Switch Until Released
b. Switch When Released
c. Latch Until Released
d. Latch When Released
Notes
Topics
A. Arrays
B. Clusters
C. Type Definitions
A. Arrays
An array consists of elements and dimensions. Elements are the data that
make up the array. A dimension is the length, height, or depth31of an array.
An array can have one or more dimensions and as many as (2 ) – 1
elements per dimension, memory permitting.
You can build arrays of numeric, Boolean, path, string, waveform, and
cluster data types. Consider using arrays when you work with a collection
of similar data and when you perform repetitive computations. Arrays are
ideal for storing data you collect from waveforms or data generated in loops,
where each iteration of a loop produces one element of the array.
Restrictions
You cannot create arrays of arrays. However, you can use a
multidimensional array or create an array of clusters where each cluster
contains one or more arrays. Also, you cannot create an array of subpanel
controls, tab controls, .NET controls, ActiveX controls, charts, or multiplot
XY graphs.
Refer to the Clusters section of this lesson for more information about
clusters.
An example of a simple array is a text array that lists the nine planets of our
solar system. LabVIEW represents this as a 1D array of strings with nine
elements.
Array elements are ordered. An array uses an index so you can readily
access any particular element. The index is zero-based, which means it is in
the range 0 to n – 1, where n is the number of elements in the array. For
example, n = 9 for the nine planets, so the index ranges from 0 to 8. Earth is
the third planet, so it has an index of 2.
You must insert an object in the array shell before you use the array on the
block diagram. Otherwise, the array terminal appears black with an empty
bracket and has no data type associated with it.
Two-Dimensional Arrays
The previous examples use 1D arrays. A 2D array stores elements in a grid.
It requires a column index and a row index to locate an element, both of
which are zero-based. The following figure shows an 8 column by 8 row 2D
array, which contains 8 × 8 = 64 elements.
Column Index
0 1 2 3 4 5
0
Row Index 1
2
3
Initializing Arrays
You can initialize an array, or leave it unitialized. When an array is
initialized, you defined the number of elements in each dimension, and the
contents of each element. An unitialized array has dimension but no
elements. Figure 4-3 shows an uninitialized 2D array control. Notice that
the elements are all greyed out. This indicates that the array is unitialized.
Array Inputs
If you enable auto-indexing on an array wired to a For Loop input terminal,
LabVIEW sets the count terminal to the array size so you do not need to wire
the count terminal. Because you can use For Loops to process arrays an
element at a time, LabVIEW enables auto-indexing by default for every
array you wire to a For Loop. Disable auto-indexing if you do not need to
process arrays one element at a time.
In Figure 4-5, the For Loop executes a number of times equal to the number
of elements in the array. Normally, if the count terminal of the For Loop is
not wired, the run arrow is broken. However, in this case the run arrow is not
broken.
If you enable auto-indexing for more than one tunnel or if you wire the count
terminal, the count becomes the smaller of the choices. For example, if two
auto-indexed arrays enter the loop, with 10 and 20 elements respectively,
and you wire a value of 15 to the count terminal, the loop executes 10 times,
and the loop indexes only the first 10 elements of the second array.
Array Outputs
When you auto-index an array output tunnel, the output array receives a new
element from every iteration of the loop. Therefore, auto-indexed output
arrays are always equal in size to the number of iterations. The wire from
the output tunnel to the array indicator becomes thicker as it changes to an
array at the loop border, and the output tunnel contains square brackets
representing an array, as shown Figure 4-6.
Right-click the tunnel at the loop border and select Enable Indexing or
Disable Indexing from the shortcut menu to enable or disable auto-indexing.
Auto-indexing for While Loops is disabled by default.
For example, disable auto-indexing if you need only the last value passed
out of the tunnel.
Description
You are given a VI and asked to enhance it for a variety of purposes. For
each part of this exercise, begin with the Array Investigation.vi
located in the C:\Exercises\LabVIEW Basics I\Manipulating
Arrays directory. The front panel of this VI is shown in Figure 4-8.
In this exercise, you are given the scenario for each part first. If you want
detailed implementation instructions, they are given for each part at the end
of this exercise.
Part 1: Implementation
Modify Array Investigation VI so that after the array is created, the array is
indexed into For Loops where each element of the array is multiplied by
100, and coerced to the nearest whole number. The resulting two
dimensional array is graphed to an Intensity Chart.
5. Iterate Array.
❑ Wire the Array indicator terminal to the interior For Loop border.
This creates an auto-indexed input tunnel on both For Loops.
❑ Wire the output of the Multiply function to the input of the Round
To Nearest function.
8. Create a 2D array on the output of the For Loops to recreate the modified
array.
❑ Wire the output of the Round To Nearest function to the outer For
Loop. This creates an auto-indexed output tunnel on both For Loops.
Part 2: Implementation
Modify Part 1 to accomplish the same goals without using the nested For
Loops.
4. Right-click the interior For Loop, containing the Multiply and Round to
Nearest function, and select Remove For Loop.
5. Right-click the remaining For Loop and select Remove For Loop from
the shortcut menu. Your block diagram should resemble the one shown
in Figure 4-12.
Part 3: Implementation
Modify Array Investigation VI so that the VI creates a new array that
contains the contents of the third row, and another new array that contains
the contents of the second column.
In the following steps, you build a block diagram similar to that shown in
Figure 4-13.
4. Retrieve the third row of data from Array using the Index Array
function.
Tip The Index Array function accepts an n-dimension array. After you wire the input
array to the Index Array function, the input and output terminal names change to match
the dimension of the array wired. Therefore, wire the input array to the Index Array
function before wiring any other terminals.
❑ Enter 2 in the constant to retrieve the third row because the index
begins at zero.
5. Retrieve the second column of data from Array using the Index Array
function.
❑ Select Create»Constant.
❑ Select Create»Indicator.
B. Clusters
Clusters group data elements of mixed types. An example of a cluster is the
LabVIEW error cluster, which combines a Boolean value, a numeric value,
and a string. A cluster is similar to a record or a struct in text-based
programming languages.
Refer to the Error Checking and Error Handling topic of the LabVIEW
Help for more information about using error clusters.
Bundling several data elements into clusters eliminates wire clutter on the
block diagram and reduces the number of connector pane terminals that
subVIs need. The connector pane has, at most, 28 terminals. If your front
panel contains more than 28 controls and indicators that you want to pass to
another VI, group some of them into a cluster and assign the cluster to a
terminal on the connector pane.
Most clusters on the block diagram have a pink wire pattern and data type
terminal. Clusters of numeric values, sometimes referred to as points, have
a brown wire pattern and data type terminal. You can wire brown numeric
clusters to Numeric functions, such as Add or Square Root, to perform the
same operation simultaneously on all elements of the cluster.
Clusters differ from arrays in that they are a fixed size. Like an array, a
cluster is either a control or an indicator. A cluster cannot contain a mixture
of controls and indicators.
You can use a cluster constant to store constant data or as a basis for
comparison with another cluster.
If you have a cluster control or indicator on the front panel and you want to
create a cluster constant containing the same elements on the block diagram,
you can either drag that cluster from the front panel to the block diagram or
right-click the cluster on the front panel and select Create»Constant from
the shortcut menu.
Cluster Order
Cluster elements have a logical order unrelated to their position in the shell.
The first object you place in the cluster is element 0, the second is element
1, and so on. If you delete an element, the order adjusts automatically. The
cluster order determines the order in which the elements appear as terminals
on the Bundle and Unbundle functions on the block diagram. You can view
and modify the cluster order by right-clicking the cluster border and
selecting Reorder Controls In Cluster from the shortcut menu. The toolbar
and cluster change, as shown in Figure 4-16.
5 4
The white box on each element shows its current place in the cluster order.
The black box shows the new place in the order for an element. To set the
order of a cluster element, enter the new order number in the Click to set to
text box and click the element. The cluster order of the element changes, and
the cluster order of other elements adjusts. Save the changes by clicking the
Confirm button on the toolbar. Revert to the original order by clicking
the Cancel button.
To wire clusters to each other, both clusters must have the same number of
elements. Corresponding elements, determined by the cluster order, must
have compatible data types. For example, if a double-precision floating-
point numeric value in one cluster corresponds in cluster order to a string in
the another cluster, the wire on the block diagram appears broken and the VI
does not run. If the numeric values are different representations, LabVIEW
coerces them to the same representation.
You also can create the Bundle, Bundle by Name, Unbundle, and Unbundle
by Name functions by right-clicking a cluster terminal on the block diagram
and selecting Cluster Palette from the shortcut menu. The Bundle and
Unbundle functions automatically contain the correct number of terminals.
The Bundle by Name and Unbundle by Name functions appear with the first
element in the cluster. Use the Positioning tool to resize the Bundle by Name
and Unbundle by Name functions to show the other elements of the cluster.
Assembling Clusters
Use the Bundle function to assemble a cluster from individual elements or
to change the values of individual elements in an existing cluster without
having to specify new values for all elements. Use the Positioning tool to
resize the function or right-click an element input and select Add Input
from the shortcut menu.
Modifying a Cluster
If you wire the cluster input, you can wire only the elements you want to
change. For example, the Input Cluster shown in Figure 4-18 contains three
controls.
If you know the cluster order, you can use the Bundle function to change
the Command value by wiring the elements shown in the following figure.
You can also use the Bundle by Name function to replace or access labeled
elements of an existing cluster. Bundle by Name works similarly to the
Bundle function, but instead of referencing cluster elements by their cluster
order, it references them by their owned labels. You can access only
elements with owned labels. The number of inputs does not need to match
the number of elements in output cluster.
Use the Operating tool to click an input terminal and select an element from
the pull-down menu. You also can right-click the input and select the
element from the Select Item shortcut menu.
In Figure 4-19, you can use the Bundle by Name function to change
Command and Function.
Use the Bundle by Name function for data structures that might change
during development. If you add a new element to the cluster or modify its
order, you do not need to rewire the Bundle by Name function because the
names still are valid.
Disassembling Clusters
Use the Unbundle function to split a cluster into its individual elements.
Use the Unbundle by Name function to return the cluster elements whose
names you specify. The number of output terminals does not depend on the
number of elements in the input cluster.
Use the Operating tool to click an output terminal and select an element
from the pull-down menu. You also can right-click the output terminal
and select the element from the Select Item shortcut menu.
For example, if you use the Unbundle function with the following cluster, it
has four output terminals that correspond to the four controls in the cluster.
You must know the cluster order so you can associate the correct Boolean
terminal of the unbundled cluster with the corresponding switch in the
cluster. In this example, the elements are ordered from top to bottom starting
with element 0. If you use the Unbundle by Name function, you can have an
arbitrary number of output terminals and access individual elements by
name in any order.
Error Clusters
LabVIEW contains a custom cluster called the error cluster. LabVIEW uses
error clusters to pass error information. An error cluster contains the
following elements:
• status—Boolean value that reports TRUE if an error occurred.
• code—32-bit signed integer that identifies the error numerically.
• source—String that identifies where the error occurred.
Refer to Lesson 5, Debugging VIs, for more information about using error
clusters.
Description
In this exercise, follow the instructions to experiment with clusters, cluster
order and cluster functions. The VI built has no practical applications, but is
useful for understanding cluster concepts.
In the following steps, you build a front panel similar to Figure 4-21.
10. Verify the cluster order of Cluster, Modified Cluster, and Small
Cluster.
In the following steps, build the block diagram shown in Figure 4-23.
11. Place the While Loop from the Structures category of the Functions
palette on the block diagram.
❑ Select Numeric in the first node, and Boolean 1 in the second node.
If a label name is not correct, use the Operating tool to select the
correct item.
❑ Select Numeric in the first node, and Boolean 1 in the second node.
If a label name is not correct, use the Operating tool to select the
correct item.
15. Complete the block diagram and wire the objects as shown in Figure 4-
23.
19. Enter different values in Cluster and run the VI again. Notice how
values entered in Cluster affect the Modified Cluster and Small
Cluster indicators. Is this the behavior you expected?
20. Try changing the cluster order of Modified Cluster. Run the VI.
How did the changed order affect the behavior?
Scenario
In the weather station project, use a cluster to group the temperature data.
Design
Create a cluster constant on the block diagram containing the following:
Notice that the data placed in the cluster are the input and output data of the
temperature weather station. Using a cluster to pass the data simplifies the
block diagram.
Implementation
1. Open the weather station project.
❑ Press the <Ctrl> key and click and drag the Temperature constant to
make a copy.
❑ Press the <Ctrl> key and click and drag the T Upper Limit constant
to make a copy.
C. Type Definitions
Type definitions are frequently used to define custom arrays and clusters.
Custom Controls
Use custom controls and indicators to extend the available set of front panel
objects. You can create custom user interface components for an application
that vary cosmetically from built-in LabVIEW controls and indicators. You
can save a custom control or indicator you created in a directory or LLB and
use the custom control or indicator on other front panels. You also can create
an icon for the custom control or indicator and add it to the Controls palette.
Use the Control Editor window to customize controls and indicators. For
example, you can change the size, color, and relative position of the
elements of a control or indicator and import images into the control or
indicator.
You can display the Control Editor window in the following ways:
• Right-click a control or indicator on the front panel and select
Advanced»Customize from the shortcut menu.
• Use the Positioning tool to select a control or indicator on the front panel
and select Edit»Customize Control.
• Use the New dialog box.
The Control Editor appears with the selected front panel object in its
window. The Control Editor has two modes, edit mode and customize mode.
The Control Editor window toolbar indicates whether you are in edit mode
Click the Edit Mode button to change to customize mode. Click the
Customize Mode button to return to edit mode. You also can switch
between modes by selecting Operate»Change to Customize Mode or
Operate»Change to Edit Mode.
Use edit mode to change the size or color of a control or indicator and to
select options from its shortcut menu, just as you do in edit mode on a front
panel.
Edit Mode
In edit mode, you can right-click the control and manipulate its settings as
you would in the LabVIEW programming environment.
1 2 3 4 5 6
Customize Mode
In customize mode, you can move the individual components of the control
around with respect to each other. For a listing of what you can manipulate
in customize mode, select Window»Show Parts Window.
1 2 3 4 5 6
One way to customize a control is to change its type definition status. You
can save a control as a control, a type definition, or a strict type definition,
depending on the selection visible in the Type Def. Status ring. The control
option is the same as a control you would select from the Controls palette.
You can modify it in any way you need to, and each copy you make and
change retains its individual properties.
Saving Controls
After creating a custom control, you can save it for use later. By default,
controls saved on disk have a .ctl extension.
You also can use the Control Editor to save controls with your own default
settings. For example, you can use the Control Editor to modify the defaults
of a waveform graph, save it, and later recall it in other VIs.
Type Definition
Use type definitions and strict type definitions to link all the instances of a
custom control or indicator to a saved custom control or indicator file. You
Type definitions identify the correct data type for each instance of a custom
control or indicator. When the data type of a type definition changes, all
instances of the type definition automatically update. In other words, the
data type of the instances of the type definition change in each VI where the
type definition is used. However, because type definitions identify only the
data type, only the values that are part of the data type update. For example,
on numeric controls, the data range is not part of the data type. Therefore,
type definitions for numeric controls do not define the data range for the
instances of the type definitions. Also, because the item names in ring
controls do not define the data type, changes to ring control item names in a
type definition do not change the item names in instances of the type
definition. However, if you change the item names in the type definition for
an enumerated type control, the instances update because the item names are
part of the data type. An instance of a type definition can have its own
unique label, description, default value, size, color, or style of control or
indicator, such as a knob instead of a slide.
If you change the data type in a type definition, LabVIEW converts the old
default value in instances of the type definition to the new data type, if
possible. LabVIEW cannot preserve the instance default value if the data
type changes to an incompatible type, such as replacing a numeric control
or indicator with a string control or indicator. When the data type of a type
definition changes to a data type incompatible with the previous type
definition, LabVIEW sets the default value of instances to the default value
for the new data type. For example, if you change a type definition from a
Type definitions and strict type definitions are typically used to create a
custom control using a cluster of many controls. If you need to add a new
control and pass a new value to every subVI, you can add the new control
to the custom control cluster, instead of having to add the new control to
each subVIs front panel and making new wires and terminals.
Scenario
In the weather station project, you use an enumerated control to define the
states of the state machine. In this exercise create a type-define enum for the
enumerated control. Type-defining the control makes it easier to add more
states to the state machine in the future.
Design
The enumerated control contains the following data:
Notice that these items correspond to the states of the state transition
diagram designed for this project.
Initialize
Acquisition
Time Elapsed=TRUE
and
Stop=False
Warning=TRUE
Analysis
Datalog
Time Elapsed=FALSE
and
Stop=FALSE
Time Check
Warning=FALSE
Stop=TRUE
Implementation
1. Open the weather station project.
❑ Place an Enum anywhere on the front panel. You will remove this
control later in this exercise.
❑ Enter the item names shown in Table 4-2. Figure 4-26 shows an
example of the Enum Properties dialog box, with the item names
entered. Be careful not to add any blank entries to the list.
❑ Select Type Def. from the Type Definition Status pull down menu,
as shown in Figure 4-27.
❑ Select File»Save.
5. Right-click the Enum. Notice that new options are available in the
shortcut menu allowing you to interact with the type-definition.
Notice that you can now select between the states on the block diagram.
Also notice that the control on the front panel has been removed.
Self-Review: Quiz
1. You can create an array of arrays.
a. True
b. False
4. You are inputting data that represents a circle. The circle data includes
an x position, a y position and a radius. All three pieces of data are
double precision. In the future, you might need to store the color of the
circle, represented as an integer. How should you represent the circle on
your front panel?
a. Three separate controls for the two positions and the radius.
b. A cluster containing all of the data.
c. A custom control containing a cluster.
d. A type definition containing a cluster.
e. An array with three elements.
Notes
Notes
Topics
A. Correcting Broken VIs
B. Debugging Techniques
C. Undefined or Unexpected Data
D. Error Checking and Error Handling
If the button still appears broken when you finish wiring the block diagram,
the VI is broken and cannot run.
Click the broken Run button or select View»Error List to find out why a
VI is broken. The Error list window lists all the errors. The Items with
errors section lists the names of all items in memory, such as VIs and
project libraries that have errors. If two or more items have the same name,
this section shows the specific application instance for each item. The
errors and warnings section lists the errors and warnings for the VI you
select in the Items with errors section. The Details section describes the
errors and in some cases recommends how to correct the errors. Click the
Help button to display a topic in the LabVIEW Help that describes the error
in detail and includes step-by-step instructions for correcting the error.
B. Debugging Techniques
If a VI is not broken, but you get unexpected data, you can use the following
techniques to identify and correct problems with the VI or the block diagram
data flow:
• Wire the error in and error out parameters at the bottom of most built-in
VIs and functions. These parameters detect errors encountered in each
node on the block diagram and indicate if and where an error occurred.
You also can use these parameters in the VIs you build.
• To eliminate all VI warnings, select View»Error List and place a
checkmark in the Show Warnings checkbox to see all warnings for the
VI. Determine the causes and correct them in the VI.
• Triple-click the wire with the Operating tool to highlight its entire path
and to ensure that the wires connect to the proper terminals.
• Use the Context Help window to check the default values for each
function and subVI on the block diagram. VIs and functions pass default
values if recommended or optional inputs are unwired. For example, a
Boolean input might be set to TRUE if unwired.
• Use the Find dialog box to search for subVIs, text, and other objects to
correct throughout the VI.
• Select View»Browse Relationships»This VI's Hierarchy to find
unwired subVIs. Unlike unwired functions, unwired VIs do not always
generate errors unless you configure an input to be required. If you
mistakenly place an unwired subVI on the block diagram, it executes
when the block diagram does. Consequently, the VI might perform extra
actions.
• Use execution highlighting to watch the data move through the block
diagram.
• Single-step through the VI to view each action of the VI on the block
diagram.
• Use the Probe tool to observe intermediate data values and to check the
error output of VIs and functions, especially those performing I/O.
• Use breakpoints to pause execution, so you can single-step or insert
probes.
• 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.
• Determine if the data that one function or subVI passes is undefined.
This often happens with numbers. For example, at one point in the VI an
operation could have divided a number by zero, thus returning Inf
(infinity), whereas subsequent functions or subVIs were expecting
numbers.
• If the VI runs more slowly than expected, confirm that you turned off
execution highlighting in subVIs. Also, close subVI front panels and
block diagrams when you are not using them because open windows can
affect execution speed.
• Check the representation of controls and indicators to see if you are
receiving overflow because you converted a floating-point number to an
integer or an integer to a smaller integer. For example, you might wire a
16-bit integer to a function that only accepts 8-bit integers. This causes
the function to convert the 16-bit integer to an 8-bit representation,
potentially causing a loss of data.
• Determine if any For Loops inadvertently execute zero iterations and
produce empty arrays.
• Verify you initialized shift registers properly unless you intend them to
save data from one execution of the loop to another.
• Check the cluster element order at the source and destination points.
LabVIEW detects data type and cluster size mismatches at edit time, but
it does not detect mismatches of elements of the same type.
• Check the node execution order.
• Check that the VI does not contain hidden subVIs. You inadvertently
might have hidden a subVI by placing one directly on top of another
node or by decreasing the size of a structure without keeping the subVI
in view.
• Check the inventory of subVIs the VI uses against the results of
View»Browse Relationships»This VI's SubVIs and View»Browse
Relationships»Unopened SubVIs to determine if any extra subVIs
exist. Also open the VI Hierarchy window to see the subVIs for a VI. To
help avoid incorrect results caused by hidden VIs, specify that inputs to
VIs are required.
Execution Highlighting
View an animation of the execution of the block diagram by clicking the
Highlight Execution button, shown as follows.
Note Execution highlighting greatly reduces the speed at which the VI runs.
Single-Stepping
Single-step through a VI to view each action of the VI on the block diagram
as the VI runs. The single-stepping buttons, shown as follows, affect
execution only in a VI or subVI in single-step mode.
Enter single-step mode by clicking the Step Over or Step Into button on the
block diagram toolbar. Move the cursor over the Step Over, Step Into, or
Step Out button to view a tip strip that describes the next step if you click
that button. You can single-step through subVIs or run them normally.
Probe Tools
Use the Probe tool, shown as follows, to check intermediate values on a wire
as a VI runs.
Use the Probe tool if you have a complicated block diagram with a series of
operations, any one of which might return incorrect data. Use the Probe tool
Types of Probes
You can check intermediate values on a wire when a VI runs by using a
generic probe, by using an indicator on the Controls palette to view the
data, by using a supplied probe, by using a customized supplied probe, or by
creating a new probe.
Generic
Use the generic probe to view the data that passes through a wire. Right-
click a wire and select Custom Probe»Generic Probe from the shortcut
menu to use the generic probe.
The generic probe displays the data. You cannot configure the generic probe
to respond to the data.
LabVIEW displays the generic probe when you right-click a wire and select
Probe, unless you already specified a custom or supplied probe for the data
type.
You can debug a custom probe similar to a VI. However, a probe cannot
probe its own block diagram, nor the block diagram of any of its subVIs.
When debugging probes, use the generic probe.
If the data type of the indicator you select does not match the data type of
the wire you right-clicked, LabVIEW does not place the indicator on the
wire.
Supplied
Supplied probes are VIs that display comprehensive information about the
data that passes through a wire. For example, the VI Refnum Probe returns
information about the VI name, the VI path, and the hex value of the
reference. You also can use a supplied probe to respond based on the data
that flows through the wire. For example, use an Error probe on an error
cluster to receive the status, code, source, and description of the error and
specify if you want to set a conditional breakpoint if an error or warning
occurs.
The supplied probes appear at the top of the Custom Probe shortcut menu.
Right-click a wire and select Custom Probe from the shortcut menu to
select a supplied probe. Only probes that match the data type of the wire you
right-click appear on the shortcut menu.
Custom
Use the Custom Probe Wizard to create a probe based on an existing probe
or to create a new probe. Right-click a wire and select Custom Probe»New
from the shortcut menu to display the Custom Probe Wizard. Create a probe
when you want to have more control over how LabVIEW probes the data
that flows through a wire. When you create a new probe, the data type of the
probe matches the data type of the wire you right-clicked. If you want to edit
the probe you created, you must open it from the directory where you saved
it.
After you select a probe from the Custom Probe shortcut menu, navigate to
it using the Select a Control palette option, or create a new probe using the
Custom Probe Wizard, that probe becomes the default probe for that data
type, and LabVIEW loads that probe when you right-click a wire and select
Probe from the shortcut menu. LabVIEW only loads probes that exactly
match the data type of the wire you right-click. That is, a double precision
floating-point numeric probe cannot probe a 32-bit unsigned integer wire
even though LabVIEW can convert the data.
Note If you want a custom probe to be the default probe for a particular data type, save
the probe in the user.lib\_probes\default directory. Do not save probes in the
vi.lib\_probes directory because LabVIEW overwrites those files when you
upgrade or reinstall.
Breakpoints
Use the Breakpoint tool, shown as follows, to place a breakpoint on a VI,
node, or wire on the block diagram and pause execution at that location.
When you set a breakpoint on a wire, execution pauses after data passes
through the wire. Place a breakpoint on the block diagram to pause
execution after all nodes on the block diagram execute.
When you reach a breakpoint during execution, the VI pauses and the Pause
button appears red. You can take the following actions:
• Single-step through execution using the single-stepping buttons.
• Probe wires to check intermediate values.
• Change values of front panel controls.
• Click the Pause button to continue running to the next breakpoint or
until the VI finishes running.
Suspending Execution
Suspend execution of a subVI to edit values of controls and indicators, to
control the number of times the subVI runs before returning to the caller, or
to go back to the beginning of the execution of the subVI. You can cause all
calls to a subVI to start with execution suspended, or you can suspend a
specific call to a subVI.
To suspend all calls to a subVI, open the subVI and select Operate»
Suspend when Called. The subVI automatically suspends when another VI
calls it. If you select this menu item when single-stepping, the subVI does
not suspend immediately. The subVI suspends when it is called.
To suspend a specific subVI call, right-click the subVI node on the block
diagram and select SubVI Node Setup from the shortcut menu. Place a
checkmark in the Suspend when called checkbox to suspend execution
only at that instance of the subVI.
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
Comparison function Not A Number/Path/Refnum? to the value you
suspect is invalid.
To disable automatic error handling for the current VI, select File»VI
Properties and select Execution from the Category pull-down menu. To
disable automatic error handling for any new, blank VIs you create, select
Tools»Options and select Block Diagram from the Category list. To
disable automatic error handling 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.
Use the LabVIEW error handling VIs and functions on the Dialog & User
Interface palette and the error in and error out parameters of most VIs and
functions to manage errors. For example, if LabVIEW encounters an error,
you can display the error message in different kinds of dialog boxes. Use
error handling in conjunction with the debugging tools to find and manage
errors.
VIs and functions return errors in one of two ways—with numeric error
codes or with an error cluster. Typically, functions use numeric error codes,
and VIs use an error cluster, usually with error inputs and outputs.
When you perform any kind of input and output (I/O), consider the
possibility that errors might occur. Almost all I/O functions return error
information. Include error checking in VIs, especially for I/O operations
(file, serial, instrumentation, data acquisition, and communication), and
provide a mechanism to handle errors appropriately.
Use the LabVIEW error handling VIs, functions, and parameters to manage
errors. For example, if LabVIEW encounters an error, you can display the
error message in a dialog box. Or you can fix the error programmatically
then erase the error by wiring the error out output of the subVI or function
to the error in input of the Clear Errors VI. Use error handling in conjunction
with the debugging tools to find and manage errors. National Instruments
strongly recommends using error handling.
Error Clusters
Use the error cluster controls and indicators to create error inputs and
outputs in subVIs.
The error in and error out clusters include the following components of
information:
• status is a Boolean value that reports TRUE if an error occurred.
• code is a 32-bit signed integer that identifies the error numerically. A
nonzero error code coupled with a status of FALSE signals a warning
rather than a error.
• source is a string that identifies where the error occurred.
Error handling in LabVIEW follows the dataflow model. Just as data values
flow through a VI, so can error information. Wire the error information from
the beginning of the VI to the end. Include an error handler VI at the end of
the VI to determine if the VI ran without errors. Use the error in and error
out clusters in each VI you use or build to pass the error information through
the VI.
Explain Error
When an error occurs, right-click within the cluster border and select
Explain Error from the shortcut menu to open the Explain Error dialog
box. The Explain Error dialog box contains information about the error.
The shortcut menu includes an Explain Warning option if the VI contains
warnings but no errors.
You also can access the Explain Error dialog box from the Help»Explain
Error menu.
VIs and functions return errors in one of two ways—with numeric error
codes or with an error cluster. Typically, functions use numeric error codes,
and VIs use an error cluster, usually with error inputs and outputs.
When you wire an error cluster to the selector terminal of a Case structure,
the case selector label displays two cases—Error and No Error—and the
border of the Case structure changes color—red for Error and green for No
Error. If an error occurs, the Case structure executes the Error
subdiagram.
When an error cluster is wired to the selection terminal, the Case structure
recognizes only the status Boolean of the cluster.
When an error cluster is wired to the conditional terminal, the shortcut menu
items Stop if True and Continue if True change to Stop on Error and
Continue while Error.
In Figure 5-5, the error cluster and a stop button are used together to
determine when to stop the loop. This is the recommended method for
stopping most loops.
Description:
Complete the following steps to load a broken VI and correct the error.
Use single-stepping and execution highlighting to step through the VI.
❑ Select File»Open.
❑ Notice the Run button on the toolbar appears broken, shown at left,
indicating that the VI is broken and cannot run.
2. Display and examine the block diagram of Debug Exercise (Main) VI.
❑ Click the broken Run button to display the Error list window,
which lists all the errors.
❑ Click the Help button to display a topic in the LabVIEW Help that
describes the error in detail and includes step-by-step instructions
for correcting the error.
❑ Click the Step Over button, shown at left, after each node to step
through the entire block diagram. Each time you click the Step Over
button, the current node executes and pauses at the next node.
❑ Data appear on the front panel as you step through the VI. The VI
generates a random number and multiplies it by 10.0. The subVI
adds 100.0 and takes the square root of the result.
❑ When a blinking border surrounds the entire block diagram, click the
Step Out button, shown at left, to stop single-stepping through the
Debug Exercise (Main) VI.
❑ When the Debug Exercise (Sub) VI blinks, click the Step Into
button. Notice the run button on the subVI.
❑ Use the Probe tool, shown at left, to click any wire. The Probe
window appears.
❑ Use the Breakpoint tool, shown at left, to click nodes or wires. Place
a breakpoint on the block diagram to pause execution after all nodes
on the block diagram execute.
❑ Click the Run button to run the VI. When you reach a breakpoint
during execution, the VI pauses and the Pause button on the toolbar
appears red.
❑ Use the Breakpoint tool to click the breakpoints you set and
remove them.
Notes
Topics
A. What is Modularity?
B. Icon and Connector Pane
C. Using SubVIs
A. What is Modularity?
Modularity defines the degree to which your VI is composed of discrete
components such that a change to one component has minimal impact on
other components. These components are called modules, or subVIs.
Modularity increases the readability and reusability of your VIs.
The upper right corner of the front panel and block diagram displays the
icon for the VI. This icon is the same as the icon that appears when you place
the VI on the block diagram.
As you create VIs, you might find that you perform a certain operation
frequently. Consider using subVIs or loops to perform that operation
repetitively. For example, the following block diagram contains two
identical operations.
The example calls the Temperature VI as a subVI twice on its block diagram
and functions the same as the previous block diagram.You also can reuse the
subVI in other VIs.
The connector pane is a set of terminals that correspond to the controls and
indicators of that VI, similar to the parameter list of a function call in text-
based programming languages. The connector pane defines the inputs and
outputs you can wire to the VI so you can use it as a subVI. A connector
pane receives data at its input terminals and passes the data to the block
diagram code through the front panel controls and receives the results at its
output terminals from the front panel indicators.
Creating an Icon
The default icon contains a number that indicates how many new VIs you
have opened since launching LabVIEW. Create custom icons to replace the
default icon by right-clicking the icon in the upper right corner of the front
panel or block diagram and selecting Edit Icon from the shortcut menu or by
double-clicking the icon in the upper right corner of the front panel.
You also can drag a graphic from anywhere in your file system and drop it
in the upper right corner of the front panel or block diagram. LabVIEW
converts the graphic to a 32 × 32 pixel icon.
Refer to the Icon Art Glossary at ni.com for standard graphics to use in a VI
icon.
Refer to the National Instruments Web site at ni.com/info and enter the info
code expnr7 for standard graphics to use in a VI icon.
Depending on the type of monitor you use, you can design a separate icon
for monochrome, 16-color, and 256-color mode. LabVIEW uses the
monochrome icon for printing unless you have a color printer.
Use the tools on the left side of the Icon Editor dialog box to create the icon
design in the editing area. The normal size image of the icon appears in the
appropriate box to the right of the editing area, as shown in Figure 6-3.
Use the Edit menu to cut, copy, and paste images from and to the icon.
When you select a portion of the icon and paste an image, LabVIEW resizes
the image to fit into the selection area. You also can drag a graphic from
anywhere in your file system and drop it in the upper right corner of the front
panel or block diagram. LabVIEW converts the graphic to a 32 × 32 pixel
icon.
Use the Copy from option on the right side of the Icon Editor dialog box
to copy from a color icon to a black-and-white icon and vice versa. After
you select a Copy from option, click the OK button to complete the change.
Note If you do not draw a complete border around a VI icon, the icon background
appears transparent. When you select the icon on the block diagram, a selection marquee
appears around each individual graphic element in the icon.
Use the tools on the left side of the Icon Editor dialog box to create the icon
design in the editing area. The normal size image of the icon appears in the
appropriate box to the right of the editing area. The following tasks can be
performed with these tools:
Use the Line tool to draw straight lines. To draw horizontal, vertical, and
diagonal lines, press the <Shift> key while you use this tool to drag the
cursor.
Use the Color Copy tool to copy the foreground color from an element in
the icon.
Use the Fill tool to fill an outlined area with the foreground color.
Use the Rectangle tool to draw a rectangular border in the foreground color.
Double-click this tool to frame the icon in the foreground color.
Use the Filled Rectangle tool to draw a rectangle with a foreground color
frame and filled with the background color. Double-click this tool to frame
the icon in the foreground color and fill it with the background color.
Use the Select tool to select an area of the icon to cut, copy, move, or make
other changes. Double-click this tool and press the <Delete> key to delete
the entire icon.
Use the Text tool to enter text into the icon. Double-click this tool to select
a different font. (Windows) The Small Fonts option works well in icons.
Use the options on the right side of the editing area to perform the following
tasks:
• Show Terminals—Displays the terminal pattern of the connector pane
• OK—Saves the drawing as the icon and returns to the front panel
• Cancel—Returns to the front panel without saving any changes
The menu bar in the Icon Editor dialog box contains more editing options
such as Undo, Redo, Cut, Copy, Paste, and Clear.
The following front panel has four controls and one indicator, so LabVIEW
displays four input terminals and one output terminal on the connector pane.
You also can have more front panel controls or indicators than terminals.
A solid border highlights the pattern currently associated with the icon. You
can assign up to 28 terminals to a connector pane.
The most commonly used pattern is shown at left. This pattern is used as a
standard to assist in simplifying wiring.
Figure 6-5 shows an example of the standard layout used for terminal
patterns. The top inputs and outputs are commonly used for passing
references and the bottom inputs and outputs are used for error handling.
Note Assigning more than 16 terminals to a VI can reduce readability and usability.
You also can select the control or indicator first and then select the terminal.
Note Although you use the Wiring tool to assign terminals on the connector pane to
front panel controls and indicators, no wires are drawn between the connector pane and
these controls and indicators.
C. Using SubVIs
To place a subVI on the block diagram, click the Select a VI button on the
Functions palette. Navigate to the VI you want to use as a subVI and and
double-click to place it on the block diagram.
You also can place an open VI on the block diagram of another open VI. Use
the Positioning tool to click the icon in the upper right corner of the front
panel or block diagram of the VI you want to use as a subVI and drag the
icon to the block diagram of the other VI.
You can edit a subVI by using the Operating or Positioning tool to double-
click the subVI on the block diagram. When you save the subVI, the
changes affect all calls to the subVI, not just the current instance.
You can designate which inputs and outputs are required, recommended,
and optional to prevent users from forgetting to wire subVI terminals.
For terminal inputs, required means that the block diagram on which you
placed the subVI will be broken if you do not wire the required inputs.
Required is not available for terminal outputs. For terminal inputs and
outputs, recommended or optional means that the block diagram on which
you placed the subVI can execute if you do not wire the recommended or
optional terminals. If you do not wire the terminals, the VI does not generate
any warnings.
The new subVI uses a default pattern for the connector pane and a default
icon. Double-click the subVI to edit the connector pane and icon, and to
save the subVI.
Note Do not select more than 28 objects to create a subVI because 28 is the maximum
number of connections on a connector pane.If your front panel contains more than
28 controls and indicators that you want to use programmatically, group some of them
into a cluster and assign the cluster to a terminal on the connector pane.
Scenario
You have created a VI that determines a warning string based on the inputs
given. Create an icon and a connector pane so that this VI can be used as a
subVI in the Weather Station project.
Design
The SubVI contains the following inputs and outputs:
Inputs Outputs
Current Temp Warning Text
Max Temp Warning?
Min Temp
Use the standard connector pane, shown at left, to assure room for future
expansion. Add an error input and error output to the VI so that the code runs
if there is no error, but does not run if there is an error.
Implementation
1. Open the Determine Warnings VI.
4. Connect the inputs and outputs to the connector as shown in Figure 6-7.
1 2
❑ Using the wiring tool, click the upper-left terminal of the connector
pane.
❑ Continue wiring the connector pane until all controls and indicators
are wired, and the Context Help window matches that shown in
Figure 6-7.
5. Create an icon.
❑ Right-click the connector pane and select Edit Icon. The Icon Editor
window opens.
❑ Use the tools in the Icon Editor window to create an icon. Make the
icon as simple or as complex as you want, however, it should be
representative of the function of the VI. Figure 6-8 shows a simple
example of an icon for this VI.
❑ Click OK when you are finished to close the Icon Editor window.
Tip Double-click the selection tool to select the existing graphic. Press <Delete> to
delete the graphic.
Tip Double-click the text tool to modify fonts. You can select Small Fonts to choose
fonts smaller than 9 points in size.
6. Right-click the connector pane and select Show Icon from the shortcut
menu to return to Icon view.
❑ Place the error out terminal to the right of the Case structure.
❑ Wire the error cluster through the Case structure to the error out
terminal as shown in Figure 6-9.
❑ Wire the error cluster through the case to the error out tunnel.
If an error enters the VI, the VI outputs Error in Warning Text, and True in
Warning? and passes out the error. If an error does not enter the VI, the VI
operates as originally designed.
Testing
Use a blank VI to test the subVI.
3. Place the subVI on the block diagram of the blank test VI.
6. Enter test values in Current Temp, Max Temp and Min Temp.
8. After you have finished testing, close the test VI. You do not need to
save the test VI.
Self-Review: Quiz
1. On a subVI, which setting causes an error if the terminal is not wired?
a. Required
b. Recommended
c. Optional
2. You must create an icon to use a VI as a subVI.
a. True
b. False
Notes
Topics
A. Computer-Based Measurement Systems
B. Measurement Concepts
C. Increasing Measurement Quality
Physical Phenomenon
Light, Pressure, Temperature, etc.
+ + + +
V
– HV
– –
mV
–
345
SC-2
SCX
MAINFR
I
AME
ON
STAND
BY
Application Software
LabVIEW, LabWindows/CVI, Measurement Studio, or Other Programming Environments
B. Measurement Concepts
This section introduces you to concepts you should be familiar with before
taking measurements with DAQ device and instruments.
Signal Acquisition
Signal acquisition is the process of converting physical phenomena into data
the computer can use. A measurement starts with using a transducer to
convert a physical phenomenon into an electrical signal. Transducers can
generate electrical signals to measure such things as temperature, force,
sound, or light. Table 7-1 lists some common transducers.
Phenomena Transducer
Temperature Thermocouples
Resistance temperature detectors (RTDs)
Thermistors
Integrated circuit sensors
Light Vacuum tube photosensors
Photoconductive cells
Sound Microphones
Force and pressure Strain gages
Piezoelectric transducers
Load cells
Position Potentiometers
(displacement) Linear voltage differential transformers (LVDT)
Optical encoders
Fluid flow Head meters
Rotational flowmeters
Ultrasonic flowmeters
pH pH electrodes
Signal Sources
Analog input acquisitions use grounded and floating signal sources.
of grounded sources are devices that plug into a building ground through
wall outlets, such as signal generators and power supplies.
+
Vs
–
Ground
Note The grounds of two independently grounded signal sources generally are not at the
same potential. The difference in ground potential between two instruments connected to
the same building ground system is typically 10 mV to 200 mV. The difference can be
higher if power distribution circuits are not properly connected. This causes a
phenomenon known as a ground loop.
+
Vs
–
Ground
Signal Conditioning
Signal conditioning is the process of measuring and manipulating signals to
improve accuracy, isolation, filtering, and so on. Many stand-alone
instruments and DAQ devices have built-in signal conditioning. Signal
conditioning also can be applied externally, by designing a circuit to
condition the signal or by using devices specifically made for signal
conditioning. National Instruments has SCXI devices and other devices that
are designed for this purpose. Throughout this section, different DAQ and
SCXI devices illustrate signal conditioning topics.
To measure signals from transducers, you must convert them into a form a
measurement device can accept. For example, the output voltage of most
thermocouples is very small and susceptible to noise. Therefore, you might
need to amplify the thermocouple output before you digitize it. This
amplification is a form of signal conditioning. Common types of signal
conditioning include amplification, linearization, transducer excitation, and
isolation.
Figure 7-4 shows some common types of transducers and signals and the
signal conditioning each requires.
Amplification
Amplification is the most common type of signal conditioning. Amplifying
electrical signals improves accuracy in the resulting digitized signal and
reduces the effects of noise.
Noise
Instrumentaion
Amplifier
+
MUX
– Lead ADC
Wires
Low-Level
Signal External
Amplifier DAQ Device
If you amplify the signal at the DAQ device while digitizing and measuring
the signal, noise might have entered the lead wire, which decreases SNR.
However, if you amplify the signal close to the signal source with a SCXI
module, noise has a less destructive effect on the signal, and the digitized
representation is a better reflection of the original low-level signal. Refer to
the National Instruments Web site at ni.com/info and enter the info code
exd2hc for more information about analog signals.
Linearization
Many transducers, such as thermocouples, have a nonlinear response to
changes in the physical phenomena you measure. LabVIEW can linearize
the voltage levels from transducers so you can scale the voltages to the
measured phenomena. LabVIEW provides scaling functions to convert
voltages from strain gages, RTDs, thermocouples, and thermistors.
Transducer Excitation
Signal conditioning systems can generate excitation, which some
transducers require for operation. Strain gages and RTDs require external
voltage and currents, respectively, to excite their circuitry into measuring
physical phenomena. This type of excitation is similar to a radio that needs
power to receive and decode audio signals.
Isolation
Another common way to use signal conditioning is to isolate the transducer
signals from the computer for safety purposes.
Caution When the signal you monitor contains large voltage spikes that could damage
the computer or harm the operator, do not connect the signal directly to a DAQ device
without some type of isolation.
You also can use isolation to ensure that differences in ground potentials do
not affect measurements from the DAQ device. When you do not reference
the DAQ device and the signal to the same ground potential, a ground loop
Measurement Systems
You configure a measurement system based on the hardware you use and the
measurement you take.
MUX
CH0+
CH1+
CH2+
Instrumentation
CH7+ + Amplifier
+
MUX
CH0– –
Vm
CH1–
CH2–
–
CH7–
AIGND
MUX
CH0
CH1
Instrumentation
CH2 + Amplifier
CH15
–
Vm
AIGND –
MUX
CH0+
CH1+
Instrumentation
CH2+ + Amplifier
CH15+
–
Vm
AISENSE
AIGND
Examples Examples
• Ungrounded Thermocouples • Plug-in Instruments with
Input • Signal Conditioning with Nonisolated Outputs
Isolated Outputs
• Battery Devices
ACH(+) ACH(+)
+ +
+ V + V
– 1 ACH(–) – 1 ACH(–)
– –
Differential
(DIFF) R
AIGND AIGND
NOT RECOMMENDED
ACH ACH
+ +
+ V + V
– 1 AIGND – 1
Single-Ended — – –
+ Vg –
Ground
Referenced
(RSE) AIGND
ACH ACH
+ +
+ V + V
– 1 AISENSE – 1 AISENSE
– –
Single-Ended —
Nonreferenced
(NRSE) R
AIGND AIGND
Resolution
The number of bits used to represent an analog signal determines the
resolution of the ADC. The resolution on a DAQ device is similar to
the marks on a ruler. The more marks a ruler has, the more precise the
measurements are. The higher the resolution is on a DAQ device, the higher
the number of divisions into which a system can break down the ADC range,
and therefore, the smaller the detectable change. A 3-bit ADC divides the
range into 23 or eight divisions. A binary or digital code between 000 and
111 represents each division. The ADC translates each measurement of the
analog signal to one of the digital divisions. The following illustration shows
a 5 kHz sine wave digital image obtained by a 3-bit ADC. The digital signal
does not represent the original signal adequately because the converter has
too few digital divisions to represent the varying voltages of the analog
signal. However, increasing the resolution to 16 bits to increase the ADC
number of divisions from eight (23) to 65,536 (216) allows the 16-bit ADC
to obtain an extremely accurate representation of the analog signal.
10.00
111
8.75
110 16-bit
7.50
Amplitude (V)
101
6.25
100
5.00
011
3.75
010 3-bit
2.50
001
1.25
000
0
0 50 100 150 200
Time ( s)
Device Range
Range refers to the minimum and maximum analog signal levels that the
ADC can digitize. Many DAQ devices feature selectable ranges (typically
0 to 10 V or –10 to 10 V), so you can match the ADC range to that of the
signal to take best advantage of the available resolution to accurately
measure the signal. For example, in the following illustration, the 3-bit ADC
in chart 1 has eight digital divisions in the range from 0 to 10 V, which is a
unipolar range. If you select a range of –10 to 10 V, which is a bipolar range,
as shown in chart 2, the same ADC separates a 20 V range into eight
divisions. The smallest detectable voltage increases from 1.25 to 2.50 V, and
the right chart is a much less accurate representation of the signal.
1 2
10.00 10.00
111 111
8.75 7.50
110 110
7.50 5.00
Amplitude (V)
Amplitude (V)
101 101
6.25 2.50
100 100
5.00 0
011 011
3.75 –2.50
010 010
2.50 –5.00
001 001
1.25 –7.50
000 000
0 –10.00
0 50 100 150 200 0 50 100 150 200
Time ( s) Time ( s)
Amplification
Amplification or attenuation of a signal can occur before the signal is
digitized to improve the representation of the signal. By amplifying or
attenuating a signal, you can effectively decrease the input range of an ADC
and thus allow the ADC to use as many of the available digital divisions as
possible to represent the signal.
10.00
111
8.75
110
7.5
Gain = 2 101
6.25
100 Gain = 1
V 5.00
011
3.75
Gain = 1 010
2.50
001
1.25
000
0.00
Gain = 2
sec
Code Width
Code width is the smallest change in a signal that a system can detect.
Code width is calculated using the following formula where C is code
width, D is device input range, and R is bits of resolution:
1
C = D ⋅ ----------
R
(2 )
Device input range is a combination of the gain applied to the signal and the
input range of the ADC. For example, if the ADC input range is –10 to
+10 V peak to peak and the gain is 2, the device input range is –5 to +5 V
peak to peak, or 20 V.
The smaller the code width, the more accurately a device can represent
the signal. The formula confirms what you have already learned in the
discussion on resolution, range, and gain:
• Larger resolution = smaller code width = more accurate representation
of the signal
1 1 -
C = D ⋅ ----------
R
= 10 ⋅ -----------
12
= 2.4mV
(2 ) (2 )
1 1 -
C = D ⋅ ----------
R
= 20 ⋅ -----------
12
= 4.8mV
(2 ) (2 )
Where fsampling is the sampling rate, and fsignal is the highest frequency
component of interest in the measured signal.
The Nyquist Theorem states that you must sample a signal at a rate greater
than twice the highest frequency component of interest in the signal to
capture the highest frequency component of interest. Otherwise, the
high-frequency content aliases at a frequency inside the spectrum of
interest, called the pass-band.
To determine how fast to sample, refer to Figure 7-13 which shows the
effects of various sampling rates. In case A, the sine wave of frequency f is
sampled at the same frequency f. The reconstructed waveform appears as an
alias at DC. However, if you increase the sampling rate to 2f, the digitized
waveform has the correct frequency (same number of cycles) but appears as
a triangle waveform. In this case f is equal to the Nyquist frequency. By
increasing the sampling rate to well above f, for example 5f, you can more
accurately reproduce the waveform. In case C, the sampling rate is at
4f-
----
3
(----------------
4f ) ⁄ 3 = 2f -----
2 3
Because f is larger than the Nyquist frequency, this sampling rate reproduces
an alias waveform of incorrect frequency and shape.
The faster the sample, the better the shape recovery of the signal. However,
available hardware often limits the sampling rate.
Decreasing Noise
To reduce noise take the following precautions:
• Use shielded cables or a twisted pair of cables.
• Minimize wire length to minimize noise the lead wires pick up.
• Keep signal wires away from AC power cables and monitors to reduce
50 or 60 Hz noise.
• Reduce the signal-to-noise (SNR) ratio by amplifying the signal close to
the signal source.
• Acquire data at a higher frequency than necessary, then average the data
to reduce the impact of the noise, as noise tends to average to zero.
Description
1. Open Resolution.vi in the C:\Exercises\LabVIEW Basics
I\Measurement Fundamentals directory.
This VI simulates the acquisition of a sine wave and the digitization that
occurs with an analog to digital convertor (ADC). This VI contains the
following controls and indicators:
• Input Signal Voltage: This input specifies the range of the signal
being acquired. The default value of the control is +/- 1 Volt.
This means that the range of the signal is 2 V: voltage between the
highest point of the signal and the lowest point of the signal.
• Device Input Range: The input incorporates the input range of the
ADC and the gain applied to the signal. The default value of the
control is +/– 1 Volts. This peak to peak voltage is equivalent to
2 volts. Since the input range of the ADC is +/– 10 V, this means that
there is a gain of 10 applied to the signal.
• Code Width: This output calculates the code width using the current
values of the controls, where C is code width, D is device input
range, and R is bits of resolution:
1 1-
C = D ⋅ ----------
R
= 2 ⋅ ---------
3
= 0.25V
(2 ) (2 )
The red plot demonstrates the actual input sinewave. The white plot
demonstrates the output of the ADC. Notice that the white plot is a
poor representation of the signal. You can see the code width of .25
volts shown on the graph representing only 8 discrete levels.
Notice that when too large of an input range is chosen, the resolution
is not efficiently divided among the signals range. When too small
of an input range is chosen, part of the signal is cut off.
It is important to ensure that the input signal range is as close to the device
input range as possible. In the next lesson, you learn to set the device input
range in software.
3. Using the Resolution VI, determine the code width of an input signal
that varies between +/– 0.8 V using a data acquisition board with a
resolution of 16 bits. Assume that gain is efficiently applied.
Code Width:
4. Determine the code width of an input signal that varies between +/-10 V
using a data acquisition board with a resolution of 8 bits. The device
input range is set to +/– 10 V.
Code Width:
5. If the device input range is +/– 1 V, and the resolution is 12 bits, what is
the largest input signal you can read without cutting off the input signal?
• Original Signal:
– Frequency: This input specifies the frequency of the signal
being acquired. You can increase or decrease this frequency by
turning the knob.
– Sampled Waveform: The input allows you to choose between a
sine wave or a square wave. Use the sine wave input to
experiment with the Nyquist Theorem, and the square wave to
understand how the sampling frequency affects shape recovery.
• Sampled Signal:
– Sampling Rate (Hz): This input specifies the rate at which the
data acquisition board takes a sample of the acquired signal.
According to the Nyquist Theorem, this rate should be at least
twice the frequency of the sampled signal.
8. Run the VI and experiment with the values of the controls until the
acquired frequency is wrong.
10. Set the Sampled Waveform to Square. Modify the controls to see how
shape recovery is affected by the sampling frequency and the frequency
of the signal.
Self-Review: Quiz
1. Calculate the code-width for signal acquired using a 16 bit data
acquisition board with a device input range of 5 V.
2. You are acquiring a triangle wave with a frequency of 1100 Hz. Which
sampling frequency should you use for best shape recovery of the
signal?
a. 1 kHz
b. 10 kHz
c. 100 kHz
d. 1000 kHz
3. You are acquiring a triangle wave with a frequency of 1100 Hz. You can
sample the signal at the following rates. Which is the minimum
sampling frequency you should use to reliably acquire the frequency of
the signal?
a. 1 kHz
b. 10 kHz
c. 100 kHz
d. 1000 kHz
1 1 -
C = D ⋅ ----------
R
= 5 ⋅ -----------
16
= 76.29µV
(2 ) (2 )
2. You are acquiring a triangle wave with a frequency of 1100 Hz. Which
sampling frequency should you use for best shape recovery of the
signal?
a. 1 kHz
b. 10 kHz
c. 100 kHz
d. 1000 kHz
3. You are acquiring a triangle wave with a frequency of 1100 Hz. You can
sample the signal at the following rates. Which is the minimum
sampling frequency you should use to reliably acquire the frequency of
the signal?
a. 1 kHz
b. 10 kHz
c. 100 kHz
d. 1000 kHz
Notes
Topics
A. Hardware
B. Software Architecture
C. Simulating a DAQ Device
D. Analog Input
E. Analog Output
F. Counters
G. Digital I/O
A. Hardware
A typical DAQ system has three basic types of hardware—a terminal block,
a cable, and a DAQ device, as shown in Figure 8-1.
2 4
NATIONAL
INSTRUMENTS
NATIONAL
INSTRUMENTS
A cable transports the signal from the terminal block to the DAQ device.
Cables come in 100-, 68-, and 50-pin configurations. Choose a
configuration depending on the terminal block and the DAQ device you are
using. Cables, like terminal blocks, are shielded or non-shielded.
A digital trigger button produces a TTL pulse for triggering analog input or
output. When you press the trigger button, the signal goes from +5 V to 0 V
when pressed and returns to +5 V when you release the button. Four LEDs
connect to the first four digital lines on the DAQ device. The LEDs use
reverse logic, so when the digital line is high, the LED is off and vice versa.
The DAQ Signal Accessory has a quadrature encoder that produces two
pulse trains when you turn the encoder knob. Terminals are provided for the
input and output signals of two counters on the DAQ device. The DAQ
Signal Accessory also has a relay, a thermocouple input, and a microphone
jack.
DAQ Device
Most DAQ devices have four standard elements: analog input, analog
output, digital I/O, and counters.
You can transfer the signal you measure with the DAQ device to the
computer through a variety of different bus structures. For example, you can
use a DAQ device that plugs into the PCI bus of a computer, a DAQ device
connected to the PCMCIA socket of a laptop, or a DAQ device connected to
the USB port of a computer. You also can use PXI/CompactPCI to create a
portable, versatile, and rugged measurement system.
If you do not have a DAQ device, you can simulate one in Measurement and
Automation Explorer to complete your software testing. You learn to
simulate a device in the Simulating a DAQ Device section of this lesson.
B. Software Architecture
National Instruments data acquisition boards have a driver engine that
communicates between the board and the application software. There are
two different driver engines to choose from: NI-DAQmx and Traditional
NI-DAQ. You can use LabVIEW to communicate with these driver engines.
You have already used the DAQ Assistant in LabVIEW to communicate
with your data acquisition board. The DAQ Assistant is an Express VI that
communicates with NI-DAQmx.
NI-DAQ
NI-DAQ 7.0 contains two NI-DAQ drivers—Traditional NI-DAQ (Legacy)
and NI-DAQmx—each with its own application programming interface
(API), hardware configuration, and software configuration.
• Traditional NI-DAQ (Legacy) is an upgrade to NI-DAQ 6.9.x, the earlier
version of NI-DAQ. Traditional NI-DAQ (Legacy) has the same VIs and
functions and works the same way as NI-DAQ 6.9.x. You can use
Traditional NI-DAQ (Legacy) on the same computer as NI-DAQmx,
which you cannot do with NI-DAQ 6.9.x.
• NI-DAQmx is the latest NI-DAQ driver with new VIs, functions, and
development tools for controlling measurement devices. The advantages
of NI-DAQmx over previous versions of NI-DAQ include the DAQ
Assistant for configuring channels and measurement tasks for a device;
increased performance, including faster single-point analog I/O and
multithreading; and a simpler API for creating DAQ applications using
fewer functions and VIs than earlier versions of NI-DAQ.
Windows
The Windows Configuration Manager keeps track of all the hardware
installed in the computer, including National Instruments DAQ devices.
If you have a Plug & Play (PnP) device, such as an E Series MIO device,
the Windows Configuration Manager automatically detects and configures
the device. If you have a non-PnP device, or legacy device, you must
configure the device manually using the Add New Hardware option
in the Control Panel.
primary MAX window. MAX is also the means for SCXI and SCC
configuration.
1: AT-MIO-64E-3
The device parameters that you can set using the configuration utility
depend on the device. MAX saves the logical device number and the
configuration parameters in the Windows Registry.
Scales
You can configure custom scales for your measurements. This is very useful
when working with sensors. It allows you to bring a scaled value into your
application without having to work directly with the raw values. For
example, in this course you use a temperature sensor that represents
temperature with a voltage. The conversion equation for the temperature is:
Voltage x 100 = Celsius. After a scale is set, you can use it in your
application program, providing the temperature value, rather than the
voltage.
Note In the configuration tree in MAX, the icons for NI-DAQmx simulated devices are
yellow. The icons for physical devices are green.
Description
Complete the following steps to examine the configuration for the
DAQ device in the computer using MAX and use the test routines
in MAX to confirm operation of the device. If you do not have a DAQ
device, you can simulate a device using the instructions in Part A. Creating
a Simulated Device.
Note Portions of this exercise that can only be completed with the use of a real device
and a DAQ signal accessory are marked Hardware. Some of these steps have alternative
instructions for simulated devices and are marked No Hardware.
❑ Click OK.
Note You might have a different device installed, and some of the options shown might
be different. Click the Show Help/Hide Help button in the top right corner of MAX to
hide the online help and show the DAQ device information.
6. Select the Device Routes tab to see detailed information about the
internal signals that can be routed to other destinations on the device, as
shown in Figure 8-4. This is a powerful resource that gives you a visual
representation of the signals that are available to provide timing and
synchronization with components that are on the device and other
external devices.
10. Click the Test Panels button to test the individual functions of the
DAQ device, such as analog input and output. The Test Panels dialog
box appears.
❑ Use the Analog Input tab to test the various analog input channels
on the DAQ device. Click the Start button to acquire data from
analog input channel 0.
– Hardware: If you have a DAQ Signal Accessory, channel
Dev1/ai0 is connected to the temperature sensor. Place your
finger on the sensor to see the voltage rise. You also can move
the Noise switch to On on the DAQ Signal Accessory to see the
signal change in this tab. When you are finished, click the Stop
button.
– No Hardware: If you are using a simulated device, a sine wave
is shown on all input channels. Experiment with the setting on
this tab. When you are finished, click the Stop button.
❑ Click the Analog Output tab to set up a single voltage or sine wave
on one of the DAQ device analog output channels.
❑ Hardware: Click the Analog Input tab and change the channel to
Dev1/ai1. Click the Start button to acquire data from analog input
channel 1. LabVIEW displays the sine wave from analog output
channel 0.
❑ Click the Digital I/O tab to test the digital lines on the DAQ device.
❑ Click the Close button to close the Test Panel and return to MAX.
❑ Right-click the Scales section and select Create New from the
shortcut menu.
❑ Click Next.
❑ Select Linear.
❑ Click Finish.
❑ Click the Save button on the toolbar to save the scale. You use this
scale in later exercises.
D. Analog Input
Analog input is the process of measuring an analog signal and transferring
the measurement to a computer for analysis, display or storage. An analog
signal is a signal that varies continuously. Analog input is most commonly
used to measure voltage or current. You can use many types of devices to
perform analog input, such as multifunction DAQ (MIO) devices,
high-speed digitizers, digital multimeters (DMMs) and Dynamic Signal
Acquisition (DSA) devices.
Analog-to-Digital Conversion
Acquiring an analog signal with a computer requires a process known as
analog-to-digital conversion, which takes an electrical signal and translates
it into digital data so that a computer can process it. Analog-to-digital
converters (ADCs) are circuit components that convert a voltage level into
a series of ones and zeroes.
ADCs sample the analog signal on each rising or falling edge of a sample
clock. In each cycle, the ADC takes a snapshot of the analog signal, so that
the signal can be measured and converted into a digital value. A sample
clock controls the rate at which samples of the input signal are taken.
Because the incoming, or unknown signal is a real world signal with infinite
precision, the ADC approximates the signal with fixed precision. After the
ADC obtains this approximation, the approximation can be converted to a
series of digital values. Some conversion methods do not require this step,
because the conversion generates a digital value directly as the ADC reaches
the approximation.
Task Timing
When performing analog input, the task can be timed to Acquire 1 Sample,
Acquire n Samples, or Acquire Continuously.
Acquire 1 Sample
Acquiring a single sample is an on-demand operation. In other words, the
driver acquires one value from an input channel and immediately returns the
value. This operation does not require any buffering or hardware timing. For
example, if you periodically monitor the fluid level in a tank, you would
acquire single data points. You can connect the transducer that produces a
voltage representing the fluid level to a single channel on the measurement
device and initiate a single-channel, single-point acquisition when you want
to know the fluid level.
Acquire n Samples
One way to acquire multiple samples for one or more channels is to acquire
single samples in a repetitive manner. However, acquiring a single data
sample on one or more channels over and over is inefficient and time
consuming. Moreover, you do not have accurate control over the time
between each sample or channel. Instead you can use hardware timing,
which uses a buffer in computer memory, to acquire data more efficiently.
Programmatically, you need to include the timing function and specify the
sample rate and the sample mode (finite). As with other functions, you can
acquire multiple samples for a single channel or multiple channels.
With NI-DAQmx, you also can gather data from multiple channels. For
instance, you might want to monitor both the fluid level in the tank and the
temperature. In such a case, you need two transducers connected to two
channels on the device.
Acquire Continuously
If you want to view, process, or log a subset of the samples as they are
acquired, you need to continually acquire samples. For these types of
applications, set the sample mode to continuous.
Task Triggering
When a device controlled by NI-DAQmx does something, it performs an
action. Two very common actions are producing a sample and starting a
waveform acquisition. Every NI-DAQmx action needs a stimulus or cause.
When the stimulus occurs, the action is performed. Causes for actions are
called triggers. The start trigger starts the acquisition. The reference trigger
establishes the reference point in a set of input samples. Data acquired up to
the reference point is pretrigger data. Data acquired after the reference point
is posttrigger data.
Scenario
Build a VI that measures the voltage signal on channel AI1 of the DAQ
device. The VI begins measuring when a digital trigger is pressed and the
Power switch on the front panel is on. The VI stops measuring when the
Power switch on the front panel is off.
Design
User Interface Inputs and Outputs
Implementation
In the following steps, you build the front panel shown in Figure 8-7.
❑ Rename the waveform chart Analog Input Data. You set up the
scaling for the chart later in this exercise.
❑ Create two free labels, Off and On, using the Labeling tool.
In the following steps, you build the block diagram shown in Figure 8-8.
5. Set up the DAQ Assistant to acquire data on AI1 at 50KHz when the
digital trigger is pressed. If you are using a simulated device, acquire the
data without need of a trigger.
❑ Set the Rate (Hz) in the Clock Settings section of theTask Timing
tab to 20k.
❑ If you are using the DAQ Signal Accessory, switch to the Task
Triggering tab. If you are using a NI-DAQmx Simulated Device,
click the OK button and continue to step 6.
6. Click OK when the DAQ Assistant asks if you would like to have a
While Loop automatically generated. Notice that it creates the While
Loop, status Unbundle by Name, Or function and a Stop button for you.
7. Delete the Stop button; you use the Power switch instead.
❑ Click OK.
10. Place a Simple Error Handler VI to the right of the While Loop.
❑ Use the Labeling tool to change the last value on the X Scale of the
Waveform Chart to 100.
Testing
1. If you are using the DAQ Signal Accessory, confirm that a wire connects
the sine function generator to analog in channel 1.
2. Use the Operating Tool to put the Power switch in the On position.
Hardware
❑ Press the digital trigger button on the DAQ Signal Accessory. The
waveform chart should start displaying a sine wave.
❑ Change the frequency of the sine wave using the Frequency Adjust
dial on the DAQ Signal Accessory.
No Hardware
❑ The waveform chart should start displaying a sine wave. You do not
use a trigger because you cannot set up a digital trigger on a
simulated device because there is no physical trigger to switch.
4. Switch the Power switch to the Off position when you are finished. The
VI should stop.
5. What happens if you start the VI with the switch in the Off position? Is
this desired behavior?
❑ Use the Operating tool to place the Power switch in the On position.
7. Run the VI. Does the Power switch behave as you expect?
E. Analog Output
Analog output is the process of generating electrical signals from your
computer. Analog output is generated by performing digital-to-analog
(D/A) conversions. The available analog output types for a task are voltage
and current.
Task Timing
When performing analog output, the task can be timed to Generate
1 Sample, Generate n Samples, or Generate Continuously.
Generate 1 Sample
Use single updates if the signal level is more important than the generation
rate. For example, generate one sample at a time if you need to generate a
constant, or DC, signal. You can use software timing to control when the
device generates a signal.
This operation does not require any buffering or hardware timing. For
example, if you need to generate a known voltage to stimulate a device,
a single update would be an appropriate task.
Generate n Samples
One way to generate multiple samples for one or more channels is to
generate single samples in a repetitive manner. However, generating a single
data sample on one or more channels over and over is inefficient and time
consuming. Moreover, you do not have accurate control over the time
between each sample or channel. Instead, you can use hardware timing,
which uses a buffer in computer memory to generate samples more
efficiently.
You can use software timing or hardware timing to control when a signal is
generated. With software timing, the rate at which the samples are generated
is determined by the software and operating system instead of by the
measurement device. With hardware timing, a TTL signal, such as a clock
on the device, controls the rate of generation. A hardware clock can run
much faster than a software loop. A hardware clock is also more accurate
than a software loop.
Note Some devices do not support hardware timing. Consult the device documentation
if you are unsure if the device supports hardware timing.
Generate Continuously
Continuous generation is similar to Generate n Samples, except that an
event must occur to stop the generation. If you want to continuously
generate signals, such as generating a non-finite AC sine wave, set the
timing mode to continuous.
Task Triggering
When a device controlled by NI-DAQmx does something, it performs an
action. Two very common actions are producing a sample and starting a
generation. Every NI-DAQmx action needs a stimulus or cause. When the
stimulus occurs, the action is performed. Causes for actions are called
triggers. A start trigger starts the generation.
Digital-to-Analog Conversion
Digital-to-analog conversion is the opposite of analog-to-digital conversion.
In digital-to-analog conversion, the data starts in the computer. The data
might have been acquired earlier using analog input or may have been
generated by software on the computer. A digital-to-analog converter (DAC)
accepts this data and uses it to vary the voltage on an output pin over time.
The DAC generates an analog signal that the DAC can send to other devices
or circuits.
A DAC has an update clock that tells the DAC when to generate a new value.
The function of the update clock is similar to the function of the sample
clock for an analog-to-digital converter (ADC). At each cycle the clock, the
DAC converts a digital value to an analog voltage and creates an output as a
voltage on a pin. When used with a high speed clock, the DAC can create a
signal that appears to vary constantly and smoothly.
F. Counters
A counter is a digital timing device. You typically use counters for event
counting, frequency measurement, period measurement, position
measurement, and pulse generation.
• Count Register—Stores the current count of the counter. You can query
the count register with software.
• Source—An input signal that can change the current count stored in the
count register. The counter looks for rising or falling edges on the source
signal. Whether a rising or falling edge changes the count is software
selectable. The type of edge selected is referred to as the active edge of
the signal. When an active edge is received on the source signal, the
count changes. Whether an active edge increments or decrements the
current count is also software selectable.
• Gate—An input signal that determines if an active edge on the source
changes the count. Counting can occur when the gate is high, low, or
between various combinations of rising and falling edges. Gate settings
are made in software.
• Output—An output signal that generates pulses or a series of pulses,
otherwise known as a pulse train.
When you configure a counter for simple event counting, the counter
increments when an active edge is received on the source. In order for the
counter to increment on an active edge, the counter must be armed or started.
A counter has a fixed number it can count to as determined by the resolution
of the counter. For example, a 24-bit counter can count to:
When a 24-bit counter reaches 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.
Scenario
You have been asked to build a VI that counts pulses from the quadrature
encoder on the DAQ Signal Accessory.
Design
Quadrature Encoder
A 24-pulse per revolution mechanical quadrature encoder measure the
position of a shaft as it rotates. The DAQ signal accessory quadrature
encoder is a knob located in the upper central portion of the top panel. The
quadrature encoder produces two pulse train outputs corresponding to the
shaft position as you rotate the knob. Depending on the direction of rotation,
phase A leads phase B by 90° or phase B leads phase A by 90°.
External Inputs
• Counter 0 Source (PFI8): Phase A of quadrature encoder
• Counter 0 Up/Down (DIO6): Phase B of quadrature encoder
Implementation
1. Open a blank VI and build the front panel shown in Figure 8-9.
Testing
1. On the DAQ Signal Accessory, confirm that the A output of the
quadrature encoder is wired to the SOURCE input of counter 0.
G. Digital I/O
Digital signals are electrical signals that transfer digital data over a wire.
These signals typically have only two states: on and off, also known as high
and low, or 1 and 0. When sending a digital signal across a wire, the sender
applies a voltage to the wire and the receiver uses the voltage level to
determine the value being sent. The voltage ranges for each digital value
depend on the voltage level standard being used. Digital signals have many
uses; the simplest application of a digital signal is controlling or measuring
digital or finite state devices such as switches and LEDs. Digital signals also
can transfer data; you can use them to program devices or communicate
between devices. In addition, you can use digital signals as clocks or triggers
to control or synchronize other measurements.
You can use the digital lines in a DAQ device to acquire a digital value. This
acquisition is based on software timing. On some devices, you can configure
the lines individually to either measure or generate digital samples. Each
line corresponds to a channel in the task.
You can use the digital port(s) in a DAQ device to acquire a digital value
from a collection of digital lines. This acquisition is based on software
timing. You can configure the ports individually to either measure or
generate digital samples. Each port corresponds to a channel in the task.
Scenario
Write a VI that converts the number of events generated by the quadrature
encoder to a digital number to display on the LEDs on the DAQ Signal
Accessory. Because there are only four LEDs, you are limited to a number
between 0 and 15 (24). For numbers greater than 15 and less than 0, the
LEDs should continue changing as though there were more LEDs available.
Design
Digital I/O
Each LED is wired to a digital line on the DAQ device. The lines are
numbered 0, 1, 2, and 3, starting with the LED on the right. You can write
to these lines individually or as a digital port. However, the digital port
includes all 8 DIO lines. Because the quadrature encoder uses DIO6 for
up/down counting, you cannot write to DIO6. Therefore, in this example,
you should write a Boolean array to digital lines 0–4.
Flowchart
When a number is converted to a Boolean array, the number of elements in
the array depends on the representation of the number used. If the number
is 32-bytes, there are 32 elements in the Boolean array. However, because
there are only four LEDs, you only need the first 4 elements of the array.
Acquire Counter 0
Output
No
Convert Output to
a Boolean array
Reduce the
array to a
4 element array
Write Boolean
array to digital Stop?
lines 0 - 3
Yes
Implementation
1. Open Count Events.vi in the C:\Exercises\LabVIEW
Basics I\Count Events directory.
5. Delete the wire connected from the error terminal to the status element
of the Unbundle by Name functions.
6. Enlarge the While Loop and increase the amount of space between the
DAQ Assistant and the stop conditions.
8. Create a subarray containing the first four elements of the Boolean array.
❑ Select Dev1»line 0–line 3 for the physical channels and click the
Finish button.
❑ For each line, select Invert Line because the LEDs use negative
logic.
Note In this exercise, you use individual lines rather than a port because DIO6 is used
by Phase B of the Quadrature Encoder.
Testing
1. Display the front panel.
3. Turn the quadrature encoder and observe the changes on the DAQ Signal
Accessory.
Self-Review: Quiz
1. You are reading a signal at 50kHz. You want to acquire the signal until
a stop trigger is pressed. Which task timing should you use?
a. Acquire 1 Sample
b. Acquire N Samples
c. Acquire Continuously
Self-Review: Quiz
1. You are reading a signal at 50kHz. You want to acquire the signal until
a stop trigger is pressed. Which task timing should you use?
a. Acquire 1 Sample
b. Acquire N Samples
c. Acquire Continuously
Notes
Topics
A. Instrument Control
B. GPIB
C. Serial Port Communication
D. Using Other Interfaces
E. Software Architecture
F. Instrument I/O Assistant
G. VISA
H. Instrument Drivers
A. Instrument Control
When you use a PC to automate a test system, you are not limited to the type
of instrument you can control. You can mix and match instruments from
various categories. The most common categories of instrument interfaces
are GPIB, serial, modular instruments, and PXI modular instruments.
Additional types of instruments include image acquisition, motion control,
USB, Ethernet, parallel port, NI-CAN, and other devices.
When you use PCs to control instruments, you need to understand properties
of the instrument, such as the communication protocols to use. Refer to the
instrument documentation for information about the properties of an
instrument.
B. GPIB
The ANSI/IEEE Standard 488.1-1987, also known as General Purpose
Interface Bus (GPIB), describes a standard interface for communication
between instruments and controllers from various vendors. GPIB, or
General Purpose Interface Bus, instruments offer test and manufacturing
engineers the widest selection of vendors and instruments for general-
purpose to specialized vertical market test applications. GPIB instruments
are often used as stand-alone benchtop instruments where measurements are
taken by hand. You can automate these measurements by using a PC to
control the GPIB instruments.
You can obtain faster data rates with HS488 devices and controllers. HS488
is an extension to GPIB that most NI controllers support.
Note Refer to the National Instruments GPIB support Web site at ni.com/support/
gpibsupp.htm for more information about GPIB.
1
3
76.6F
You must specify four parameters for serial communication: the baud rate
of the transmission, the number of data bits that encode a character, the
sense of the optional parity bit, and the number of stop bits. A character
frame packages each transmitted character as a single start bit followed by
the data bits.
Baud rate is a measure of how fast data moves between instruments that use
serial communication.
Data bits are transmitted upside down and backwards, which means that
inverted logic is used and the order of transmission is from least significant
bit (LSB) to most significant bit (MSB). To interpret the data bits in a
character frame, you must read from right to left and read 1 for negative
voltage and 0 for positive voltage.
An optional parity bit follows the data bits in the character frame. The parity
bit, if present, also follows inverted logic. This bit is included as a means of
error checking. You specify ahead of time for the parity of the transmission
to be even or odd. If you choose for the parity to be odd, the parity bit is set
in such a way so the number of 1s add up to make an odd number among the
data bits and the parity bit.
The last part of a character frame consists of 1, 1.5, or 2 stop bits that are
always represented by a negative voltage. If no further characters are
transmitted, the line stays in the negative (MARK) condition. The
transmission of the next character frame, if any, begins with a start bit of
positive (SPACE) voltage.
The following figure shows a typical character frame encoding the letter m.
Space
Mark
Bit Time
Character Frame
RS-232 uses only two voltage states, called MARK and SPACE. In such a
two-state coding scheme, the baud rate is identical to the maximum number
of bits of information, including control bits, that are transmitted per second.
The output signal level usually swings between +12 V and –12 V. The dead
area between +3 V and –3 V is designed to absorb line noise.
Interpreting the data bits for the transmission yields 1101101 (binary) or
6D (hex). An ASCII conversion table shows that this is the letter m.
This transmission uses odd parity. There are five ones among the data bits,
already an odd number, so the parity bit is set to 0.
transmission rate. The hardware on one end or the other of the serial link
might not be able to reach these rates, for various reasons.
USB and ethernet interfaces transform USB ports or ethernet ports into
asynchronous serial ports for communication with serial instruments. You
can install and use these interfaces as standard serial ports from your
existing applications.
USB, ethernet, and IEEE 1394 controllers transform any computer with
these ports into a full-function, Plug and Play, IEEE-488.2 Controller that
can control up to 14 programmable GPIB instruments.
E. Software Architecture
The software architecture for instrument control using LabVIEW is similar
to the architecture for DAQ. Instrument interfaces such as GPIB include a
set of drivers. Use MAX to configure the interface. VISA, Virtual
Instrument Software Architecture, is a common API to communicate with
the interface drivers and is the preferred method used when programming
for instrument control in LabVIEW, because VISA abstracts the type of
interface used. Many LabVIEW VIs used for instrument control use the
VISA API. For example, the Instrument I/O Assistant is a LabVIEW
Express VI that can use VISA to communicate with message-based
instruments and convert the response from raw data to an ASCII
representation. Use the Instrument I/O Assistant when an instrument driver
is not available. In LabVIEW, an instrument driver is a set of VIs specially
written to communicate with an instrument.
Note GPIB drivers are available on the LabVIEW Installer CD-ROM and most GPIB
drivers are available for download at ni.com/support/gpib/versions.htm.
Always install the newest version of these drivers unless otherwise instructed in the
release notes.
Note (Mac OS and UNIX) Refer to documentation supplied with your GPIB interface
device for information about configuring and testing the interface.
Description
1. Configure the NI Instrument Simulator.
❑ Set the left bank of switches on the side of the box to match
Figure 9-4.
❑ Verify that both the Power and Ready LEDs are lit.
OFF
ON
1
2
❑ Select the GPIB interface and click the Properties button on the
toolbar to display the Properties dialog box.
❑ Examine but do not change the settings for the GPIB interface.
❑ Make sure the GPIB interface is still selected in the Devices and
Interfaces section.
5. Set a VISA alias of devsim for the NI Instrument Simulator so you can
use the alias instead of having to remember the primary address.
To launch the Instrument I/O Assistant, place the Instrument I/O Assistant
Express VI on the block diagram in LabVIEW. The Instrument I/O
Assistant Express VI is available in the Instrument I/O category of the
Functions palette. The Instrument I/O Assistant configuration dialog box
appears. If it does not appear, double-click the Instrument I/O Assistant
icon. Complete the following steps to configure the Instrument I/O
Assistant.
1. Select an instrument. Instruments that have been configured in MAX
appear in the Select an instrument pull-down menu.
2. Choose a Code generation type. VISA code generation allows for more
flexibility and modularity than GPIB code generation.
3. Select from the following communication steps using the Add Step
button:
• Query and Parse—Sends a query to the instrument, such as *IDN?
and parses the returned string. This step combines the Write
command and Read and Parse command.
• Write—Sends a command to the instrument.
• Read and Parse—Reads and parses data from the instrument
4. After adding the desired number of steps, click the Run button to test
the sequence of communication that you have configured for the
Express VI.
5. Click the OK button to exit the Instrument I/O Assistant configuration
dialog box.
LabVIEW adds input and output terminals to the Instrument I/O Assistant
Express VI on the block diagram that correspond to the data you receive
from the instrument.
To view the code generated by the Instrument I/O Assistant, right-click the
Instrument I/O Assistant icon and select Open Front Panel from the
shortcut menu. This converts the Express VI to a subVI. Switch to the block
diagram to see the code generated.
Note After you convert an Express VI to a subVI, you cannot reconvert the Express VI.
❑ Set the left bank of switches on the side of the box to match Figure 9-
6.
1
2
3
OFF
ON
❑ Verify that the Power, Ready, and Listen LEDs are lit to indicate that
the device is in serial communication mode.
You build a block diagram similar to the one in Figure 9-7 in the following
steps.
❑ Click Write.
Note The Instrument Simulator returns the byte size of the response, the termination
character, the response, then another termination character. Therefore, after *IDN? is
sent to the instrument, the response must be read twice; once to retrieve the size of the
response, and once to retrieve the response.
❑ Click the Run button (not the Run this step button). The Run
button runs the entire sequence.
❑ Click the Auto parse button. The value returned is the size in bytes
of the query response.
❑ Click the Auto parse button. The value returned is the identification
string of the NI Instrument Simulator.
Tip To allow LabVIEW to handle errors automatically, do not connect a Simple Error
Handler VI to error out.
❑ Set the left bank of switches on the side of the box to match Figure 9-
10.
OFF
ON
1
2
❑ Verify that both the Power and Ready LEDs are lit.
You build a block diagram similar to the one in Figure 9-11 in the following
steps.
❑ Click Query and Parse to write and read from the Instrument
Simulator.
❑ Click the Run this step button. If no error warning appears in the
lower half of the dialog box, this step has successfully completed.
❑ To parse the data received, click the Auto parse button. The data
returned is a random numeric value.
❑ Click the OK button to exit the I/O Assistant and return to the block
diagram.
Tip To allow LabVIEW to handle errors automatically, do not connect a Simple Error
Handler VI to error out.
9. Display the front panel. The front panel should be similar to the front
panel in Figure 9-13.
G. VISA
Virtual Instrument Software Architecture (VISA) is the lower layer of
functions in the LabVIEW instrument driver VIs that communicates with
the driver software. VISA by itself does not provide instrumentation
programming capability. VISA is a high-level API that calls low-level
drivers. VISA can control VXI, GPIB, serial, or computer-based
instruments and makes the appropriate driver calls depending on the type of
instrument used. When debugging VISA problems, remember that an
apparent VISA problem could be an installation problem with one of the
drivers that VISA calls.
Interface Syntax
Asynchronous serial ASRL[board][::INSTR]
You can use an alias you assign in MAX instead of the instrument
descriptor. (Mac OS) Edit the visaconf.ini file to assign a VISA alias.
(UNIX) Use the visaconf utility.
Figure 9-14 shows how to send the identification query command *IDN? to
the instrument connected to the COM2 serial port. The VISA Configure
Serial Port VI opens communication with COM2 and sets it to 9,600 baud,
eight data bits, odd parity, one stop bit, and XON/XOFF software
handshaking. Then, the VISA Write function sends the command. The
VISA Read function reads back up to 200 bytes into the read buffer, and the
Simple Error Handler VI checks the error condition.
Note The VIs and functions located on the Functions»All Functions»Instrument I/O»
Serial palette are also used for parallel port communication. You specify the VISA
resource name as being one of the LPT ports. For example, you can use MAX to
determine that LPT1 has a VISA resource name of ASRL10::INSTR.
Description
This VI uses VISA to communicate with either a serial or a GPIB interface
to an instrument. The VI can send one buffer of data to the instrument, and
read one buffer back. If using GPIB, the user specifies how many bytes to
read from the bus. If using serial, the VI determines how many bytes are
available, and reads them all.
1. Open the VISA Write & Read.vi in the C:\Exercises\
LabVIEW Basics I\VISA Write & Read directory.
Figure 9-16. GPIB portion of the VISA Write & Read VI Block Diagram
Test A: Serial
1. Configure the NI Instrument Simulator to communicate through the
serial port. It may still be set up from the last exercise.
❑ Set the left bank of switches on the side of the box to match Figure 9-
17.
1
2
3
OFF
ON
❑ Verify that the Power, Ready and Listen LEDs are lit.
2. Enter values into the controls in preparation for communicating with the
instrument. You do not need to enter a value in the byte count, as this
control is only used for GPIB communication.
4. The top of the instrument simulator lists other commands that are
recognized by this instrument. Try other commands in this VI.
Test B: GPIB
1. Configure the NI Instrument Simulator to communicate through the
GPIB interface.
❑ Set the left bank of switches on the side of the box to match Figure 9-
18.
OFF
ON
1
2
❑ Verify that both the Power and Ready LEDs are lit.
2. Enter values into the controls in preparation for communicating with the
instrument.
4. The top of the instrument simulator lists other commands that are
recognized by this instrument. Try other commands in this VI.
H. Instrument Drivers
Imagine the following scenario. You wrote a LabVIEW VI that
communicates with a specific oscilloscope in your lab. Unfortunately, the
oscilloscope no longer works, and you must replace it. However, this
particular oscilloscope is no longer made. You found a different brand of
oscilloscope that you want to purchase, but your VI no longer works with
the new oscilloscope. You must rewrite your VI.
When you use an instrument driver, the driver contains the code specific to
the instrument. Therefore, if you change instruments, you must replace only
the instrument driver VIs with the instrument driver VIs for the new
instrument, which greatly reduces your redevelopment time. Instrument
drivers help make test applications easier to maintain because the drivers
contain all the I/O for an instrument in one library, separate from other code.
When you upgrade hardware, upgrading the application is easier because
the instrument driver contains all the code specific to that instrument.
For the external structure of the instrument driver, the user interacts with the
instrument driver using an API or an interactive interface. Usually, the
interactive interface is used for testing or for end-users. The API is accessed
through LabVIEW. The instrument driver communicates with the
instrument using VISA.
Internally, the VIs in an instrument driver are organized into six categories.
These categories are summarized in the following table.
Category Description
Initialize The initialize VI establishes communication with
the instrument and is the first instrument driver VI
called.
Description
In this exercise, you install the instrument driver the NI Instrument
Simulator. After installation, you explore the VIs that the instrument driver
provides and the example programs that are added to the NI Example
Finder.
11. Explore the palette using the Context Help window to familiarize
yourself with the functionality.
16. Prepare the Instrument Simulator. This VI can communicate with the
instrument through serial or GPIB.
1
2
3
OFF
ON
OFF
ON
1
2
17. Select the communication type on the VISA Resource Name control.
❑ If you are using serial, select the resource (COM1 or COM2) that the
serial cable is connected to.
19. Explore the block diagram of the VI. Do not save changes.
23. Select the same VISA Resource Name you selected in Step 17.
28. Close the VI and the NI Example Finder when you are finished. Do not
save changes.
Notes
You have learned how to acquire data and how to display it, but analysis and
storage of your data is usually a very important part of any project. In this
lesson, you learn about manipulating strings, analyzing numerical data,
processing signals, and storing ASCII data.
Topics
A. Analyzing and Processing Numeric Data
B. Reading and Writing Data to File
Other examples for inline analysis are applications where the parameters of
the measurement need to be adapted to the characteristics of the measured
signal. One case is where one or more signals need to be logged, but these
change very slowly except for sudden bursts of high-speed activity. In order
to reduce the amount of data logged, the application would have to quickly
recognize the need for a higher sampling rate, and reduce it when the burst
is over. By measuring and analyzing certain aspects of the signal, the
application can adapt to the circumstances and enable the appropriate
execution parameters. Although this is only one example, there are
thousands of applications where a certain degree of intelligence – the ability
to make decisions based on various conditions – and adaptability are
required, which can only be provided by adding analysis algorithms to the
application.
Use offline analysis when the results do not need to be obtained in real-time
fashion in order to make decisions on the process. Offline analysis
applications require only that sufficient computational resources are
available. The main intent of such applications is to identify cause and effect
of variables affecting a process by correlating multiple data sets. These
applications generally require importing data from custom binary or ASCII
files and commercial databases such as Oracle, Access, and other SQL/
ODBC-enabled databases. After the data is imported into LabVIEW, users
perform several or hundreds of available analysis routines, manipulate the
data, and arrange it in a specific format for reporting purposes.
You can also perform significant data reduction and formatting before
storing it to disk, so that when the stored data is retrieved for further
analysis, it is easier to handle.
Analysis Categories
LabVIEW offers hundreds of built-in analysis functions that cover different
areas and methods of extracting information from acquired data. You can
use these functions as is, or modify, customize, and extend them to suit a
particular need. These functions are categorized in the following groups:
Measurement, Signal Processing, Mathematics, Image Processing, Control,
Simulation, and Application Areas.
• Measurement
– Amplitude and Level
– Frequency (Spectral) Analysis
– Noise and Distortion
– Pulse and Transition
– Signal and Waveform Generation
– Time Domain Analysis
– Tone Measurements
• Signal Processing
– Digital Filters
– Convolution and Correlation
– Frequency Domain
– Joint Time-Frequency Analysis (Signal Processing Toolset)
– Sampling/Resampling
– Signal Generation
– Super-Resolution Spectral Analysis (Signal Processing Toolset)
– Transforms
– Time Domain
– Wavelet and Filter Bank Design (Signal Processing Toolset)
– Windowing
• Mathematics
– Basic Math
– Curve Fitting and Data Modeling
– Differential Equations
– Interpolation and Extrapolation
– Linear Algebra
– Nonlinear Systems
– Optimization
– Root Finding
– Special Functions
– Statistics and Random Processes
• Image Processing
– Blob Analysis and Morphology
– Color Pattern Matching
– Filters
– High-Level Machine Vision Tools
– High-Speed Grayscale Pattern Matching
– Image Analysis
– Image and Pixel Manipulation
– Image Processing
– Optical Character Recognition
– Region-of-Interest Tools
• Control
– PID and Fuzzy Control
• Simulation
– Simulation Interface (Simulation Interface Toolkit)
• Application Areas
– Machine Condition Monitoring (Order Analysis Toolset)
– Machine Vision (IMAQ, Vision Builder)
– Motion Control
– Sound and Vibration (Sound and Vibration Analysis Toolset)
Description
For each scenario, circle which forms of analysis to use. Most scenarios use
more than one form.
Scenario 1
The failure rate of your manufacturing line is related directly to the speed of
production. Monitor the failure rate programmatically. If the failure rate is
greater than 3 %, decrease the speed of the line. If the failure rate is less than
2 %, increase the speed of the line.
Scenario 2
You are listening to a radio station. The frequency components of the radio
station signal are determined and recorded to file. If you have difficulty
hearing the radio station, you tell the VI to pass the signal through a filter
before recording the data.
Scenario 3
You are recording temperature and pressure data. Once a week, you prepare
a report for your manager correlating the temperature and pressure trends
during thunderstorms.
Scenario 4
You are performing stress analysis on a bridge. During rush hour, you must
also record vibration data on the bridge. It is considered rush hour when
more than 100 cars use the bridge in 5 minutes. A sensor records the number
of cars crossing the bridge.
Scenario 1
• Inline Analysis
• Programmatic Analysis
Inline analysis occurs to determine the speed of the line and the failure rate.
Programmatic analysis occurs to determine when to change the speed of the
line.
Scenario 2
• Inline Analysis
• Interactive Analysis
The user tells the VI when to apply the filter, which means the analysis is
interactive. However, because the filtering happens immediately when the
user specifies, the analysis is inline.
Scenario 3
• Offline Analysis
The data can be correlated at any point; does not need to occur as the data is
acquired. When it is analyzed, it is most likely be analyzed
programmatically. However, without more information, you cannot
determine whether programmatic or interactive analysis is appropriate.
Scenario 4
• Programmatic Analysis
The VI uses the sensor to determine when rush hour is occurring and
immediately begins recording the additional data. Since no information is
given on how the data is analyzed, cannot determine whether inline or
offline analysis is appropriate.
File Formats
LabVIEW can use or create the following file formats: Binary, ASCII,
LVM, and TDM.
• Binary— Binary files are the underlying file format of all other file
formats.
• ASCII—An ASCII file is a specific type of binary file that is a standard
used by most programs. It consists of a series of ASCII codes. ASCII
files are also called text files.
• LVM— The LabVIEW measurement data file (.lvm) is a tab-delimited
text file you can open with a spreadsheet application or a text-editing
application. The .lvm file includes information about the data, such as
the date and time the data was generated. This file format is a specific
type of ASCII file created for LabVIEW.
• TDM—This file format is a specific type of binary file created for
National Instruments products. It actually consists of two separate files:
an XML section contains the data attributes, and a binary file for the
waveform.
In this course, you learn about creating text (ASCII) files. Use text files
when you want to access the file from another application, if disk space and
file I/O speed are not crucial, if you do not need to perform random access
read or writes, and if numeric precision is not important.
You used an LVM file in Lesson 2. To learn more about binary and TDM
files, refer to the LabVIEW Help or the LabVIEW Basics II course.
system to help you organize and locate the data files LabVIEW generates.
By default, the Write LabVIEW Measurement File Express VI stores the
.lvm files it generates in this directory, and the Read LabVIEW
Measurement File Express VI reads from this directory. The Default Data
Directory constant, shown at left, and the Default Data Directory property
also return the LabVIEW Data directory by default.
Select Tools»Options and select Paths from the top pull-down menu to
specify a different default data directory. The default data directory differs
from the default directory, which is the directory you specify for new VIs,
custom controls, VI templates, or other LabVIEW documents you create.
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 that file, device, or network
connection. All operations you perform on open files, devices, or network
connections use the refnums to identify each object.
The examples in Figure 10-2 and Figure 10-1 show the advantages of using
disk streaming. In the first example, the VI must open and close the file
during each iteration of the loop. The second example uses disk streaming
to reduce the number of times the VI must interact with the operating system
to open and close the file. By opening the file once before the loop begins
and closing it after the loop completes, you save two file operations on each
iteration of the loop.
Avoid placing the high-level VIs in loops, because the VIs perform open and
close operations each time they run.
Scenario
The business card contacts for your company are stored in the Windows
Address Book. You must extract specific data from an individual business
card into a LabVIEW text display.
Design
Flowchart
To understand how to design this program, you must first view the text file
created by the Address Book.
2. Select File»Open.
BEGIN:VCARD¶
VERSION:2.1¶
N:McGillicuttey;Heather;Louise;Ms.¶
FN:Heather Louise McGillicuttey¶
NICKNAME:Lou¶
ORG:National Instruments;Internal Affairs¶
TITLE:President¶
NOTE:I am an imaginary person.¶
TEL;WORK;VOICE:512-555-1212¶
TEL;HOME;VOICE:512-555-1212¶
TEL;CELL;VOICE:512-555-1212¶
TEL;PAGER;VOICE:512-555-1212¶
TEL;WORK;FAX:512-555-1212¶
TEL;HOME;FAX:512-555-1212¶
ADR;WORK:;Corner;11500 N. Mopac Expressway;Austin;Texas;78759;USA¶
LABEL;WORK;ENCODING=QUOTED-PRINTABLE:Corner=0D=0A11500 N. Mopac
Expressway=0D=0AAustin, Texas 78759=0D=0AUSA¶
ADR;HOME:;;111 Easy Street;Austin;Texas;78759;USA¶
LABEL;HOME;ENCODING=QUOTED-PRINTABLE:111 Easy Street=0D=0AAustin, Texas
78759=0D=0AUSA¶
EMAIL;PREF;INTERNET:[email protected]¶
REV:20050818T150422Z¶
END:VCARD
Notice that the file contains beginning and end tags. You can use the end tag
to determine when to stop reading the file. The file also had a end of line at
the end of each tag. There is also a colon between the tag and the
corresponding data. There is a semicolon separating different parts of a each
data element. All of this information is useful when writing a VI meant to
parse data.
No
Create an array of
Seperate the data
clusters (tag and
into two strings at End of File? Yes Close File
display name) for
the colon
data of interest
No
Get data from
specificed index
Replace
semicolons with
carriage returns
Yes
Display 2D Array
of data
This program consists of two loops. One loop reads the data from the
business card file, line by line. The second loop chooses which pieces of
data to display, replaces each tag name with a more meaningful name, and
replaces the semicolons with end of line characters. The flowchart elements
in Figure 10-3 with a thicker border represent VIs that have already been
built for you for this exercise.
Implementation
1. Create a business card entry in the Windows Address Book.
❑ Click Save.
In the following steps, you create a block diagram similar to Figure 10-4. In
this block diagram, you read the vCard you just created as a 2D array of
strings. The first dimension of the array contains the tags; the second
dimension contains the data.
❑ Place a Read From Text File function inside the While Loop.
❑ Wire the text terminal of the Read Text function to the string
terminal of the Match Pattern function.
❑ Right-click the output tunnel and select Enable Indexing from the
shortcut menu.
❑ Right-click the output tunnel and select Enable Indexing from the
shortcut menu.
7. Stop the While Loop if an error occurs or when the end of the file has
been reached.
❑ Wire the error out terminal of the Read From Text File function to
create an output tunnel on the While Loop.
❑ Right-click the tunnel and select Replace with Shift Register from
the shortcut menu. Your cursor should change into a shift register,
indicating that you should choose the input side of the shift register.
❑ Click the error input tunnel on the right side of the While Loop to
change the input tunnel to a shift register.
❑ Wire the error out from the Read from Text File function to the
Unbundle By Name function.
❑ Wire the status element of the error cluster to the x input of the Or
function.
❑ Select Create»Constant.
❑ Wire the refnum out terminal of the Read From Text File function
to create an output tunnel on the While Loop.
❑ Right-click the tunnel and select Replace with Shift Register. Your
cursor should change into a shift register, indicating that you should
choose the input side of the shift register.
❑ Click the left refnum input tunnel of the While Loop to replace the
tunnel with a shift register.
❑ Wire the refnum output tunnel to the refnum input terminal of the
Close File function.
❑ Wire the error output tunnel to the error in terminal of the Close File
function.
❑ Right-click the before the substring indexed output tunnel and select
Create»Indicator from the shortcut menu.
❑ Place a Simple Error Handler to the right of the Close File function.
❑ Wire the error out terminal from the Close Function to the error in
terminal of the Simple Error Handler.
Figure 10-5 shows an example of the front panel after running this VI.
Notice that it is very similar to opening the text file. The names used for each
category are not very clear. In the rest of this exercise, you modify the VI so
that it parses the data for you, making it more legible to a user.
In the following steps, you add to the block diagram to parse the data in the
arrays. To simplify this process, two VIs have already been built for you.
One of these VIs creates an array where each array element is a cluster
containing a tag and a replacement name for the tag. The second VI opens a
dialog box that displays the final data in a table.
17. Delete the wire connecting the Close File function to the Simple Error
Handler.
18. Move the Simple Error Handler out of the way. You use this VI later in
this exercise.
❑ Place the Vcard Tags.vi to the right of the Close File function.
This VI is located in the C:\Exercises\LabVIEW
Basics I\Read VCard directory.
Tip Use the Select a VI category of the Functions palette to locate a VI that is not part
of the Functions palette. After you have placed the VI on the block diagram, you can
double-click the VI to open it and examine its block diagram.
❑ Wire the error out terminal from the Close File function to the
error in terminal of the Vcard Tags VI.
❑ Wire the Array terminal from the Vcard Tags VI to create an input
tunnel on the For Loop. Notice that indexing has automatically been
enabled.
❑ Wire the tag array to the 1D array terminal of the Search 1D Array
function. The tag array is the top indexed output tunnel of the While
Loop. Disable indexing on the For Loop tag away tunnel.
❑ Wire the data array to the array terminal of the Index Array
function. The data array is the bottom indexed output tunnel of the
While Loop. Disable indexing on the For Loop data away tunnel.
❑ Place a Search and Replace String function to the right of the Index
Array function.
❑ Wire the element terminal of the Index Array to the input string
terminal of the Search and Replace String.
❑ Wire the End of Line Constant to the replace string terminal of the
Search and Replace String function.
❑ Wire the result string terminal for the Search and Replace String
function to the input of the Trim Whitespace VI.
❑ Wire the error cluster from the Vcard Tags VI to the Table Dialog VI.
❑ Move the Simple Error Handler VI to the right of the Table Dialog
VI.
❑ Wire the error out terminal of the Table Dialog VI to the error in
terminal of the Simple Error Handler VI.
Testing
1. Run the VI.
2. When prompted, navigate to the business card file you created earlier in
this exercise.
Self-Review: Quiz
1. You are writing a testing application to test the audio characteristics of
microphones as they are manufactured. For each microphone you test,
you must acquire 1 second of sound data and compare the data to an
ideal signal. You then need to log the acquired data and a pass/fail status
to a file. What type of analysis should you use?
a. Inline programmatic analysis
b. Offline programmatic analysis
c. Interactive analysis
2. For the situation described in the previous question, your continuously
running test program logs to a single file the results of all tests that occur
in one hour. If you are concerned about the execution speed of your
program, should you use low-level or high-level File I/O VIs?
a. Low-level file I/O VIs
b. High-level file I/O VIs
3. If you want to view data in a text editor such as Notepad, what file
format should you use to save the data?
a. ASCII
b. TDM
Notes
There are many design patterns for LabVIEW. Most applications use at least
one design pattern. In this course, you explore the State Machine design
pattern. Learn more about design patterns in LabVIEW Basics II.
Topics
A. Sequential Programming
B. State Programming
C. State Machines
D. Parallelism
A. Sequential Programming
In Lesson 1, Problem Solving, you designed a flow chart for a Temperature
Weather Station. The Temperature Weather Station is a set of steps:
1. Read the temperature
2. Test the temperature for limits and display warnings
3. Graph and log the temperature
After you reach the end of the sequence of events, you check to see if the
stop button has been pressed, and, if not, the sequence repeats.
Many of the VIs you write in LabVIEW accomplish sequential tasks. How
you program these sequential task can be very different. Consider the block
diagram in Figure. In this block diagram, a voltage signal is acquired, then
a dialog is presented to the user asking them to turn on the power, then the
voltage signal is acquired again, and the user is asked to turn off the power.
However, in this example, there is nothing in the block diagram to force the
execution order of these events. Any one of these events could happen first.
Figure 11-4. Tasks that have been sequenced using Sequence Structures and an
error cluster
The best way to write this VI is to enclose the dialog boxes in a case
structure, wiring the error cluster to the case selector.
Figure 11-5. Tasks that have been sequenced using an error cluster and Case
structures
B. State Programming
Although a Sequence structure and sequentially wired subVIs both
accomplish the task, sometimes more is necessary:
❑ What if you must repeat one item in the sequence more often than the
other items?
❑ What if you must stop the program immediately, rather than waiting
until the end of the sequence?
Although your program may not have any of the above requirements, there
is always the possibility that the program must be modified in the future. For
this reason, a state programming architecture is a good choice, even if a
sequential programming structure would be sufficient.
C. State Machines
The state machine design pattern is a common and very useful design
pattern for LabVIEW. You can use the state machine design pattern to
implement any algorithm that can be explicitly described by a state diagram
or flow chart. A state machine usually implements a moderately complex
decision-making algorithm, such as a diagnostic routine or a process
monitor.
The advantage of using a state machine is that once you have created a state
transition diagram, you can build LabVIEW VIs easily.
The flow of the state transition diagram is implemented by the While Loop.
The individual states are represented by cases in the Case structure. A shift
register on the While Loop keeps track of the current state and
communicates the current state to the Case structure input.
Default Transition
Use enumerated type controls to control the initialization and transition of
state machines. There are several common design patterns used to develop
the transition code. Figure 11-7 shows a design pattern that uses a default
transition implemented for a temperature data acquisition system. For the
default transition, no code is needed to determine the next state.
This method works well if you know that the individual state always
transitions between two states. However, this method limits the scalability
of the application. If you need to modify the state to transition among more
than two states, this solution would not work and would require a major
modification of the transition code.
Note The LabVIEW State Diagram Toolkit is not included in the LabVIEW
Professional Development System, it is available for purchase separately.
The following conditions must exist in the State Diagram Toolkit state
machine:
• There must always be a default transition.
• The default transition must always have lowest priority so it is
evaluated last.
• The default transition condition must always be TRUE. You can
wire a Boolean constant to the condition output for the default
transition.
Scenario
Complete the course project using a state machine and the state flow chart
developed earlier in the course.
Design
You have already completed the design stage for this project. The inputs and
outputs and flowchart are repeated here.
Initialize
Acquisition
Time Elapsed=TRUE
and
Stop=False
Warning=TRUE
Analysis
Datalog
Time Elapsed=FALSE
and
Stop=FALSE
Time Check
Warning=FALSE
Stop=TRUE
Implementation
In the following steps, you set up the state machine in the Weather Station
UI VI.
❑ Right-click the Case structure and select Add Case for Every Value
from the shortcut menu.
5. Place a Wait function in the loop so that the processor can handle other
tasks when needed.
❑ Place a Wait (ms) function inside the While Loop, outside the Case
structure.
6. Pass the temperature cluster into the state machine so that it can be
accessed from any state.
❑ Wire the output of the Bundle function to the While Loop to create
a tunnel.
Acquisition State
Hardware
❑ Place the DAQ Assistant in the Acquisition state.
❑ Skip to step 3.
No Hardware
❑ Select the Temperature Simulator VI in the Project Explorer
window and drag it into the Acquisition state. In future steps, you
wire the inputs and outputs of the Temperature Simulator VI instead
of the DAQ Assistant.
4. Update the temperature cluster with the current temperature, upper limit,
and lower limit.
❑ Move the Upper Limit and Lower Limit terminals into the
Acquisition state.
❑ Wire the Upper Limit terminal to the T Upper Limit element of the
Unbundle by Name function.
❑ Wire the Lower Limit terminal to the T Lower Limit element of the
Unbundle by Name function.
❑ Wire the enumerated type constant to the output state shift register.
Analysis State
In previous exercises, you wrote a subVI that performs the analysis required
for this state machine: Determine Warnings VI. This VI is already added to
the project file, but needs to be placed in the main VI.
❑ Wire the enumerated type control to the output state shift register.
4. Pass the error cluster and file refnum into the state machine so that it can
be used by all states.
❑ Place the Write To Text File function in the Data Log state.
❑ Wire the output of the Format Into String function to the text input
of the Write To Text File function.
❑ Wire the error clusters to and from the Write To Text File function.
❑ Wire the file refnum to and from the Write To Text File function.
❑ Place the Close File function to the right of the state machine.
❑ Wire the error cluster and the file refnum to the Close File function.
❑ Place a Simple Error Handler to the right of the Close File function.
❑ Wire the error out terminal from the Close File function to the
Simple Error Handler.
8. Place a copy of the Weather Station State enumerated type control inside
the Data Log state.
3. Determine when half a second has passed since the last data acquisition.
❑ Place the Elapsed Time Express VI on the block diagram inside the
While Loop, but outside the Case structure.
❑ Wire the Time has Elapsed terminal from the Elapsed Time
Express VI to the case selector.
❑ Place a copy of the Weather Station State constant inside the True
case.
5. Navigate to the Time Check state if the time has not elapsed.
❑ Place a copy of the Weather Station State constant inside the False
case.
2. Determine when to stop the state machine. Stop when an error occurs or
the user has clicked the stop button, but only after a full sequence has
occurred (Acquisition, Analysis, Data Log).
❑ Wire the status element of the error cluster to the top input of the Or
function.
❑ From the Time Check state, wire the Stop button to the bottom input
of the Or function.
3. Set the Elapsed Time Express VI to start counting when the VI begins.
❑ Place a True constant outside the While Loop, to the left of the
Elapsed Time Express VI.
❑ Wire the constant to the Reset terminal of the Elapsed Time Express
VI.
Testing
1. Run the VI.
5. Modify the Lower Limit until it is higher than the current temperature
reading.
8. Modify the Upper Limit until it is lower than the current temperature
reading.
11. The Upper Limit < Lower Limit Warning should appear.
D. Parallelism
Often, you need to program multiple tasks so that they execute at the same
time. In LabVIEW tasks can run in parallel if they do not have a data
dependency between them, and if they are not using the same shared
resource. An example of a shared resource is a file, or an instrument.
You learn about LabVIEW design patterns for executing multiple tasks at
the same time in the LabVIEW Basics II course. These design patterns
include parallel loops, master/slave and producer/consumer.
Summary
The benefits of using a state machine instead of a sequential programming
structure include:
• You can change the order of the sequence.
• You can repeat individual items in the sequence.
• You can set condition to determine when an item in the sequence should
execute.
• You can stop the program at any point in the sequence.
Notes
If you searched ni.com and could not find the answers you need, contact
your local office or NI corporate headquarters. Phone numbers for our
worldwide offices are listed at the front of this manual. You also can visit the
Worldwide Offices section of ni.com/niglobal to access the branch
office Web sites, which provide up-to-date contact information, support
phone numbers, email addresses, and current events.
LabVIEW Resources
This section describes how you can receive more information regarding
LabVIEW.
LabVIEW Publications
The following publications offer more information about LabVIEW.
LabVIEW Technical Resource (LTR) Newsletter
Subscribe to LabVIEW Technical Resource to discover tips and techniques
for developing LabVIEW applications. This quarterly publication offers
detailed technical information for novice users and advanced users. In
addition, every issue contains a disk of LabVIEW VIs and utilities that
implement methods covered in that issue. To order the LabVIEW Technical
Resource, contact LTR publishing at (214) 706-0587 or visit
www.ltrpub.com.
LabVIEW Books
Many books have been written about LabVIEW programming and
applications. The National Instruments Web site contains a list of all
the LabVIEW books and links to places to purchase these books.
info-labview Listserve
info-labview is an email group of users from around the world who
discuss LabVIEW issues. The list members can answer questions about
building LabVIEW systems for particular applications, where to get
instrument drivers or help with a device, and problems that appear.
A C
arrays callers
2D, 4-3 chain of, 5-10
auto-indexing, 4-4 displaying, 5-10
creating 2D arrays using auto-indexing, Case structures
4-7 Boolean cases, 3-68
creating constants, 4-4 enum cases, 3-70
creating controls and indicators, 4-3 error cases, 5-14
dimensions, 4-2 executing, 3-66
examples of 1D arrays, 4-2 integer cases, 3-69
examples of 2D arrays, 4-3 selecting cases, 3-67
restrictions, 4-2 specifying a default case, 3-66
auto-indexing string cases, 3-69
creating 2D arrays, 4-7 certification (NI resources), A-2
using to set For Loop count, 4-5 chain of callers
automatic wires, 2-22 displaying, 5-10
automatic wiring, 2-22 charts
update mode, 3-55
B wiring, 3-56
clusters
block diagram
assembling from individual elements,
automatic wiring, 2-22
4-18
creating cluster constants, 4-16
constants, 4-15
data flow, 2-39
creating, 4-15
nodes, 2-19
creating constants, 4-16
toolbar, 2-23
disassembling, 4-19
wiring automatically, 2-22
error, 5-12
wiring to charts, 3-56
order, 4-16
Boolean controls and indicators, 2-13
order of elements, 4-16
Breakpoint tool
replacing or accessing elements, 4-18
conditional breakpoints with probes, 5-8
wire patterns, 4-15
debugging VIs, 5-8
coercion
broken VIs
numeric data, 3-42
common causes, 5-3
communicating with instruments, 9-29
correcting, 2-45, 5-2
serial, 9-3
displaying errors, 5-2
VISA, 9-23
Bundle By Name function, 4-18
conditional breakpoints
Bundle function, 4-18
See probes
conditional terminals, 3-32
configuration
M R
multiple-plot waveform graphs, 3-58 Read from Measurement File VI, 10-12
multiplot XY graphs, 3-60 Read From Spreadsheet File VI, 10-11
refnums
N file I/O, 10-9
National Instruments support and services,
A-1 S
NI scope chart, 3-55
Certification, A-2 SCXI
nodes, 2-19 signal conditioning
numeric controls and indicators, 2-13 amplification, 7-6
numeric conversion, 3-42 linearization, 7-7
phenomena and transducers (table),
O 7-4
objects transducer excitation, 7-7
wiring automatically on block diagram, searching
2-22 for controls, VIs, and functions, 2-26
online help, 2-58 serial port communication, 9-3
Operating tool, 2-29 hardware overview, 9-6
order shift registers
in clusters, 4-16 stacked, 3-50
order of cluster elements, 4-16 signal conditioning
order of execution, 2-39 See also SCXI
outputs amplification, 7-6
setting, 6-9 linearization, 7-7
phenomena and transducers (table), 7-4
V
VIs
broken, 2-45, 5-2
configuring the connector pane, 6-6
correcting, 2-45, 5-2
error handling, 5-12
icons, 2-19, 6-2
nodes, 2-19
VISA, 9-23
terminalogy, 9-23
W
waveform charts
wiring, 3-56
waveform graphs
multiple-plot, 3-58
single-plot, 3-58
Web resources, A-1
While Loops
auto-indexing arrays, 4-4
conditional terminals, 3-32
error handling, 5-14
iteration terminals, 3-33
stacked shift registers, 3-50
wires
automatic, 2-22
wiring
automatically, 2-22
charts, 3-56
tunnels, 3-67
Wiring tool, 2-32
Write to Measurement File VI, 10-11
Write to Spreadsheet File VI, 10-11
X
XY graphs
configuring, 3-57
multiplot, 3-60
single-plot, 3-60
Instructor
Please evaluate the instructor by checking the appropriate circle. Unsatisfactory Poor Satisfactory Good Excellent
Instructor’s ability to communicate course concepts ❍ ❍ ❍ ❍ ❍
Instructor’s knowledge of the subject matter ❍ ❍ ❍ ❍ ❍
Instructor’s presentation skills ❍ ❍ ❍ ❍ ❍
Instructor’s sensitivity to class needs ❍ ❍ ❍ ❍ ❍
Instructor’s preparation for the class ❍ ❍ ❍ ❍ ❍
Course
Training facility quality ❍ ❍ ❍ ❍ ❍
Training equipment quality ❍ ❍ ❍ ❍ ❍
Was the hardware set up correctly? ❍ Yes ❍ No
The course length was ❍ Too long ❍ Just right ❍ Too short
The detail of topics covered in the course was ❍ Too much ❍ Just right ❍ Not enough
The course material was clear and easy to follow. ❍ Yes ❍ No ❍ Sometimes
Did the course cover material as advertised? ❍ Yes ❍ No
I had the skills or knowledge I needed to attend this course. ❍ Yes ❍ No If no, how could you have been
better prepared for the course? ____________________________________________________________________
_____________________________________________________________________________________________
What were the strong points of the course? __________________________________________________________
_____________________________________________________________________________________________
What topics would you add to the course? ___________________________________________________________
_____________________________________________________________________________________________
What part(s) of the course need to be condensed or removed? ____________________________________________
_____________________________________________________________________________________________
What needs to be added to the course to make it better? ________________________________________________
_____________________________________________________________________________________________
How did you benefit from taking this course? ________________________________________________________
_____________________________________________________________________________________________
Are there others at your company who have training needs? Please list. ____________________________________
_____________________________________________________________________________________________
_____________________________________________________________________________________________
Do you have other training needs that we could assist you with? _________________________________________
_____________________________________________________________________________________________
How did you hear about this course? ❍ NI Web site ❍ NI Sales Representative ❍ Mailing ❍ Co-worker
❍ Other _____________________________________________________________________________________