LabVIEW TM Core 1 Participant Guide Cour-15-314
LabVIEW TM Core 1 Participant Guide Cour-15-314
LabVIEW TM Core 1 Participant Guide Cour-15-314
A. What is LabVIEW?
Objective: Recognize benefits of LabVIEW.
Benefits of LabVIEW
• A platform-based approach for measurement and control
• Interfaces with wide variety of hardware
• Scales across different targets and operating systems
• Provides built-in analysis libraries
Graphical Multi-threaded
Uses icons and wires instead of with text. Enables your code to have automatic
parallelism.
Dataflow-oriented Object-oriented
Data-driven, or data-dependent. The flow of Allows a variety of similar, yet different
data between nodes in the G code items, to be represented as a class of objects
determines the execution order. in software.
Compiled Multi-target
Compiles G code directly to machine code. Targets multicore processors and other
parallel hardware such as field-programmable
gate arrays (FPGAs).
Multi-platform Memory-managed
Is portable between LabVIEW on different Provides you with options for improving
operating systems. performance.
Synchronous
Event-driven
Allows the user's direct interaction with the
program without the need for polling.
B. Project Explorer
Objective: Recognize the main components of the Project Explorer.
Project Explorer Projects in LabVIEW consist of VIs, files necessary for those VIs to run
properly, and supplemental files such as documentation or related
links. Use the Project Explorer window to manage projects in
LabVIEW. A LabVIEW project is denoted by a project file (.lvproj)
LabVIEW Files
Listed below are some of the characteristics of a LabVIEW project.
• Manages project files
• Deploys programs to remote embedded targets such as NI CompactRIO
• Creates stand-alone executables and installers for distribution
• Makes it possible to distribute code to developers and create shared libraries
• Can integrate LabVIEW programs with source code control software such as Perforce
1-4 | ni.com
LabVIEW Core 1 Participant Guide
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 sections. You can add files under each target.
1 2 3 4
8 7 6 5
Tip The Source Control toolbar is only available if you have source control
configured in LabVIEW.
Adds a directory on disk to the project Organizes project items and does not
represent files on disk
C. Parts of a VI
Objective: Recognize and understand the difference between the front panel and block
diagram.
Demonstration: Components of a VI
LabVIEW VIs contain three main components—the front panel window, the block diagram, and
the icon/connector pane.
Is the user interface. Contains the graphical Represents the VI and makes
source code. it possible to use the VI as a
subVI.
Has controls (inputs) and Contains terminals for front Maps the inputs and outputs
indicators (outputs). panel controls and to the VI.
indicators.
1-6 | ni.com
LabVIEW Core 1 Participant Guide
D. Front Panel
Objective: Recognize the components and functionality of the Front Panel window and
select appropriate controls and indicators
Front Panel User interface for the VI. Contains controls and indicators, which are
the interactive input and output terminals of the VI, respectively.
Controls Indicators
Knobs, push buttons, dials, and other inputs Graphs, LEDs, and other displays
Simulate instrument input devices and Simulate instrument output devices and
supply data to the block diagram display data the block diagram acquires or
generates
1-8 | ni.com
LabVIEW Core 1 Participant Guide
E. Block Diagram
Objective: Recognize features of the Block Diagram and be able to select functions.
Block Diagram Block diagram objects include terminals, subVIs, functions, constants,
structures, and wires, which transfer data among other block diagram
objects.
1-10 | ni.com
LabVIEW Core 1 Participant Guide
Component Description
Terminals Terminals are the entry and exit ports that exchange information
between the front panel and block diagram. You can view terminals as
icon conserve space.
Nodes Nodes are objects on the block diagram that have inputs and/or outputs
and perform operations when a VI runs. Nodes are analogous to
statements, operators, functions, and subroutines in text-based
programming languages. Nodes can be functions, subVIs, or structures.
Function Nodes Functions are fundamental operating elements of LabVIEW and do not
(Functions) have front panels or block diagrams. Function icons have pale yellow
backgrounds.
SubVIs SubVIs are VIs that run on the block diagram of another VI. They have
front panels and block diagrams. Any VI has the potential to be used as
a subVI. When you double-click a subVI, the front panel and block
diagram open.
Use the icon from the upper-right corner of the front panel as the icon
that appears when you place the subVI on a block diagram.
Connector Pane The connector pane is the map of inputs and outputs of a VI
Express VIs
Express VIs are a type of subVI that you configure with dialog boxes. Icons for Express VIs
appear on the block diagram as icons surrounded by a blue field.
Nodes Appearance
You can display VIs and Express VIs as either icons or expandable nodes. Use icons if you want
to conserve space on the block diagram. By default, subVIs appear as icons on the block
diagram, and Express VIs appear as expandable nodes.
To display a subVI or Express VI as an expandable node, right-click the subVI or Express VI and
remove the checkmark next to the View As Icon shortcut menu item.
Wires
Wires transfer data between block diagram objects. A broken wire appears as a dashed black
line with a red X in the middle. You cannot run a VI that contains a broken wire.
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
1-12 | ni.com
LabVIEW Core 1 Participant Guide
To toggle display of the Context Help window select Help»Show Context Help, press the
<Ctrl-H> keys, or click the Show Context Help Window button on the toolbar.
LabVIEW Help
You can access the LabVIEW Help by clicking the More Help button in the Context Help
window, selecting Help»LabVIEW Help, or clicking the blue Detailed Help link in the Context
Help window. You also can right-click an object and select Help from the shortcut menu.
Examples
Use the NI Example Finder to browse or search examples installed on your computer or on the
NI Developer Zone at ni.com/zone. These examples demonstrate how to use LabVIEW to
perform a wide variety of test, measurement, control, and design tasks. Select Help»Find
Examples to launch the NI Example Finder.
1-14 | ni.com
Exercise 1-1 Concept: Exploring a VI
Goal
As a class, identify the parts of an existing VI.
Description
You received a VI from an employee that takes the seconds until a plane arrives at an airport and converts the time 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.
3. On the front panel, identify the following items. How many can you find of each item?
Controls
Indicators
Free labels
Run button
Icon
Connector pane
4. Press <Ctrl-T> to view the front panel and block diagram at the same time or select Window»Tile Up and Down or Window»Tile Left and Right.
Tip To switch between the front panel window and the block diagram without tiling the windows, press <Ctrl-E>.
5. On the block diagram, identify the following items. How many can you find of each item?
Controls
Indicators
Constants
Free labels
| 1-15
6. Use the Context Help to learn more about the items on the block diagram.
1-16
Lesson 1
Press <Ctrl-H> to open the Context Help window or select Help»Show Context Help.
|
ni.com
Move the Context Help window to a convenient area where the window does not hide part of the block diagram.
Navigating LabVIEW
Place your cursor over each of the different color wires to see which data type they represent.
The Context Help window content changes to show information about the object that your mouse is over.
Place your cursor over the Quotient & Remainder function. Read the Context Help window and click the Detailed Help link to launch the LabVIEW
Help and learn more about this function.
8. Refer to Figures 1-1 and 1-2 to verify that you identified all items correctly.
3 4 5
Lesson 1
Figure 1-2. Block Diagram Items
|
2
ni.com
Navigating LabVIEW
1
3
5
For each input, compare the given outputs to the outputs listed in Table 1-1. If the VI works correctly, they should match.
Navigate the subpalettes or use the Search button to search the Controls palette.
1-20 | ni.com
LabVIEW Core 1 Participant Guide
Functions Palette
The Functions palette contains the VIs, functions and constants you use to create the block
diagram. Select View»Functions Palette to display it.
Navigate the subpalettes or use the Search button to search the Functions palette.
Quick Drop
The Quick Drop dialog box lets you quickly find controls, functions, VIs, and other items by
name. Press the <Ctrl-Space> keys to display the Quick Drop dialog box.
Global Search
Use the Search bar in the top right of the front panel and block diagram windows to search
palettes, LabVIEW Help, and ni.com.
Lesson 1
Goal
|
ni.com
Learn to use the palettes and search for controls, functions, and VIs.
Navigating LabVIEW
Description
1. Open a blank LabVIEW project.
Click the Create Project button in the LabVIEW Getting Started window and then click Blank Project.
Click Finish.
Right-click My Computer in the Project Explorer window and select New»VI from the shortcut menu.
3. Select View»Controls Palette from the menu of the VI front panel window.
Select the following palettes to add them to the Controls palette and click the OK button. Do not deselect any palettes.
– Silver
– Signal Processing
Notice that the three palettes you just selected now appear in the Controls window.
Use palettes to locate controls and functions when you want to explore the options available to you or when you are not sure of the name of the control
or function you need.
Click String Control (Silver) in the search results and drag it to the front panel window to place the object.
6. Open the block diagram and right-click anywhere on the block diagram to display the Functions palette.
Click the pin in the upper left-hand corner to keep the palette open.
Tip You can customize the Functions palette just like you customized the Controls palette.
– In the search results, double-click Cosine <<Trigonometric Functions>> to display the function on the palette.
– Double-click File I/O in the search results to display the File I/O palette.
– Drag the Write To Text File function from the palette to the block diagram.
Use the Quick Drop feature when you know the name of the function or VI you want to use.
Type Bundle By Name and double-click Bundle By Name in the search results. The cursor changes to a hand with the Bundle By Name function.
© National Instruments
Double-click the function in the search results and place the function on the block diagram.
Type Random in the Search bar in the upper right hand corner of the block diagram.
| 1-23
Note As you type, the global search automatically looks for matches in the LabVIEW Help and LabVIEW palettes. It also searches for online
material related to your query.
Hover the mouse over the first result in the Palette section, Random Number (0-1). You now see the following three options:
1-24
Lesson 1
– Drop—Allows you to place this function immediately on the block diagram
|
ni.com
Navigating LabVIEW
– Help—Brings up the help topic for this function.
Right-click the Add function and notice that Numeric palette is available from the shortcut menu.
Practice placing functions from the Numeric palette on the block diagram.
11. Close the VI and LabVIEW project. You do not need save the files.
Additional Resources
Topics
+ Dataflow
+ LabVIEW Data Types
+ Tools for Programming, Cleaning and Organizing Your VI
+ Building a Basic VI
Exercises
Exercise 2-1 Selecting a Tool
Exercise 2-2 Simple AAV VI
LabVIEW Core 1 Participant Guide
A. Dataflow
Objective: Recognize characteristics of dataflow on the block diagram.
Dataflow Dataflow is the movement of data through the nodes of a block diagram.
1 Node executed only when all the input data are available.
2 Node supplies data to the output terminals only when it is finished executing.
Description: Work through this exercise on your own first, and then as a class, we will discuss
how data flow determines execution order. You can find answers to these questions following
this section.
Note Nodes are objects on the block diagram that have inputs and/or outputs and
perform operations when a VI runs.
1. Which node executes first? Is there any dependency between the File Dialog function and
the Simulate Signal Express VI?
3. Because a wire connects the File Dialog function to the TDMS File Viewer VI, can the TDMS
File Viewer VI execute before the TDMS Close function?
4. How many nodes must execute before the TDMS Write function can execute?
2-4 | ni.com
LabVIEW Core 1 Participant Guide
7. In Figure 2-3 an error wire connects the Express VIs. Which Express VI executes last?
3. Because a wire connects the File Dialog function to the TDMS File Viewer VI, can the TDMS
File Viewer VI execute before the TDMS Close function?
No. The TDMS File Viewer VI cannot execute before the TDMS Close function because the
yellow error wire connecting the TDMS Close function and the TDMS File Viewer VI forces
data dependency. Remember, the data to all inputs of a node must be available before a
node can execute. Therefore, the TDMS File Viewer VI must receive data from both the
green Boolean wire and the yellow error wire before the VI can execute.
4. How many nodes must execute before the TDMS Write function can execute?
Three nodes must execute before the TDMS Write function can execute: File Dialog, TDMS
Open, and Simulate Signal. The TDMS Write function also depends on the Simulated Signal
string constant, but that input is instantaneous.
5. Should a well-designed block diagram flow in a particular direction?
Yes. A well-designed block diagram typically flows from left to right. This makes it easier
to see the flow of data on the block diagram. However, do not assume left-to-right or
top-to-bottom execution when no data dependency exists.
6. In Figure 2-2, which Express VI executes last?
Either the Statistics Express VI or the Write to Measurement File Express VI executes last
or they execute in parallel. The DAQ Assistant Express VI cannot execute last because both
the Statistics Express VI and the Write to Measurement File Express VI are dependent on
the data signal from the output of the DAQ Assistant Express VI.
Note In LabVIEW, the flow of data, rather than the sequential order of commands,
determines the execution order of block diagram elements. Therefore, it is possible
to have simultaneous operations.
7. In Figure 2-3 an error wire connects the Express VIs. Which Express VI executes last?
The Write to Measurement File Express VI executes last. It has a data dependency on both
the DAQ Assistant Express VI and the Statistics Express VI.
8. In Figure 2-4, which Tone Measurements Express VI executes last?
Either one of the Tone Measurement Express VIs can execute last. Even though the Tone
Measurements 2 Express VI has an extra dependency on the Filter Express VI, the Filter
Express VI might execute before the Tone Measurements 1 Express VI allowing the Tone
Measurements 2 Express VI to execute before the Tone Measurements 1 Express VI.
Although it seems as if the Tone Measurements 1 Express VI would execute first, without
an explicit data dependency there is no way to know definitely it would execute first.
2-6 | ni.com
LabVIEW Core 1 Participant Guide
Boolean Data
Use Boolean controls and indicators to enter and display Boolean (TRUE/FALSE) 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.
Complete the multimedia module, Mechanical Actions of Boolean Controls, available in the
<Exercises>\LabVIEW Core 1\Multimedia\ folder.
2-8 | ni.com
LabVIEW Core 1 Participant Guide
Strings
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.
• Controlling instruments with text commands
• Storing numeric data to disk. To store numeric data in an ASCII file, first convert data to
strings.
• Instructing or prompting with dialog boxes.
• Right-click a string control or indicator on the front panel to select from the display type.
Hex Display Displays the ASCII value of 5468 6572 6520 6172 6520 666F
each character in hex 7572 2064 6973 706C 6179 2074
instead of the character 7970 6573 2E0A 5C20 6973 2061
itself. 2062 6163 6B73 6C61 7368 2E
Demonstration: Enums
Enums give users a list of items from which to select. Enums are useful because they make
strings equivalent to numbers, which are easy to manipulate on the block diagram. Each item
represents a pair of values: a string value and a 16-bit integer.
How might a Path data type differ from a String data type?
Although it is easy to convert a Path to a String, it is best to use a Path data type when working
with a location of a file or directory because LabVIEW can handle the folder specifiers for the
specific operating system, such as using a backslash on Windows OS.
2-10 | ni.com
LabVIEW Core 1 Participant Guide
Tip You can manually choose the tool you need by selecting it on the Tools palette.
Select View»Tools Palette or press <Shift> and right-click to display the palette.
Color Copy Use the Color Copy tool to copy colors for
pasting with the Coloring tool.
• To reroute multiple wires and objects, select a section of your block diagram then click the
Clean Up Diagram button.
• To clone an object, select the object with the Positioning tool and hold the <CTRL> key
down while dragging the object to a new location.
2-12 | ni.com
LabVIEW Core 1 Participant Guide
Description
During this exercise, you complete tasks in a partially built front panel and block diagram. These
tasks give you experience using the automatic tool selection.
3. Select View»Tools Palette from the menu to display the Tools window.
Tip Press <Shift> and right-click the front panel to open the Tools palette
temporarily.
Figure 2-5 shows an example of the front panel as it appears after your modifications. In steps 4
through 9 you increase the size of the waveform chart, rename the numeric control, change the
value of the numeric control, and move the knob.
Move the cursor to the right edge of the Chart waveform chart until you see the resizing
nodes appear around the chart.
Move the cursor to the middle right resizing node until the cursor changes to a double
arrow, as shown in Figure 2-6.
Drag the repositioning node until the waveform chart is the size you want.
Double-click the word Chart. LabVIEW highlights the word and automatically selects
the Labeling tool in the Tools window.
Complete the entry by clicking outside the control label or clicking the Enter Text button
on the toolbar.
Notice that LabVIEW automatically returns to the Positioning tool in the Tools window.
The Positioning tool is the default tool. If LabVIEW does not switch back to the
Positioning tool, click the Automatic Tool Selection button in the Tools window to
enable automatic tool selection.
6. Rename the Numeric control to Number of Measurements using the Labeling tool.
Complete the entry by clicking outside the control or clicking the Enter Text button on
the toolbar.
7. Change the value of the Number of Measurements control to 100 using the Labeling tool.
When the cursor changes to the Labeling tool icon, click the mouse button.
2-14 | ni.com
LabVIEW Core 1 Participant Guide
Complete the entry by clicking outside the control, clicking the Enter Text button on
the toolbar, or pressing the <Enter> key on the numeric keypad,
Change the value of the Delay Multiplier knob using the Operating tool.
When the cursor changes to the Operating tool icon, press the mouse button and drag
to the value you want.
8. Change the color of the Delay Multiplier knob using the Coloring tool.
Click the background square in the Coloring button and select a color from the color
picker.
When the cursor changes to a paintbrush, click the Delay Multiplier knob.
Click the Automatic Tool Selection button again to turn on automatic tool selection.
9. Try changing the value of objects, resizing objects, and renaming objects until you are
comfortable with using these tools.
Figure 2-7 shows an example of the block diagram as it appears after your modifications.
Steps 11 through 12 instruct you on how to update the block diagram to move the Number
of Measurements terminal and wire the terminal to the count terminal of the For Loop.
11. Move the Number of Measurements terminal using the Positioning tool.
Move the cursor over the terminal until the cursor changes to an arrow.
Click and drag the terminal to the new location as shown in Figure 2-7.
12. Wire the Number of Measurements terminal to the count terminal of the For Loop using the
Wiring tool.
Move the cursor to the right of the terminal, stopping when the cursor changes to a
wiring spool.
Move the cursor to the count (N) terminal of the For Loop.
13. Try moving other objects, deleting wires and rewiring them, and wiring objects and wires
together until you are comfortable with using these tools.
Tip You can also select specific objects to clean up, such as wires or individual
nodes. <Shift>-click to select multiple objects and then click the Clean Up Diagram
button. LabVIEW cleans up only the objects that you select and not the entire block
diagram. Configure how LabVIEW cleans up objects by selecting Tools»Options from
the menu, clicking the Block Diagram category, and changing the options in the
Block Diagram Cleanup section.
Note Boolean controls and indicators have Boolean text labels in addition to their
control labels. Boolean text labels change depending on the value of the control or
indicator. The label for the control or indicator does not change depending on the
value of the control or indicator.
2-16 | ni.com
LabVIEW Core 1 Participant Guide
Right-click the Stop Button terminal and select Properties from the shortcut menu. Set
the properties as shown in Figure 2-8.
Figure 2-8. Changing the Boolean Text for the Stop Control
1 Control label—This text identifies the terminal of the Boolean control for programming
purposes. This text does not appear on the front panel unless you select Visible.
2 Boolean text—This text appears only on the front panel, and by default, appears in the
center of the Boolean control.
Right-click the Stop Button terminal and select Find Control from the shortcut menu.
Notice the control label is Stop Button and the button text is End.
Tip You can also double-click the Stop Button terminal to find the button control
on the front panel.
The time required to execute this VI is equivalent to Number of Measurements times Delay
Multiplier. When the VI is finished executing, the Temperature Chart displays the data.
17. Close the VI and click the Don’t Save - All button. You do not need to save the VI.
Label Guidelines
• Use free labels to document algorithms and add reference information.
• Label structures to specify the main functionality.
• Label long wires to identify their use/contents.
• Label constants to specify the nature of the constant.
• To avoid clutter, document the Context Help window of subVIs or functions instead of
labels.
Default Values
Setting a default value on a control or indicator can aid in future development and
troubleshooting by giving the programmer an idea of the expected data for that object.
Configure default values for controls and indicators by right-clicking on the object and selecting
Data Operations»Make Current Value Default from the short-cut menu.
2-18 | ni.com
LabVIEW Core 1 Participant Guide
D. Building a Basic VI
Objective: Recognize Express VIs and be able to apply them appropriately.
Building a Basic VI
Express VIs are designed specifically for completing common, frequently used operations.
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.
VI Icon Description
Read from Reads a file that was created using the Write
Measurement To Measurement File Express VI. It
File specifically reads LVM or TDM file formats.
This Express VI does not read ASCII files.
VI Icon Description
2-20 | ni.com
LabVIEW Core 1 Participant Guide
2. Analyze: Circle the Express VI that is best suited to determining the average value of the
acquired data.
3. Visualize: Circle the Express VIs and/or indicators that are best suited to displaying the data
on a graph and logging the data to file.
2. Analyze: Use the Statistics Express VI to determine the average value of the sine wave.
Because this signal is cyclical, you could also use the Cycle Average option in the Amplitude
and Level Measurements Express VI to determine the average value of the sine wave.
3. Visualize: Use the Write to Measurement File Express VI to log the data and use the
Waveform Graph to display the data on the front panel window.
2-22 | ni.com
LabVIEW Core 1 Participant Guide
Scenario
You need to acquire a sine wave for 0.1 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, a file that logs the data, and an indicator that displays the average data value.
Flowchart
The flowchart in Figure 2-9 illustrates the data flow for this design.
Log Data
Implementation
1. Prepare your hardware to generate a sine wave. If you are not using hardware, skip to
step 2.
Find the BNC-2120 and visually confirm that it is connected to the DAQ device in your
computer.
Using a BNC cable, connect the Analog In Channel 1 to the Sine Function Generator,
as shown in Figure 2-10.
Set the Frequency Selection switch and the Frequency Adjust knob to their lowest
levels.
3
PFI 0 / P1.0
4
1. RES+
2. AI GND
3. AI SENSE
4. RES-
PULSES
UP /DN
AI 0 AI 1
PFI 1 / P1.1
FS GS FS GS
PFI 2 / P1.2
PFI 3 / P1.3
PFI 4 / P1.4
PFI 5 / P1.5
AI 2 AI 3
PFI 6 / P1.6
FS GS FS GS
PFI 7 / P1.7
PFI 8 / P2.0
PFI 9 / P2.1
PFI 12 / P2.4
AI 4 AI 5 PFI 13 / P2.5
FS GS FS GS
PFI 14 / P2.6
+5 V
D GND
AI 6 AI 7 USER-DEFINED
SIGNALS*
FS GS FS GS
ANALOG OUTPUTS
USER 1
USER 2
AO
AO 0 AO 1
DIGITAL I/O
P0.6
P0.5
P0.4
P0.3
Sine /Triangle TTL Square Wave
P0.2
P0.1
P0.0
D GND
LO HI LO HI
Amplitude Adjust Frequency Adjust
2. Open LabVIEW.
4. Add a new VI to the project from the Project Explorer window and save the VI as Simple
AAV.vi in the <Exercises>\LabVIEW Core 1\Simple AAV directory.
2-24 | ni.com
LabVIEW Core 1 Participant Guide
In steps 5 through 6 you will build a front panel similar to the one in Figure 2-11.
5. Add a waveform graph to the front panel window to display the acquired data.
Type Waveform in the text box and double-click Waveform Graph (Silver) in the search
results list.
6. Add a numeric indicator to the front panel window to display the average value.
Type Numeric Indicator in the text box and double-click Numeric Indicator (Silver)
in the search results list.
In the steps 7 through 14 you build a block diagram similar to the one in Figure 2-12.
Note The terminals corresponding to the front panel window objects appear on the
block diagram.
8. Acquire a sine wave for 0.1 seconds by following the instructions in Table 2-1. If you have
hardware installed, follow the instructions in the Hardware Installed column to acquire the
data using the DAQ Assistant. If you do not have hardware installed, follow the instructions
in the No Hardware Installed column to simulate the acquisition using the Simulate Signal
Express VI.
1. Press <Ctrl-Space> to open the Quick 1. Press <Ctrl-Space> to open the Quick
Drop dialog box. Drop dialog box.
2. Type DAQ Assist in the text box and 2. Type Simulate Signal in the text
double-click DAQ Assistant in the box and double-click Simulate Signal in
search results list. the search results list.
3. Place the DAQ Assistant on the block 3. Place the Simulate Signal Express VI on
diagram. the block diagram.
4. Wait for the DAQ Assistant dialog box 4. Wait for the Simulate Signal dialog box
to open. to open.
5. Select Acquire Signals»Analog Input» 5. Select Sine for the signal type.
Voltage for the measurement type.
6. Select ai1 (analog input channel 1) for 6. Set the signal frequency to 100.
the physical channel.
7. Click the Finish button. 7. In the Timing section, set the Samples
per second (Hz) to 1000.
2-26 | ni.com
LabVIEW Core 1 Participant Guide
9. In the Timing Settings section enter 9. In the Timing section, set the Number
100 in Samples To Read. of samples to 100.
10. Enter 1000 in Rate (Hz). 10. In the Timing section, select the
Simulate acquisition timing option.
Tip Reading 100 samples at a rate of 1,000 Hz retrieves 0.1 seconds worth of
data.
9. Use the Statistic Express VI to determine the average value of the data acquired.
Place the Statistics Express VI on the block diagram to the right of the DAQ Assistant
(or Simulate Signal Express VI).
Type write to measurement in the text box and double-click Write to Measurement
File in the search results list.
Place the Write to Measurement File Express VI on the block diagram below the
Statistics Express VI.
Wait for the Write to Measurement File Express VI dialog box to open.
Leave all configuration settings in the Write to Measurement File dialog box as default.
Note Future exercises do not detail the directions for finding specific functions or
controls in the palettes. Use Quick Drop, the palette search feature, or the global
search 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 the Sine output
of the 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 the Sine
output of the Simulate Signal Express VI) at the location where the cursor changes to
the Wiring tool.
Place the mouse cursor over the Waveform 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 the Sine
output of the 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.
Test
1. Switch to the front panel window of the VI.
Use the labeling tool to change the last number on the Time scale of the waveform
graph to .1.
4. Click the Run button on the front panel toolbar to run the VI. 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.
2-28 | ni.com
LabVIEW Core 1 Participant Guide
Additional Resources
5. If an input to a function is marked with a red dot (known as coercion dot), what does the
dot indicate?
a. Data was transferred into a structure.
b. That input has not been wired
c. The wire is broken
d. The value passed into a node was converted to a different representation.
6. Which mechanical action causes a Boolean control in the FALSE state to change to TRUE
when you click it and stay TRUE until LabVIEW has read the value?
a. Switch Until Released
b. Switch When Released
c. Latch When Pressed
d. Latch When Released
5. If an input to a function is marked with a red dot (known as coercion dot), what does the
dot indicate?
a. Data was transferred into a structure.
b. That input has not been wired
c. The wire is broken
d. The value passed into a node was converted to a different representation.
6. Which mechanical action causes a Boolean control in the FALSE state to change to TRUE
when you click it and stay TRUE until LabVIEW has read the value?
a. Switch Until Released
b. Switch When Released
c. Latch When Pressed
d. Latch When Released
Topics
+ Correcting Broken VIs
+ Debugging Techniques
+ Error Handling
Exercises
Exercise 3-1 Debugging
LabVIEW Core 1 Participant Guide
If the Run button appears broken when you finish wiring the block diagram, the VI is broken and
cannot run.
Example Cause
Required terminal is
unwired.
Control wired to
another control.
B. Debugging Techniques
Objective: Identify the LabVIEW tools for debugging and select the tool appropriate to the
situation.
Debugging Tips
The following table includes a few common problems to look for when debugging your VIs.
3-4 | ni.com
LabVIEW Core 1 Participant Guide
Job Aid
If a VI is not broken, but you get unexpected data, you can use the following checklist 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.
Select View»Error List and place a checkmark in the Show Warnings checkbox to see all
warnings for the VI.
Triple-click a wire 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.
Use the Find dialog box to search for subVIs, text, and other objects to correct throughout
the VI.
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.
Click the Retain Wire Values button on the block diagram toolbar to retain wire values for
use with 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.
If the VI runs more slowly than expected, confirm that you turned off execution highlighting
in subVIs.
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.
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.
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.
3-6 | ni.com
LabVIEW Core 1 Participant Guide
Breakpoints
Use the Breakpoint tool to place a breakpoint on a VI, node, or wire and pause execution at that
location.
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
Tip Always remember to turn this feature off when you are done debugging to free
memory.
3-8 | ni.com
Exercise 3-1 Debugging
Goal
Use the debugging tools built into LabVIEW.
Description
The VIs in this exercise check the validity of a triangle and then calculate the area. For a triangle to be valid, all three sides must have a length that is greater
than zero. The subVI in this exercise uses Heron’s formula to calculate the area of a triangle. You can use this method when you know the lengths of all
three sides of a triangle.
Heron’s formula
A = s( s – a)( s – b)(s – c )
where
a+b+c
s = ----------------------
2
The default values, which you will use to debug and test this VI, are Side A = 6, Side B = 8, Side C = 10. Therefore the correct values are as follows:
6 + 8 + 10
s = ------------------------ = 12
2
A = 12 × 6 × 4 × 2 = 24
You might want to refer to this calculation as you debug the VI.
breakpoints and probes to determine if the calculations are correct and figure out where an error originates.
| 3-9
Edit-Time Errors
3-10
Lesson 3
Locate and correct errors that prevent the VI from running.
|
Open Area and Validity of a Triangle VI from the Project Explorer window.
Notice the Run button on the toolbar appears broken, indicating that the VI is broken and cannot run.
2. Display and examine the block diagram of Area and Validity of a Triangle VI shown in Figure 3-2.
This VI takes input values for each of the three sides of a triangle, passes the values into a subVI that determines the area, and checks that the values
entered are valid for a triangle.
Click the broken Run button to display the Error list window, which lists all the errors.
Select an error description in the Error list window. The Details section describes the error and in some cases recommends how to correct the error.
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 Show Error button or double-click the error description to highlight the area on the block diagram that contains the error.
Tip For errors in the Area of a Triangle subVI, double-click to open it. In the Area of Triangle VI, notice that the formula for calculating the area
of a triangle requires the sum of the sides be divided by 2. Right-click the y input of the Divide function and select Create»Constant and enter a
value of 2.
Lesson 3
Identify and correct errors that cause the VI to behave unexpectedly and return incorrect responses.
|
Use the default values for each side. These values are valid measurements for a triangle.
Notice that although the numbers you entered are valid, the LED is not illuminated and the Area of a Triangle indicator displays NaN.
Click the Highlight Execution button on the toolbar to enable execution highlighting.
Click the Retain Wire Values button on the toolbar so you can see the last value passed on a wire.
Right-click each of the input wires to the Compound Arithmetic Function and select Probe. This displays the Probe Watch Window.
Notice that one of the wire values is False as shown in Figure 3-3.
Because you are checking to see that all three sides of the triangle have positive lengths, either the input value is invalid or the logic is incorrect.
The input values were all positive numbers, so that means the logic is incorrect.
Notice that the node returning a value of False is a Less than Zero? function, but this section of code should be checking to see if the value is
greater than zero.
Right-click the Less than Zero? function and select Replace»Comparison Palette»Greater than Zero?.
| 3-13
4. Test the VI.
3-14
Lesson 3
Run the VI.
|
ni.com
The area of the triangle is calculated in the subVI, so you must continue debugging in the Area of a Triangle subVI.
Display the block diagram of the Area and Validity of a Triangle VI.
Click the Step Into button to start single-stepping through the VI. Execution highlighting shows the flow of data on the block diagram from one node
to another. Nodes blink to indicate they are ready to execute.
Click the Step Over button after each node to step through the entire block diagram until you get to the subVI. Each time you click the Step Over
button, the current node executes and pauses at the next node.
When you get to the subVI, click the Step Into button to open the block diagram of the Area of Triangle subVI. The subVI is paused.
1 The breakpoint stops the VI after the Square Root node executes and before the value is output to the Area of Triangle indicator.
6. Click the red pause button to resume the execution of the VI.
The VI continues executing until the breakpoint and then pauses again.
Move the cursor to hover over the input wire of the Square Root function. You should see a tip strip with a value of -576. You cannot take the
square root of a negative number, which is why the Area of Triangle indicator returns NaN.
Tip If you cannot see the tip strip, you can click the wire to open the Probe Watch window to see the value.
Hover over other wires or use the Probe Watch window to examine other intermediate values.
Notice that the value on the (S-B) wire is also a negative number. If you look more closely, you notice that the inputs for the subtract function are
reversed.
Tip Press <Ctrl> and click one of the inputs to switch them. When you press <Ctrl> and hover over an input, you see the cursor change.
Lesson 3
Run the VI again.
|
ni.com
Check the intermediate values as the VI runs or hover over the wires after it pauses at the breakpoint and verify that the values returned are correct.
Turn off execution highlighting in the Area of Triangle VI and the Area and Validity of a Triangle VI.
Test
1. Test the Area and Validity of a Triangle VI using the values for Side A, Side B, and Side C in Table 3-1. For each set of test values, record the area you
get when you run the VI.
24 30 18
12 12 12
15 20 25
Table 3-2. Area and Validity of a Triangle Test Values - Area Answers
24 30 18 216
12 12 12 62.35
15 20 25 150
C. Error Handling
Objective: Describe the difference between automatic and manual error handling.
Enabling automatic error handling does not override manual error handling. If the error cluster is
wired and the VI uses the Simple Error Handler, then LabVIEW defaults to manual error handling.
Error Clusters
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. Use the error cluster controls and indicators to create error inputs and
outputs in subVIs.
Errors Warnings
Passed to the next node without executing Node executes normally, but it is important
that part of the code to monitor warnings during development to
ensure proper behavior of your application
3-18 | ni.com
LabVIEW Core 1 Participant Guide
Merge Errors
The Merge Errors Function:
• Returns the first error found. If no error is found, it returns the first warning.
• Does not concatenate errors.
At the end of your application after all error sources are merged into one error cluster, you must
report errors to the user using the Simple Error Handler VI or another error reporting mechanism.
Additional Resources
Execution Highlighting
Single-Stepping through a VI
Managing Breakpoints
Displaying Warnings
Handling Errors
3-20 | ni.com
LabVIEW Core 1 Participant Guide
2. Which of the following are components and data types of the error cluster?
a. Status: Boolean
b. Error: String
c. Code: 32-bit integer
d. Source: String
3. All errors have negative error codes and all warnings have positive error codes.
a. True
b. False
2. Which of the following are components and data types of the error cluster?
a. Status: Boolean
b. Error: String
c. Code: 32-bit integer
d. Source: String
3. All errors have negative error codes and all warnings have positive error codes.
a. True
b. False
Topics
+ Loops Review
+ While Loops
+ For Loops
+ Timing a VI
+ Data Feedback in Loops
+ Plotting Data
Exercises
Exercise 4-1 Pass Data Through Tunnels
Exercise 4-2 Calculating Average Temperature
Exercise 4-3 Temperature Monitor VI—Plot Multiple Temperatures
LabVIEW Core 1 Participant Guide
A. Loops Review
Objective: Recognize loop structures and explain how to use them.
While Loops—Review
• Similar to Do Loop or a Repeat-Until Loop
• Repeats code segment until a condition is met
• Always execute at least once
• Iteration terminal—output that contains the number of complete iterations
Code
No Repeat (code);
Condition Until Condition met;
Code
met?
End;
Yes
End
1 2 3
For Loops—Review
• Repeats code a certain number of times
• The value in the count terminal (an input terminal) indicates how many times to repeat the
subdiagram in the For Loop.
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
Stops executing only if the value at the Executes a set number of times
conditional terminal meets the condition
Tunnels automatically output the last value Tunnels automatically output an array of
data
Description
For the following scenarios, decide whether to use a While Loop or a For Loop.
4-4 | ni.com
LabVIEW Core 1 Participant Guide
Scenario 1
Acquire pressure data in a loop that executes once per 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 pressure data until the pressure is greater than or equal to 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 pressure and temperature data 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 incrementally 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?
1. If you use a While Loop, what is the condition that you need to stop the loop?
While Loop: Time = 1 minute
2. If you use a For Loop, how many iterations does the loop need to run?
For Loop: 60 iterations
Scenario 2
Acquire pressure data until the pressure is greater than or equal to 1400 psi.
1. If you use a While Loop, what is the condition that you need to stop the loop?
While Loop: Pressure = 1400 psi
2. If you use a For Loop, how many iterations does the loop need to run?
For Loop: unknown
Scenario 3
Acquire pressure and temperature data 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?
While Loop: [(Last Temperature = Previous Temperature) for 2 minutes or more] and [(Last
Pressure = Previous Pressure) for 2 minutes or more]
2. If you use a For Loop, how many iterations does the loop need to run?
For Loop: unknown
Scenario 4
Output a voltage ramp starting at zero, increasing incrementally 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?
While Loop: Voltage = 5 V
4-6 | ni.com
LabVIEW Core 1 Participant Guide
2. If you use a For Loop, how many iterations does the loop need to run?
For Loop: 11 iterations (Including the two end points, count the iteration for each value -
0, 0.5, 1.0, 1.5, ... 4.5, 5.0.)
B. While Loops
Objective: Recognize tunnels and explain their purpose on a loop structure and demonstrate
how to use error checking and error handling inside a loop.
Tunnels
Tunnels transfer data into and out of structures. Data pass out of a loop after the loop
terminates.
1 Use the error cluster and a stop button to determine when to stop the loop.
Lesson 4
|
Goal
ni.com
Use a While Loop and an iteration terminal and pass data through a tunnel.
Using Loops
Scenario
Create 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 generating the matching number.
Design
Use the following flowchart and input/output list to create the VI for this exercise. The flowchart in Figure 4-1 illustrates the data flow for this design.
Figure 4-1. Auto Match Flowchart
Generate a
Random Number No
Between 0 and 1
Multiply by 1000
Add 1 to
Round to Nearest Display Value = Number
Yes Iteration
Integer Value to User to Match?
Terminal
Display Number
of Iterations
Lesson 4
The following table describes the inputs and outputs for this exercise.
|
Using Loops
Type Name Properties
Numeric control Number to Match Double-precision, floating-point between 0 and 1000, coerce to nearest whole
number, default value = 50
Implementation
1. Create a blank project and save it as Auto Match.lvproj in the <Exercises>LabVIEW Core 1\Auto Match directory.
2. Create a new VI in the project and save it as Auto Match.vi in the same directory as the project.
1 Set the default value of the Number to Match control to 50—Enter 50 in the Number to Match control and then right-click the control and select Data
Operations»Make Current Value Default.
2 Set Number of Iterations indicator to output a signed, long integer—Right-click the indicator and select Representation»I32.
4. Set the properties for the Number to Match control so that the data type is a 32-bit unsigned integer, the data range is from 0 to 1000, the increment
value is 1, and the digits of precision is 0.
Right-click the Number to Match control and select Representation»U32 from the shortcut menu.
Right-click the Number to Match control and select Data Entry from the shortcut menu. Set the properties on the Data Entry and Display Format
tabs as shown in Figure 4-3.
1 2
Lesson 4
Right-click the Current Number indicator and select Representation»U32 from the shortcut menu.
|
ni.com
Right-click the Current Number indicator and select Display Format. Set the properties as shown in Figure 4-4.
Using Loops
Figure 4-4. Current Number Indicator Display Format Properties
6. Create the block diagram shown in Figure 4-5.
1 2 9
3 4 5 6 7 8
Tip Coercion dots can cause a VI to use more memory and increase its run time, so try to keep data types consistent in the VIs you create.
| 4-13
7. Update the VI to remove the coercion dots.
4-14
Lesson 4
Right-click the wire coming from the Round To Nearest function and select Insert»Numeric Palette»Conversion»To Unsigned Long Integer as shown
|
in Figure 4-6. This inserts the To Unsigned Long Integer function on the wire.
ni.com
Using Loops
Figure 4-6. Inserting the To Unsigned Long Integer Function on a Wire
10. Right-click the Current Number indicator and select Advanced»Synchronous Display.
Note If synchronous display is enabled, then every time the block diagram sends a value to the Current Number indicator, the block diagram
stops executing until the front panel has updated the value of the indicator. In this exercise, you enable the synchronous display, so you can see
the Current Number indicator get updated repeatedly on the front panel. Typically, the synchronous display is disabled to increase execution
speed since you usually do not need to see every single updated value of an indicator on the front panel.
Test
1. Change the number in the Number to Match control to a number that is in the data range, which is 0 to 1000 with an increment of 1.
3. Change the Number to Match value and run the VI again. Current Number updates at every iteration of the loop because it is inside the loop.
Number of Iterations updates upon completion because it is outside the loop.
On the block diagram toolbar, click the Highlight Execution button to enable execution highlighting.
| 4-15
5. Run the VI and observe the data flow.
4-16
Lesson 4
6. Turn off execution highlighting to quickly finish executing the VI.
|
ni.com
Using Loops
Change the Number to Match value to a number that is out of the data range, 0 - 1000.
Notice LabVIEW coerces the out-of-range value to the nearest value in the data range you specified in step 4 of the Implementation section.
C. For Loops
Objective: Demonstrate how to add a conditional terminal to a For Loop and describe how
numeric conversion occurs on the For Loop count terminal.
Conditional Terminal
You can add a conditional terminal to configure a For Loop to stop when a Boolean condition or
an error occurs. A For Loop with a conditional terminal executes until the condition occurs or
until all iterations are complete, whichever happens first.
The following For Loop generates a random number every second until 100 seconds has passed
or until the user clicks the stop button.
1 Right-click the loop border and select Conditional Terminal from the shortcut menu.
2 Red glyph appears in the count terminal and a conditional terminal in the lower right corner.
1 Coercion Dot
For better performance, avoid coercion by using matching data types or programmatically
converting to matching data types.
D. Timing a VI
Objective: Identify scenarios that require loop timing and apply the appropriate function
Wait Until Next ms Multiple Monitors a millisecond counter and waits until the millisecond
counter reaches a multiple of the amount you specify. This
function is synced to the system clock.
Wait (ms) Waits until the millisecond counter counts to an amount equal
to the input you specify
Time Delay Express VI Similar to the Wait (ms) function with the addition of built-in
error clusters.
4-18 | ni.com
LabVIEW Core 1 Participant Guide
1 2
4-20 | ni.com
Exercise 4-2 Calculating Average Temperature
Goal
Use a While Loop and shift registers to average data.
Scenario
The Temperature Monitor VI acquires and displays temperature. Modify the VI to average the last five temperature measurements and display the running
average on the waveform chart.
Design
Figure 4-8 shows the Temperature Monitor VI front panel and block diagram.
To modify this VI, you need to retain the temperature values from the previous four iterations of the While Loop and average the values. To accomplish this,
you modify this VI as follows:
• Initialize the shift register with a reading from the simulated thermometer.
• Calculate and chart only the average temperature.
| 4-21
Implementation
4-22
Lesson 4
1. Test the VI.
|
Using Loops
Open Temperature Monitor VI from the Project Explorer window.
Run the VI. Notice the variation in the simulated temperature reading.
1 3 4
1 Shift Registers—Stacked shift registers collect multiple temperature readings. Right-click the border of the While Loop and select Add Shift Register.
Drag the lower resizing handle of the shift register to display four shift registers.
2 Create a copy of the Thermometer (Demo) VI—Press <Ctrl> while dragging the subVI outside the While Loop to create a copy. The Thermometer
(Demo) VI returns one temperature measurement and initializes the left shift registers before the loop starts.
3 Compound Arithmetic—Returns the sum of the current temperature and the four previous temperature readings. Resize the function to have five
terminals.
4 Divide—Returns the average of the last five temperature readings.
Note You can create stacked shift register terminals on the left side of a loop to remember multiple previous iterations and carry those values
to the next iterations. This technique is useful for averaging data points. Stacked shift registers can occur only on the left side of the loop because
the right terminal transfers the data generated from only the current iteration to the next iteration.
Test
1. Run the VI.
During each iteration of the While Loop, the Thermometer (Demo) VI takes one temperature measurement. The VI adds this value to the last
four measurements stored in the left terminals of the shift register. The VI divides the result by five to find the average of the five measurements—the
current measurement plus the previous four. The VI displays the average on the waveform chart. Notice that the VI initializes the shift register with a
temperature measurement.
F. Plotting Data
Objective: Use data feedback in a loop to plot waveform charts.
Waveform Chart
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.
6
1
7
4
4-24 | ni.com
LabVIEW Core 1 Participant Guide
You can configure how the chart updates to display new data. 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.
• Scope Chart—Shows one item of data, such as a pulse or wave, scrolling partway across
the chart from left to right.
• 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.
Lesson 4
|
Goal
ni.com
Plot multiple data sets on a single waveform chart and customize the chart view.
Using Loops
Scenario
Modify the VI from Exercise 4-2 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 4-10 shows the front panel for the existing Temperature Monitor VI and Figure 4-11 shows the block diagram.
To modify the block diagram in Figure 4-11, 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 terminal.
Implementation
1. Open the Temperature Monitor VI you created in Exercise 4-2.
Lesson 4
Figure 4-12. Temperature Monitor VI Block Diagram—Plotting Multiple Temperatures
|
ni.com
Using Loops
1 Bundle—Passes the current temperature and average temperature to the Temperature History chart.
3. Modify the front panel so that it resembles Figure 4-13.
1 Show both plots in the plot legend—Use the positioning tool to resize the plot legend to show two objects. Double-click the label to edit the plot names.
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.
2 Change the plot type of Current Temperature—Use the Operating tool to select the plot in the plot legend. Click the plot icon, select Common Plots
from the menu, and choose the plot you want.
3 Display Graph Palette—Right-click the Temperature History chart and select Visible Items»Graph Palette.
4 Display Scale Legend—Right-click the Temperature History chart and select Visible items»Scale Legend.
Test
1. Run the VI. Use the tools in the scale legend and the graph palette to examine the data as it generates.
Additional Resources
4-30 | ni.com
LabVIEW Core 1 Participant Guide
In this lesson you will learn about arrays, clusters, and type
definitions and be able to identify applications where using
these data structures can be beneficial.
Topics
+ Arrays
+ Common Array Functions
+ Polymorphism
+ Auto-Indexing
+ Clusters
+ Type Definitions
Exercises
Exercise 5-1 Manipulating Arrays
Exercise 5-2 Temperature Warnings VI—Clusters
Exercise 5-3 Temperature Warnings VI—Type Definition
LabVIEW Core 1 Participant Guide
A. Arrays
Objective: Identify when to use arrays and learn how to create and initialize arrays.
Arrays
Note Array indexes in LabVIEW are zero-based. The index of the first element in
the array, regardless of its dimension, is zero.
1D and 2D Examples
Arrays can have multiple dimensions.
• 1D array:
For example, LabVIEW represents a text array that lists the twelve months of the year as a
1D array of strings with twelve elements. Index is zero-based, which means the range is 0
to n - 1, where n is the number of elements in the array. For example, n = 12 for the twelve
months of the year, so the index ranges from 0 to 11. March is the third month, so it has
an index of 2.
• 2D array:
Column Index
0 1 2 3 4 5 6 7
0
1
2
Row Index
3
4
5
6
7
For example, LabVIEW represents a table of data with rows and columns as a 2D array.
2D 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.
Initializing Arrays
An uninitialized array contains a fixed number of dimensions but no elements. An initialized
defines the number of elements in each dimension and the contents of each element.
1 2
Create an array control or indicator on the front panel by adding an array shell to the front panel,
as shown in the following front panel, and dragging a data object or element, which can be a
numeric, Boolean, string, path, refnum, or cluster control or indicator, into the array shell.
To create an array constant on the block diagram, select an array constant on the Functions
palette, place the array shell on the block diagram, and place a string constant, numeric
constant, a Boolean constant, or cluster constant in the array shell.
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 multi-plot
XY graphs.
5-4 | ni.com
LabVIEW Core 1 Participant Guide
Initialize Array
Creates an n-dimensional array in which every element is initialized to the value of element.
Search 1D Array
Searches for an element in a 1D array starting at start index. Because the search is linear, you
need not sort the array before calling this function. LabVIEW stops searching as soon as the
element is found.
5-6 | ni.com
LabVIEW Core 1 Participant Guide
Description
Each of the VIs shown has missing information. Determine what belongs in the highlighted
section.
C. Polymorphism
Objective: Understand the ability of various VIs to accept input data of different data types.
Polymorphism
Polymorphism The ability of VIs and functions to automatically adapt to accept input data of
different data types.
5-8 | ni.com
LabVIEW Core 1 Participant Guide
D. Auto-Indexing
Objective: Use auto-indexed inputs and outputs to create graphs and arrays.
Auto-Indexing
If you wire an array to or from a For Loop or While Loop, you can link each iteration of the loop
to an element in that array by enabling auto-indexing. The tunnel image changes from a solid
square to the image to indicate auto-indexing.
1 3
1 Right-click the tunnel and select Enable Indexing or Disable Indexing to toggle the state of
the tunnel.
2 Auto-indexed output arrays are always equal in size to the number of iterations.
3 Only one value (the last iteration) is passed out of the loop when auto-indexing is disabled.
Waveform Graphs
A waveform graph collects the data in an array and then plots the data to the graph.
For example, consider the following block diagram. The array Input Array contains the following
elements: 7, 2, 0, 3, 1, 9, 5, and 7. Because of the conditional tunnel, the Values less than 5
array contains only the elements 2, 0, 3, and 1 after this loop completes all iterations.
1 Right-click the loop output tunnel and selecting Tunnel Mode»Conditional from the
shortcut menu.
1 The inner loop creates the column elements and the outer loop creates the row elements.
5-10 | ni.com
LabVIEW Core 1 Participant Guide
Auto-Indexing Input
Use an auto-indexing input array to perform calculations on each element in an array. If you wire
an array to an auto-indexing tunnel on a For Loop, you do not need to wire the count (N)
terminal.
I
1 2
1 The For Loop executes the number of times equal to the number of elements in the array.
2 If the iteration count terminal is wired and arrays of different sizes are wired to
auto-indexed tunnels, the actual number of iterations becomes the smallest of the choices.
1 The For Loop iterates 5 times and because the iterations are zero-based, the output is 4.
Lesson 5
|
Goal
ni.com
Implementation
1. Open Manipulating Arrays.lvproj in the <Exercises>\LabVIEW Core 1\Manipulating Arrays directory.
2. Open Array Manipulation VI from the Project Explorer window. The front panel, shown in Figure 5-1, is already built for you.
2 1
1 Build Array—Expand this node to accept two inputs, and then right-click and select Concatenate inputs from the shortcut menu.
2 Wire the sine wave and square wave outputs to the Build Array function to create a 1D array with both waveforms.
4. Switch to the front panel and test the Concatenate Channels case.
Run the VI and notice that the sine wave is concatenated with a square wave.
6. Switch to the block diagram and select the Add/Subtract Channels case.
| 5-13
7. Complete the Add/Subtract Channels case as shown in Figure 5-3 and Figure 5-4.
5-14
Lesson 5
Figure 5-3. Array Manipulation VI—Add/Subtract Channels True Case
|
ni.com
1 Subtract?—Wire this to the case selector terminal so that the correct case executes when you click the Subtract? button on the front panel.
2 Case Structure—Place a Subtract function in the True case, so that the VI subtracts the elements of the array when the Subtract? button on the front
panel is pressed.
1 When the value of the Subtract? Boolean control is False, the array elements are added.
Note This case demonstrates polymorphic functionality by adding and subtracting elements of the array.
8. Switch to the front panel and test the Add/Subtract Channels case.
Click the Subtract? button and observe the behavior of subtracting the square wave from the sine wave.
10. Switch to the block diagram and select the Select a Channel case.
1 2
1 Build Array—Combines the sine and square waves into one 2D array.
2 Index Array—Extracts row 0 or 1 from the 2D array. The output from this function is a 1D array and is the waveform you select with the Select Channel
control. The waveform is displayed on the Single Channel of Data Waveform Graph and the Single Channel of Data Array indicator.
3 Select Channel—Wire to the row input of the Index Array function.
4 Array Size—Because you are using a 1D array, this function outputs a scalar value.
| 5-15
Note The Select a Channel case uses a property node to change the color of the graph plot. You learn about Property Nodes LabVIEW Core 2.
5-16
Lesson 5
12. Switch to the front panel and test the Select a Channel case.
|
ni.com
Switch between Channel 0 and Channel 1 and notice the different values shown in the Single Channel of Data Array indicator.
14. Switch to the block diagram and select the Waveform Data case.
15. Complete the Waveform Data case block diagram as shown in Figure 5-6.
The waveform datatype is a special kind of cluster that contains additional timing information about the waveform.
1 Add—Uses the value from the Offset control to modify the value of the waveform in the waveform datatype. Notice the value from the Offset control
must be coerced to be used with the waveform datatype.
Note Polymorphism is the ability of VIs and functions to automatically adapt to accept input data of different data types, including arrays,
scalars, and waveforms. VIs and functions are polymoprhic to varying degrees.
16. Switch to the front panel and test the Waveform Data case.
Change the value of the Offset control and notice the square wave move on the Waveform Data chart.
18. Switch to the block diagram and select the All Data Channel case.
19. Complete the All Data Channel case as shown in Figure 5-7.
2 3 4
1 Add—Modify the same data in one array by adding the value of the Channel 1 Offset to each element of the array.
2 For Loop—Extracts each element of the array using auto indexing so that the Add function in the For Loop can add the scalar value.
3 Build Array—Takes the two 1D arrays and builds a 2D array. Each 1D array becomes a row in the 2D array.
4 Array Size—Outputs a 1D array where each element shows the size of each dimension. In this exercise, you have 2 elements of data for the number
| 5-17
Lesson 5
array elements, as you do with the two Add functions in the All Data Channel case.
|
20. Switch to the front panel and test the All Data Channel case.
ni.com
Change the value of the Channel 1 Offset control and observe the behavior.
22. Switch to the block diagram and select the Waveform Subset case.
2 1
1 Array Subset—Extracts a subset of an existing array. In this exercise, you use this function to zoom in on a subset of the waveform you generated.
2 Numeric Constant—These constants specify that the function extract the first two rows starting at element 0.
3 Start Value—Sets the start index. The default value is set to start at element 0.
4 Length—Sets the number of elements to extract. The default value is set to output 1000 elements.
24. Switch to the front panel and test the Waveform Subset case.
Change value of the Start Value and Length sliders and notice that the Subset Data waveform graph x-axis starts at zero and finishes at the number
of elements in the new array. The x-axis starts at zero because the VI creates a brand new array and the graph does not know where the data was
located in the original array.
Complete the following steps to use the NI Example finder to locate example VIs that demonstrate different ways to use the Array function.
4. Click one of the example VIs in the search results list and read the description.
6. Read through the comments on the front panel and block diagram to learn more about what this example VI demonstrates.
7. Run the example, examine the different cases, and click the Stop button to exit.
8. Close the VIs and the NI Example Finder when you are finished.
E. Clusters
Objective: Identify when to use clusters and be able to create them.
Clusters
Cluster Array
5-20 | ni.com
LabVIEW Core 1 Participant Guide
Resize the cluster shell by dragging the cursor while you place the cluster shell.
Cluster Order
Cluster elements have a logical order unrelated to their position in the shell. 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.
Autosizing Clusters
Autosizing helps you arrange elements in clusters.NI recommends the following:
• Arrange cluster elements vertically.
• Arrange elements compactly.
• Arrange elements in their preferred order.
Disassembling Clusters
Use the Unbundle and Unbundle By Name functions to return individual cluster elements.
1 2
1 Unbundle By Name—Returns the cluster elements whose names you specify. The number
of output terminals does not depend on the number of elements in the input cluster.
2 Unbundle—Splits a cluster into its individual elements
Modifying a Cluster
Use Bundle By Name whenever possible to access elements in a cluster. Use Bundle when some
or all cluster elements are unnamed.
I
5-22 | ni.com
LabVIEW Core 1 Participant Guide
Plotting Data
Use the Context Help window to determine how to wire multi-plot data to Waveform Graphs,
Charts and XY Graphs.
Error Clusters
LabVIEW contains a custom cluster called the error cluster. LabVIEW uses error clusters to pass
error information.
5-24 | ni.com
Exercise 5-2 Temperature Warnings VI—Clusters
Goal
Create a cluster datatype containing the data to be passed around an application and, in the process, create scalable, readable code.
Scenario
Another developer has created a VI that displays temperature warnings. This VI is part of the temperature weather station project studied throughout this
course. Your task is to update this VI to use clusters instead of individual terminals for inputs and outputs.
Design
The flowchart in Figure 5-9 illustrates the data flow for the design of the Temperature Warnings VI.
Lesson 5
|
ni.com
Yes
Warning Text =
Warning Text =
Heatstroke
No Warning
Warning
Current Temp
No
<= Min Temp?
Yes
Warning
Text = No No
Warning?
Yes
Lesson 5
1. Open Weather Warnings.lvproj in the <Exercises>\LabVIEW Core 1\Weather Warnings directory.
|
1 3
1 Cluster—Use the Cluster control from the Silver palette and change the label to Weather Data.
2 Select controls and indicators to include in the cluster. <Shift>-click to select multiple objects.
3 Drag the controls and indicators into the Weather Data cluster.
4. Resize the cluster so that all the elements are visible and arranged vertically as shown in Figure 5-12.
Arrange Vertically.
| 5-29
5. Reorder the items in the cluster as shown in Figure 5-13.
5-30
Lesson 5
Figure 5-13. Reorder Cluster
|
ni.com
1 Right-click the edge of the cluster and select Reorder Controls in Cluster.
2 Click the controls to toggle the order of the items in the cluster.
3 Click the Confirm button to save the changes.
6. Modify the VI to receive and return cluster data.
Figure 5-14. Temperature Warnings—Weather Data In and Weather Data Out Clusters
1
2
1 Weather Data—<Ctrl>-click the Weather Data cluster and drag it to create a copy. Rename the copy Weather Data In.
2 Weather Data—Right-click the original cluster and select Change to Indicator. Rename the indicator Weather Data Out.
| 5-31
7. Modify the block diagram as shown in Figure 5-15 to extract data from the input cluster.
5-32
Lesson 5
Figure 5-15. Temperature Warnings with Clusters Block Diagram
|
ni.com
1 Unbundle By Name—Wire the Weather Data In control and expand the Unbundle By Name function to display three items. Wire the outputs of the
Unbundle By Name function to the broken wires in the order shown. Because you moved individual controls and indicators into a single cluster, you
must use the Unbundle By Name function to wire the internal controls and indicators independently of each other.
2 Bundle By Name—Wire the Weather Data In cluster around the analysis code to the input cluster of the Bundle by Name function. Display two elements
and use the Operating tool to select Warning? and Warning Text elements. Connect the broken wires to the Unbundle By Name inputs as shown.
Note If the order of the elements in the Unbundle By Name and the Bundle By Name functions is different than what you want, you can use
the Operating tool to change the order.
8. Save and close the Temperature Warnings VI.
Test
1. Enter values in the Current Temperature, Max Temperature and Min Temperature controls in the Weather Data In cluster.
2. Run the VI and verify that the Weather Data indicator displays correct values.
3. Save and close the VI
F. Type Definitions
Objective: Identify and determine when to use a type definition, strict type definition, or
control.
Control Options
Use custom controls and indicators to extend the available set of front panel objects and to
make them available on other front panels.
5-34 | ni.com
Exercise 5-3 Temperature Warnings VI—Type Definition
Goal
To improve the scalability of your application by using type definitions made from custom cluster controls, indicators, and constants of a particular data type.
Scenario
As a LabVIEW developer, you can encounter situations where you need to define your own custom data types in the form of clusters and enums. A challenge
associated with using custom data types is that you may need to change them later in development. In addition, you may need to change them after they
have already been used in VIs. For example, you create copies of a custom data type and use them as controls, indicators, or constants in one or more VIs.
Then you realize that the custom data type needs to change. You need to add, remove, or change items in the cluster data type or the enum.
Usually, you want all the copies of the custom data type to update if you update the original custom data type. To achieve this you need copies of the
custom data types to be tied to a type definition, which is defined as follows:
Type definition—A master copy of a custom data type that multiple VIs can use.
Implementation
In this exercise, you modify the Temperature Warnings VI that you revised in Exercise 5-2 in such a way that the changes to the Weather Data custom data
type propagate through the application.
When complete, the Weather Station application monitors temperature and wind information. This exercise modifies the Temperature Warnings VI. In the
Challenge exercise, you modify the Windspeed Warnings VI.
Place a File Path Control (Silver) in the Weather Data In cluster control.
Notice that the Temperature Warnings VI is broken. This is because the Weather Data In and Weather Data Out clusters are no longer the same
data type.
Open the block diagram and notice the broken wire connected to the Weather Data Out terminal.
| 5-35
Lesson 5
Right-click the border of the Weather Data In control and select Make Type Def.
|
ni.com
On the block diagram, the Weather Data In terminal now has a black triangle on the corner indicating that it is connected to a type definition.
1 The control type is Type Def, which maintains the link between this file and the custom control copies used in VIs.
Save the custom control as Weather Data.ctl in the <Exercises>\LabVIEW Core 1\Weather Warnings directory and close the control editor
window.
On the block diagram of the Temperature Warnings VI, notice the coercion dot on the Weather Data Out indicator terminal. This indicates that the
indicator is not tied to the type definition.
5. Tie the Weather Data Out indicator to the type definition.
Right-click the border of the Weather Data Out indicator on the front panel and select Replace»Select a Control from the shortcut menu.
Browse to and select the Weather Data.ctl file you just created.
Note You can no longer add or remove elements to or from the cluster control and indicator on the front panel. You must open the type
definition and add or remove the element from the control editor window.
Lesson 5
Right-click the border of the Weather Data In control and select Open Type Def from the shortcut menu.
|
ni.com
1 Enum (Silver)—Place an enum in the cluster and rename it Units. Right-click the enum and select Edit items. Create an item for Celsius and
Fahrenheit.
Save the Weather Data type definition and close the control editor window.
Notice that the Weather Data In control and Weather Data Out indicator on the Temperature Warnings VI have been updated with the changes you
made to the Weather Data type definition. Arrange the front panel of the VI as shown in Figure 5-18.
Figure 5-18. Temperature Warnings VI with Type Def Controls and Indicators
Challenge
In this challenge exercise, you modify the Windspeed Warnings VI to augment the Weather Station application.
In the Project Explorer window, right click My Computer and select Add»File from the shortcut menu.
| 5-39
Navigate to <Exercises>\LabVIEW Core 1\Weather Warnings\Support VIs and select Windspeed Warnings.vi.
2. Open the Windspeed Warnings VI.
5-40
Lesson 5
3. Copy the Weather Data In cluster from the Temperature Warnings VI to the Windspeed Warnings VI.
|
ni.com
4. Right-click the Weather Data In cluster and select Open Type Def from the shortcut menu.
7. Open Temperature Warnings VI and notice that the Weather Data In control and Weather Data Out indicator is updated to include the Windspeed data.
Additional Resources
5-42 | ni.com
LabVIEW Core 1 Participant Guide
2. You have two input arrays wired to a For Loop. Auto-indexing is enabled on both tunnels.
One array has 10 elements, the second array has five elements. A value of 7 is wired to the
Count terminal, as shown in the following figure. What is the value of the Iterations
indicator after running this VI?
3. Which of the following custom control settings defines the data type of all instances of a
control but allows for different colors and font styles?
a. Control
b. Type Definition
c. Strict Type Definition
d. Cluster control
4. You have input data representing a circle: X Position (I16), Y Position (I16), and Radius
(I16). In the future, you might need to modify your data to include the color of the circle
(U32).
What data structure should you use to represent the circle in your application?
a. Three separate controls for the two positions and the radius.
b. A cluster containing all of the data.
c. A custom control containing a cluster.
d. A type definition containing a cluster.
e. An array with three elements.
2. You have two input arrays wired to a For Loop. Auto-indexing is enabled on both tunnels.
One array has 10 elements, the second array has five elements. A value of 7 is wired to the
Count terminal, as shown in the following figure. What is the value of the Iterations
indicator after running this VI?
Value of Iterations = 4
LabVIEW does not exceed the array size. This helps to protect against programming error.
LabVIEW mathematical functions work the same way—if you wire a 10 element array to
the x input of the Add function, and a 5 element array to the y input of the Add function,
the output is a 5 element array.
Although the for loop runs 5 times, the iterations are zero based, therefore the value of the
Iterations indicators is 4.
3. Which of the following custom control settings defines the data type of all instances of a
control but allows for different colors and font styles?
a. Control
b. Type Definition
c. Strict Type Definition
d. Cluster control
4. You have input data representing a circle: X Position (I16), Y Position (I16), and Radius
(I16). In the future, you might need to modify your data to include the color of the circle
(U32).
What data structure should you use to represent the circle in your application?
a. Three separate controls for the two positions and the radius.
b. A cluster containing all of the data.
c. A custom control containing a cluster.
d. A type definition containing a cluster.
e. An array with three elements.
Topics
+ Case Structures
+ Event-Driven Programming
Exercises
Exercise 6-1 Temperature Warnings With Error Handling
Exercise 6-2 Converting a Polling Design to an Event Structure Design
LabVIEW Core 1 Participant Guide
A. Case Structures
Objective: Recognize and use the basic features and functionality of Case Structures.
6-4 | ni.com
LabVIEW Core 1 Participant Guide
Boolean
A newly-created Case structure defaults to a
Boolean input.
The Case Structure includes a True case and
a False Case.
Integer
Case Structure has any number of cases.
Specify a Default case.
The numeric representation of the integer
input will determine the range of possible
values for the Case Selector Label.
You can specify ranges of values for the
Case Selector Label.
Use Radix option in shortcut menu to specify
whether the Case Selector Label displays
values in decimal, hexadecimal, octal, or
binary.
String
Case Structure has any number of cases.
Specify a Default case.
By default, string values are case sensitive.
Shortcut menu includes option for Case
Insensitive Match for the string text.
Enum
Possible to ensure that the Case Structure
includes a case for every item in the enum.
Right-click the border of the Case Structure
and select Add Case for Every Value to
create a case for every item.
Error Cluster
Case Structure includes an Error Case and a
No Error Case.
Wire an error cluster to the terminal to
execute code if there is no error and skip
code if there is an error.
6-6 | ni.com
LabVIEW Core 1 Participant Guide
Numeric 0
Boolean FALSE
Lesson 6
|
Goal
ni.com
Design
Modify the flowchart created for the original Temperature Warnings VI as shown in Figure 6-3.
Output
MinTemp
Min Temp>= No Current
Min TempTemp
>= No Current Temp No No Warning
Max Temp MaxTemp
Max Temp Min Temp and
FALSE
Output Output
Heatstroke Freeze Warning
Create Error
Warning and and
TRUE TRUE
Output
Upper Limit
< Lower Limit
and TRUE
You must add a Case structure to the Temperature Warnings VI to execute the code if the maximum temperature is less than or equal to the minimum
temperature. Otherwise, the VI does not execute the code. Instead, the VI generates a new string and the Warning? indicator is set to TRUE.
Figure 6-4. Original Temperature Warnings VI Block Diagram
Implementation
1. Open Weather Warnings.lvproj in the <Exercises>\LabVIEW Core 1\Weather Warnings directory.
3. Open the block diagram and create space to add the Case structure.
Select the Weather Data In type-defined cluster terminal, the Unbundle by Name function, and the Error In terminal.
Tip To select more than one item press the <Shift> key while you select the items.
While the objects are still selected, use the left arrow key on the keyboard to move the controls to the left.
Tip Press and hold the <Shift> key to move the objects in five pixel increments.
Tip Press the <Ctrl> key and use the Positioning tool to drag out a region of the size you want to insert.
Select the Weather Data Out type-define cluster terminal, the Bundle by Name function, and the Error Out terminal.
| 6-9
While the terminals are still selected, use the right arrow key on the keyboard to move the indicators to the right.
6-10
Lesson 6
Select the wire connecting the Weather Data In terminal and the Bundle by Name function.
|
ni.com
While the wire is still selected, use the up arrow key on the keyboard to move the wire upward.
1 Less?—Compares the Max Temperature and Min Temperature. Make sure the Less? function is outside the Case structure.
2 Case Structure—Do not include the Weather Data In, Error In, Weather Data Out, or Error Out terminals in the Case structure because these controls
and indicators are used by both cases.
3 Set True and False cases—With the True case visible, right-click the border of the Case structure and select Make this Case False.
4 Case Structure—Wire the Error In terminal to the selector terminal to create No Error and Error cases. By default, the Case structure has True and False
cases. These cases change to Error and No Error cases only after you wire Error In to the selector terminal.
Figure 6-6. Temperature Warnings VI—No Error, True Case
1 True case—If the Max Temperature is set lower than the Min Temperature, the True case executes. Click the case selector label to choose the True
case.
2 True Constant—When the True case executes, the Temperature Warning? LED illuminates in the Weather Data Out cluster.
3 String Constant—If the Max Temperature is set lower than the Min Temperature, the warning Upper Limit < Lower Limit displays on the front
panel. Enter the text in the String Constant.
5. Predict the values for Temperature Warning Text and Temperature Warning? given each set of inputs.
Current Temperature Max Temperature Min Temperature Temperature Warning Text Temperature Warning?
30 30 10
25 30 10
10 30 10
25 20 30
| 6-11
6. Create the Error case in the outer Case structure so this VI can be used as a subVI.
6-12
Lesson 6
Figure 6-7. Temperature Warnings VI—Error Case
|
ni.com
Test
1. Switch to the front panel of the VI.
2. Test the VI by entering values from Table 6-2 in the Current Temperature, Max Temperature, and Min Temperature controls and running the VI for each
set of data.
Table 6-2 shows the expected Temperature Warning Text and Temperature Warning? Boolean value for each set of data.
Current Temperature Max Temperature Min Temperature Temperature Warning Text Temperature Warning?
25 30 10 No Warning False
What happens if you set the value for all three inputs to 10?
3. Test the Error case. To use this VI as a subVI, the VI must be able to handle an error coming into the VI. Test the Error case to make sure that this VI
can output the error information it receives.
On the front panel, use the Operating tool to click the status Boolean indicator inside the Error In cluster so that the indicator turns red and enter 7
in the code control.
Run the VI. The error information you entered passes through the Error case in the VI and is output in the Error Out cluster.
Display the block diagram, select the No Error case, highlight execution, and then run the VI again to see the error pass through the Error case.
On the front panel, right-click the border of the Error Out cluster and select Explain Error to display information about the error that was returned.
B. Event-Driven Programming
Objective: Recognize basic features and functionality of event structures.
Event-driven Method of programming where the program waits on an event to occur before
programming executing the code written to handle that event.
Event An asynchronous notification that something has occurred. Events can
originate from the user interface, external I/O, or other parts of the program. In
this course, you will only learn about user interface events, which include
mouse clicks, key presses, and value changes of a control.
Polling Event
6-14 | ni.com
LabVIEW Core 1 Participant Guide
1 2 3
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.
6-16 | ni.com
LabVIEW Core 1 Participant Guide
Lesson 6
|
Goal
ni.com
To convert a polling-based application to an event-based application and compare the different in performance.
Next, you modify the polling VI to create a more efficient, event-driven VI and observe the changes in behavior.
Table 6-3 lists the events you will implement in the UI Event Handler VI you create.
“Time Check”: Value Change Displays a time stamp when you click the Time Check button.
“Pane”: Mouse Down Displays the coordinates of the front panel point you click.
Panel Close? Handles the event in which the user tries to close the running VI by clicking the window close button.
“Stop”: Mouse Enter Produces a beep when the mouse cursor moves over the Stop button.
Open the Events.lvproj file in the <Exercises>\LabVIEW Core 1\Events directory and open the Polling VI from the project.
Press the <Ctrl-Alt-Delete> keys and select Start Task Manager from the menu.
3. Open the block diagram, turn on execution highlighting, and run the VI again.
4. Notice how often the Time Check terminal sends data to the Case structure and how often the While Loop iterates.
Select Open additional copy and add the copy to the project.
2. Close Polling.vi.
3. Open the block diagram of UI Event Handler.vi and move the Stop terminal and the Time Check terminal outside the While Loop. You move these
terminals into the appropriate event cases later in this exercise.
5. Place an Event structure inside the While Loop between the iteration terminal and the conditional terminal.
6. Right-click the Event structure and select Edit Events Handled by This Case from the shortcut menu.
Lesson 6
Figure 6-8. Configuring the "Stop": Value Change Event
|
ni.com
1 NewVal event data—Resize the event data items list so that only one item displays. Click the item and select NewVal.
4. Notice that the While Loop is executing the first iteration. The Event structure is waiting for an event.
7. Notice that the VI stops running even though the Stop button is disconnected.
8. Notice that the Stop button stays depressed even though the mechanical action is set to Latch When Released. The reason the button stays depressed
is because the VI stopped running after you clicked the button.
Lesson 6
Figure 6-10. “Stop”: Value Change Event with Stop Button Terminal
|
ni.com
12. Notice this time the VI stops and the button resets.
Programming the "Time Check": Value Change Event
1. Add a new event case and create a “Time Check”: Value Change event as shown in Figure 6-11.
Figure 6-11. Event Structure with "Time Check": Value Change Event
1 In the Edit Events window, select Time Check in the Event Sources panel and Value Change in the Events panel.
2 Move the Time Check terminal from outside the While Loop into the "Time Check": Value Change event case.
3 Get Date/Time In Seconds—Creates a time stamp in memory.
4 Indicator—Displays the current time output of the Get Date/Time In Seconds function.
3. Click the Time Check button to see the current time display in the current time indicator.
4. Display the Task Manager window and notice that CPU usage has decreased when you use events instead of polling.
Lesson 6
1. Add a new event case and create a Mouse Down event as shown in Figure 6-12.
|
ni.com
1 In the Edit Events window, select Panes»Pane in the Event Sources panel and Mouse»Mouse Down in the Events panel.
2 Coords event data—Click the event data node and select Coords»All Elements.
3 Coords indicator—Right-click the output of the Coords event data item and select Create»Indicator from the shortcut menu.
Notice that the Coords indicator displays the coordinates for each point you click.
1
4
5
3
1 After you add the event, in the Edit Events window, select <This VI> in the Event Sources panel and Panel Close? in the Events panel.
2 Event data node—Click the Event Data Node and select Source from the menu.
3 Two Button Dialog function and Not function—Wire the T button? output to the Not function and wire the Not function to the Discard? event filter node.
4 String constant—Wire Are you sure you want to close the window? to the message input.
5 Yes and No string constants—Wire Yes to the T button name ("OK") input and wire No to the F button name ("Cancel") input.
3. Click the “X” at the top-right of the window of the front panel.
4. Notice that clicking the No button cancels the event and returns to the VI.
Challenge
1. If you have a sound card, add an event that produces a sound when the cursor is over the Stop button.
Think about the VIs that you will need to develop at your job.
Will you use event-based programming to implement any of your VIs? Why or why not?
Additional Resources
Deciding whether to use events Caveats and Recommendations when Using Events in
LabVIEW
Determining which notifier to use Determining Which Type of User Interface Events to
Use
6-26 | ni.com
LabVIEW Core 1 Participant Guide
2. How many events can an Event structure handle each time it executes?
a. As many as have occurred since the last time the event structure executed
b. One per configured event case
c. One
2. How many events can an Event structure handle each time it executes?
a. As many as have occurred since the last time the event structure executed
b. One per configured event case
c. One
Topics
+ Understanding Modularity
+ Icon
+ Connector Pane
+ Documentation
+ Using SubVIs
Exercises
Exercise 7-1 Temperature Warnings VI—As SubVI
LabVIEW Core 1 Participant Guide
A. Understanding Modularity
Objective: Recognize the benefit of using modular code and identify sections of code that
could be reused.
Modularity The degree to which a program is composed of discrete modules such that a
change tonne module has minimal impact on other modules. Modules in LabVIEW
are called subVIs.
SubVI A VI used within another VI.The degree to which a program is composed of
discrete modules such that a change tonne module has minimal impact on other
modules. Modules in LabVIEW are called subVIs.
SubVIs—Reusing Code
SubVIs are similar to a subroutine in text-based programming languages. Use subVIs when you
have code that performs identical operations on different parts of your block diagram or in
another VI.
SubVIs
The following pseudo-code and block diagrams demonstrate the analogy between subVIs and
subroutines.
B. Icon
Objective: Recognize characteristics of a good icon and use the LabVIEW Icon Editor to
create a custom icon.
Purpose of Icon
This icon displayed in the upper right corner of the front panel is the same as the icon that
appears when you place the VI on the block diagram.
7-4 | ni.com
LabVIEW Core 1 Participant Guide
C. Connector Pane
Objective: Select and configure a connector pane for a subVI.
Connector Pane 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.
Patterns
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. The connector pane is displayed next to the icon on the front panel
window. You can select from many different patterns depending on how many inputs and
outputs are required.
7-6 | ni.com
LabVIEW Core 1 Participant Guide
Assigning Terminals
Click the connector pane terminal and then click the front panel control or indicator to assign
the terminal.
1 5
2
6
3
4 7
Standards
The standard connector pane, shown in the following figure is 4 x 2 x 2 x 4.
D. Documentation
Objective: Explain how to document code in LabVIEW using descriptions and tip strips, and
describe four methods for documenting code on the block diagram.
7-8 | ni.com
LabVIEW Core 1 Participant Guide
1 Free label
2 Owned label
E. Using SubVIs
Objective: Demonstrate how to place subVIs on the block diagram, explain terminal settings
and error handling, and create subVIs from a section of existing code.
Terminal Settings
You can designate which inputs and outputs are required, recommended, and optional to
prevent users from forgetting to wire subVI terminals. LabVIEW sets inputs and outputs of VIs
you create to Recommended by default. Set a terminal to required only if the VI must have the
input to run properly.
In the Context Help window, terminal labels appear differently depending on their setting.
Bold Required The block diagram containing the subVI will be broken
if you do not wire the required inputs.
Plain Recommended The block diagram containing the subVI can execute
if you do not wire the recommended or optional
Dimmed Optional terminals. If you do not wire the terminals, the VI
does not generate any warnings.
Handling Errors
Use a Case structure to handle errors passed into the subVI.
7-10 | ni.com
LabVIEW Core 1 Participant Guide
Lesson 7
|
Goal
ni.com
Create the icon and connector pane for a VI so that you can use the VI as a subVI.
Modularity
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 you can use this VI as a subVI.
Design
The Temperature Warnings VI contains the following inputs and outputs:
Inputs Outputs
Use the standard connector pane terminal pattern to assure room for future expansion.
Implementation
1. Open Weather Warnings.lvproj in the <Exercises>\LabVIEW Core 1\Weather Warnings directory.
3. Connect the inputs and outputs to the connector pane as shown in Figure 7-1.
1 2
1 Connector Pane—Located in the upper right corner of the VI window, the connector pane displays potential terminals for the VI. The connector pane
shown here displays the standard pattern of terminals. You can right-click the connector pane and select Patterns to choose different terminal designs.
2 Connections—The Context Help window displays the connections for the VI.
Using the Wiring tool, click the upper-left terminal of the connector pane.
Notice that the connector pane terminal fills in with a color to match the data type of the control connected to it.
Continue wiring the connector pane until all controls and indicators are wired, and the Context Help window matches that shown in Figure 7-1.
4. Create an icon.
Lesson 7
of the function of the VI. Figure 7-2 shows a simple example of an icon for this VI.
|
Modularity
Tip Double-click the Selection tool to select the existing graphic. Press the <Delete> key to delete the graphic. Then, double-click the rectangle
tool to automatically create a border for the icon.
Tip Double-click the Text tool to modify fonts. You can select Small Fonts to choose fonts smaller than 9 points in size.
Tip Select the Glyphs tab and filter the glyphs by the keyword temperature, then drag a thermometer glyph onto your icon. And then filter
by the keyword warning and drag a warning glyph onto your icon.
5. Click OK when you are finished to close the Icon Editor dialog box.
1. Add files to the Weather Warnings LabVIEW project as shown in Figure 7-3.
Add an auto-populating folder to the Weather Warnings LabVIEW project. LabVIEW continuously monitors auto-populating folders and updates the
folder in the Project Explorer window according to changes made in the project and on disk.
– Right-click My Computer in the Weather Warnings project and select Add»Folder (Auto-populating) from the shortcut menu.
– Navigate to <Exercises>\LabVIEW Core 1\Shared Files and click the Select Folder button.
The Shared Files folder contains shared files that you use in this and future exercises.
– Navigate to <Exercises>\LabVIEW Core 1\Weather Warnings\Test VIs\SubVI Tester.vi and click Add File.
| 7-15
2. Open the SubVI Tester VI and complete the block diagram as shown in Figure 7-4.
7-16
Lesson 7
Figure 7-4. Test SubVI Block Diagram
|
ni.com
1 2 3 4 5 6
Modularity
1 Initialize shift register—Right-click the left shift register and select Create»Constant to initialize the shift register. Right-click the cluster and select View
Cluster as Icon.
2 Enum Constant—Right-click the Units (0:Celsius) input of the Thermometer (Demo) VI and select Create»Constant. Creating the enum constant from
the Thermometer (Demo) VI automatically populates the enum with the appropriate choices. Use the Operating tool to select Celsius.
3 Thermometer (Demo)—Locate this VI in the Shared Files folder in the Project Explorer window, drag it to the block diagram and wire it as shown. This
VI generates sample temperature values.
4 Wire the Units (0:Celsius) constant to the Units element of the Bundle By Name function.
5 Bundle By Name—Expand the node to display four elements. Use the Operating tool to select Units.
6 Temperature Warnings—Because of the modifications you made to Temperature Warnings VI, you can use it as a subVI. Wire the Temperature Warnings
VI using the connections you just created.
3. Arrange the front panel as shown in Figure 7-5.
4. On the front panel of the SubVI Tester VI, enter test values for the Max Temperature and Min Temperature controls.
The Thermometer (Demo) VI generates sample temperatures, which the SubVI Tester VI displays on the Current Temperature indicator.
6. Notice how Temperature Warning Text indicator changes as the temperature rises and falls.
7. After you have finished testing, save and close the VI.
Additional Resources
7-18 | ni.com
LabVIEW Core 1 Participant Guide
Topics
+ Measurement Fundamentals with NI DAQ Hardware
+ Automating Non-NI Instruments
Exercises
Exercise 8-1 Using NI MAX to Examine a DAQ Device
Exercise 8-2 Programming with the DAQmx API
Exercise 8-3 Instrument Configuration with NI MAX
Exercise 8-4 Exploring Instrument Drivers
LabVIEW Core 1 Participant Guide
Bus
DAQmx LabVIEW
The following table lists common sensors and the phenomenon they measure.
Sensor Phenomenon
Microphone Sound
Accelerometer Acceleration
pH probe pH
8-4 | ni.com
LabVIEW Core 1 Participant Guide
Implementation
Complete the following steps to examine the configuration for the DAQ device in the computer
using MAX. 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 step 3.
Note Portions of this exercise can only be completed with the use of a real device
and a BNC-2120, shown in Figure 8-1. Some of these steps have alternative
instructions for simulated devices.
2. If you have a DAQ device installed, skip step 3 and go to the Examining the DAQ Device
Settings section.
3. Create an NI-DAQmx simulated device to allow you to complete the exercises without
hardware.
Right-click Devices and Interfaces and select Create New from the shortcut menu.
In the Create New dialog box, select Simulated NI-DAQmx Device or Modular
Instrument.
In the Create Simulated NI-DAQmx Device dialog box, select M Series DAQ»
NI PCI 6225.
1
ANALOG INPUTS NATIONAL
+
_ Floating
Source (FS)
Ground Ref.
Source (GS)
+
_ INSTRUMENTS
1 RES
AI 3
! BNC-2120 PWR
24
BNC
TIMING I/O
2
2 3
PFI 0 / P1.0
4 23
3 1. RES+
2. AI GND
3. AI SENSE
4 4. RES-
6
PULSES
UP/DN
21
AI 0 AI 1
PFI 1 / P1.1
FS GS FS GS
PFI 2 / P1.2
PFI 3 / P1.3
PFI 4 / P1.4
PFI 5 / P1.5
AI 2 AI 3
PFI 6 / P1.6
FS GS FS GS
7 PFI 7 / P1.7
PFI 8 / P2.0
20
8 PFI 9 / P2.1
PFI 12 / P2.4
AI 4 AI 5 PFI 13 / P2.5
FS GS FS GS
PFI 14 / P2.6
+5 V
D GND
AI 6 AI 7 USER-DEFINED
SIGNALS*
FS GS FS GS
ANALOG OUTPUTS 19
USER 1
18
9 AO
USER 2
AO 0 AO 1
10 DIGITAL I/O
17
0.1-10 kHz 1-100 kHz 13-1000 kHz P0.7
P0.6
11 P0.5
P0.4
12
Sine /Triangle TTL Square Wave
P0.3
16
P0.2
13
P0.1
14 P0.0
D GND
15 LO HI LO HI
Amplitude Adjust Frequency Adjust
8-6 | ni.com
LabVIEW Core 1 Participant Guide
2. Select the device that is connected to your machine. Green icons represent real devices and
yellow icons represent simulated devices. You might have a different device installed, and
some of the options shown might be different.
MAX displays National Instruments hardware and software in the computer. The device
alias appears in quotes following the device type. The Data Acquisition VIs use this device
alias to determine which device performs DAQ operations. MAX also displays the attributes
of the device such as the system resources that the device uses. Figure 8-2 shows the
simulated PCI-6225 device.
Make sure the device you use is named Dev 1. To rename a device, right-click the device
and select Rename from the shortcut menu.
Tip The Show Help/Hide Help button in the top right corner of MAX is available for
certain items. Click the Show Help/Hide Help button to hide online help or show the
DAQ device information.
3. Select the Device Routes tab at the bottom of MAX to see detailed information about the
internal signals that can be routed to other destinations on the device, as shown in
Figure 8-3. 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.
4. Select the Settings tab, as shown in Figure 8-4, to see information about the last time the
device was calibrated both internally and externally. Not all devices contain calibration
information.
5. If you are using a physical device, right-click the NI-DAQmx device in the configuration tree
and select Self-Calibrate to update the built-in calibration constants and calibrate the DAQ
device using a precision voltage reference source. When the device has been calibrated,
8-8 | ni.com
LabVIEW Core 1 Participant Guide
information in the Self-Calibration section updates. Skip this step if you are using a
simulated device.
2. 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 Analog Input tab. Click the Start button to acquire data from analog input
channel 0 and click the Stop button when you finish.
– If you are using the BNC-2120, make sure the switch over the AI 0 connector is
in the Temp. Ref. position to connect the temperature sensor to ai0. Place your
finger on the sensor to see the voltage rise.
– If you are using a simulated device, a sine wave is shown on all input channels.
Use the Analog Output tab to set up a single voltage or sine wave on one of the DAQ
device analog output channels. Click the Analog Output tab.
– Select Sinewave Generation in the Mode drop-down menu and click the Start
button. MAX generates a continuous sine wave on analog output channel 0.
– If you have hardware installed, you can read the sine wave that channel 0 outputs.
On the BNC-2120, wire Analog Out Ch0 to Analog In Ch1. Click the Analog Input
tab in the Test Panels dialog box and select Dev1/ai1 from the Channel Name
drop-down menu. Click the Start button to acquire data from analog input channel
1. MAX displays the sine wave from analog output channel 0.
Use the Digital I/O tab to test the digital lines on the DAQ device. Click the Digital I/O
tab.
– Click Start to begin the digital output test, then toggle the switches in the Select
State section shown in Figure 8-6. If you have a BNC-2120, toggling the switches
turns the LEDs on or off. Notice that the LEDs use negative logic.
Use the Counter I/O tab to determine if the DAQ device counter/timers are functioning
properly. Click the Counter I/O tab.
– If you have hardware installed, you can verify counter/timer operations by selecting
Edge Counting from the Mode drop-down menu and clicking the Start button. The
Counter Value indicator increments rapidly. Click Stop to stop the counter test.
Click the Close button to close the Test Panel dialog box and return to MAX.
8-10 | ni.com
LabVIEW Core 1 Participant Guide
Access MAX by double-clicking the NI MAX desktop icon or selecting Tools»Measurement &
Automation Explorer in LabVIEW.
1: AT-MIO-64E-3
8-12 | ni.com
The following diagram shows how this process might be implemented.
1 Create task—The DAQmx Create Virtual Channel VI creates a channel and adds it to a task.
2 Configure task—The DAQmx Timing VI configures the starting and stopping of a task or the triggering of an application.
3 Start task—The DAQmx Start Task VI starts the task.
4 Acquire or generate data—The DAQmx Read VI or DAQmx Write VI acquires or generates data. You must select a compatible instance from the
pull-down menu.
5 Clear task—The DAQmx Clear Task VI stops the task and releases resources.
6 Check for errors—Use the Simple Error Handler VI or other manual error handling techniques to check for and respond to errors in your data acquisition
application.
Lesson 8
|
Goal
ni.com
Explore a DAQmx example program that continuously acquires data, and modify it to wait on a digital trigger.
Implementation—External Connections
1. If you are using the BNC-2120, connect the Sine/Triangle output on the function generator to channel AI 1 with a BNC cable, and make sure the switch
on the function generator is set to the sine wave. Also, ensure that there is a wire connecting the UP/DN screw terminal to the PFI 1 screw terminal in
the Timing I/O section.
Note The UP/DN terminal on the BNC-2120 outputs a high or a low signal indicating the rotation direction of the Quadrature Encoder knob.
When you rotate the Quadrature Encoder knob clockwise, the UP/DN terminal outputs a high signal. When you rotate the Quadrature Encoder
knob counterclockwise, the UP/DN terminal outputs a low signal. In this exercise, this signal triggers the VI to start acquiring data.
2. Select File»Save As to save the VI as <Exercises>\LabVIEW Core 1\Triggered Analog Input\Trigger AI Acquisition.vi. When prompted,
select Copy - Substitute copy for original.
3. Open and explore the block diagram as shown in Figure 8-7.
1 DAQmx Create Virtual Channel VI—Click the pull-down menu and notice it is set to Analog Input»Voltage.
2 Press <Ctrl-H> to open the Context Help window. Hover over each of the DAQmx functions to learn about each function.
3 Property Node—Gets or sets properties for a reference. You can learn more about Property Nodes in LabVIEW Core 2 or refer to the LabVIEW Help.
Use the Frequency Selection switch and the Frequency Adjust knob on the BNC-2120 to change the frequency of the generated and acquired signal.
Lesson 8
1. Modify the block diagram as shown in Figure 8-8 to add trigger functionality. After you modify this VI, the VI waits for a trigger before acquiring data.
|
ni.com
2 1
1 DAQmx Trigger VI—Place to the right of the DAQmx Configure Logging VI. Delete the task out and error out wires from the DAQmx Configure Logging
VI and then wire them through the DAQmx Trigger VI to the DAQmx Start Task VI.
2 Configure the trigger—Click the DAQmx Trigger VI pull-down menu and select Start»Digital Edge.
3 Create controls—Right-click the source input and the edge input of the DAQmx Trigger VI and select Create»Control.
4 Free label—Create a label and enter Trigger Settings.
2. Modify the front panel and set the default settings as shown in Figure 8-9.
2 3 4 1
1 Move the Acquired Data group—Select all the items in the Acquired Data group and shift them to the right. <Shift>-click to select multiple items and
press <Shift-arrow key> to move them.
2 Create Trigger Settings group—Copy a container from another group, label the copy Trigger Settings, and place the edge and source controls in it.
3 Select Rising in the edge control.
4. Run the VI. Turn the Quadrature Encoder knob on the BNC-2120 counterclockwise then clockwise to begin the acquisition.
Hardware connectivity The physical cable connecting the instrument. Also, the
communication protocol, or bus.
8-18 | ni.com
LabVIEW Core 1 Participant Guide
Set Up
This exercise uses the NI Instrument Simulator to simulate an instrument. Before MAX can
recognize the NI Instrument Simulator as a device with a GPIB interface, you must configure the
NI Instrument Simulator using the Instrument Simulator Wizard.
Complete the following steps to configure the NI Instrument Simulator to have a GPIB interface.
Set the configuration switch on the rear panel to CFG, as shown in Figure 8-10.
Power on the NI Instrument Simulator using the power switch on the front of the unit.
Verify that the PWR LED is lit and the RDY LED is flashing.
Note This wizard is installed with the NI Instrument Simulator Software, available
for download at ni.com.
Click Next.
Click Next.
On the Select Interface page, select GPIB Interface and click Next.
Click Next.
Click Update.
Click OK when you get the message that the update was successful.
8-20 | ni.com
LabVIEW Core 1 Participant Guide
Power off the NI Instrument Simulator using the power switch on the front of the unit.
Power on the NI Instrument Simulator using the power switch on the front of the unit.
Verify that both the PWR and RDY LEDs are lit.
Implementation
1. Launch MAX by either double-clicking the icon on the desktop or by selecting Tools»
Measurement & Automation Explorer in LabVIEW.
Expand the Devices and Interfaces section to display the installed interfaces. If a GPIB
interface is listed, the NI-488.2 software is correctly loaded on the computer.
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.
Expand the GPIB interface selected in the Devices and Interfaces section. An
instrument named Instrument Simulator appears.
Click the Communicate with Instrument button on the toolbar. An interactive window
appears. You can use it to query, write to, and read from that instrument.
Enter *IDN? in the Send String text box and click the Query button. The instrument
returns its make and model number in the String Received indicator as shown in
Figure 8-11. You can use this communicator window to debug instrument problems or
to verify that specific commands work as described in the instrument documentation.
Enter MEASURE:VOLTAGE:DC? in the Send String text box and click the Query button.
The NI Instrument Simulator returns a simulated voltage measurement.
4. 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.
While Instrument Simulator is selected in MAX, click the VISA Properties tab.
Enter devsim in the VISA Alias on My System field. You use this alias later in the
course.
Click Save.
8-22 | ni.com
LabVIEW Core 1 Participant Guide
The VIs in an instrument driver are organized into six categories. These categories are
summarized in the following table.
Category Description
Configure Configure VIs are software routines that configure the instrument to
perform specific operations. After calling these VIs, the instrument
is ready to take measurements or stimulate a system.
Utility Utility VIs perform a variety of auxiliary operations, such as reset and
self-test.
8-24 | ni.com
LabVIEW Core 1 Participant Guide
Implementation
Install the instrument driver for the NI Instrument Simulator. After installation, explore the VIs
that the instrument driver provides and the example programs that are added to the NI Example
Finder.
4. If you do not have an ni.com profile, follow the onscreen instructions to create one at this
time. Be sure to make a note of the user ID and password you create.
5. After you log in, click the Scan for Instruments button. If you have an instrument
connected, clicking this button detects the instrument and finds the correct driver. In this
case, it detects the Instrument Simulator.
6. Double-click Instrument Simulator in the list and click the Search button.
7. Select Version 2.0 of the instrument driver from the Driver list.
12. Close the NI Instrument Driver Finder window and go to the Explore Instrument Driver
section to continue this exercise.
1. If you have it open, close LabVIEW and then navigate to the <Exercises>\LabVIEW Core
1\Instrument Driver directory. This folder contains a zip file with the LabVIEW Plug and
Play instrument drivers for the Instrument Simulator.
2. Right-click the zip file and follow the wizard to extract all files to the <Program
Files>\National Instruments\LabVIEW 2014\instr.lib directory.
2. Verify that the PWR and RDY LEDs are lit on the Instrument Simulator.
3. Select devsim from the VISA Resource Name control on the front panel. You specified the
VISA alias for this GPIB instrument as devsim in step 4 of Exercise 8-3, Instrument
Configuration with NI MAX.
6. Open the Functions palette and navigate to the Instrument I/O»Instrument Drivers»National
Instruments Instrument Simulator palette.
7. Explore the palette and subpalettes using the Context Help window to familiarize yourself
with the functionality of functions on the palette.
10. Select the same VISA resource name you selected in step 3.
To familiarize yourself with the VI’s functionality, explore the block diagram using the
Context Help window.
8-26 | ni.com
LabVIEW Core 1 Participant Guide
Open to the block diagram of the Read Waveform VI. Notice that it uses VISA functions
to communicate with the instrument.
15. Close the VIs and project when you are finished. Do not save changes.
Additional Resources
Learn More About LabVIEW Help Topic or ni.com
8-28 | ni.com
LabVIEW Core 1 Participant Guide
Topics
+ Accessing Files from LabVIEW
+ High-Level and Low-Level File I/O Functions
+ Comparing File Formats
Exercises
Exercise 9-1 Exploring High-Level File I/O
Exercise 9-2 Temperature Monitor VI—Logging Data
LabVIEW Core 1 Participant Guide
1 2 3 4
Perform three steps of the file I/O process. Perform one step of the file I/O process.
(open/write/close)
Create unnecessary resource overhead when used Save memory resources when used in
in loops. loops.
Are good to use when writing to a file in a single Are good to use when streaming data to
operation. disk.
9-4 | ni.com
LabVIEW Core 1 Participant Guide
Scenario
The Spreadsheet Example VI does the following:
• Generates sine, noise, and cosine data for 128 points
• Stores this data in a 2D array that is 128 rows × 3 columns.
• Displays the 2D array in a Table indicator with three columns (Sine, Noise, and Cosine) for
the first 14 rows of the array.
• Plots each column in a Waveform Graph indicator.
• Uses the Write To Spreadsheet File VI to save the numeric 2D array in a text file so a
spreadsheet application can access the file.
Implementation
Complete the following steps to examine how the Spreadsheet Example VI performs the tasks
described in the Scenario section.
1. Open Spreadsheet Example.lvproj in the
<Exercises>\LabVIEW Core 1\Spreadsheet Example directory.
2. Open Spreadsheet Example.vi from the Project Explorer window.
• Sine Pattern VI—Returns a numeric array of 128 elements containing a sine pattern.
The constant 90.0, in the second instance of the Sine Pattern VI, specifies the phase
of the sine pattern which generates the cosine pattern.
• Uniform White Noise VI—Returns a numeric array of 128 elements containing a noise
pattern.
• Build Array function—Builds the following 2D array from the sine array, noise array, and
cosine array.
Sine Array …
Noise Array …
Cosine Array …
S N C
… … …
• Write To Spreadsheet File VI—Formats the 2D array into a spreadsheet string and
writes the string to a file. The string has the following format, where an arrow (→)
indicates a tab, and a paragraph symbol (¶) indicates an end of line character.
S N C
® ® ¶
® ® ¶
® ® ¶
… … …
® ® ¶
9-6 | ni.com
LabVIEW Core 1 Participant Guide
Note This example stores only three arrays in the file. To include more arrays,
increase the number of inputs to the Build Array function.
7. Open the wave.txt file using a word processor, spreadsheet application, or text editor and
view its contents.
Open wave.txt. The sine waveform data appear in the first column, the random
(noise) waveform data appear in the second column, and the cosine waveform data
appear in the third column.
8. Exit the word processor or spreadsheet application and return to LabVIEW.
1 2 3 4
File Refnums
File refnums identify unique file I/O sessions.
9-8 | ni.com
LabVIEW Core 1 Participant Guide
String Functions
To write data to a text file, you must first convert the data into a string data type. Use the items
from the String palette to convert numerics and other data types to text.
Tip Refer to the LabVIEW Help for details about formatting a string using the
Format Into String function.
Lesson 9
|
Goal
ni.com
Scenario
You have been given a VI that plots the current temperature and the average of the last three temperatures. Modify the VI to log the current temperature
to an ASCII file.
Implementation
1. Open Temperature Monitor.lvproj in the <Exercises>\LabVIEW Core 1\Temperature Monitor directory.
1 3 2 4 5 6 7
1 Open/Create/Replace File—Creates or replaces an existing file for the data log. Right-click the operation input and select Create»Constant.
Set the constant to replace or create.
2 Format Into String—Formats temperature data into a string. Expand the node to accept two inputs.
3 End of Line Constant—Adds an end-of-line constant after each piece of data so that data values are separated by line breaks.
4 Write to Text File—Writes the data to a file.
5 Or—Stops the VI when an error occurs or when the Stop Button is clicked.
6 Close File—Closes the data log file created or replaced when the VI started running.
7 Simple Error Handler—Indicates whether an error occurred. If an error occurred, this VI returns a description of the error and optionally displays a dialog
box.
Lesson 9
Figure 9-4. Configuring the Format Into String Function
|
ni.com
1 Format Into String—Double-click the Format Into String function to open the Edit Format String dialog box.
2 Use specified precision—Place a checkmark in this checkbox and enter 3 in the text box to specify that data have a floating point precision of three
digits.
3 Corresponding format string—This text box automatically updates based on the configuration you specify. After you click the OK button in the dialog
box, the block diagram updates to display the format string.
4 Help button—Click the Help button for more information about format specifier elements, such as %3f, and configuration options for the Format Into
String function.
Click the Stop button after the VI has been running for a few samples.
To improve the usability of the log file, you are asked to include a header at the top of the log file as shown in Figure 9-5.
Hints:
• Because you write the header to the text file only once, you should write to the header outside the While Loop.
• Use the functions on the Strings palette to manipulate and format a string for use in a word processing or spreadsheet application.
Lesson 9
Objective: Create Log File with Two Columns and Headers
|
ni.com
Modify the VI to write both the current temperature and the average temperature to the log file. Separate the columns of data with a tab character and place
Figure 9-6. Temperature Monitor VI Log File with Two Columns and Headers
1 2
Hint: Use the Format Into String function and expand it to convert and format the data into a string.
Easily Exchangeable X X X
Inherent attributes X X
High-speed streaming X
Additional Resources
File Formats for file I/O Determining Which File Format to Use
Topics
+ Using Sequential Programming
+ Using State Programming
+ State Machines
Exercises
Exercise 10-1 Weather Station Project
LabVIEW Core 1 Participant Guide
Flow-Through Parameters
To enforce sequential programming in LabVIEW, you can complete sequential tasks by placing
each task in a separate subVI, and wiring the subVIs in the order you want them to execute
using the error cluster wires.
However, in this example, only two of the tasks have a error cluster. Using the error clusters,
you can force the execution order of the two DAQ Assistants, but not the One Button Dialog
functions, as shown in the following figure.
Sequence Structures
A Sequence structure contains one or more subdiagrams, or frames, that execute in sequential
order; a frame cannot begin execution until everything in the previous frame has completed
execution.
10-4 | ni.com
LabVIEW Core 1 Participant Guide
State Part of a program that satisfies a condition, performs an action or waits for an
event.
Transition Condition, action, or event that causes the program to move to the next state.
Initialize
Acquistion
Warning = TRUE
Analysis
Data log
Stop = TRUE
C. State Machines
Objective: Determine when to use a state machine.
10-6 | ni.com
LabVIEW Core 1 Participant Guide
Sequential Process
• A state represents each segment of the process.
• Depending on the result of each state’s test, a different state might be called.
• Can happen continually, resulting in an in-depth analysis of the process you are testing
UI-Driven Process
• Different user actions process different code and act as a state in the state machine.
• Each segment can lead to another segment for further processing or wait for another user
action.
• The state machine constantly monitors the user for the next action to take.
• Applications require an initialization state, followed by a default state, where many different
actions can be performed. The actions performed can depend on previous and current
inputs and states. A shutdown state commonly performs clean up actions.
Initialize
Acquistion
Warning = TRUE
Analysis
Data log
Stop = TRUE
10-8 | ni.com
Exercise 10-1 Weather Station Project
Goal
Create a VI that implements a state machine using a type-defined enum.
Scenario
You must design a VI for a user interface state machine. The VI acquires a temperature every half second, analyzes each temperature to determine if the
temperature is too high or too low, and alerts the user if there is a danger of heatstroke or freeze. The program logs the data if a warning occurs. If the user
has not clicked the stop button, the entire process repeats. The state machine must also allow for expansion, because processes may be added in the future.
Design
Use a flowchart and states list to create the VI in this exercise. The flowchart in Figure 10-1 illustrates the data flow for this design.
Lesson 10
Figure 10-1. Temperature Warnings VI Flowchart
| ni.com
Acquistion
Warning = TRUE
Analysis
Data log
Stop = TRUE
The following table describes the states in this state machine.
Acquisition Set time to zero, acquire data from the temperature sensor Analysis
Analysis Read front panel controls and determine warning level Data Log if a warning occurs
Time Check if no warning occurs
Data Log Log the data in a tab-delimited ASCII file Time Check
Time Check Check whether time is greater than or equal to .5 seconds Acquisition if time has elapsed
Time Check if time has not elapsed
Implementation
1. Open Weather Station.lvproj in the <Exercises>\LabVIEW Core 1\Weather Station directory.
Lesson 10
for the Weather Station.
Lesson 10
Open the block diagram and create an Enum constant to the left of the While Loop.
| ni.com
Right-click the enum constant on the block diagram and select Make Type Def.
4. Modify the new type definition and add it to the Weather Station project.
Save the type definition as Weather Station States.ctl in the <Exercises>\LabVIEW Core 1\Weather Station\Supporting Files
directory.
In the Project Explorer window, notice that Weather Station States.ctl has been added to your Supporting Files folder because that folder is an
auto-populating folder.
5. Control the state machine with the type-defined enum and update the framework as shown in Figure 10-5.
1 3
1 Shift Register—Right-click the While Loop and select Add Shift Register.
2 Enum type definition constant—Right-click and select Visible Items»Label. Change the label to Beginning State. Wire the Beginning State constant
to the shift register to initialize the shift register to the Acquisition state. Wire the shift register to the case selector of the Case Structure.
3 Add more cases—Right-click the Case structure and select Add Case For Every Value to create different cases for each value in the enum.
4 Weather Data In—Drag Weather Data.ctl from the Project Explorer window to the block diagram to create a type definition cluster constant. Right-click
the cluster and select View Cluster As Icon.
5 Shift Register—Place a shift register on the While Loop and wire the Weather Data In constant to it.
| 10-15
Note After you finish wiring the Acquisition case in step 6, some tunnels are empty because not all cases are wired yet.
6. Complete the Acquisition state shown in Figure 10-6.
10-16
Lesson 10
Figure 10-6. Weather Station UI VI Acquisition State
| ni.com
1 2 3 4
1 Thermometer or Thermometer (Demo)—Drag one of these VIs from the Shared Files folder in the Project Explorer window to the block diagram. Drag
the Thermometer VI if you have hardware and drag the Thermometer (Demo) VI if you do not have hardware.
2 Temperature History—Move this indicator into the Acquisition state of the Case structure.
3 Bundle By Name—Wire the Temperature Value output of the Thermometer VI to the Current Temperature input.
4 Next State enum—<Ctrl>-click the Beginning State enum and drag a copy into the Acquisition case. Rename this copy of the Weather Station States
type definition Next State. Set the enum to Analysis and wire it through a tunnel on the Case structure to the shift register on the While Loop.
5 True Constant—Create a True constant and wire it through the Case structure to the Elapsed Time shift register. The True constant resets the Elapsed
Time counter every time the VI executes the Acquisition case.
7. Complete the Analysis case as shown in Figure 10-7.
1 2 3 4 7 5
1 Upper Limit and Lower Limit—Move these controls from outside the While Loop.
2 Bundle By Name—Replaces the Max Temperature and Min Temperature items with the values from the Upper Limit and Lower Limit controls. The
Bundle By Name function makes it possible to wire the Upper Limit and Lower Limit values to the Weather Data In input of the Temperature Warnings VI.
3 Temperature Warnings—Drag the Temperature Warnings VI from the Supporting Files folder in the Project Explorer window.
Lesson 10
Figure 10-8. Weather Station UI VI—Data Log Case
| ni.com
1 2 3 4
1 2 4
3 5
1 Next State—Wire two copies of the Weather Station States type definition to the Select function.
2 Select—Determines which state to execute next depending on whether or not time has elapsed.
3 Stop Button—Move the Stop Button terminal from outside the While Loop. Wire the Stop Button terminal to the Or function outside of the Case
structure.
4 Next State wire—Wire the tunnel for the Next State wire to the shift register.
5 Use default if unwired—Right-click these tunnels and select Use Default If Unwired.
Lesson 10
1. Run the VI.
| ni.com
4. Notice the changes in the upper and lower limit values and the placement of tabs and line breaks.
Initialize
User
State 2
Additional Resources
10-22 | ni.com
LabVIEW Core 1 Participant Guide
2. Which of the following are benefits of using a state machine instead of a sequential
structure?
a. You can change the order of the sequence.
b. You can repeat individual items in the sequence.
c. You can set conditions to determine when an item in the sequence should execute.
d. You can stop the program at any point in the sequence.
2. Which of the following are benefits of using a state machine instead of a sequential
structure?
a. You can change the order of the sequence.
b. You can repeat individual items in the sequence.
c. You can set conditions to determine when an item in the sequence should execute.
d. You can stop the program at any point in the sequence.
A. NI Services
To get started, register your product at ni.com/myproducts.
Log in to your National Instruments ni.com User Profile to get personalized access to your
services.
• Declaration of Conformity (DoC)—A DoC is our claim of compliance with the Council of the
European Communities using the manufacturer’s declaration of conformity. This system
affords the user protection for electromagnetic compatibility (EMC) and product safety. You
can obtain the DoC for your product by visiting ni.com/certification.
For information about other technical support options in your area, visit ni.com/services, or
contact your local office at ni.com/contact.
You also can visit the Worldwide Offices section of ni.com/niglobal to access the branch
office websites, which provide up-to-date contact information, support phone numbers, email
addresses, and current events.
A-4 | ni.com