0 ratings0% found this document useful (0 votes) 415 views135 pagesLabview Core2 Course Manual New PDF
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content,
claim it here.
Available Formats
Download as PDF or read online on Scribd
SLNAWNULLSNI of Buuren woo
“TYNOLLWN.
jenuey| esuno9
€ 9109 wMAIAIETLabVIEW™ Core 2
Course Manual
Course Software Version 2011
August 2011 Edition
Part Number 325292C-01
Conyrignt
(©1993-2011 National Instruments Corporation. Al rights reserved
Under the copyright laws. this pubication may nt be reproduced or transmitted in any form, electronic or mechanical ineluding
photcoopying, recording, storing inan informaton retriava yster, or transtating, in whol orn part, without he prior written consent
‘of National Instruments Corporation,
National Instruments raspests the intallactual property of others, and we ask cur users todo the same. software is protected by
Copyright and cther intellectual property laws. Where NI sotware may be used to reproduca software o other matarils balonging te
thers, You may use Ni sofware only to reproduce materia Inet you may reproduce in accordance with the terms of any apolicadte
ene or other legal restriction.
For components used in USI (Xerces G+, [OU, HOTS, B64, Singray, and STLpor) the following copyright stipuations apply. Fora
sting ofthe conditions and d'sclaars, refer to ater ie USTCopyrights «chm orthe Cogyrights topc in your sofware
Xerces Cer. This product insludes software that was developed by the Apache Software Foundation (neep: //wnes.apachs.org/)
GGopyright 1$99 The Apache Sofware Foundation. Al rights reserved.
ICU. Copyright 1905-2009 International Business Machines Corporation and others. Alrights reserved,
DFS, NCSA HDFS (Hierarchical Data Format 5) Software Library and Utiities
Copytight 1998, 1999, 2000, 2001, 2008 ny the Board! Trustees ofthe Univers of Iinois. Al ight reserved.
164, Copyright © 2004-2006, Matthew Wilson and Synesis Software. All Rights Reserved.
Stingray. This sotware includes Stingray software developed by the Rogue Wave Software division of Quovack. Inc
Copytight 1995-2006, Quovadx, Inc. A Fights Reserved.
STLport Copyright 1934-2008 Boris Fomritchev
Trademarks
CVI, LabVIEW, National Instruments, NI, ri.cor, the National Instrumente corporate logo, and the Eagle logo are trademarks ot
National Insvuments Corporation. Rete tothe Trademark information at ni. com/tredemasks for other National Instruments
trademarks.
“The mark LabWindows is used under a license from Microsoft Corporation. Windows isa registred trademark of Microsett
Corporation inthe United States and other Counties. tier product and company names mentioned herein are tademerks or trade
names oftheir respective companias,
‘Members of the National struments Aliance Partner Program are business entities independont from tational instruments and have
no agency, parmership, or jpin-venture rdatonship wth National instruments.
Patents
For patents cavering Natioral Instruments produetsechnology, refer tothe appropriate location: Help»Patents in your software,
the patents. tact fle on your magia or the Nationa instruments Patent Notice at ni .con/patentsWorldwide Technical Support and Product Information
Worldwide Offices
Visit ni .com/niglobal 10 access the branch office Web sites, which provide up-to-date contact information, support phone
‘numbers, email addresses, and current events,
Notional instruments Corporate Headquarters
1150 Non Mopac Expressway Austin, Texes 78759-2504 USA Tel: 512683 0100
For further support information. refer tothe Additional Information and Resources appendix. To corament on National Instruments
documentation, eferto the National Instruments Web steal ni. com/in£o und enter the Info Cade feedback.Contents
_—_—$—
Student Guide
NI Certification.
Course Description .
What You Need to Get Started
Installing the Course Software.
Course Goals
Course Conventions.
mmonw>
Lesson 1
Common Design Techniques
A. Design Patterns
B. Single Loop Design Patterns...
C. Multiple Loop Design Patterns
D, Timing a Design Pattern...
Lesson 2
Synchronization Techniques
A, Notifier onsen
B. Queues ..
Lesson 3
Event Programming
A. Events.
B. Event-Driven Programming.....
C. Caveats and Recommendations
D. Event-Based Design Patterns
Lesson 4
Error Handling
Importance of Error Handling...
Detect and Report Errors
Enrors and Warnings
Ranges of Error Codes
Error Handle1
moow>
Lesson 5
Controlling the User Interface
‘A. Property Nodes
B, Invoke Nodes
C. Vi Server Architecture
D. Control References ..
(© National asumens Corporaton 8 LabVIEW Gore 2 Course Marua!ontents
Lesson 6
File 1/0 Techniques
A. File Formats
B. Binary Files.
Cc. TDMS Files.
Lesson 7
Improving an Existing VI
A. Refactoring Inherited Code
B. Typical Refactoring
C. Comparing VIs.....
Lesson &
Creating and Distributing Analcations
A. Preparing the Files...
B. Build Specifications
C. Building the Application and Installer...
Appendix A
Additional Information and Resources
Glossary
LabWiEW Core 2 Cowrse Naat » comStudent Guide
‘Thank you for purchasing the LabVIEW Core 2 course kit. You can begin
developing an application soon after you complete this course, This course
manual and the accompanying software are used in the two-day, hands-on
LabVIEW Core 2 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,
Visitni . com/ training for online course schedules, syllabi, training
centers, and class registration.
A. NI Certification
The LabVIEW Core 2 course is part of a series of courses designed to build
your proficiency with LabVIEW and help you prepare for the NI Certified
LabVIEW Associate Developer exam. The following illustration shows the
courses that are part of the LabVIEW training series. Refer to ni .com/
training for more information about NI Certification.
New User Exporionced User ‘Advanced Usor
Courses
LabVIEW Cove 1* LabVIEW Core 0° Maneging Software
Engineering ip LabVIEW
{LABVIEW Cannectvty Advanced Architectures
in LabVIEW
LabVIEW Core 2°
Object Ofiented Design
‘nd Programming
in LABVIEW
LabVIEW Poriormance
catia
cae aee Catal anew Seite aE
natin tosytian fy “Suapertan ace
toes
LabVIEW Instrument Control LabVIEW RealTime 1 LabVIEW Real-Time 2
LabVIEW FPGA LabVIEW DAQ and Signal Conatoning Modular Instuments Series
“Core nurses are strony commanded te rele maximum poaucty gas wen using Labview.
(© Rational instruments Corporation r LaDMIEW Gore 2 Course MaruatStudent Guide
B. Course Description
8
LaDVEW Core 2 Course Manual
‘The LabVIEW Core 2 course teaches you programming concepis,
techniques, features, VIs, and functions you can use 10 create test
and measurement, data acquisition, instrument control, datalogging,
measurement analysis, and report generation applications. This course
assumes that you are familiar with Windows, that you have experience
writing algorithms in the form of flowcharts or block diagrams, and that you
have taken the LabVIEW Core | course or have equivalent experience. The
course and exercise manuals are divided into lessons, described as follows.
In the course manual, each lesson consists of the following:
+ Anintroduction that describes the purpose of the lesson and what
you will leazn
+ A description of the topics in the lesson
+ A summary quiz that tests and reinforces important concepts and
skills taught in the lesson
In the exercise manual, each lesson consists of the following:
+ Asset of exercises to reinforce those topics
+ Some lessons include optional and challenge exercise sections or
asset of additional exercises to complete if time permits
For course and exercise manual updates and corrections, refer toni .com/into
and enter the Info Code core2
Several exercises use a plug-in multifunction data acquisition (DAQ) device
connected to a DAQ Signal Accessory or BNC-2120 containing a
temperature sensor, function generator, and LEDs,
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 another National
Instruments DAQ device connected to a signal source, such as a funetion
generator.
Ww iconStudent Guise
C. What You Need to Get Started
Before you use this course manual, make sure you have all of the following
items:
Windows XP or later installed on your computer: this course is
optimized for Windows XP_
o
Multifunction DAQ device configured as Dev using Measurement &
‘Automation Explorer (MAX)
DAQ Signal Accessory or BN
120, wires, and cable
LabVIEW Professional Development System 2011 or later
DAQmx 9.3.5 of later
oboaoagcad
LabVIEW Core 2 course CD, from which you install the following
folders:
Directory Deseription
Exercises Contains Vis used in the course
Solutions Contains completed course exercises
D. Installing the Course Software
‘Complete the following steps to install the course software,
1. Insert the course CD in your computer. The LabVIEW Core 2 Course
Setup dialog box appears.
2. Click Install the course materials.
3. Follow the onscreen instcuctions to complete installation and setup.
Exercise files are located in the \LabVvIEW Core 2\ folder,
BY Note Folder namesin angle brackets, such as , refer to folders on the root
directory of your computer.
© Aiton sruments Corporation w LaDIEW Cove 2 Course ManualStudent Guide
E. Course Goals
This course prepares you to do the following:
‘+ Apply common design pattems that use notifiers, queues, and events
+ Use event programming effectively
+ Programmatically control user interface objects
* Evaluate binary file I/O formats and use them in applications
+ Modify existing code for improved usability
+ Prepare, build, and deploy stand-alone applications
‘You will apply these concepts as you build a project that uses VIs you create
throughout the course. While these VIs individually illustrate specific
concepts and features in LabVIEW, they constitute part of a larger project
built throughout the course.
‘This course does not describe any of the following:
+ LabVIEW programming methods covered in the LabVIEW Core I
course
+ Every built-in V1, funetion, or object; refer to the LabVIEW Help for
more information about LabVIEW features not described in this course
* Developing a complete application for any student in the class; refer to
the NIExample Finder, available by selecting Help»Find Examples,
for example VIs you can use and incorporate into VIs you create
La0VIEW Gore 2 Course Manual vi ‘com‘Stun Guido
F. Course Conventions
monospace
monospace bold
Platform
© Nationa tasruments Corporation »
The following conventions appear in this course manual:
“The » symbol leads you through nested menu items and dialog box options
to. final action, The sequence Tools»Instrumentation»Find Instrument
Drivers directs you to drop down the Tools menu, select the
Instrumentation item, and finally select the Find Instrument Drivers
option,
‘This icon denotes a tip. which alerts you to advisory information.
‘This icon denotes a note, which alerts you to important information.
This icon denotes a caution, which advises you of precautions to take to
avoid injury, data loss, or a system crash
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 sections of dialog
boxes and hardware labels.
Italic text denotes variables, emphasis, a cross-reference, or an introduction
toa key concept. Italic text also denotes text that is a placeholder for a word
or value that you must supply.
eatin 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, director
programs, subprograms, subroutines, device names, functions, operations,
variables, filenames, and extensions.
‘Bold text in this font denotes the messages and responses tha the computer
automatically prints to the sereen. This font also emphasizes lines of code
that are different from the other examples.
Text in this font denotes a specific platform and indicates that the text
following it applies only to that platform.
LaDviEW Gove 2 Course ManualVues uUoOvUeSeVUBDBAeaARIAFIFTIAIWAACommon Design Techniques
Topics
You can develop better programs in LabVIEW and in other programming
languages if you follow consistent programming techniques. Design
patterns represent techniques that have proved themselves useful time and
lime again. To facilitate development, LabVIEW provides templates for
several common design pattems. This lesson discusses two different
categories of programming design patterns—single loop and multiple loops.
Single loop design pattems include the simple VI, the general VI, and the
state machine.
Multiple loop design patterns include the parallel loop V1, the master/slave,
and the producer/consumer.
Understanding the appropriate use of each design pattern helps you create
more efficient LabVIEW VIs.
A. Design Patterns
B. Single Loop Design Patterns
C. Multiple Loop Design Patterns
D. Timing a Design Pattern
(© National instruments Corparaton 4 Laninew core2 Gourso Manvel,Lesson t Common DesionTechnaues
A. Design Patterns
Application design patterns represent LabVIEW code implementations and
techniques that are solutions to specific problems in software design. Design
patterns typically evolve through the efforts of many developers and are
fine-tuned for simplicity, maintainability, and readability. Design patterns
represent the techniques that have proved themselves useful over time
Furthermore, as @ paitern gains acceptance, it becomes easier to
recognize—this recognition alone helps you to read and make changes
to your code.
LabVIEW includes several built-in VI templates for several standard design
patterns that you will learn about in later lessons. To access the design
patterns, select File»New to display the New dialog box. The design
patterns are available in the VI>From Template»Frameworks»Desiga
Patterns folder. Listed helow are the different kinds of design patterns.
+ Master/Slave Design Pattern—Use this template to build a masterlslave
design pattern. The master loop alway’ executes, It notifies one or more
slave loops to execute their code. The slave loop or loops continue
executing until they complete, then wait for another notification.
Contrast this with the producer/consumer pattern in which the consumer
loops execute only when they have data in their queue.
+ Producer/Consumer Design Pattern (Data)—Use this template to build
a producer/consumer design pattern. Use this template when you need
to exccute a process, such as data analysis, when a data source, such as,
triggered acquisition, produces data at an uneven rate and you need to
‘execute the process when the data becomes available.
+ Producet/Consumer Design Pattern (Events}—Use this template to
build a producer/consumer design pattern with events to produce queue
items. Use this design pattern instead of the user interface event handler
patiern for user interfaces when you want to execute code
asynchronously in response to an event without slowing the user
interface responsiveness.
+ Queved Message Handler—Use this template to builda queued message
handler design pattern, in which each message handling code can queue
any number of new messages
LabVIEW Core? Gourse Manual re iconLesson} Common Design Techniques
+ Standard State Machine—Use this template to build a standard state
‘machine design pattern, Each state executes code and determines which
state to transition to. Contrast this design pattern with the user interface
event handler pattem, in which code executes in response to user
actions, Contrast this design pattern also with the queued message
handler pattern, in which each message handling code can queue any
number of messages.
+ User Interface Event Handler—Use this template to build a user
interface event handler design pattern, Use this pattern for dialog boxes
and other user interfaces in which code executes in response to user
actions. You also can create and execute user-defined events that the VI
can handle the same way as user interface events.
B. Single Loop Design Patterns
You learned to design three different types of design patterns in the
LabVIEW Core 1 course—the simple architecture, the general architecture,
and the state machine,
imple VI Design Patterns
When performing calculations or making quick lab measurements, you do
not need a complicated architecture. Your program might consist of a single
‘VI that takes a measurement, performs calculations, and either displays the
results or records them to disk. The simple VI design patiern usually does
not require a specific start or stop action from the user. The userjust clicks
the Run buttoa. Use this architecture for simple applications or for
functional components within larger applications. You can convert these
simple VIs into subVIs that you use as building blocks for larger
applications.
Figure 1-1 displays the block diagram of the Determine Warnings VI that
was the course project in the LabVIEW Core 1 course. This VI performs a
single task—it determines what warning to output dependent on a set of
inputs, You can use this VI 2s a subVI whenever you must determine the
warning level.
Notice that the VI in Figure 1-1 contains no start or stop actions from the
user, In this VI all block diagram objects are connected through data flow.
‘You can determine the overall order of operations by following the flow of
data, For example, the Not Equal function cannot execute until the Greater
Than or Equal function, the Less Than or Equal function, and both Select
functions have executed.
(© Nationa asruments Corporation 13 LabvEW Gore 2 Cowse Manus!Lesson + Common Design Technioies
Current Tero
warning Test
aba
‘warring?
TE
Figure 1-1. Simple VI Architecture
General VI Design Patterns
A general VI design pattern has three main phases—startup, main
application, and shutdown, Each of the following phases may contain code
that uses another type of design pattern,
+ Startup—tnitializes hardware, reads configuration information from
files, or prompts the user for data file locations,
+ Main Application—Consists of at least one loop that repeats until the
user decides to exit the program or the program terminates for other
reasons such as 1/0 completion.
+ Shutdown—Closes files, writes configuration information to disk, or
resets I/O to the default state.
Figure 1-2 shows the general VI design pattern.
Sattbsi ni
Enter your code here
Oo fe
Figure 1-2. General VI Design Patter
“LADVIEW Core 2 Course Maruat i] a.comLesson Common Design Tectniaues
Tn Figure the error cluster wires control the execution order of the three
sections, The While Loop does not execute until the Start Up VI finishes
running and returns the error cluster data. Consequently, the Shut Down VI
cannot run until the main application in the While Loop finishes and the
error cluster data leaves the loop.
@ Tip Most loops require a Wait function, especially if that Joop monitors user input
on the front panel. Without the Wait function, the loop might run continuously and
use all of the computer system resources. The Wait function forces the loop to run
asynchronously even if you specify 0 milliseconds as the wait period. If the operations
inside the main loop react to user inputs, you can increase the wait period to a level
acceptable forreaction times. A wait of 100 to 200 ms is usually good because most users
cannot detect that amount of delay between clicking a button on the front panel and the
subsequent event execution.
For simple applications, the main application loop is obvious and contains
code that uses the simple VI design pattern. When the application incudes
complicated user interfaces or multiple tasks such as user actions, /O
triggers, and so on, the main application phase gets more complicated.
State Machine Design Pattern
The state machine design pattern is a modification of the general design
‘pattern, It usually has a start up and shut down phase. However, the main
application phase consists of a Case structure embedded in the loop. This
architecture allows you to run different code each time the loop executes,
depending upon some condition. Each case defines a state of the machine,
hence the name, siate machine. Use this design pattem for VIs that are casily
divided into several simpler tasks, such as Vis that act as a user interface.
A state machine in LabVIEW consists of a While Loop, a Case structure,
and a shift register. Each state of the state machine is a separate case in
the Case structure. You place VIs and other code that the state should
execute within the appropriate case. A shift register stores the state that
should execute upon the next iteration of the loop. The block diagram of a
state machine VI with five states appears in Figure 1-3. Figure 1-4 shows the
other cases, or states, of the state machine.
© Nationa! instruments Corporation 8 {LaDVIEW Gore 2 course manualLesson t Common Design Tochniuee
os fa
= sia
L ae se
o mpe
Figure 1-3. State Machine with Startup State
[Idle", Default ~bP™
|
Event 1 Code Here
Nest State
Event 2 Cade Here
Net State
Figure 1-4. Idle (Defautt), Event 1, and Event 2 States
In the state machine design pattern, you design the list of possible tasks, or
states, and then map them to each case. For the V1 in the previous example,
the possible states are Startup, Idle, Event 1, and Event 2. An enumerated
LabVIEW Core 2 Course Manual 1 comLesson Common Design Tetoues
constant stores the states, Each state has its own case in the Case structure.
The outcome of one case determines which case to execute next. The shift
register stores the value that determines which case to execute next.
The state machine design pattern can make the block diagram much smaller,
and therefore, easier to read and debug. Another advantage of the state
machine architecture is that each case determines the next state, unlike
Sequence structures that must execute every frame in sequence.
A disadvantage of the state machine design pattern is that with the approach
in the previous example, it is possible to skip states, If two states in the
structure are called at the same time, this model handles only one state, and
the other state does not execute, Skipping states can lead to errors that are
difficult to debug because they are difficult to reproduce. More complex
versions of the state machine design pattern contain extra code that creates
queue of events, or states, so that you do not miss a state. Refer to
Lesson 2, Synchronization Techniques, for more information about
queue-based state machines.
C. Multiple Loop Design Patterns
‘This section describes the following multiple loop design pattems—parallel
loop, master/slave, and producer/consumer data.
Parallel Loop Design Pattern
Some applications must respond to and run several tasks concurrently.
‘One way to improve parallelism is 10 assign a different loop to cach task.
For example, you might have a different loop for each button on the front
panel and for every other kind of task, such as a menu selection, I/O trigger.
and so on. Figure 1-5 shows this parallel loop design pattern.
Batupst
* Magers soon.
Process 1 Code Here
a a
Process 2 Code Here
i
Figure 1-5. Parallal Loop Design Pattern
© Natal nsvuments Corporation "7 “LaOMIEW core 2 Course Manu’lesson 1 Common Desion Techies
This structure is straightforward and appropriate forsome simple menu VIs,
where you expect « user to select from one of several buttons that perform
different actions, The parallel loop design pattern lets you handle multiple,
wultaneous, independent tasks. In this design pattern, responding to
one action does not prevent the VI from responding to another action. For
example, if a user clicks a button that displays a dialog box, parallel loops
can continue to respond to VO tasks,
However, the parallel loop design pattern requires you to coordinate and
communicate between different loops. You cannot use wires to pass data
between loops because doing so prevents the loops from running in parallel
Instead, you mustuse a messaging technique for passing information among
processes. Refer to Lesson 2, Synchronization Techniques, for messaging
techniques using notifiers and queues.
Mastet/Slave Design Pattern
LabVIEW Gore 2 Course Manual
‘The master/slave design patiem consists of multiple parallel loops. Each of
the loops may execute tasks at different rates. One Joop acis as the master,
and the other loops act as slaves. The master loop controls all the slave loops
and communicates with them using messaging techniques, as shown in
Figure 1-6.
Figure 1-6. Master/Siave Design Pattern
Use the master/slave design pattern when you need a VI to respond to user
imerface controls while simultaneously collecting data. For example, you
want to create a VI that measures and logs a slowly changing voltage once
every five seconds. The VI acquires a waveform from a transmission line
and displays it on a graph every 100 ms, The VI also provides a user
interface that allows the userto change parameters for each acquisition. The
master/slave design pattern is well suited for this acquisition application,
For this application, the master loop contains the user interface. The voltage
acquisition occurs in one slave loop, while the graphing occurs in another
slave loop.
18 scomLisson} Common Design Tectnigves
Using the standard master/slave design pattern approach to this VI, you
‘would put the acquisition processes in two separate While Loops, both of
them driven by a master loop that receives inputs from the user interface
controls. This ensures that the separate acquisition processes do not affect
each other, and that any delays caused by the user interface, such as
displaying a dialog box, do not delay any iterations of the acquisition
processes.
Vis that involve control also benefit from the use of master/slave design
patterns. Consider a VI where a user controls a free-motion robotic arm
using buttons on a front panel. This type of VI requires efficient, accurate,
and responsive control because of the physical damage to the arm or
surroundings that might occur if control is mishandled. For example. if the
user instructs the arm (0 stop its downward motion, but the program is
‘occupied with the arm swivel control, the robotic arm might collide with the
support platform. Apply the master/slave design pattern to the application to
avoid these problems, In this case, the master loop handles the user
interface, and each controllable section of the robotic arm has its own slave
loop. Because each controllable section of the arm has its own loop and its
‘own piece of processing time, the user interface has more responsive control
of the robotic arm,
With a master/slave design pattern, it is important that no two While Loops
write to the same shared data, Ensure that no more than one While Loop
may write to any given piece of shared data. Refer to Lesson 2,
Synchronization Techniques, for more information about implementing an
application based on the master/slave design pattern.
The slave must not take too long to respond to the master. If the slave is
processing a signal fiom the master and the master sends more than
one message to the slave, the slave receives only the latest message. This
use of the masterislave architecture could cause a loss of data. Use a
master/slave architecture only if you are certain that each slave task takes
Jess time to execute than the master loop.
Producer/Consumer Design Pattern
‘The producer/consumer design pattern is hased on the master/slave design
patiern and improves data sharing among multiple loops running at different
rates, Similar to the master/slave design pattem, the producer/consumer
design pattern separates tasks that produce and consume data at different
rates, The parallel loops in the producer/consumer design pattern are
separated into two categories—those that produce data and those that
consume the data produced. Data queues communicate data among the
loops. The data queues also buffer data among the producer and consumer
loops.
© National instruments Copoataon 18 LabVIEW Core2 Course Marua!Lesson 1 Common Design Techniaves
@ Te Abuiferis a memory device that stores temporary data among two devices, or in
this case, multiple loops.
Use the producer/consumer design pattern when you must acquire multiple
sets of data that must be processed in order. Suppose you want to create a VI
that accepts data while processing the data sets in the order they were
received, The producer/consumer pattern is ideal for this type of VI because
queuing (producing) the data occurs much faster than the data can be
processed (consumed), You could put the producer and consumer in the
same Joop for this application, but the processing queue could not receive
additional data until the first piece of data was completely processed. The
producer/consumer approach to this VI queues the data in the producer loop
and processes the data in the consumer loop, as shown in Figure 1-7.
Q Ti Queve functions allow you to store a set of data that can be passed among multiple
loops running simultaneously or umong Vis. Refer to Lesson 2, Synchronization
Techniques, for more information about queues and implementing applications using the
producer/consumer design patter.
[Papa cendtonat
lccde mete ets
Feennng Heaamue
n= ep ee cote
sorte
Tf %
a
war pee TE
[tis the usu
Figure 1-7. Producer/Consumer Design Pattern
This design pattern allows the consumer loop to process the data at its own
pace, while the producer loop continues to queue additional dats.
LabVIEW Gore 2 Course Manual 10 comLesson Gammon Design Techniques:
You also can use the produces/consumer design pattern to create a VI that
analyzes network communication. This type of VI requires two processes to
‘operate at the same time and at different speeds. The first process constantly
polls the network line and retrieves packets. The second process analyzes
the packets retrieved by the first process
In this example, the first process acts as the producer because it supplies data
to the second process, which acts as the consumer. The producer/consumer
design pattern is an effective architecture for this VI. The parallel producer
and consumer loops handle the retrieval and analysis of data off the network,
and the queued communication between the )Wo loops allows buffering of
the network packets retrieved. Buffering can become important when
network communication is busy. With buffering, packets can be retrieved
and communicated faster than they can be analyzed.
D. Timing a Design Pattern
Execution Timing
‘This section discusses two forms of timing—execution timing and software
contol timing, Execution timing uses timing functions to give the processor
time to complete other tasks. Software control timing involves timing
real-world operation to perform within a set time period.
Execution timing involves timing a design pattern explicitly or based on
events that occur within the VI. Explicit timing uses a function that
specifically allows the processor time to complete other tasks, such as the
‘Wait Until Next ms Multiple function. When timing is based on events, the
design pattern waits for some action to occur before continuing and allows
the processor to complete other tasks while it waits
‘se explicit timing for design patterns such as the master/slave,
producer/consumer, and state machine. These design patterns perform some
type of polling while they execute.
Tip Polling is the process of making continuous requests for data from another device.
Tn LabVIEW, this generally means that the block diagram continuously asks if there is
data available, usually from the user interface.
(© Rational instruments Corporation
For example, the master/slave design pattern shown in Figure 1-8 uses a
While Loop and a Case structure to implement the master loop. The master
‘executes continuously and polls for an event of some type, such as the user
clicking a button. When the event occurs, the master sends a message to the
slave, You need to time the master so it does not take over the execution of
the processor. In this case, you typically use the Wait (ms) function to
regulate how frequently the master polls.
rt {LaUiAEW Core 2 Course Manuatlesson 1 Common Design Techniques
Q Th Always use a timing funetion such asthe Wait ms) funetion or the Wait Until Next
ms Multiple function in any design pattern that continually executes and needs to be
regulated. If you do not use a timing function in a continuously executing structure,
LabVIEW uses all the processor time, and background processes may not run.
be wy 0)
ra er
Ta Fence on
| x”)
(Bacar
isa opraiia Bea
foncititerne | ED} orotate
lee
LaDVIEW Gore 2 Course Manual
Figure 1-8. Master/Slave Design Pattern
Notice that the slave loop does not contain any form of timing. The use of
Synchronization functions, such as queues and notifiers, to pass messages
provides an inherent form of timing in the slave loop because the slave loop
waits for the Notifier function to receive a message. After the Notifier
function receives a message, the slave executes on the message. This creates
an efficient block diagram that does not waste processor cycles by polling
for messages. This is an example of execution timing by waiting for an
event,
When you implement design patterns where the timing is based on the
occurrence of events, you do not have to determine the correct timing
frequency because the execution of the design pattem occurs only when an
event occurs. In other words, the design pattern executes only when it
receives an event.
we nicomLesson} Common Design Technicues
Software Control Timing
Many applications that you create must execute an operation for a specified
amount of time. Consider implementing a state machine design pattern for
a temperature data acquisition system. If the specifications require that the
system acquire temperature data for 5 minutes, you could remain in the
acquisition state for 5 minutes. However, during that time you cannot
process any user interface actions such as stopping the VI. To process user
interface actions. you must implement timing so that the VI continually
executes for specified time. Implementing this type of timing involves
keeping the application executing while monitoring a real-time clock
In the LabVIEW Core 1 course, you implemented software control timing to
monitor the time until the VI should acquire the next piece of data, as shown
in Figure 1-9. Notice the use of the Elapsed Time Express VI to keep track
of a clock.
ma ofa
Fie Pep a
je FEES men ae
rae am
@ =
ah ee t _ :
(o
Figure 1-9. Use of the Elapsed Tima Express V/
Ifyou use the Wait (ms) function or the Wait Until Next ms Multiple
function to perform software timing, the execution of the function you are
timing does not occur until the wait function finishes. These timing
functions are not the preferred method for performing software control
timing, especially for VIs where the system must continually execute. A
better method for software control timing utilizes the Get Date/Time In
Seconds function to get the current time and track it using shift registers.
© Nationa nstuments Corporation rag LADVIEW Core 2 Course Mansa!essen Common Desin Tesiaves
Figure 1-10. Software Timing Using the Get Date/Time In Seconds Function
‘The Get Date/Time In Seconds function, connected to the leftterminalof the
shift register, initializes the shift register with the current sysicm time. Each
state uses another Get Date/Time In Seconds function and compares the
current time to the start time. If the difference in these (wo times is greater
or equal to the wait time, the state finishes executing and the rest of the
application executes.
Tip Always use the Get Date/Time In Seconds function instead of the Tick Count (ms)
function for this type of comparison because the value of the Tick Count (ms) function
can rollover to 0 during execution.
LabVIEW Core 2 Course Manat He iconLesson 1 Common Design Techniques:
Self-Review: Quiz
© Ritiona instruments Corporation
‘The state machine is an example of a design pattern.
a. True
b. False
Which of the following are reasons for using a multiple loop design
pattern’?
a, Execute multiple tasks concurrently
b. Exccute different states in a state machine
cc, Execute tasks at different rates
d. Execute slart up code, main loop, and shutdown code
Software control timing allows the processor time to complete other
tasks,
a True
b. False
115) LaDVIEW Gore 2 couse Manualwevu Yo
o
a
2
o9oa3097Lesson? Common Design Tectniaues
Self-Review: Quiz Answers
(© Rational nsrurnents Corporation
‘The state machine is an example of a design pattern
a. True
b. False
‘Which of the following are reasons for using a multiple loop design
pattern?
a, Exeeute multiple tasks concurrently
b. Exccute different states in a state machine
c. Execute tasks at different rates
d. Execute start up code, main loop, and shutdown code
Software control timing allows the processor time to complete other
tasks.
a True
b. False
tr LAbWIEW Gore2 Course Marua!Lesson | Common Design Techniques
Notes
LabVIEW Core 2 Gourse Mana
comSynchronization Techniques
Variables are useful in LabVIEW for passing data between parallel
processes. However, when using variables it is often difficult to synchronize
data transfers and you must take care to avoid race conditions. This lesson
introduces noiifiers and queues as alternative methods for passing data
‘between parallel processes, Notifiers and queues have advantages over
using variables because of the ability to synchronize the transfer of data.
Topics
A. Notifiers
B. Queues
© Natonainstrumerts Gorporatan at Lab MEW Core 2 Course MaruatLessan2 Synchronization Techniques
A. Notifiers
A more effective implementation of the master/slave design pattern uses
notifiers to synchronize data transfer. A notifier sends data along with a
notification that the data is available. Using a notifier to pass data from the
‘master to the slave removes any issues with race conditions. Using notifiers
also provides a synchronization advantage because the master and slave are
timed when data is available, providing foran elegant implementation of the
master/slave design pattern, Figure 2-1 shows the master/slave design
pattern using notifiers.
EHO
aicoanba tee
. pasanan
Ease |_2) x")
whitececte| 1 sae Tee Aare] a
|
ili, Fon arabs Ea Sa
=a
dinate be ay yea)
i)
“LADWIEW Gore 2 Course Manual
Figure 2-1. Master/Slave Dasign Pattern Using Notifies
‘The notifier is created before the loops begin using the Obtain Notifier
function, The master loop uses the Send Notification function to notify the
slave loop through the Wait on Notification function. After the VI has
finished using the notifiers, the Release Notifier function releases the
aotifiers,
‘The following benefits result from using notifiers in the master/slave design
pattem:
+ Both loops are synchronized to the master loop. The slave loop only
executes when the master loop sends a notification.
22 iconB. Queues
Lesson 2 S\nciraniationTestniques
+ You can use notifiers to ereate globally available data, Thus, you can
send data with a notification, For example, in Figure 2-1, the Send
Notification function sends the string instruction.
+ Using notifiers creates eificient code. You need not use polling to
determine when data is available from the master loop.
However, using notifiers can have drawbacks, A notifier does not buffer the
data. If the master loop sends another piece of data before the slave loop(s)
reads the first piece of data, that data is overwritten and lost
Queves are similar to notifiers, except that a queue can store multiple pieces
of data, By default, queues work in a first in, first out (FIFO) manner.
‘Therefore, the first piece of data inserted into the queue is the first piece of
data that is removed from the queue, Use a queue when you want to process
all data placed in the queue. Use a notifier if you want to process only the
current data,
‘When used, the producer/consumer design pattern, queues pass data and
synchronize the loops.
soca te ay 6}
a
(Retaeete pone)
[igde nia ea |
pinche atte eed
nea ma) age
2
Ears, x
[>a i>
‘al ina yor ease BRITT
Figure 2-2. Producer/Consumer Design Pattern Using Queues
(© Waal instruments Corporation 23 LabVIEW Core 2 Course MaaualLesson? Synchronization Tecniques
‘The queue is created before the loops begin using the Obtain Queue
function. The producer loop uses the Enqueue Element function to add data
to the queue. The consumer loop removes data from the queue using the
Dequeue Element function. The consumer loop does not execute until data
is available in the queve. After the VI has finished using the queues, the
Release Queue function releases the queues. When the queue releases, the
Dequeue Element function generates an error, effectively stopping the
consumer loop. This eliminates the need to use a variable to stop the loops.
‘The following benefits result from using queues in the producer/consumer
design pattern:
* Both loops are synchronized to the producer loop. The consumer loop
only executes when data is available in the queue.
* You can use queues to create globally available data that is queued,
removing the possibility of losing the data in the queue when new data
is added to the queue.
+ Using queues creates efficient code, You need not use polling to
determine when data is available from the producer loop.
Queues are also useful for holding state requests in a state machine, In the
implementation of a state machine that you have learned, if two states are
requested simultancously, you might lose one of the state requests. A queue
stores the second state request and exccutes it when the first has finished.
To practice the concepts in this section, complete Exercise 2-1.
Case Study: Weather Station Project
LaDVIEW Core 2 Gourse thanual
‘The weather station project acquires temperature and wind speed data,
and analyzes it to determine if the situation requires a warning, If the
temperature is too high or too low, it alerts the user to u danger of heatsiroke
or freezing, It also monitors the wind speed to generate a high wind warning
when appropriate.
The block diagram consists of two parallel loops, which are synchronized
using queues. One loop acquires data for temperature and wind speed and
the other loop analyzes the data. The loops in the block diagram use the
producer/consumer design pattem and pass the data through the queue.
Queues help process every reading acquired from the DAQ Assistant,
Code for acquiring temperature and wind speed is placed in the producer
loop. Code containing the state machine for analysis of temperature-weather
conditions is within the no error case of the consumer loop. The code using
2 queue is more readable and efficient than the code using only state
machine architecture. The Obtain Queue function creates the queue
24 ricansss0n2—Syncivontation Techniques
reference. The producer loop uses the Enqueue Element function to add data
obtained from the DAQ Assistant to the queue. The consumer loop uses the
Dequeue Element function to get the data from the queue and provide it 10
the state machine for analysis, The Release Queue function marks the end
‘of queue by destroying it, The use of queues also climinates the need for a
shared variable to stop the loops because the Dequeue Element function
stops the consumer loop when the queue is released,
Figure 2-3 shows the block diagram consisting of a producer and a
consumer loop. Data transfer and synchronization between the loops is
achieved by the queue functions.
Figure 2-3. Data Transfer and Synchronization of Parallel Loops Using Queues
© Rational Insiurments Corporation 29 LavMiEW Coe 2 Course Marua\Pee uuvuenevuvevyvvu YOUO927D32 37790Lesson 2 Synchronkaton Techniques
Self-Review: Quiz
1. Which of the following buffer data?
a. Notifiers
1b. Queues
¢. Global Variables
d. Local Variables
2. Match the following:
Obtain Queue Destcoys the queue reference
x
it
Get Queue Status Assigns the data type of the queue
7
>|
Release Queue Adds an element to the back of the queue
*
a
Engueue Element Determines the number of elements currently
=. in the queue
3. Which of the following are valid data types for Queues and Notifiers?
a. Suing
b. Numeric
cc. Enum
d. Array of Booleans
e. Cluster of a String and a Numeric
(© Ratonal instruments Corporation 27 LaDMEW Core 2 Course Manual, ee euruUvruUVeUUYeEyYUVVOoDsSIFBDIDFT7DDtLesson 2 Synchronization Techniques
Self-Review: Quiz Answers
1, Which of the following buffer data?
a. Notifiers
b. Queues
cc. Global Variables
d. Local Variables
2. Match the following:
Obtain Queue Assigns the data type of the queue
ti
Get Queue Status Determines the number of elements
7 currently in the queue
th
Release Queue Destroys the queue reference
Enqucue Element Adds an element to the back of the queue
3. Which of the following are valid data types for Queues and Notifiers?
a. String
b, Numeric
c. Enum
4. Array of Booleans
e. Cluster of a String and a Numeric
© Nationa Insruments Corporation 29 Lavmew Gore 2 course Marua!Lesson 2 Synchronization Techniues
Notes
LabVIEW Core 2 Course Mansal 20 ‘comEvent Programming
Event-based design patterns allow you to create more efficient and flexible
applications. Event-based design patterns use the Event structure to respond
directly 10 the user or other events. This lesson describes event-driven
programming using the Eveat structure and design patterns that use the
Event structure.
Topics
Events
Event-Driven Programming
Caveats and Recommendations
pane
Event-Based Design Patterns
© Rational nsturments Corporation a LanvEW Gore 2 Course Manualesson3 Bret Programming
A. Events
LabVIEW is a dataflow programming environment where the flow of data
determines the execution order of block diagram elements. Event-driven
programming features extend the LabVIEW dataflow environment to allow
the user's direct interaction with the front panc! and other asynchronous
activity to further influence block diagram execution
EY Note _Event-criven programming features are available only in the Lab VIEW Full and
Professional Development Systems. You can run a VI built
ith these features in the
Lab VIEW Base Package, but you cannot reconfigure the event-handling components.
What Are Events?
Why Use Events?
{LabVIEW Cove 2 Course Manual
An event is an asynchronous notification that something has occurred.
Events can originate from the user interface, external /O, or other parts of
the program. User interface events include mouse clicks, key presses, and so
on. External I/O events include hardware timers or triggers that signal when
data acquisition completes or when an error condition occurs. Other types
of events can be generated programmatically and used to communicate with
different parts of the program, LabVIEW supports user interface and
programmatically generated events, LabVIEW also supports ActiveX and
-NET generated events, which are external /O events.
In an event-driven program, events that occur in the system directly
influence the execution flow. In contrast, a procedural program executes in
a pre-determined, sequential order. Event-driven programs usually include
aa loop that waits foran event to occur, executes code to respond to the event,
and reiterates to wait for the next event. How the program responds to each.
event depends on the code written for that specific event. The order in which
an event-driven program executes depends on which events occurand on the
order in which they occur. Some sections of the program might execute
frequently because the events they handle occur frequently, and other
sections of the program might not execute at all because the events never
occur,
Use user interface events in LabVIEW to synchronize user actions on the
front panel with block diagram execution, Events allow you 10 execute a
specific event-handling case each time a user performs a specific action.
Without events, the block diagram must poll the state of front panel objects
in aloop, checking to see if any change has occurred. Polling the front panel
requires a significant amount of CPU time and can fail to detect changes if
they occur too quickly. By using events to respond to specific user actions,
you eliminate the need to poll the front panel to determine which actions the
user performed. Instead, LabVIEW actively notifies the block diagram each
32 icoLesson'3 Event Prowamming
time an interaction you specified occurs. Using events reduces the CPU
requirements of the program, simplifies the block diagram code, and
‘guarantees that the block diagram ean respond to all interactions the user
makes
Use programmatically generated events to communicate among different
parts of the program that have no dataflow dependency. Programmatically
generated events have many of the same advantages as user interface events
and can share the same event-handling code, making it easy to implement
advanced architectures, such as queued state machines using events.
B. Event-Driven Programming
In Lesson 1, Common Design Techniques, you learned how event-driven
programming extends the LabVIEW dataflow environment to allow
user interaction with the front panel. You also learned ahout
programmatically-generated events allow for easy implementation of
advanced architectures, such as queued state machines.
Event Structure Components
f(D Application Exit? *}
Use the Event structure, shown as follows, to handle events in a VI.
‘The Event structure works like a Case structure with a built-in Wait on
Notification function. The Event structure can have multiple cases, each of
which is a separate event-handling routine. You can configure each case 10
handle one or more events, but only one of these events can occur at a time.
‘When the Event structure executes, it waits until one of the configured
‘events occur, then executes the corresponding case for that event. The Event
structure completes execution after handling exactly one event, It does not
implicitly loop to handle multiple events. Like a Wait on Notification
function, the Event structure can time out while waiting for notification of
an event. When this occurs, a specific Timeout case executes.
The event selector label at the top of the Event structure indicates which
events cause the currently displayed case to execute.
View other event cases by clicking the down arrow next to the case name and
selecting another case from the shorteut menu
‘The Timeout terminal at the top lefi comer of the Event structure specifies
the number of milliseconds to wait for an event before timing out.
© national instruments Corporation a LaDVIEW Gore 2 Gowrse Manus!lesson 3 Event Programming
‘The default is —1, which specifies to wait indefinitely for an event to occur,
If you wire a value to the Timeout terminal, you must provide a Timeout
case.
‘The Event Data Node behaves similarly to the Unbundle By Name function,
‘This node is attached to the inside left border of each event case. The node
identifies the data Lab VIEW provides when an event occurs. You can resize
this node vertically to add more data items, and you can set cach data item
in the node to access any event data element. The node provides different
data elements in each case of the Event structure depending on which
event(s) you configure that ease to handle. If you configure @ single case to
handle multiple events, the Event Data Node provides only the event data
elements that are common to all the events configured for that case.
aa ‘The Event Filter Node is similar to the Event Data Node.
This node is attached to the inside right border of filter event cases. The node
identifies the subset of data available in the Event Data Node that the event
case can modify. The node displays different data depending on which
event(s) you configure that case to handle. By default, these items are
inplace to the corresponding data items in the Event Data Node. If you do
not wire a value to a data item of an Event Filter Node, that data item
remains unchanged.
Refer to the Nonify and Filter Events section of this lesson for more
information about filter events.
a The dynamic event terminals are available by right-clicking the Event
structure and selecting Show Dynamic Event Terminals from the shortcut
menu,
These terminals are used only for dynamic event registration.
Refer to the Dynamic Event Registration topic and the Modifying
Registration Dynamically topic of the LabVIEW Help for more information
about using these terminals.
FY Note Like a Case structure, the Event structure supports tunnels. However, by default
you do not have to wire Event structure output tunnels in every ease. All unwired tunnels
use the default value for the tunnel data type. Right-click a tunnel and deselect Use
Default If Unwired from the shortcut menu to revert to the default Case structure
behavior where tunnels must be wired in all cases. You also ean configure the tunnels to
wire the input and output tunnels automatically in unwired cases.
Refer to the LabVIEW Help for information about the default values for data
types.
La VeW cor 2 Course Manval a nicerLesson Even! Programming
Notify and Filter Events
Notify events are an indication that a user action has already occurred, such
as when the user has changed the value of a control. Use notify events to
respond toan event after it has occurred and LabVIEW has processed it, You
can configure any number of Event structures to respond to the same notify
event on a specific object. When the event occurs, LabVIEW sends a copy
of the event to each Event structure configured to handle the event in
parallel.
Filler events inform you that the user has performed an action before
LabVIEW processes it, which allows you to customize how the program
responds to interactions with the user intesface. Use filter events to
participate in the handling of the event, possibly overriding the default
behavior for the event. In an Event structure case for a filter event, you can
validate of change the event data before Lab VIEW finishes processing it, or
‘you can discard the event entirely to prevent the change from affecting the
VI. For example, you can configure an Event structure to discard the Panel
Close? event, which prevents the user from interactively closing the front
panel of the VI.
Filter events have names that end with a question mark, such as Panel
Close?, to help you distinguish them from notify events. Most filter events
have an associated notify event of the same name, but without the question
mark, which LabVIEW generates after the filter event if no event case
discarded the event.
Forexample, you can use the Mouse Down? and Shorteut Menu Activation?
filter events to display a context menu when You left-click a control. To
perform this action, modify the data retuned by the Button event dats field
of the Mouse Down? filter event. The value of the left mouse button is |,and
the value of the right mouse button is 2. In order to display the context menu
when you left-click a control, change the Button event data field to 2 so that
LabVIEW treats a left-click like a right-click. Refer to the Leti-click
Shortcut Menu VI in the labview\examples\general directory for an
‘example of using filter events.
As with notify events, you can configure any number of Event structures t0
respond to the same filter event on a specific object. However, LabVIEW
sends filler events sequentially to each Event structure configured for the
event. The order in which LabVIEW sends the event to each Event structure
depends on the order in which the events were registered. Each Event
structure must complete its event case for the event before LabVIEW can,
notify the next Event structure. If an Event structure case changes any of the
event data, LabVIEW passes the changed data to subsequent Event
structures in the chain. If an Event structure in the chain discards the event,
LabVIEW does not pass the event to any Event structures remaining in the
© Nationa! instruments Corporaton 38 LabVIEW Core 2 Course Manuallesson
g
vent Programming
chain. LabVIEW completes processing the user action which triggered the
event only after all configured Event structures handle the event without
discarding it.
Note National Instruments recommends you use filter events only when you want to
take part in the handling of the user action, either by discarding the event or by modifying
the event data, If you only want to know that the user performed a particular action, use
notify events.
Event structure cases that handle filter events have an Event Filter Node,
You can change the event data by wiring new values to these terminals, If
you do not wire a value to the data item of the Event Filter Node, the default
value equals the value that the comesponding item in the Event Data Node
returns, You can completely discard an event by wiring a TRUE value to the
Discard? terminal.
Note A single case in the Event structure cannot handle both notify and filter events.
A case can handle multiple notify events but can handle multiple filter events only if the
event data items are identical for all events.
Refer to the Using Events in LabVIEW section of this lesson for more
information about event registration.
Tip Inthe Edit Events dialog box, notify events are signified by a green arrow, and filter
events are signified by a red arrow.
Using Events in LabVIEW
LabVIEW can generate many different events. To avoid generating
unwanted events, use event registration to specify which events you want
LabVIEW to notify you about. LabVIEW supports two models for event
registration—static and dynamic.
Static registration allows you to specify which events on the front panel of
a VI you want to handle in each Event structure case on the block diagram
of that V1. LabVIEW registers these events automatically when the V1 runs,
so the Event structure begins waiting for events as soon as the VI begins
running. Each event is associated with a control on the front panel of the VI,
the front panel window of the VI as a whole, or the LabVIEW application.
You cannot statically configure an Event structure to handle events for the
front panel of a different VI. Configuration is static because you cannot
change at run time which events the Event structure handles.
Dynamic event registration avoids the limitations of static registration by
integrating event registration with the VI Server, which allows you to use
Application, VI, and control references to specify at run time the objects for
LaQVIEW Cove 2 Gorse Wansal 38 comLesson’ Event Programming
which you want to generate events, Dynamic registration provides more
flexibility in controlling what events LabVIEW generates and when it
generates them, However, dynamic registration is more complex than static
registration because it requires using VI Server references with block
diagram functions to explicitly register and unsegister for events rather than
handling registration automatically using the information you configured in
the Event structure.
ZY Note in general, Lab VIEW generates user interface events only as a result of direct user
interaction with the active front panel. LabVIEW does not generate events, such as Value
Change, when you use shared variables, global variables, local variables, DataSocket.
and so on. However, you can use the Value (Signaling) property to generate a Value
‘Change event programmatically. In many cases, you can use programmatically generated
events instead of queues and notifiers.
“The event data provided by a LabVIEW event always include a time stamp,
an enumeration that indicates which event occurred, and a VI Server
reference to the object that triggered the event. The time stamp is a
millisecond counter you can use to compute the time elapsed between
‘Wo events or to determine the order of occurrence. The reference to the
‘object that generated the event is strictly typed to the VI Server class of that
object. Events are grouped into classes according to what type of object
generates the event, such as Application, VI, or Control. Ifa single case
handles multiple events for objects of different V1 Server classes, the
reference type is the common parent class of all objects. For example, if you
configure a single case in the Event structure to handle events for a numeric
control and a color ramp control, the type of the control reference of the
event source is Numeric because the numeric and color ramp controls are in
the Numeric class. If you register for the same event on both the VI and
Control class, LabVIEW generates the VI event first.
FX Note Clusters are the only container objects for which you can generate events.
LabVIEW generates Control events for clusters, before it generates events for the objects
they contain, except in the case of the Value Change event. The Value Change event
‘generates the event on an element in the cluster, then on the cluster itself. If the Event
structure case for a VI event or for a Control event on a container object discards the
event, LabVIEW does not generate further events.
Each Event structure and Register For Events function on the block diagram
‘owns a queue that Lab VIEW uses to store events. When an event occurs,
LabVIEW places a copy of the event into each queue registered for that
event. An Event structure handles all events in its queue and the events in
the queues of any Register For Events functions that you wired to the
dynamicevent terminals of the Event structure. LabVIEW uses these queues
to cnsure that events are reliably delivered to each registered Event structure
in the order the events occur.
© Ratna! instruments Corporation a {LaDVIEW Gore 2 Gourss Manuallesson 3 Fron Programming
By default, when an event enters a queue, LabVIEW locks the front panel
that contains the object that generated that event, LabVIEW keeps the front
pane! locked until all Event structures finish handling the event, While the
front panel is locked, LabVIEW does not process front panel activity but
places those interactions in a buffer and handles them when the front panel
is unlocked.
For example, a user might anticipate that an event case launches an
application that requires text entry. Since the user already knows text entry
is needed, he might begin typing before the application appears on the front
panel. If the Lock front panel (defer processing of user action) until this
event case completes option is enabled, once the application launches and
appears on the front panel, it processes the key presses in the order in which
they occurred. If the Lock front panel (defer processing of user action)
until this event case completes option is disabled, the key presses might be
processed elsewhere on the front panel, since LabVIEW does not queue
their execution to depend on the completion of the event case.
Front panel locking does not affect certain actions, such as moving the
window, interacting with the scroll bars, and clicking the Abort button.
LabVIEW can generate events even when no Event structure is waiting to
handle them. Because the Event structure handles only one event each time
it executes, place the Event structure in a While Loop to ensure that an Event
structure can handle all events that occur.
LX Caution Tf no Event structure executes to handle an event and front panel locking is
enabled, the user interface of the VI becomes unresponsive, If this occurs, click the
Abort button to stop the VI. You can disable front panel locking by right-clicking the
Eyeat structure and removing the checkmark from the Lock front panel (defer
processing of user action) until this event case completes checkbox in the Edit Events
dialog box. You cannot turn off front panel locking for filter events.
Static Event Registration
Static event registration is available only for user interface events. Use the
Edit Events dialog box to configure an Event structure to handle a statically
registered event. Select the event source, which can be the application, the
VI, or an individual control. Select a specific event the event source can
generate, such as Panel Resize, Value Change, and so on. Edit the case to
handle the event data according to the application requirements.
LabVIEW statically registers events automatically and transparently when
you run a VI that contains an Event structure. LabVIEW generates events
fora VI only while that VI is running or when another running VI calls the
Vias a subVI.
LabVIEW Core 2 Course Manual w8 icalesson Bent Programming
When you run a VI, LabVIEW sets that top-level VI and the hierarchy of
subVIs the VI calls on its block diagram to an execution state called
reserved, You cannot edit a VI or click the Run button while the VI is in the
reserved siate because the VI can he called as a subVI at any time while its
parent VI runs. When LabVIEW sets a VIto the reserved state, it
automatically registers the events you statically configured in all Event
structures on the block diagram of that VI. When the top-level VI finishes
running, LabVIEW sets it and its subVI hierarchy to the idle execution state
and automatically unregisters the events.
Refer to the labview\ examples \general \uievents.11b for
examples of using static event registration
Configuring Events
Before you configure events for the Event structure to handle, refer to the
Caveats and Recommendations when Using Events in LabVIEW topic of the
LabVIEW Help.
Complete the following steps to configure an Event structure case to handle
an event
1, (Optional) If you want to configure the Event structure to handle a user
event, a Boolean control within a radio buttons control, or a user
interface event that is generated based on a reference to an application,
VI, or control, you first must dynamically register that event. Refer to
the Dynamically Registering Events topic of the LabVIEW Help for
more information about using dynamic events.
2. Right-click the border of the Event structure and select Edit Events
Handled by This Case from the shortcut menu to display the Edit
Events dialog box to edit the current case. You also can select Add
Event Case from the shortcut menu to create a new case.
3. Specify an event source in the Event Sources panc.
4. Select the event you want to configure for the event source, such as Key
Down, Timeout, or Value Change from the Events list. When you
select a dynamic event source trom the Event Sources list. the Events
list displays that event. This is the same event you selected when you
registered the event. If you have registered for events dynamically and
wired event reg refnum out to the dynamic event terminal, the sources
appear in the Dynamie section.
5. Ifyou want to add additional events for the current case to handle, click
the + button and repeat steps 3 and 4 ta specify each additional event.
‘The Event Specifiers section at the top of the dialog box lists all the
events for the case to handle. When you click an item in this list, the
Event Sources section updates to highlight the event source you
© fatonalnsruments Corporation 39 LabVIEW Gore 2 Course Maruatessen Event Programming
selected. You can repeat steps 3 and 4 to redefine each event or click the
X button to remove the selected event.
6. Click the OK button to save the configuration and close the dialog box.
‘The event cases you configured appear as selection options in the event
selector label at the top of the Event structure and the Event Data node
displays the data common to all events handled in that case.
7. (Optional) You can use a Timeout event to configure an Event structure
to wait a specified amount of time for an event to occur. Wire a value to
the Timeout terminal at the top left of the Event structure to specify the
number of milliseconds the Event structure should wait for an event to
occur before generating a Timeout event. The default value for the
‘Timeout terminal is -1, which specifies to wait indefinitely for an event
to occur.
8 Repeat steps 1 through 6 for each event case you want to configure.
Refer to the following VIs for examples of using events:
laby iew\ examples \general \dynamicevents,11b
Jabview\examples\ceneral\uievents.11b
Event Example
Ry Note
Figure 3-1 shows an Event structure configured with the Menu Selection
(User) event, This V1 uses the Event structure to capture menu selections
made using the user-defined menu named sample. rtm. The ItemTag
returns the menu item that was selected and the MenuRef returns the refnum
to the menubar. This information is passed to the Get Mena Item Info
function, Refer to examples \general\uievents. 11b for more
examples of using events.
Figure 3-1, Menu Selection (User) Event
If you use the Get Menu Selection function with an Event structure configured to
handle the same menu item, the Event structure takes precedence, and LabVIEW ignores
the Get Menu Selection function. In any given VI, use the Event structure or the Get
‘Menu Selection function to handle menu events, not both,
To practice the concepts in this section, complete Exercise 3-1.
LabVIEW Gore 2 Course Manual #10 ‘comLesson 3 Event Programming
C. Caveats and Recommendations
‘The following list describes some of the caveats and recommendations to
consider when incorporating events into LabVIEW applications.
+ Avoid using an Event structure outside a loop.
LabVIEW can generate events even when no Event structure is waiting
to handle them. Because the Event structure handles only one event each
time it executes, place the Event structure in a While Loop that
terminates when the VI is no longer interested in events to ensure that an
Event structure handles all events that occur.
+ Remember to read the terminal of a latched Boolean contro] in its Value
Change event case.
When you trigger an event on a Boolean control configured with a
latching mechanical action, the Boolean control does not reset to its
default value until the block diagram reads the terminal on the Boolean
control. You must read the terminal inside the event case for the
mechanical action to work correctly.
+ Avoid placing two Event structures in one loop.
National Instruments recommends that you place only one Event
structure in a loop. When an event occurs in this configuration, the Event
structure handles the event, the loop iterates, and the Event structure
‘waits for the next event to accur. If you place two Event structures in a
single loop, the loop cannot iterate until both Event structures handle an
event. If you have enabled front panel locking for the Event structures,
the user interface of the VI can become unresponsive depending on how
the user interacts with the front panel.
Refer to the Caveats and Recommendations when Using Events in
LabVIEW topic of the LabVIEW Help for more caveats and
recommendations when you use events in LabVIEW.
D. Event-Based Design Patterns
Event-based design patterns provide efficiency gains because they only
respond when an event occurs. When LabVIEW executes the Event
structure, the VI that contains the Event structure sleeps until a registered
events occurs, or generates. When a registered event generates, the Event
structure automatically wakes up and executes the appropriate subdiagram
to handle the event.
© Natoral nstramants Gomoraton sin {1aDVIEW Core 2 Cowse ManuelLesson’ Event Programming
User Interface Event Handler Design Pattern
“LADEN Gore 2 Course naval
‘The user interface event handler design pattern provides a powerful and
efficient architecture for handling user interaction with LabVIEW. Use the
user interface event handler for detecting when a user changes the value of
‘a control, moves or clicks the mouse, or presses a key.
‘The standard user interface event handler template consists of an Event
structure contained in a While Loop, as shown in Figure 3-2. Configure the
Event structure to have one case for each category of event you want to
detect. Each event case contains the handling code that executes
immediately after an event occurs.
Because the event handler loop wakes up precisely when an event occurs
and sleeps in between events, you do not have to poll or read control values
repeatedly in order to detect when a user clicks a button. The user interface
event handler allows you to minimize processor use without sacrificing
interactivity.
Taialvas" Value Change |
1 Event Structure 3 Timeout Terminal
2 While Loop 4 Event Data Node
Figure 3-2. User interface Event Handler Design Pattern
Acommon problem when using the user interface event handler is that it
computes the While Loop termination before the Event structure executes.
This can cause the While Loop to iterate one more time than you expected,
To avoid this situation, compute the While Loop termination within all your
event handling code.
‘The event handler code must execute quickly, generally within 200 ms.
Anything slower can make it feel as if the user interface is locked up. Also,
if the event handler code takes a long time to execute, the Event structure
might lock. By default, the front pane! locks while an event is handled, You
#1 iconLesson Event Programming
can disable front panel locking for each event case to make the userinterface
more responsive. However, any new events that are generated while an event
is being handled will notbe handled immediately. So, the user interface will
still seem unresponsive.
Any code that is in an event case cannot be shared with another Event
structure, You must use good code desiga when using the Event structure.
Modularize code that will he shared between multiple Event structure cases.
‘The Event structure includes a Timeout event, which allows you to control
when the Timeout event executes. For example, if you set a Timeout of
200 ms, the Timeout event case executes every 200 ms in the absence of
other events. You can use the Timeout event to perform critical timing in
your code.
Producer/Consumer (Events) Design Pattern
(One of the most versatile and flexible design patterns combines the
producer/consumer and user interface event handler design patterns,
AVI built using the producer/consumer (events) paltern responds to the
user interface asynchronously, allowing the user interface to continuously
respond to the user. The consumer loop of this pattern responds as events
‘occur, similarto the consumer loop of the producer/consumer (data) design
pattern.
‘The producer/consumer (events) design pattern uses the same
implementation as the producer/consumer (data) design pattern except the
producer loop uses an Event structure to respond to user interface events, as
shown in Figure 3-3. The Event structure enables continuous response 10
user interaction.
(© fatona!istuments Corporation a LapMiEW Cove 2 Course anualLesson’ vet Prearammng
(haere
fa fonbeony 7 x
~ La i Litt
Se (coon
> ops ne concer
a ee
o
aka
=
Es a
+
oO #
Figure 3-3. Producer/Consumer (Events) Design Patten
Figure 3-3 shows how the Producer/Consumer (Events) template uses
synchronization functions to expand the functionality of the design pattern,
Queues have the ability to transfer any data type. The data type transferred
in Figure 3-3 isa string, A string is not the most efficient data type for
passing data in design patterns. A more efficient data type for passing data
in design patterns isa cluster consisting of an enumerated type control and
a variant,
To practice the concepts in this section, complete Exercise 3-2.
‘LaOVIEW Gore 2 Course Manuat oH icoLesson’ Event Prosramming
Self-Review: Quiz
Using user interface events allows you to synchronize user actions on
the front panel with block diagram execution.
a. True
b. False
‘The Event structure handles only one event each time it executes.
a. True
b. False
3. Which of the following are examples of user interface events?
a, Mouse click
Keystroke
Event Filter Node
Value change of a control
aoe
4, Which of the following operations will generate a Value Change event
fora numeric control?
a. Click inside the digital display window and enter a number from the
keyboard
b. Click the increment or decrement arrow butions
c. Place the cursor to the right of the digit you want to change and press
the up or down arrow keys
d. Update the numeric control using a local variable
(© fatal nsiruments Corporation HI LaDviEW core Course Maruat‘FUDUNOOYOOD90O 5Lisson Bent Prooramming
Self-Review: Quiz Answers
v
(© National Insruments Corporation
Using user interface events allows you to synchronize user actions on
the front panel with block diagram execution.
a. True
b. False
‘The Event structure handles only one event each time it executes.
a, True
b. False
‘Which of the following are examples of user interface events?
a. Mouse click
b. Keystroke
c. Event Filter Node
d. Value change of a control
Which of the following operations will generate a Value Change event
for a numeric control?
a, Click inside the digital display window and enter a number from
the keyboard
b. Click the increment or decrement arrow buttons
¢. Place the cursor to the right of the digit you want to change and
press the up or down arrow keys
d, Update the numeric control using a local variable
a7 LabVIEW Gore 2 Course Marua)esson 3 Event Programming
Notes
LABVIEW Cove 2 Course Mansa)
418Error Handling
Topics
By default, LabVIEW automatically handles any error when a VI runs by
suspending execution, highlighting the subVI or function where the error
occurred, and displaying an error dialog box. Automatic error handling is
convenient for quick prototypes and proof-of-concept development, but not
recommended for professional application development. If you rely on
automatic error handling your application might stop in a critical section of
your code because of an error dialog box. The user might be unable to
continue running the application or fix the problem,
By manually implementing error handling, you control when popup dialogs
occur. If you plan to create a stand-alone application, you must incorporate
‘manval error handling because LabVIEW does not display automatic error
handling dialog boxes in the LabVIEW Run-Time Engine.
Importance of Error Handling
Detect and Report Errors
Errors and Warnings
Ranges of Error Codes
Error Handlers
Fone >
© Nationa nsruments Corporation 4 Laptiew core 2 course Manualessen 4 Frror Harling
A. Importance of Error Handling
Error handling is the mechanism for anticipation, detection, and resolution
of wamings and errors. Error handling is an essential component in your
LabVIEW application development. With error handling you quickly
pinpoint the source of programming errors, Without it, you might observe
unexpected behavior but struggle to find the sourve of the problem.
Error handling is also extremely valuable when you test your application to
ensure that your error reporting is meaningful and that the error handling
code safely stops your application when an error occurs. For example,
during stress testing you are setting values or conditions that are beyond the
normal operational capacity of your application which often result in errors.
‘When such errors occur, you want to ensure proper shutdown of your
application.
Error handling continues to be important after an application is deployed.
Error handling can help detect system and environment differences—such
‘as differences in file systems, memory, and disk resources,
B. Detect and Report Errors
To implement good error handling, you must determine the actions to take
when an error occurs at every point in your application, To begin with, you
‘must utilize the error terminals on functions and VIs. Since the error cluster
is implemented asa flow-through parameter, you should propagate errors by
wiring the error out cluster of the first node you want to execute to the error
in cluster of the next node you want to execute. You must continue to do this
for sequences of nodes.
As the VI runs, LabVIEW tests for errors at each node. If LabVIEW does
not find any errors, the node executes normally. If LabVIEW detects an
error, the node passes the error to the next node without executing that part
of the code. Any subVJs that you create should also implement this
flow-through behavior.
Use the Merge Error function to merge the error out cluster values from,
parallel sequences. Refer to Figure 4-1 for an example of merging error
information from parallel node sequences.
LabVIEW Core 2 Course Manual 2 icon