LabVIEW Core 1 - Participant Guide
LabVIEW Core 1 - Participant Guide
LabVIEW Core 1
▪ In the Create New dialog box, select Simulated NI-DAQmx Device or Modular Instrument,
and click Finish.
2
▪ Expand the M Series DAQ tree, and select NI PCI-6221.
▪ Click OK.
3
▪ Select the simulated device and name it PCI-6221 under the Settings section.
4
3. Click Device Pinouts and explore the pinout information.
4. Select the Settings tab to see the 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-DAQ device, e.g. NI PCI-6221 or NI USB-
6212, etc., 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, information in the Self-Calibration section updates. Skip this step if
you are using a simulated device.
6. Close NI MAX when finished.
End of Exercise 2-1
5
Exercise 2-2: Validating I/O (NI DAQ Device)
Goal
▪ To verify that the inputs and outputs of your DAQ device behaves correctly.
Scenario
You want to validate that your DAQ system acquires/generates the following data correctly:
▪ Acquired analog input voltage measurement from the temperature sensor.
▪ Generated analog output voltage.
▪ Generated digital output voltage.
Hardware setup
(BNC-2120) Make sure that you have Sine/Triangle BNC Connector connected to the Analog Input 2,
and the Sine/Triangle Waveform Switch is set to Sine.
Instructions
Examine the configuration of DAQ device:
1. Launch NI MAX from the Windows Start menu.
2. Expand Devices and Interfaces and select the PCI-6221 or USB-6212.
Note that from here till the end of the course choose the NI-DAQ device that you have
connected to your PC, e.g. if you are using USB-6212, then select it each time you see PCI-
6221 is mentioned.
3. Right-click the device and select Test Panels from the shortcut menu.
4. Validate the analog input of your device.
▪ Make sure that the Analog Input tab is selected in the Test Panels dialog box.
▪ Select PCI-6221/ai2 from the Channel Name control, which corresponds to the ai2 pin of the
device.
▪ Change Mode to Continuous enables the measurement-specific settings, e.g. Rate (Hz),
and Samples to Read.
▪ Click the Start button to start the acquisition.
▪ Explore data on the chart, then click Stop.
▪ Change Samples To Read to other values, e.g. 5000, 10000, etc.
▪ Start the acquisition, and explore how it affects the acquired signal.
6
▪ Click the Stop button.
▪ You can disable the Auto-scale chart option, and change the scaling of the x-scale to adjust
the graph by double-clicking the maximum and minimum values of the scale and typing the
appropriate ones.
5. Validate the analog output of your device.
▪ Switch to the Analog Output tab.
▪ Set the Channel Name control, e.g. PCI-6221/ao0.
▪ You can either change Mode to Voltage Sinewave Generation or leave Voltage DC.
▪ Set Output Value (V) to the constant voltage you want to output.
▪ Click the Update button to start the generation.
▪ Click Stop.
6. Validate the digital I/O of your device.
▪ Switch to the Digital I/O tab.
▪ Select the port from the Port Name control. Port is a collection of lines, and each line can
output a high or low voltage.
▪ Select All Output in the Select Direction section.
▪ Configure the output voltage in the Select State section by changing the line state.
▪ Click Start.
▪ Select All Low and click Stop.
▪ Close the Test Panels dialog box.
7. Close NI MAX.
End of Exercise 2-2
7
Exercise 3-1: Connecting Hardware (Non-NI Instrument)
Goal
▪ Connect a non-NI instrument to your computer so that the instrument can be programmatically
controlled by LabVIEW.
Scenario
You are creating an application that acquires data from a non-NI instrument (for example, a non-NI
oscilloscope or non-NI digital multimeter).
In this exercise, you will explore how to connect a non-NI instrument to your computer.
8
Furthermore, imagine that your computer has a GPIB instrument control device, such as the
GPIB-USB-HS, which allows your computer to communicate with a GPIB instrument.
Complete the following steps to connect the GPIB instrument to your computer:
1. Notice that the NI Instrument Simulator has a GPIB port.
2. Connect the NI Instrument Simulator to your computer GPIB interface with a GPIB cable. For
example, connect the USB end of the GPIB-USB-HS to your computer and the GPIB end of the
GPIB-USB-HS to the GPIB port of the NI Instrument Simulator.
3. Now you can programmatically control (send commands to, receive data from) the NI Instrument
Simulator (that is a non-NI instrument).
Implementation
1. Launch NI MAX from the Windows Start menu.
▪ In NI MAX, expand the Devices and Interfaces to display the installed interfaces. If a
GPIB interface is listed, the NI-488.2 software is correctly loaded on the computer.
▪ Select the GPIB interface.
▪ Examine but do not change the settings for the GPIB interface.
2. Communicate with the GPIB instrument.
▪ Make sure the GPIB interface is still selected in the Devices and Interfaces.
▪ Click the Scan for Instruments button on the toolbar.
▪ Expand the GPIB interface selected in the Devices and Interfaces. An instrument named
Instrument Simulator appears. If the Instrument Simulator does not appear, please
complete the next section—Set Up the NI Instrument Simulator.
▪ Click Instrument Simulator to display information about it in the right pane of NI
MAX.
▪ Click the Settings tab at the bottom. Notice the NI Instrument Simulator has a GPIB
primary address.
▪ 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.
9
▪ Enter *IDN? in the Send String text box and click the Query button. The instrument
returns its manufacturer and model number in the String Received indicator as shown in
the figure. 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.
▪ Click the Query button again to return a different value.
▪ Click the Exit button when done.
3. You can communicate with your non-NI instrument using VISA Test Panel as well.
▪ Select your instrument and click the Open VISA Test Panel tab.
▪ Navigate to the Input/Output and enter your SCPI command.
4. Set a VISA alias of MyGPIBInstrument 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 NI MAX, click the VISA Properties tab.
▪ Enter MyGPIBInstrument in the VISA Alias on My System field. You use this alias
later in the course.
▪ Click Save.
5. Exit NI MAX
6. Click Yes if prompted to save the instrument.
10
Set Up the NI Instrument Simulator (Optional—Skip this section if you have passed the previous section
successfully)
1. Configure the NI Instrument Simulator.
▪ Power off the NI Instrument Simulator.
▪ Set the configuration switch on the rear panel to CFG, as shown in the figure below.
▪ 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.
▪ Launch the NI Instrument Simulator Wizard from Start»All Programs»National
Instruments»Instrument Simulator»Instrument Simulator Wizard.
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.
▪ Select Change GPIB Settings and click Next.
▪ Select Single Instrument Mode and click Next.
▪ Set GPIB Primary Address to 1.
▪ Set GPIB Secondary Address to 0(disabled).
▪ Click Next.
▪ Click Update.
▪ Click OK when you get the message that the update was successful.
▪ Power off the NI Instrument Simulator using the power switch on the front of the unit.
▪ Set the configuration switch on the rear panel to NORM.
▪ 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.
▪ Close all opened programs and windows.
11
Exercise 4-1: Exploring an Existing Project and a VI
Goal
▪ Explain the purpose of the main LabVIEW project/VI development environment items.
▪ Differentiate between controls and indicators.
▪ Differentiate between numeric, Boolean, and string data types.
Instructions
Explore an existing project
1. Open Explore Existing Project.lvproj in the C:\Exercises\ LabVIEW Core
1\Explore Existing Project directory.
2. Notice that the Project Explorer window contains the following two items.
▪ Thermocouple task
▪ Temperature Acquisition VI
12
3. Explore the Thermocouple task.
▪ Double-click the Thermocouple task to launch DAQ Assistant.
▪ In the opened window you can configure the DAQmx task by changing different values of
sample rate, samples to read, signal input range, and by adding physical and virtual channels
to the task.
▪ Configure the Thermocouple task as shown in the figure below.
13
Explore and run the VI in the project
1. Open the VI in the project.
▪ In the Project Explorer window, double-click the Temperature Acquisition VI.
2. Run the VI.
▪ Notice that Current Temperature displays the temperature.
▪ Run the VI a couple more times.
▪ Set Max Temperature Threshold to values above and below the current temperature, and
observe how this affects the Threshold Exceeded? And Message indicators.
14
Explore the Block Diagram
The block diagram defines the functionality of the VI and contains the code for the VI.
1. Select Window» Show Block Diagram in the front panel toolbar to display the block diagram.
▪ On the block diagram, identify the following items. How many can you find of each item?
▪ Controls
▪ Indicators
▪ Constants
▪ Free labels
▪ Functions
▪ VIs
2. Use the context help to learn more about the items on the block diagram.
▪ Press <Ctrl-H> to open the Context Help window or select Help» Show Context Help.
▪ Move the Context Help window to a convenient area where the window does not hide
part of the diagram.
▪ 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.
1. Select function – Place your cursor over the function. In the Context Help window, click the
Detailed help link to launch the LabVIEW Help and learn more about this function.
15
Check Your Answers
1. Refer following figures to verify that you identified all items correctly.
1. Numeric Control
2. Numeric Indicator
3. Boolean Indicator
4. String Indicator
16
1. Comments
2. Functions
3. VIs
4. Indicators
5. Control
6. Constants
On the Job
Describe the controls and indicators that you need when you create VIs at work. (Name, data type)
___________________________________________________________________________________
___________________________________________________________________________________
___________________________________________________________________________________
17
Exercise 4-2: Exploring Hardware Example Programs (Optional)
Goal
▪ Explore hardware example programs included in LabVIEW.
Instructions
NI-DAQmx Example Programs
1. Explore NI-DAQmx examples.
18
2. In the NI Example Finder window, double-click Hardware Input and Output» DAQmx,
double-click the folder for the type of example you want to explore, and then double-click one
of the examples to launch an example DAQmx project.
19
Non-NI Instrument Example Programs
1. Explore Non-NI Instrument Example.
▪ Switch to NI Example Finder and navigate to Hardware Input and Output»
Instrument Drivers» LabVIEW Plug and Play folder.
20
2. Select the instrument driver example that you want to explore to launch an example instrument
driver VI.
If you are taking this course in a classroom with an NI Instrument Simulator, you can explore the
NI Instrument Simulator instrument driver example.
4. Close the VI when you are finished. Do not save the VI.
21
Exercise 5-1: Creating a Project and a VI
Goal
▪ Create a new project and a new VI that execute the equation of a straight line: y = mx + b.
Instructions
1. Create a new project.
▪ From the Getting Started window, select Create Project.
▪ As a starting point, choose Blank Project, and click Finish.
2. Save the project.
▪ Select File» Save All.
▪ Type Simple VI in the File Name field.
▪ In the File Explorer window, browse to the C:\Exercises\LabVIEW Core 1\Simple VI
directory.
▪ Click OK.
3. Create a new VI in your project.
▪ In the Project Explorer window, Right-Click My Computer, then go to New and Click VI.
22
4. Explore the Controls Palette on the front panel.
Use palettes to locate items when you want to explore the options available to you or when you are not
sure of the name of the control, or indicator you need.
▪ From the front panel toolbar, select View» Controls Palette, or right-click in the front panel.
Note: You can access the NXG Style controls palette by right clicking in the front panel and
hovering your mouse over NXG Style submenu. Also, if you want NXG Style controls palette to
open automatically when you click in the front panel press the pin button in the upper-left
corner and drag the NXG Style controls palette to the top of the stack.
23
▪ Open the Numeric, Boolean, and String & Path palette categories to explore various types of
controls and indicators.
24
5. Create the user interface for your VI on the front panel.
▪ Right-click on the Front Panel.
▪ Go to Numeric, and then select Numeric Control.
▪ Now, place the Numeric Control on the Front Panel where you like.
▪ Do this three times to place three numeric controls on the front panel. Rename them as Slope
(m), Y-Intercept (b), and x.
Note: You can also add the Numeric Control by searching it from the Search button available
on the top right corner of the Controls palette. Press <Ctrl + Space> to quickly access the
search box.
25
6. Develop the code for your VI on the block diagram.
▪ Switch to block diagram by pressing <Ctrl-E>.
▪ The block diagram contains the terminals of the controls and indicators, placed on the front panel.
In this case it will contain the Slope (m), Y-Intercept (b), x, and y terminals as shown in the
figure below.
▪ Press <Ctrl-Space> and type multiply in the search text box. Double-click on Multiply in the
search results and place the Multiply function on the block diagram.
▪ Place an Add function to the block diagram.
▪ Wire the block diagram as shown in the following figure.
26
7. Locate the palette that contains a particular VI or function using the palette search.
▪ Right-click in the block diagram, press the Search button in the upper right hand corner of the
Functions palette and search for the term Multiply.
▪ In the search results, double-click the desired function to display the palette category that
contains the function. This allows you to browse related functions.
27
8. Practice using the global search feature.
▪ Type Multiply in the Search bar in the upper right hand corner of either front panel or block
diagram.
Note: As you type, the global search automatically looks for matches in several places,
including online Help and LabVIEW palettes.
28
9. Test the Straight-Line Equation VI using the values given in the following table.
▪ Enter the input values in the controls.
▪ Click Run.
▪ For each set of inputs, compare the given outputs to the outputs of the front panel. If the VI works
correctly, they should match.
Your Turn
1. Create a new project and name it Average.lvproj.
2. Add a new VI named Average.vi to the project.
3. Modify the VI to calculate the average of five numbers.
(X1 + X2 + X3 + X4 + X5) / 5 = Average
4. Run the VI and verify that you get the correct results.
29
Exercise 5-2: Creating an Acquire-Analyze-Visualize VI
Goal
▪ Create a VI that acquires data, analyzes data, and displays the results.
Instructions
Create the Project 1.
1. Create a new project.
▪ From the Getting Started window, select Create Project» All» Blank Project and click
Finish.
▪ Select File» Save All and enter Acquire Analyze Visualize.lvproj in the File name
field.
▪ Browse to the C:\Exercises\LabVIEW Core 1\Acquire Analyze Visualize
directory and click OK.
30
2. Configure the measurement.
▪ In the Create New dialog box that appears, select Acquire Signals» Analog Input»
Temperature» Thermocouple.
▪ Name the task Thermocouple, and click Finish.
▪ The next dialog box that appears prompts you to select the physical channel to use with
your new task. Under PCI-6221, select ai1 and click Next.
▪ Name the task Thermocouple, and click Finish.
▪ In the DAQ Assistant dialog box, configure the task as shown in the following figure.
31
Note: You should configure the task according to your specific hardware configuration, e.g. if you
have a thermocouple connected of a different type and with different signal input range connected,
then you should configure the parameters accordingly to that thermocouple characteristics.
3. Validate the signal is correct using the DAQ Assistant dialog box.
▪ On the top pane of the dialog box, switch the Display Type to Chart and run the task to verify
that the chart displays the expected temperature.
▪ Click Stop to stop the acquisition.
▪ Click <Ctrl-S> to save the VI and name it Acquire Analyze Visualize.
32
Acquire Data
1. Create a new VI in your project.
▪ In the Project Explorer window, add a VI.
▪ Click <Ctrl-S> to save the VI and name it Acquire Analyze Visualize.
2. Modify the block diagram, as shown in the following figure, to acquire data.
1. DAQmx Start Task VI – Transitions the task to the running state to begin the measurement or
generation.
2. Task constant – Right-click the task in input of the DAQmx Start Task VI and select Create
Constant. Set the constant to Thermocouple.
3. DAQmx Read VI – In the Polymorphic VI selector, set the values shown in the table below.
4. DAQmx Clear Task VI – Clears the task. Before clearing, this VI aborts the task, if necessary,
and releases any resources the task reserved.
5. Simple Error Handler VI – Indicates whether an error occurred. If an error occurred, this VI
returns a description of the error and optionally displays a dialog box.
6. Current Temperature (deg C) indicator – Right-click the data output of the DAQmx Read VI
and select Create Indicator. Rename the indicator Current Temperature (deg C).
Note: Task constant populates with any DAQmx tasks that you have created in this project.
33
DAQmx Read Configuration Settings
34
Analyze and Visualize Data
1. Modify the block diagram, as shown in the following figure, to analyze the acquired data.
35
2. Create the front panel, as shown in the following figure, to visualize your results.
▪ Right-click the Maximum Threshold (deg C) control and select Replace» Numeric»
Horizontal Pointer Slide (NXG Style). Resize the control as desired.
▪ Double-click the minimum and maximum values on the Horizontal Pointer Slide control
and set them according to the table below.
Minimum 15
50
Maximum
36
▪ Right-click the Horizontal Pointer Slide control and select Data Entry from the shortcut
menu. Set the properties on the Data Entry tab as shown in the following figure.
▪ Set the current value of the Horizontal Pointer Slide control to 30. After that, right-click the
control and select Data Operations» Make Current Value Default from the shortcut menu.
▪ Right-click the Threshold Exceeded indicator and select Replace» Boolean» LED (NXG
Style). Resize the indicator as desired.
▪ Resize the Message indicator to be larger.
3. Run the VI. Adjust the Maximum Threshold control to be above and below the Current
Temperature (deg C), and compare the indicator results.
37
Your Turn
1. Add a new VI named Celsius and Fahrenheit.vi to the project.
2. Modify the VI to acquire a temperature, display the temperature in degrees Celsius, and convert
the temperature to display the temperature in degrees Fahrenheit. The VI should have the
following indicators.
▪ Current Temperature (deg C)
▪ Current Temperature (deg F)
(Hint) Formula for converting deg Celsius to deg FahrenheitDelete the task in constant from the block
diagram.
9
Degrees Fahrenheit = Degrees Celsius x + 32
5
3. Run the VI. Use a calculator to verify that the conversion between Celsius and Fahrenheit is
correct.
38
Exercise 5-3: DAQmx Task vs. Full DAQmx API (Optional)
Goal
▪ Use and compare the DAQmx task with full DAQmx API approaches of acquiring data from a
DAQmx device.
Instructions
Approach 1: Using the DAQmx Task
This approach helps you get started quickly if you have already created a DAQmx task.
1. Open C:\Exercises\LabVIEW Core 1\DAQmx Task vs Full DAQmx API\DAQmx Task
vs Full DAQmx API.lvproj.
2. Examine the task presented in the project.
▪ Open the My Analog Input Voltage task from the Project Explorer window.
▪ Examine the settings in the DAQ Assistant dialog box. Notice Rate (Hz) is set to 2.56 kHz.
Note: Adjust Rate (Hz) to a rate that is supported by your DAQ device, if necessary.
39
▪ Click the Details button, and note that Physical Channel is set to PCI-6221/ai0.
40
6. Examine the behavior of this VI.
▪ On the front panel, set the value of the Number of Samples control to 5120.
Note: Because the sample rate defined in the My Analog Input Voltage task is 2.56 kHz
(samples per second) and Number of Samples is set to 5,120, the DAQmx Read VI will read
5,120 samples representing 2 seconds of data.
▪ Run the VI.
▪ Notice that this VI makes a single acquisition and stops. The data graph indicator now shows
5,120 samples. Notice that the Time (s) x-axis shows that graph contains 2 seconds of data.
41
Approach 2: Using the Full DAQmx API
This approach allows all the configuration settings to be contained in the VI and provides more flexibility.
This is the recommended approach for the remainder of this course.
1. Create a copy of the DAQmx Task Method VI.
▪ In the Project Explorer window, right-click the DAQmx Task Method VI and select Save As.
▪ In the appeared dialog box, select Open additional copy, check the Add copy to DAQmx
Task vs Full DAQmx API.lvproj box, and press Continue.
▪ Name the VI as Full DAQmx API Method.vi, then click OK.
▪ Close the DAQmx Task Method VI.
2. Delete the task in constant from the block diagram.
3. Programmatically create and configure the DAQmx task, as shown in the figure below by
following the instructions in the next steps.
▪ On the block diagram, hover your cursor over the physical channels input. Right-click and
select Create Control.
▪ Right-click both the minimum and maximum value inputs, and select Create Control.
42
5. Add a DAQmx Timing VI to set the sample rate and sample mode.
▪ When you add the DAQmx Timing VI, select the configuration settings as shown in the
following figure.
▪ Right-click the rate input and select Create Control. Rename it Desired Sample Rate
(Hz).
▪ Right-click the sample mode input and select Create Constant. Set the value of the constant
to Finite Samples because this VI will only read a finite number of samples.
▪ Wire the Number of Samples control to the samples per channel input of the DAQmx
Timing VI.
▪ In finite acquisition mode, the samples per channel input tells the DAQmx task how many
finite samples the DAQmx task should acquire.
43
6. Add a DAQmx Timing Property Node to get the actual sample rate.
1. Timing – Select and place the DAQmx Timing Property Node from the Quick Drop menu.
2. Sample Clock Rate – In the pull-down menu, select Sample Clock»Rate.
3. Actual Sample Rate (Hz) – Right-click the DAQmx Timing Property Node and select Change All To Read. Then right-click the
SampleClock:Rate output and select Create Indicator. Rename the indicator as Actual Sample Rate (Hz).
Note: If you can’t locate the appropriate Property Node setting follow the instructions below.
44
▪ Right-click on the property node and click Select Filter.
45
▪ The Configure Filter Settings dialog box should appear similar to the following picture.
Selecting Show All Attributes will cause LabVIEW to display all properties regardless of
which devices are configured on that computer.
46
Control Name DAQ Assistant Value Location
Configuration» Details» Physical
physical channels
Channel
Configuration» Timing Settings» Rate
Desired Sample Rate (Hz)
(Hz)
Note: Enter this value into the control in
units of Hz, not kHz.
Configuration» Signal Input Range»
maximum value
Max
Configuration» Signal Input Range»
minimum value
Min
47
Exercise 6-1: Debugging
Goal
▪ Use debugging tools and troubleshooting techniques to fix a broken VI that returns unexpected
data.
Instructions
Edit-Time Errors
1. Open and examine the Analyze Temperature VI.
▪ Open the Debug.lvproj in the C:\Exercises\LabVIEW Core 1\Debug directory.
▪ Open the Analyze Temperature (broken Run button) 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. Examine the block diagram of the Analyze Temperature VI, as shown in the following figure.
48
3. Find and fix each error.
▪ Click the broken Run button to display the Error list dialog box. Examine the errors and
warnings listed.
▪ Click the Show warnings check box.
1. Items with errors – Lists all LabVIEW items affected by errors and warnings in the current VI. If
two or more items have the same name, this list shows the specific application instance for each
ambiguous item.
2. Errors and warnings – Lists all errors and warnings associated with the VI, if a VI is selected.
3. Details – Indicates specific details of the selected error or warning.
▪ Double-click each error/warning to highlight the area on the block diagram that contains the
error.
▪ Use the information in the Error list dialog box to fix each error.
▪ Notice that after you fix all the errors, the Run button no longer appears broken. You can now
run the VI.
4. Save the VI.
49
Run-Time Errors
Identify and correct errors that cause the VI to behave unexpectedly and return incorrect responses.
When the results of your application are not what you expect, you can use a set of tools to determine
where errors occur within your code.
Although errors are often detected automatically, sometimes your code can run successfully but not as
intended. When this happens, you need to identify the source of the unintended behaviors.
▪ Execution highlighting
▪ Probes
▪ Breakpoints
▪ Single-stepping
▪ Notice that you can see how data flows through the wires. At the output of each node, you
can see the data value displays momentarily.
50
3. Probe the wire values.
▪ Add probes to the wires, as shown in the following figure (rectangular numbered boxes on
wires are probes), by right-clicking each wire and selecting Probe.
▪ The Probe Watch Window opens after you set a probe, which shows an item for each probe
you placed.
▪ Run the VI.
▪ Notice that the Probe Watch Window updates with the latest data values on the
corresponding wires. The row marked [1] data shows the data value for the wire labeled with
Probe 1.
▪ Double-click any probe item in the Probe Watch Window to highlight the corresponding
probe on the block diagram.
▪ You can view the latest data values of a probe by looking at the values in the Probe Watch
Window.
▪ By examining these probes, you determine that Probe 1 shows the correct temperature in
degrees Celsius and Probe 4 shows an incorrect value for temperature in degrees
Fahrenheit.
Question 1 – What is the mistake?
51
▪ Remove all the probes by right-clicking each probe in the Probe Watch Window and
selecting Remove.
▪ Click the Step Over button after each node to step through the entire block diagram. Each
time you click the Step Over button, the current node executes and pauses at the next node.
▪ When you step over the last node in the block diagram, it flashes to indicate that all the
nodes in the block diagram have finished executing. Click the Finish VI “Analyze
Temperature (incorrect behavior).vi” button to finish running the VI.
5. Set a breakpoint to pause the VI when execution reaches a specified point in the program.
When looking for a problem in your code, you may have an idea of the general area where the
problem exists. To help focus on this area, you can use a breakpoint to pause the VI at a
specified point in the program.
▪ Imagine that you have determined that the problem in this VI occurs right after the Add
function executes.
▪ Right-click the Add function and select Breakpoint»Set Breakpoint.
▪ Notice that the Add function is highlighted red now and that the highlighted function
corresponds to a breakpoint item in the Breakpoint Manager (Right-click on the highlighted
function, then select Breakpoint»Breakpoint Manager).
52
▪ Turn off the Highlight Execution and run the VI.
Notice that the VI pauses when it reaches the breakpoint.
▪ Now that the VI has reached the area you want to examine, you can start using your
debugging tools. For example, you can turn on Highlight Execution and click the Step Over
button to start single-stepping through the VI.
▪ When finished, remove the breakpoint by right-clicking the breakpoint on the block diagram
and selecting Breakpoint»Clear Breakpoint.
Note: If you select Disable Breakpoint instead, the breakpoint will remain on the block
diagram, but it will no longer pause execution. Then, you can right-click and enable the
breakpoint again later when you want the breakpoint to start pausing execution again.
Answer 1:
The values obtained from those probes show that the algorithm used to convert from ºC to ºF is
incorrect.
53
Exercise 7-1: Introduction to While Loop
Goal
▪ Use While Loop to execute code repeatedly and explain how its components (iteration terminal
and condition terminal) work.
Instructions
Explore the behavior of a VI without a While Loop
1. Explore the While Loop Basics VI.
▪ Open C:\Exercises\LabVIEW Core 1\While Loop Introduction\While Loop
Introduction.lvproj.
▪ From the Project Explorer window, open the While Loop Basics VI.
▪ Press <Ctrl-T> to display both the front panel and the block diagram at the same time.
2. Explore the front panel and block diagram.
▪ Run the VI several times with different values in the Total Time in Seconds control. (e.g. 10,
70, 3750).
Notice that each time you click the Run button, the VI calculates the hours, minutes, and
seconds and then stops. What if you wanted to click the Run button once and have the VI
continuously perform this calculation until the user clicks a Stop button?
54
Execute Code Repeatedly
1. Place a While Loop around the code you want to execute repeatedly.
▪ Select While Loop from the Programming » Structures menu in the Functions palette.
▪ Click and drag your mouse around the code performing the calculation and refer to the
following figure to complete the code.
55
1. Iteration terminal – Provides the current loop iteration count. The first iteration of a loop is zero.
2. Current iteration indicator – Right-click the iteration terminal and select Create Indicator.
Rename the indicator Current Iteration.
3. Conditional terminal – Right-click the terminal and select Create Control to create a Stop
button. When a True value is passed to the conditional terminal, the While Loop will exit.
3. Increase the significant digits on the Current Iteration indicator so the iteration number displays
correctly.
▪ Right-click the Current Iteration indicator and select Display Format.
▪ On the Display Format tab, select Decimal under the Type section and press OK.
56
4. Explore the functionality of the edited VI.
▪ Run the VI.
▪ Change the value of the Total Time in Seconds control. Notice that the VI continuously runs
the code in the While Loop, so the Hours, Minutes, and Seconds indicators are continuously
updated.
▪ Notice that the Current Iteration indicator is incrementing.
▪ Click the Stop button to stop the VI.
57
▪ Run the VI.
▪ On the block diagram, notice that the Current Iteration indicator returns a 0 on the first
iteration and increases by 1 for each subsequent iteration.
▪ Click the Stop button on the front panel. On the block diagram, notice that the Stop control
passes a True value to the conditional terminal, which causes the While Loop to exit.
6. Click the Highlight Execution button again to disable execution highlighting. Save the VI.
58
1. Numeric indicator – Add a numeric indicator to the front panel.
2. Increment function – This adds 1 to the value output of the iteration terminal to display the
correct number of iterations, because the first iteration of the While Loop is 0. Rename the
indicator Total Iterations.
3. Iteration output – Wire the output of the Iteration terminal through a tunnel on the While Loop to
the Increment function.
▪ Select the Total Iterations indicator and configure the display format to Decimal as you did
with Current Iteration indicator.
59
1. Create an input tunnel.
▪ Drag the Total Time in Seconds control out of the While Loop, so that your block diagram
looks like the following figure.
Because of the rules of dataflow, the While Loop must wait until all input tunnels receive data
before the While Loop can begin executing. When the While Loop begins executing, the input
tunnels will only return the original data they received. The While Loop input tunnels only read
data once (input tunnels do not continuously read data).
3. Move the Total Time in Seconds control back into the While Loop, as shown in the following
figure, so that the While Loop reads the current value of the control during every iteration.
60
4. Save the VI and project.
On the Job
In your applications, do you have code that you need to place in a While Loop?
___________________________________________________________________________________
___________________________________________________________________________________
___________________________________________________________________________________
If so, describe the code or task that you need to execute repeatedly in a While Loop.
___________________________________________________________________________________
___________________________________________________________________________________
___________________________________________________________________________________
___________________________________________________________________________________
61
Exercise 7-2: Using Timing Functions and VIs in a Loop (Optional)
Goal
▪ Use timing functions and VIs in a loop to set the loop period, decrease CPU usage, and view the
current date/time and elapsed time.
Instructions
Set Loop Period
In this part of exercise, you set a specific loop period for your While Loop.
1. Explore the Set Loop Period VI.
▪ Open C:\Exercises\LabVIEW Core 1\Using Timing Functions in a Loop\Using Timing
Functions in a Loop.lvproj.
▪ From the Project Explorer window, open the Set Loop Period VI.
3. Modify the block diagram, as shown in the following figure, to set the loop to execute every 1,000
ms.
1. Wait Until Next ms Multiple function – Right click the millisecond multiple input and select
Create Constant. Set the constant to 1000.
Note: You have configured this function to wait until the operating system (OS) timer
reaches a multiple of 1,000 before this function completes execution. As a result, this loop
executes one iteration every 1,000 milliseconds.
Note: That in the first iteration, the Wait Until Next ms Multiple function will probably wait
less than 1,000 milliseconds. For example, if the OS timer is at 5800 when the first
62
iteration starts, then the Wait Until Next ms Multiple function will only wait 200ms on the
first iteration because the next multiple of 1,000 is 6,000. However, the Wait Until Next ms
Multiple function should wait 1,000 ms on the subsequent iterations because the next
multiple will be 7,000, 8,000, 9,000, 10,000, and so on.
Note: Right-click the Windows taskbar and select Task Manager (for Windows 10).
63
5. Modify the block diagram, as shown in the following figure, to add a Wait (ms) function to lower
the CPU usage of this VI.
Note: Adding even a small amount of time to wait will decrease the CPU usage
significantly.
6. Run the VI.
7. In the Windows Task Manager, notice that the CPU usage of LabVIEW.exe is now much lower.
64
Question 1 - Because none of the functions or VIs in this While Loop wait, how many
iterations per second does this While Loop execute?
2. Examine the behavior of the Using Timestamp and Elapsed Time Functions VI.
▪ On the front panel, set the Target Time (s) control to 15.
▪ Run the VI and notice that the Elapsed Time (s) indicator continuously displays how much
time has elapsed since the While Loop started.
▪ Notice that the Current Time indicator continuously displays the current date and time.
▪ Notice that the While Loop is executing its iterations as fast as possible.
▪ Notice that the While Loop exits after 15 seconds has elapsed.
▪ In the Windows Task Manager, observe the high CPU usage of the LabVIEW.exe process
while this VI is running and record the value.
▪ Use your ideas to modify the VI to reduce the CPU usage. Did your modification work? What
is the CPU usage of the LabVIEW.exe process now?
Answer:
To reduce the CPU usage of the Using Timestamp and Elapsed Time Functions VI, you
can add a Wait (ms) function inside the While Loop, as shown in the following figure. Even
adding a small amount of time to wait will decrease the CPU usage significantly.
65
Answers
Question 1 - Answer: The While Loop executes its iterations as fast as possible because
the While Loop does not contain a function or a VI that waits.
66
Exercise 7-3: Continuously Acquiring Data Using DAQmx API Timing
Goal
▪ Create a VI that continuously acquires data from a DAQmx device.
▪ Predict the time to wait before reading data from the DAQmx device and the While Loop
frequency based on the sample rate and number of samples you specify.
Instructions
Examine the finite Acquisition VI
1. Explore the Finite Acquisition VI.
▪ Open C:\Exercises\LabVIEW Core 1\While Loop with Hardware API\ While Loop with
Hardware Timing.lvproj.
▪ Open the Finite Acquisition VI from the Project Explorer window.
▪ Notice the controls and waveform graph indicator on the front panel.
▪ Switch to the block diagram and notice that the code performs a finite acquisition.
▪ Examine the configuration of the following three VIs.
67
▪ Desired Sample Rate (Hz): 1,000
▪ Number of Samples: 1,000
▪ Run the VI and notice that this VI performs a single acquisition and is finished. The DAQmx
Read VI waits until 1,000 samples of data is available to read from the DAQ device. Then the
DAQmx Read VI returns 1,000 samples of data to the waveform graph indicator.
▪ Set the Number of Samples control to 5,000, and run the VI again.
Notice that the DAQmx Read VI must now wait until 5,000 samples of data is available to
read from the DAQ device.
Note: When the sample rate is 1,000 Hz (1,000 samples per second), 5,000 samples of
data represents 5 seconds of data
2. Modify this VI, as shown in the following figure, to acquire data continuously until the user clicks
Stop button.
68
1. Sample mode constant – Set this constant to Continuous Samples so you can continuously read acquisition data in the While Loop.
2. While Loop – Add the While Loop around the DAQmx Read VI. Because the Number of Samples control is outside the While Loop,
the DAQmx Read VI will only see the first value of the Number of Samples control when the VI begins running. This is the desired
behavior for this VI because we intend for the user to set all control values before running the VI and not modify values after the VI
begins running.
3. Stop control – Right-click the condition terminal and select Create Control.
4. OR function – Add an OR function between the Stop control and conditional terminal and wire the error wire to input x. This stops the
While Loop when the user clicks the Stop button or when an error occurs
69
3. Examine how the Desired Sample Rate (Hz) and Number of Samples values affect how long
the DAQmx Read VI waits and how often the waveform graph indicator updates.
▪ On the front panel, specify the following values to the controls:
5. Test the combinations of different sample rate and number of samples. Record the results, and
compare the results with your predictions in the previous step. You must stop the VI between
each test because the Number of Samples control is outside the While Loop.
▪ Sample Rate: 1000
Number of Samples: 500
How often will the waveform graph on the front panel update? _________
70
Exercise 7-4: Using Shift Registers
Goal
▪ Use a shift register to pass values from previous iterations through a While Loop to the next
iteration. This way, you can keep track of the maximum acquired value.
Instructions
1. Open C:\Exercises\LabVIEW Core 1\Using Shift Registers\ Using Shift
Register.lvproj.
2. From the Project Explorer window, open Track the Maximum Temperature VI.
3. Explore and run the VI.
▪ On the block diagram, modify the minimum value, maximum value, and thermocouple
type constant values to match your hardware.
▪ On the front panel, set the Thermocouple Channel control accordingly.
▪ Run the VI.
▪ Notice that this VI performs a continuous acquisition at a rate of 10 Hz. The DAQmx Read VI
reads one temperature value per loop iteration.
▪ Click the Stop button on the front panel when finished.
4. Add a shift register to the While Loop. This shift register will store the value of the maximum
acquired value.
▪ Right-click the border of the While Loop and select Add Shift Register
1. Negative Infinity constant – Wire this constant to initialize the shift register. This ensures that
the DAQmx Read VI output in the first iteration will become the new maximum value stored in the
shift register (because any number is greater than negative infinity).
2. Max & Min function – Use this function to compare the maximum acquired value with the current
value and return the higher value of the two.
71
3. Max Temperature Acquired indicator – Right-click the max(x, y) output of the Max & Min
function and select Create Indicator. Rename the indicator as Max Temperature Acquired
(deg C).
Answer:
You can compare your answer with the solution in C:\Solutions\LabVIEW Core 1\ Exercise 7-
4 directory.
On the Job
In your own application(s), do you have a need to use a shift register to keep track of a value in the
previous iteration?
72
Exercise 7-5: Using a Stacked Shift Register (Self-Study)
Goal
▪ Use a stacked shift register to store and access values from multiple previous iterations.
Instructions
1. Open C:\Exercises\LabVIEW Core 1\Stacked Shift Registers\ Using Stacked
Shift Registers.lvproj.
2. From the Project Explorer window, open Running Average Using Stacked Shift Register VI.
3. Explore the stacked shift register on the block diagram.
▪ Notice the stacked shift register.
▪ The first (top) left shift register returns data from the previous iteration.
▪ The second left shift register returns data from the second-most recent iteration. If there was
a third left shift register, it would return data from the third most recent iteration.
4. Examine the functionality of the block diagram.
▪ The purpose of the stacked shift register in this VI is to help calculate the average of the three
most-recent temperature measurements. The DAQmx Read VI in the While Loop returns the
current measurement, the first (top) left shift register returns the previous measurement, and
the second left shift register returns the measurement before the previous measurement.
▪ The Average Temperature Chart indicator displays the running average of the three most
recent temperature measurements.
▪ Notice that this VI reads one temperature measurement before the While Loop and uses this
initial temperature measurement to initialize each stacked shift register.
5. Test the VI.
▪ Run the VI.
▪ Compare the Average Temperature Chart and the Temperature Chart indicators. The
Average Temperature Chart indicator should be smoother due to the averaging.
▪ Turn on execution highlighting by clicking the Highlight Execution button to examine how
the stacked shift register stores and returns data.
▪ Click the Stop button to stop the VI when finished6. Test the VI, and observe the shift register
logic.
6. Resize the stacked shift register to access data from even earlier loop iterations.
▪ Hover your mouse cursor over the bottom border of the last left shift register.
▪ When the mouse cursor changes to the resize cursor, drag the shift register downwards to
add more elements shift register to access data from even earlier loop iterations.
▪ Alternatively, you can right-click the stacked shift register and select Add Element.
73
Your Turn
Modify the VI so that the Average Temperature Chart indicator displays the average of the five most
recent temperature measurements.
To view the answer, open the project in C:\Solutions\LabVIEW Core 1\ Exercise 7-5 (Your
Turn).
74
Exercise 8-1: Creating and Viewing an Array
Goal
▪ Create and view a numeric array.
Instructions
1. Create a new project. Save the project as Create Array.lvproj in the
C:\Exercises\LabVIEW Core 1\Create Array directory.
2. Create and open a new VI. Rename the VI as Create Array.vi.
3. Create an array of numeric controls.
▪ Add an Array shell to the front panel. Rename it as My Numeric Array.
▪ Add a numeric control inside the un-configured array.
4. Resize the array to show the 6 elements.
▪ Select the entire array control so that a blue line outlines the array, as shown below.
▪ To resize the array horizontally, drag the dot on the far right until 6 elements appear on the
front panel.
Notice that the six elements appear greyed out. This is because these elements are
uninitialized and contain no actual data.
5. Enter data into the array control. Enter 5, 10, 15, 20, 25 into the array, as shown below.
Notice that in this example, the last element is still greyed out and uninitialized.
75
6. Examine the array index display.
1. Index Display – Controls which array element is shown at the leftmost element. Use the
increment and decrement buttons to change the value in the index display.
If you set the index display to 2, then the leftmost element in the array will show the element at
index 2, and the element to its right will show the element at index 3.
▪ Increase and decrease the index display to examine how it affects which elements are
shown in the array control.
7. View how the array data appears on a graph indicator.
▪ Place a waveform graph indicator on the front panel.
▪ Create the block diagram, as shown in the following figure, to pass the array data to the
graph.
▪ Switch to the front panel and run the VI. Notice how the 1D array data is visualized in the
waveform graph indicator.
76
▪ Right-click the waveform graph indicator and select Properties to open the Graph
Properties dialog box. In the Plots tab you can configure the visual representation of the plot.
For now, configure plot as shown in the picture below for the indicator to display sequentially
connected points, which represent the data values in the array control.
▪ On the y-axis of the waveform graph, double-click Amplitude and rename it as Data
Value.
▪ On the x-axis of the waveform graph, double-click Time and rename it as Index.
77
Notice that the My Numeric Array control contains data values, but does not contain
any timing information. Therefore, the x-axis only represents the array index number
for each array data value. This is why you see points at x-axis values of 0, 1, 2, 3, and
4.
78
3. Enter data into the 2D array, as shown in the following figure.
Row Index
Column Index
79
5. View how the 2D array data appears on a graph indicator.
▪ Switch to the front panel and run the VI. Observe how the 2D array data are visualized in the
waveform graph indicator.
▪ Hover your cursor over the plot legend, and resize it to show three plots.
▪ Right-click the Waveform Graph indicator and select Properties. Configure each plot as the
first one in the Plots tab of the Properties dialog box. The Waveform Graph indicator now
displays points that represent the data values in the array control. The lines connect the
points sequentially.
80
Configure the Appearance of an Array Control
1. Right-click the body of My Numeric Array control.
2. In the Visible Items section of the drop-down menu, you can configure whether to show the
label, caption, index display, horizontal scrollbar, and vertical scrollbar.
▪ Check and uncheck these items to observe their effect on the appearance of the My Numeric
Array control.
Answers
Question 1 - Answers: 15, 25, 5
Question 2 - Answer: row index is 1; column index is 3
81
Exercise 8-2: Examining the Waveform Data Type
Goal
▪ Recognize the components and visualization of the waveform data type.
Instructions
1. Open C:\Exercises\LabVIEW Core 1\Waveform Data Type\Waveform
Data Type.lvproj.
2. Open the Examine Waveform Data Type VI from the Project Explorer window.
3. Examine the VI.
▪ Examine the front panel, which consists of a waveform control and waveform chart indicator.
▪ Examine the block diagram. Notice that the waveform control passes its data directly to the
chart indicator.
▪ Examine the waveform control, which has a waveform data type. Take notes of the following
information contained in the waveform data type.
Index 0
Index 1
Index 2
Index 3
Index 4
Index 5
Index 6
Index 7
Index 8
Index 9
Index 10
82
▪ Based on the number of data values and the interval time, what do you think is the total
duration, in seconds, of this waveform?
4. Run the VI.
▪ The waveform data type contains both data values and timing information. The x-axis of the
waveform chart indicator is in units of Time (seconds).
5. Modify the interval time (dt).
▪ Change the interval time from 0.1 seconds to 0.2 seconds. What effect do you think this
change will have on the waveform chart indicator?
▪ Run the VI.
▪ Notice that the data values have remained the same. However, the amount of time between
each point on the chart is now 0.2 seconds, and the total duration of the waveform on the
chart has increased to 2 seconds.
6. Modify the initial time (t0).
Currently the x-axis of the waveform chart indicator shows relative time in units of seconds, where
the initial time is always displayed as 0.
▪ View the initial time (t0) in units of absolute date/time on the chart indicator.
83
▪ In the Display Format tab select Default editing mode.
84
▪ Set Type to Absolute time.
▪ Notice that the Time axis now displays units of absolute date and time.
▪ Modify the date and time in the initial time element of the waveform control. What effect do
you think this change will have on the waveform chart indicator?
85
▪ Run the VI. Notice that the initial time on the left side of the Time axis now shows the new
initial time.
Note: To go back to displaying the time in seconds, right-click the waveform chart indicator,
select Properties, and set the type back to Automatic formatting in the Display Format
tab. You can also try experimenting with the other Display Format Type options.
7. Try making additional modifications to t0, dt, and Y array, and examine the effects on the chart
indicator.
86
1D Array of Waveform
1. Open the Examine 1D Array (Waveform) Data Type VI from the Project Explorer window.
2. Examine the 1D Array (Waveform) control on the front panel.
Notice that this 1D array contains three waveform elements. All three waveform elements contain
the same initial time (t0) and interval time (dt).
3. Examine the block diagram. The 1D Array (Waveform) control passes its data directly to the
Waveform Chart indicator.
87
4. Observe the behavior of the VI.
▪ Run the VI.
▪ Notice that when you pass a 1D array of waveforms to a chart, the chart displays each
waveform in the array as a separate plot.
5. Observe the effects of modifying the waveforms in the 1D Array (Waveform) control.
▪ Change the dt of one of the waveforms from 0.1 to 0.2. Run the VI to observe the effect.
▪ Change the t0 of one of the waveforms, e.g. from 6:05:10.000 to 6:05:11.000.
▪ Run the VI to observe the effect.
88
Exercise 8-3: Using Analysis Functions and VIs to Analyze Data
Goal
▪ Use analysis tools on your VI block diagram to analyze data.
Instructions
Analysis tools with the Waveform Data Type
1. Open C:\Exercises\LabVIEW Core 1\Analysis tools\Analysis tools.lvproj.
2. From the Project Explorer window, open the Using Analysis tools (Waveform data type) VI.
3. Examine the front panel and the block diagram.
▪ Set Physical Channel, Desired Sample Rate (Hz), and Number of Samples controls
appropriately to acquire a signal from your DAQ device.
Note: Make sure that you have your thermocouple connected to the Thermocouple Input
Connector, and that the BNC/Thermocouple Switch is in the right position.
89
▪ Find and place Greater? and Select functions inside the loop.
ing figure.
▪ This is to compare the high state level value of each iteration to the previous one, and if it is
greater, then VI overwrites the value passed to the max value indicator. If the new value is
less than the previous one, then VI proceeds to the next iteration while keeping the previous
value. The initial 0 constant wired to the shift register initializes the first value as 0.
90
6. View the results of the analysis tool.
▪ Switch to the front panel and arrange the items as shown in the following figure.
▪ Run the VI and keep it running for a couple of seconds. Notice that the max value indicator is
constantly rising and peaks at some point.
▪ Stop the VI.
▪ Save the VI.
Your Turn
Experiment with using other analysis tools.
91
Exercise 8-4: Visualize N-Channel Data
Goal
▪ Become familiar with the different data types that represent N-channel data.
▪ View multiple channels of data in chart, graph, and array indicators.
Scenario
Select the column that best matches the needs of your applications.
Check the option that best matches the needs of your applications.
N-Channels, 1-Sample
N-Channels, N-Samples
Based on your answers to the previous questions, check which scenario(s) are most relevant to your
applications.
92
Instructions
1. Open C:\Exercises\LabVIEW Core 1\Visualize N-Channel Data\ Visualize N-
Channel Data.lvproj.
2. Follow the instructions for the scenarios you selected in the Scenario section.
▪ Click polymorphic VI selector of the DAQmx Create Channel VI and explore the selected
instance.
▪ Notice that this VI is configured for a Voltage measurement. You can modify this configuration
if you want to acquire from a different type of measurement.
3. Examine the DAQmx Timing VI.
▪ Notice that the sample rate is set to1 Hz. This sets the DAQ device to acquire 1 sample per
channel per second.
4. Examine the DAQmx Read VI.
▪ Click polymorphic VI selector of the DAQmx Read VI and explore the selected instance.
▪ Notice that this VI is set to Multiple Channels and Single Sample. This VI will return a 1D
DBL array that contains a single sample from multiple channels.
93
5. Create the front panel.
1. Waveform Chart – Add a Waveform Chart to the front panel. Expand the plot legend to
display three plots.
2. Numeric Array Output – Add a Numeric Array control to the front panel, right-click the
control and press Change to Indicator. Resize the indicator to show 3 or more
elements and rename it to 1D Numeric Output.
94
6. Modify the block diagram, as shown in the following figure, to visualize the multiple channels
single samples data.
1. Array to Cluster – This function converts the 1D array data type to a cluster data type. To
plot a single sample from multiple channels on a waveform chart, you must pass the
waveform chart a cluster data type containing the samples.
2. Waveform Chart – Chart that can be used to show historical data and append new data.
3. 1D Numeric Output –This array indicator displays only the current array data in a specific
iteration.
95
8. Your front panel should look similar to the following figure when the VI is running.
96
N-Channel, N-Samples (1D Waveform Array)
In this section, you create a VI that acquires and visualizes 3 channels of analog input voltage. Each loop
iteration acquires/visualizes 1000 samples per channel. The samples are continuously acquired at
a hardware timed rate of 1000 Hz. The waveform data type contains the sample values (Y), the start time
for the samples (t0), and the time interval between each sample (dt).
(BNC-2120) and (Simulated Hardware) Modify this VI to acquire 3 channels of voltage (Sine Wave
Function, TTL Square Wave Function and Temperature Reference) from PCI-6221/ai0, PCI-6221/ai2:3,
at a sample rate of 2,560 Hz and number of samples of 256.
1. From the Project Explorer window, open the N-Channel, N-Samples (1D Waveform) VI.
2. Examine the DAQmx Create Channel VI.
▪ Click polymorphic VI selector of the DAQmx Create Channel VI and explore the selected
instance.
Notice that this VI is configured for an Analog Input Voltage measurement. Modify the
configuration if you want to acquire from a different type of measurement.
3. Examine the sample rate and number of samples controls.
▪ The Desired Sample Rate (Hz) control sets sample rate of this DAQ task.
▪ The Number of Samples control sets how many samples per channel the DAQmx Read VI
will wait for and output in each loop iteration.
▪ If the sample rate is 1000 Hz and number of samples is 1000, then during each While Loop
iteration, the DAQmx Read VI acquires from multiple channels at a sample rate of 1000 Hz
and outputs 1000 samples per channel.
4. Examine the DAQmx Read VI.
▪ Click polymorphic VI selector of the DAQmx Read VI and explore the selected instance.
97
5. Create the front panel.
▪ Add a waveform graph to the front panel. Resize the plot legend to show 3 plots.
▪ Add a waveform chart to the front panel. Resize the plot legend to show 3 plots.
▪ Create a 1D waveform array indicator.
▪ Add an array shell on the front panel. Rename it 1D Waveform Indicator.
▪ Add a waveform control inside the unconfigured array.
▪ Resize the array to show 4 elements.
▪ Right-click the array and select Change to Indicator.
6. Modify the block diagram, as shown in the following figure.
1. Waveform Graph – Graphs display the current array data in a specific iteration.
2. Waveform Chart – Chart that can be used to show historical data and append new data.
3. 1D Waveform Indicator – This indicator displays only the current data in a specific iteration.
Each array element is the waveform data received from an individual channel.
98
8. Configure the waveform chart properties.
▪ Right-click the Waveform Chart indicator and select Properties, then in the Display Format
tab make sure that the Default editing mode is selected and set Type to Floating point.
Click OK to save changes.
▪ Double-click Time on the x-axis and rename it Time (s). The Waveform data type contains
timing information in units of seconds.
▪ Double-click the minimum and maximum numbers on the x-axis and change them to 0 and
5. Now the waveform chart will show the most recent 5 seconds of data acquired.
▪ Right-click the waveform chart then select Chart History Length and change the history
length from 1,024 to 5,000. This setting determines the maximum number of points per plot
that the chart can show.
Note: Because this VI acquires 1000 samples per channel per second, changing the history
length to 5,000 configures the chart to show 5,000 samples per channel, which is equivalent
to the most recent 5 seconds of data.
9. Your front panel should look similar to the following figure when the VI is running.
99
In this section, you create a VI that acquires and visualizes 3 channels of analog input voltage. Each loop
iteration acquires/visualizes 256 samples per channel. The samples are continuously acquired at a HW-
timed rate of 2,560 Hz. The 2D DBL array data type contains the sample values.
(BNC-2120) and (Simulated Hardware) Modify this VI to acquire 3 channels of voltage (Sine Wave
Function, TTL Square Wave Function and Temperature Reference) from PCI-6221/ai0, PCI-6221/ai2:3
at a sample rate of 2,560 Hz and number of samples of 256.
1. From the Project Explorer window, open N-Channel N-Samples (2D DBL) VI.
2. Examine the DAQmx Create Channel VI.
▪ Switch to the block diagram, click the polymorphic VI selector of the DAQmx Create
Channel VI and explore the selected instance.
Notice that this VI is configured for an Analog Input Voltage measurement. Modify the
configuration if you want to acquire from a different type of measurement.
3. Examine the sample rate and number of samples controls.
▪ The Desired Sample Rate (Hz) control sets the sample rate for this DAQ task.
▪ The Number of Samples control sets how many samples per channel the DAQmx Read
VI will wait for and output in each loop iteration.
▪ If the sample rate is 2,560 Hz and number of samples is 256, then during each While
Loop iteration, the DAQmx Read VI will acquire from multiple channels at a sample rate of
2,560 Hz and output 256 samples per channel.
4. Examine the DAQmx Read VI.
▪ Click the polymorphic VI selector of the DAQmx Read VI and explore the selected
instance.
100
6. Modify the block diagram, as shown in the following figure, to visualize the multiple channels multiple samples (2D DBL) data.
1. Transpose 2D Array – You must transpose the 2D array before passing it to the chart for the chart to correctly interpret the 2D
array as 4 channels of data with 256 samples per channel.
2. Waveform Graph Indicator – Graph that displays the current array data in a specific iteration
3. Waveform Chart- Chart that can be used to show historical data and append new data.
4. 2D Numeric Array Indicator – This indicator displays only the current data in a specific iteration. Each row contains the data
points for a channel. When you run this VI, you will notice that for a “3 channel, 256 samples per channel” acquisition, the 2D
array has 3 rows and 256 columns.
101
7. Configure the waveform graph properties.
▪ Switch to the front panel.
▪ Resize the plot legend to show 3 plots.
▪ Double-click Time on the x-axis and rename it as Sample. The 2D DBL data type does not
contain any timing information, so the x-axis just represents the sample number.
8. Configure the waveform chart properties.
▪ Resize the plot legend to show 3 plots.
▪ Double-click Time on the x-axis and rename it as Sample. The 2D DBL data type does not
contain any timing information, so the x-axis just represents the sample number. Double-click
the minimum and maximum numbers on the x-axis and change them to 0 and 1280. Now the
chart will show the most recent 1,280 samples per channel acquired.
▪ Right-click the waveform chart then select Chart History Length and change the history
length from 1,024 to 1,280. This setting determines the maximum number of points per plot
that the chart can show.
Note: Because this VI acquires 256 samples per channel per second, changing the history
length to 1,280 configures the chart to show 1,280 samples per channel, which is
equivalent to most recent 5 seconds of data.
9. Your front panel should look similar to the following figure when the VI is running.
102
▪ 2D numeric array indicator shows the data only for the current iteration.
▪ Notice that the x-axis of the waveform chart indicates the sample number of a data point (not
seconds). This is because the 2D DBL data type does not includes timing information.
▪ Stop the VI when finished.
103
Exercise 8-5: Extracting a Subset of an N-Channel Data Array (Optional)
Goal
▪ Extract a single channel of data using the Index Array function. Extract multiple channels of data
using the Array Subset function.
Scenario
In this exercise, the acquisition data is a 1D waveform array containing the following data.
Hardware Setup
(BNC-2120) Make sure that you have Sine/Triangle BNC Connector connected to the Analog Input 2 and
the TTL Square Wave BNC Connector connected to the Analog input 3, also make sure that the
Sine/Triangle Waveform Switch is set to Sine.
Explore acquisition data in an existing VI
1. Open C:\Exercises\LabVIEW Core 1\Extract Data from N-Channel
Array\Extract Data from N-Channel Array.lvproj.
2. From the Project Explorer window, open the Extract Data from N-Channel Array (1D Waveform)
VI.
3. Explore the front panel and the block diagram. The block diagram code performs a continuous
acquisition. By clicking polymorphic VI selector of the DAQmx Read VI and exploring the
selected instance you can determine that this VI reads N-samples from N-channels and returns
the data as a 1D waveform array.
104
4. Examine the behavior of the VI.
▪ On the front panel, set the Physical Channels control to PCI-6221/ai0, PCI-6221/ai2:3. This
creates a DAQmx task that includes PCI-6221 analog input channels 0, 2, and 3.
▪ Set Desired Sample Rate (Hz) to 2560.
▪ Set Number of Samples to 256.
Note: Set the Physical Channel, Rate, and Number of Samples controls to values that are
appropriate for your DAQ device.
5. Run the VI.
▪ Notice that the All Channels indicator displays data for the three channels specified by the
Physical Channels control:
▪ AI0 channel
▪ AI2 channel
▪ AI3 channel
6. In this exercise, we are going to separate these three channels into different data sets.
105
Extract Data for a Single Channel
1. Modify the block diagram, as shown in the following figure, to extract data for a single channel.
1. Index Array function – When you pass this function a 1D waveform array and an index
value, this function will return a single waveform element at the specified index in the 1D
waveform array.
106
2. Use the context help and LabVIEW Help to learn about the Index Array function.
3. Test the VI.
▪ On the front panel, set the following values.
Rate 2560
107
Extract a Subset of Channels
1. Modify the block diagram, as shown in the following figure, to extract a subset of channels.
1. Index Array function – Use this function to extract the third channel (index 2). Right-click the
Index control, select Change to Constant. Set the constant value to 2.
2. Array Subset function – Use this function to extract the first and second channels (indices 0
and 1).
a. Right-click the index input and select Create Constant. Set the constant value to 0.
b. Right-click the length input and select Create Constant. Set the constant value to 2.
c. Right-click the subarray output and select Create Indicator. Rename the indicator as
Subset of Channels.
2. Use the context help and detailed LabVIEW Help to learn about the Array Subset function.
108
3. Test the VI.
▪ On the front panel, set the following values.
Rate 2560
109
Extract a Subset of Channels—Alternate Approach Using Index Array and Build Array
1. From the Project Explorer window, open the [Alternate Method] Extract Data from N-Channel
Array (1D Waveform) VI.
▪ Notice how this VI uses the Index Array function to extract multiple channels and then
group them together into a new array using the Build Array function.
110
Explore How to Extract Channels From 2D DBL Array Data Type
1. From the Project Explorer window, open the Extract Data from N-Channel Array (2D DBL) VI.
Rate 2560
111
3. On the block diagram, click polymorphic VI selector of the DAQmx Read VI and explore the
selected instance.
▪ Notice that the DAQmx Read VI is using the floating point data type. Notice that the output
data type is 2D DBL array.
4. Notice that the Index Array function is used to extract one channel of data (1D array = 2,560
samples from channel 0).
5. Notice that wiring a 2D array to the Index Array function causes the Index Array function to show
both a row index input and column index input.
▪ If you want to extract a row (1D array) from a 2D array, only wire the index of the row to the
index (row) input and leave the disabled index (col) input unwired.
▪ If you want to extract a column (1D array) from a 2D array, only wire the index of the column
to the disabled index (col) input and leave the index (row) input unwired.
▪ If you want to extract an individual element (single numeric) from a 2D array, then wire the
row index to the index (row) input and wire the column index to the disabled index (col) input.
In this VI, the 2D array wired to the Index Array function contains 3 rows and 2,560 columns,
where each row represents 2,560 samples acquired from one channel. Therefore, to extract
one channel of data (represented by 1D array), this VI wires the row index and leaves the
column index unwired to extract one row of data from the 2D array.
6. Notice that the Array Subset function is used to extract two channels of data.
▪ A row index of 0 and a length of 2 causes this function to extract 2 rows of data starting from
row index 0.
112
Your Turn
Option 1
1. Create a VI that acquires N-channel N-sample data and try extracting individual or groups of
channels from that acquisition data array.
2. (Simulated Hardware) Try acquiring 4 channels (10 samples per channel) of data. Extract an
individual channel or groups of channels.
Option 2: Experiment with Index Array and Array Subset functions
1. From the Project Explorer window, open [Unguided] Example 2D Array VI.
2. Familiarize yourself with the functionality of the Index Array and Array Subset functions by wiring
the 2D array to these functions, experimenting with how the input terminal values of these
functions affect their output values, and exploring the LabVIEW Help.
You can resize the Index Array function to extract more than one element/row/column.
113
Exercise 8-6: Exploring Auto-Indexing Tunnels
Goal
▪ Explore the behaviour of auto-indexing input and output tunnels.
Instructions
1. Open C:\Exercises\LabVIEW Core 1\Auto-Indexing\Auto-Indexing.lvproj.
2. From the Project Explorer window, open the Auto-Indexing Tunnels VI.
3. Modify the block diagram, as shown in the following figure, to create an auto-indexing input tunnel
and auto-indexing output tunnel to the For Loop.
▪ Wire the 1D DBL Array Input control to the left border of the For Loop, which by default
creates an auto-indexing input tunnel. Then, wire the input tunnel to the Input Tunnel Result
indicator.
Note: If you wire an array to a For Loop or While Loop, you can read and process every element
in that array by enabling indexing. When you wire an array from an external node to an input
tunnel on the loop border and enable indexing on the input tunnel, elements of that array enter
the loop one at a time, starting with the first element.
▪ Wire the output of the Multiply function to the right border of the For Loop, which by default
creates an indexing output tunnel. Then, wire the output tunnel to the Output Tunnel Result
indicator.
Note: For indexing output tunnels, scalar elements accumulate sequentially into 1D arrays, 1D
arrays accumulate into 2D arrays, and so on.
114
4. Right-click the indexing input tunnel. In the appeared menu you can set the behaviour of any
loop input tunnel to enable or disable indexing.
5. Right-click the indexing output tunnel. In the Tunnel Mode section, notice that Indexing is
selected. This is where you can set the behaviour of any loop output tunnel to Last Value,
Indexing, or Concatenating.
115
7. Run the VI.
▪ On the front panel, observe the behavior of each control/indicator.
▪ On the block diagram, observe how elements of the 1D DBL Array enter the loop one at a
time, starting with the first element.
▪ Observe how the Output Tunnel Result indicator is a 1D array that consists of every result
passed into the indexing output tunnel while the For Loop executed.
▪ Notice how the For Loop output tunnel does not return anything until the entire For Loop has
finished executing.
▪ Run the VI multiple times with Highlight Execution turned on to make all the above
observations.
▪ Stop the VI when finished.
8. Save the VI.
116
Comparing the Behavior of Auto-Indexing vs. Keeping Last Value
1. Open Compare Auto-Index and Last Value VI.
2. Explore the front panel and the block diagram.
▪ Notice that for each For Loop input tunnel and output tunnel, there is an indexing indicator
and a last value indicator.
▪ On the block diagram, select each tunnel. Notice how each tunnel is configured.
117
Exercise 8-7: Processing Data for Each Channel in an N-Channel Data Array
Goal
▪ Process data for each channel by using a For Loop to iterate through each channel in an N-
channel data array.
Process Channels Using VIs Compatible with N-Channel Array Data Types
1. Open C:\Exercises\LabVIEW Core 1\Process N-Channel Array\Process N-
Channel Array.lvproj.
2. From the Project Explorer window, open Process N-Channel Array VI.
3. Examine the VI.
▪ Explore the front panel and the block diagram.
▪ Notice that the data output of the DAQmx Read VI is a 1D waveform array data type.
▪ Run the VI.
▪ Stop the VI when finished.
118
4. Modify the block diagram, as shown in the figure below, to process all channels by scaling their
values by 100 and filtering the signals using the following items.
1. Multiply function – The input of this function can adapt to accept the 1D waveform array
data type.
2. Right-click in the block diagram and search for the DBL Numeric Constant, then wire it to
the second input of the Multiply function. Set the value of the constant to 100. This
function will multiply all Y values in every waveform element in the array by 100.
3. Right-click the output of the Multiply function and select Create Indicator. Rename the
indicator Scaled Channels.
4. Digital IIR Filter VI – Right-click in the block diagram, click Search from the Functions
palette and type Digital IIR Filter. Drag the first appeared result into the while
loop. Wire the 1D waveform array from the DAQmx Read VI to the input of the Digital IIR
Filter VI. Notice that the Digital IIR Filter VI will process each waveform contained in the
array.
5. Right-click the IIR filter specifications input and select Create Control.
6. Right-click the signal out output of the Digital IIR Filter VI and select Create Indicator.
Rename the indicator as Filtered Channels.
Note: Many Math VIs and functions can adapt to accept the 1D waveform array data type. A real-
world application can use Math VIs and functions to scale acquired data from units of voltage to
the appropriate engineering unit, such as temperature (deg Celsius), acceleration (g), etc.
119
5. Arrange and modify your front panel similar to the following figure. Make sure that the IIR filter
specifications cluster control is set as shown in the figure.
120
Process Channels Using a VI that is not Fully Compatible with N-Channel Array Data Types
1. Modify the block diagram, as shown in the following figure, to run all channels through a VI that is
not fully compatible with the 1D waveform data type.
Note: This For Loop code works for any N-channel array, whether it contains 2 channels or 16
channels.
121
2. Arrange your front panel similar to the following figure.
122
Your Turn
The following pseudocode shows how to take one channel of data and process it to display the data in
the frequency domain (frequency vs. amplitude graph).
Answer
The answer is located in the C:\Solutions\LabVIEW Core 1\Exercise 8-7 directory.
123
Exercise 9-1: Executing Code Based on a Condition
Goal
▪ Use a Case structure to execute code based on a condition.
Hardware Setup/Scenario
BNC 2120 option
▪ Make sure, that the thermocouple is connected to the Thermocouple Input Connector (AI1)
properly.
Instructions
Execute Code Conditionally Based on a Measurement Result—Conditionally Display Data on a Graph:
1. Open C:\Exercises\LabVIEW Core 1\Execute Conditional Code\ Execute
Conditional Code.lvproj.
2. From the Project Explorer window, open the Condition Based on Measurement Result VI.
3. Explore the VI.
▪ Explore the front panel and the block diagram.
▪ Set the DAQmx Physical Channel input to PCI-6221/ai1.
▪ Run the VI.
- Data will appear on the Current Temperature graph.
▪ Stop the VI when finished.
124
4. Modify the VI, as shown in the following figure, to display temperature data on the Last exceeded
temperature graph only if the temperature data has exceeded a user-specified threshold.
1. Waveform Min Max VI – The Y max output returns the maximum value of the Y array in the
waveform.
2. Greater Function – Right-click the y input of the Greater Function and select Create Control.
Rename it Temperature threshold (C).
3. Case structure – This VI will use the Case structure to update the Last exceeded temperature
waveform graph indicator only when the acquired temperature exceeds a threshold.
4. Last exceeded temperature indicator – Add a waveform graph indicator to the front panel and
wire the corresponding terminal as shown.
125
5. Configure the front panel items.
▪ Configure the Last exceeded temperature waveform graph to show the absolute time, so
you can see the exact date and time of when the acquired data last exceeded the threshold.
▪ Right-click on the waveform graph, then select X Scale»Formatting.
▪ In the opened window, make sure that the editing mode is set to Default and
select Absolute time in the Type section.
▪ Wire this indicator as shown in figure above.
6. Arrange the front panel, as shown in the following figure.
7. Set the control values, as shown in the figure above. Otherwise set the values to whatever is
appropriate for your hardware setup.
8. (BNC 2120) Lower the Temperature threshold to 30. You should be able to exceed the
temperature threshold in the next step by firmly pressing the thermocouple.
126
9. Examine the behavior of the VI.
▪ Run the VI.
▪ Adjust the value of the Temperature threshold (C) control and/or the acquired signal, so that
Current temperature exceeds Temperature threshold from time to time.
▪ Notice that every time the Current temperature graph contains a value above the
Temperature threshold (C) control value, that data is passed to the Last exceeded
temperature graph.
▪ Notice that the x-axis of the Last exceeded temperature graph shows the absolute date and
time of the last temperature waveform that exceeded the threshold.
▪ Stop the VI when finished.
10. Select File» Save All to save the VI.
11. Close the VI.
Challenge
Add code to the Condition Based on Measurement Result VI to display a running total of number of times
the threshold has been exceeded since the VI started running.
▪ Hint: Use a shift register to store the running total. Increment the running total in the Case
structure.
▪ Solution: Open C:\Solutions\Exercise 9-1\[Challenge] Condition Based on
Measurement Result with Running Total.vi
127
On the Job
In your own applications, do you need to execute code conditionally based on a measurement result? If
so, describe it below.
___________________________________________________________________________________
__________________________________________________________________________________
End of Exercise 9-1
128
Exercise 9-2: Executing Code Conditionally Based on a User Setting/ Parameter/
Configuration (Optional)
Goal
▪ Explore a DAQmx example that sets the triggering behavior based on a user-input.
Hardware Setup/Scenario
BNC 2120 option
▪ Make sure, that the Quadrature Encoder’s UP/DN terminal is connected to the PFI1 input.
Instructions
1. Open C:\Exercises\LabVIEW Core 1\Execute Conditional Code Based on User
Input\Execute Conditional Code Based on User Input.lvproj.
2. From the Project Explorer window open the Condition based on User Input (Triggering) VI.
3. Explore the block diagram.
▪ Notice that the Case structure executes code based on the value of the Triggering Enabled
control.
129
4. Test the VI.
▪ Set the following control values:
Edge Rising
Trigger Enabled? On
130
Exercise 10-1: Using High-Level I/O VIs/Functions
Goal
▪ Use high-level file I/O VIs and functions to write an array of acquisition data to a file.
Hardware Setup
▪ BNC-2120—Set up the Temperature Reference, Thermocouple, and Sine Wave Function & TTL
Square Wave Function inputs (ai0:3).
▪ Simulated—Set up ai0:3 of an analog input module.
Instructions
Finite Acquisition of N-Channels and N-Samples
1. Open the following project: C:\Exercises\LabVIEW Core 1\ High-Level Write to
File\High-Level Write to Text File.lvproj.
2. From the Project Explorer window, open the High-Level Write to Text File – N-Channel VI.
3. Examine the VI.
▪ Notice that the DAQmx Read VI is configured to read multiple samples from multiple channels
as a 2D DBL array.
▪ Notice that the DAQmx Timing VI configures this VI to perform a finite acquisition of N-
samples per channel (Number of Samples control) at a defined sample rate (Sample Rate
control).
131
4. Modify the block diagram, as shown in the following figures, to write the acquisition data to a file.
1. Write Delimited Spreadsheet VI – Use the first Write Delimited Spreadsheet VI to write
the header to the file. Place the VI on the block diagram.
2. Right-click the file path input and select Create Control. Rename the control Data log
filepath.
3. String Array Constant – Place an Array Constant on the block diagram. Create a String
Constant and drag it into the Array Constant, which changes the Array Constant to a
string array constant. Right-click the array index, select Properties»Size, and set
Dimensions to 2. Resize the constant and set the values in the first row, as shown. Wire
the constant to the 2D data input of the Write Delimited Spreadsheet VI, which will adapt
to the 2D string array data type.
4. Notice that the append to file input is unwired, so it will default to False. This means that
if a text file already exists at the data log file path, this VI will overwrite any data in that file.
132
▪ Configure the Data log filepath control.
▪ Switch to the front panel.
▪ Right-click the Data log filepath control and select Properties.
▪ In the Browse Options tab set the Selection Mode as shown in the figure below. This allows
the user to browse to a new or existing file path where the user wants to save the log file.
133
▪ Refer to the following figure to transpose the 2D array to represent data by column instead of
row and write numeric data to the file.
1. Transpose 2D Array function – Use this function to transpose the 2D array so that each
channel’s data is represented by a column instead of a row. In this exercise, this is how
we want the spreadsheet file to show the data.
2. Write Delimited Spreadsheet VI – Use the second Write Delimited Spreadsheet VI to
write the numeric data to the file. The previous Write Delimited Spreadsheet VI adds
headers to the text file, and this Write Delimited Spreadsheet VI appends data to the file
after the headers.
3. Wire the file path terminals between the two Write Delimited Spreadsheet VIs, as shown
in the figure. This tells the second VI to write to the same file as the first VI.
134
5. Complete the wiring as shown in the following figure.
135
6. Create the text file.
▪ On the front panel, set the Physical Channel control to the following values:
▪ (BNC-2120/Simulated Hardware) PCI-6221/ai0:3
▪ On the front panel, click the … button of the Data log filepath control. In the Save As dialog
box, set the file path to C:\Exercises\LabVIEW Core 1\High-Level Write to
File\Finite Acquisition Data.txt.
▪ Run the VI.
7. Explore the text file created by this VI.
▪ In the Windows Explorer, navigate to the data log file and double-click it to view the
contents.
▪ Notice the file includes a header describing each channel.
▪ Verify that the log file looks similar to the following figure.
136
▪ Try opening the text file using Microsoft Excel. Verify that the log file looks similar to the
following figure.
Your Turn
1. Use the LabVIEW Help to learn more about each node.
2. Experiment with the VI to better understand its functionality. For examples:
▪ What is the effect on the log file if you modify the values in the 2D string array for the header
text?
__________________________________________________________________________
__________________________________________________________________________
__________________________________________________________________________
▪ What is the effect on the VI if you remove the filepath input of the first Write Delimited
Spreadsheet VI?
__________________________________________________________________________
__________________________________________________________________________
__________________________________________________________________________
▪ What is the effect on the VI if you remove the filepath input of the first Write Delimited
Spreadsheet VI?
__________________________________________________________________________
__________________________________________________________________________
__________________________________________________________________________
137
On the Job
1. Do any of your applications require logging data from an N-channel N-sample finite acquisition?
___________________________________________________________________________
2. If so, how many channels? _______________________________
How many samples per channel? __________________________
List the column header names below.
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
______
138
Exercise 10-2: Using the Low-Level File I/O VIs/Functions to Stream Data to a Text File
Goal
▪ Stream single channel, single sample temperature data to a text file.
Instructions
1. Open the following project: C:\Exercises\LabVIEW Core 1\ Low-Level Stream to
Text File (1Chan 1Samp)\Low-Level Stream to Text File (1Chan
1Samp).lvproj.
2. From the Project Explorer window, open the Stream to Text File — 1 channel 1 sample VI.
3. Examine the VI.
▪ Notice that the DAQmx Create Channel VI configures the task to acquire measurements from
a thermocouple.
▪ Notice that the DAQmx Timing VI configures the task to acquire measurements continuously
at a sample rate of 1 Hz.
▪ Notice that the DAQmx Read VI reads 1 sample from 1 channel as a single DBL data type.
Question 1: How frequently does the While Loop execute? _________ times per second.
139
4. Modify the block diagram, as shown in the following figure, to stream data to a text file.
140
1. Open/Create/Replace File function – Specify the filepath of the data log file. In this exercise, leave the file path input unwired
so that when the user runs this VI, this function will launch a file dialog box for the user to choose the file path for the data log
file.
2. Concatenate Strings function – Use this function to create the header string with an End of Line constant.
3. Write to Text File function – Use the first Write to Text File function to write the header to the first line of the file before the VI
enters the While Loop.
4. Format Into String function – Use this function to convert the numeric DBL data into a string data type because the Write to
Text File function requires a string input. This function, as configured in this exercise (formatting string syntax is “%.3f%s”), will
format a DBL input of 5.123456789 into the string “5.123<end-of-line character>”. Refer to the LabVIEW Help for more details
on this function and the format string syntax.
5. Write to Text File function – Use the second Write to Text File function to continuously write data to file inside the While
Loop.
6. Close File function – Closes the file. You should always close a file when you are done accessing the file in the VI.
141
7. Explore the text file.
▪ In Windows Explorer, navigate to and double-click the data log file to view its contents.
▪ Notice the file includes a header describing each channel.
▪ Verify that the log file looks similar to the following figure.
Your Turn
Create a log file with two column headers (“Current Temperature (deg C)”, “Current Temperature (deg F)”) and two columns of data.
Answers
Question 1 - Answer: The While Loop executes 1 time per second. The DAQmx Read VI reads one sample each iteration. The
sample rate is 1 Hz, so the DAQ device acquires 1 sample per second. Therefore, the While Loop only executes one time per second
because the DAQmx Read VI must wait until a sample is available to read.
142
Exercise 10-3: Streaming N-Channels Acquisition Data to a Text File
Goal
▪ Explore examples that stream N-channels, 1-sample and N-channels, N-samples acquisition data
to a file.
Instructions
N-Channels, 1-Sample (1D DBL) Streaming Example
1. Open the following project: C:\Exercises\LabVIEW Core 1\Low-Level Stream to
Text File (NChan)\Low-Level Stream to Text File (NChan).lvproj.
2. From the Project Explorer window, open the Low-Level Stream to Text File (NChan 1Samp) VI.
3. Explore the Block Diagram.
143
1. Array to Spreadsheet String function – This function is configured to create a spreadsheet string, which adds a delimiter
between each array element and adds an end-of-line constant at the end of the string. In this VI, it turns the incoming string
array into the following string:
Channel 0<tab> Channel 1<tab> Channel 2<tab> Channel 3<end-of-line>.
2. Array to Spreadsheet String function – Use this function to convert the 1D DBL array data into a string data type because
the Write to Text File function requires a string input.
144
▪ The first Array to Spreadsheet String function will create the following result.
▪ The second Array to Spreadsheet String function, as configured in this exercise, would format
a 1D DBL input to a spreadsheet string, as shown in the following example.
4. Test the VI
▪ Run the VI.
▪ In the file dialog box, save the log file as C:\Exercises\LabVIEW Core 1\ Low-Level
Stream to Text File (NChan)\Stream Data (NChan 1Samp).txt.
▪ Click the Stop button after approximately 10 seconds.
▪ In Windows Explorer, open and explore the text file.
5. Use a probe to view wire values to better understand the functionality of the functions and VIs.
You can also create indicators of wires and view the indicator values on the front panel, if you
prefer.
145
N-Channels, N-Samples (2D DBL) Streaming Example
1. From the Project Explorer window, open the Low-Level Stream to Text File (NChan NSamp) VI.
2. Explore the block diagram
1. Array to Spreadsheet String function – In this VI, the Array to Spreadsheet String function is configured to create a
spreadsheet string, which adds a delimiter between each array element and adds an end-of-line constant at the end of the
string. In this example, it turns the incoming string array into the following string:
Channel 0<tab> Channel 1<tab> Channel 2<tab> Channel 3<end-of-line>.
2. Transpose 2D Array function – Rearranges the elements of 2D array such that 2D array becomes transposed array.
3. Array to Spreadsheet String function – Use this function to convert the 2D DBL array data into a string data type because
the Write to Text File function requires a string input.
146
▪ The first Array to Spreadsheet String function, as configured in this exercise results in the
following output.
▪ The Transpose 2D Array function rearranges the elements of the array, as shown in the
following figure.
▪ The Second Array to Spreadsheet String function, as configured in this exercise, would format
the output of the Transpose 2D Array function to a spreadsheet string, as shown in the
following figure.
147
▪ In the file dialog box, save the log file as C:\Exercises\LabVIEW Core 1\ Low-Level
Stream to Text File (NChan)\Stream Data (NChan NSamp).txt.
▪ Click the Stop button after approximately 10 seconds.
▪ In Windows Explorer, open and explore the text file.
4. Use a probe to view wire values to better understand the functionality of the functions and VIs.
You can also create indicators of wires and view the indicator values on the front panel, if you
prefer.
On the Job
Answer the following questions for your own applications.
1. Do you need to continuously stream multi-channel data to a text file?
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
___
2. If so, which of the above example is closest to meeting your needs?
▪ N-Channels, 1-Sample (1D DBL) Streaming Example
OR
▪ N-Channels, N-Samples (2D DBL) Streaming Example
3. What modifications do you need to make to these examples to meet your needs?
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
_____
148
Exercise 10-4: Programmatically Create Filenames Based on the Current Timestamp
Goal
▪ Explore example code that programmatically creates filenames based on the current date and
time.
Examine Code to Generate a Timestamped Filename in Relative Path
1. Open the following project: C:\Exercises\LabVIEW Core 1\ Timestamped
Filepath\Timestamped Filenames.lvproj.
2. From the Project Explorer window, open the Generate Timestamped Filepath VI.
3. Examine the block diagram.
<year><month><day>_<hour><minute><second>_Acquired Data.txt
Note: Refer to the LabVIEW Help for how to use the time format string input
149
4. Test the code.
▪ Run the VI multiple times.
▪ On the front panel, notice that the generated filename changes to match the current date and
time.
▪ Notice that the filepath directory is the same as the directory containing the current project file
(.lvproj).
3. Test th VI.
▪ Run the VI.
▪ Navigate to the log file in the C:\Exercises\LabVIEW Core 1\Timestamped
Filepath directory.
Notice that the filename indicates the date/time when the VI created that file.
▪ Run the VI a couple more times.
▪ Examine the additional log files that the VI generated in the C:\Exercises\LabVIEW Core
1\Timestamped Filepath directory. Notice that their filenames also indicate the date/time
when the VI created those files.
150
Your Turn
Modify the VI so that the VI creates a timestamped filename that looks similar to the following format and
saves the file in the C:\Exercises\LabVIEW Core 1\ Timestamped File directory.
<year><month><day>_<hour><minute><second>_<your own custom filename>
Example: 20190511_090030_Batch ABC.txt
On the Job
Would any of your applications benefit from creating a new timestamped filename every time you run
your VI?
___________________________________________________________________________________
___________________________________________________________________________________
___________________________________________________________________________________
___________________________________________________________________________________
__________________________________________________________
151
Exercise 10-5: Reading and Analyzing Data from a File in LabVIEW
Goal
▪ Read and analyze data from a text file in LabVIEW.
Instructions
1. Examine the text file containing the data that we want to read into LabVIEW.
▪ Open and examine the following text file: C:\Exercises\LabVIEW Core 1\Read
Delimited File\Acquired Data (NChan NSamp).txt.
▪ Notice that the first row is a header.
▪ Notice that the text file contains four columns of data. Each column represents a different
channel.
2. Open the following project: C:\Exercises\LabVIEW Core 1\Read Delimited
File\Read Delimited File into VI.lvproj.
3. From the Project Explorer window, open the Read Delimited File into VI.
152
4. Examine the block diagram.
1. Application Directory VI – Returns the path to the directory containing the current project
(.lvproj)
2. File Dialog Express VI – Displays a dialog box with which a user can specify the path to
a new or existing file or directory.
3. Read Delimited Spreadsheet VI (string) – Returns the contents of the delimited text file
as a 2D string array.
4. Index Array function – Extracts the first row, which contains a string for each column
header.
5. Read Delimited Spreadsheet VI (DBL) – Returns the contents of the delimited text file as
a 2D DBL array.
6. Array Subset function – The first line in this tab-delimited text file is a header. Use this
function to remove the first line, so that the array output contains only the numeric data.
7. Transpose 2D Array function – Transposes the 2D array. The output 2D array contains
one row for every channel.
Note: If you wire a 2D DBL array to a graph, the graph will interpret each row of the 2D DBL
array as a separate plot, which is why you must transpose the 2D array in this VI.
153
5. Examine the functionality of the VI.
▪ Run the VI.
▪ In the file dialog box, navigate to the following text file: C:\Exercises\LabVIEW Core
1\Read Delimited File\Acquired Data (NChan NSamp).txt.
▪ Use Highlight Execution and probes to examine the functionality of this VI.
Your Turn
1. Open and examine the following text file: C:\Exercises\LabVIEW Core 1\Read
Delimited File\Acquired Data (NChan NSamp).txt.
2. Modify the block diagram to process the multi-channel data that this VI has read from the text file.
▪ Display the minimum and maximum values of each channel.
▪ Your front panel should look similar to the following figure.
154
Exercise 11-1: Creating and Using a SubVI
Goal
▪ Create the icon and connector pane for a VI so that you can use the VI as a subVI.
Scenario
You will explore a VI that generates a timestamped file path in the same directory containing the project.
Create an icon and a connector pane so that you can use this VI as a subVI.
Design
The Generate Timestamped Filepath VI contains the following inputs and outputs.
Inputs Outputs
155
Creating a SubVI
Note: It is common practice to place subVIs and support files in a subdirectory and place the
main top-level VI in the parent directory. This allows the main top-level VI to be more visible
and accessible to the user.
156
3. Place an Error In control and Error Out indicator on the front panel, as shown in the figure
below.
157
5. Connect the inputs and outputs to the connector pane, as shown in the following figure below.
▪ The connector pane is located in the upper-right corner of the front panel.
▪ Click any input or output you want to assign and then click the corresponding control or
indicator on the front panel.
▪ You can change the number of input and output terminals by right-clicking the connector pane
and selecting a suitable connector pane pattern in the Patterns shortcut menu.
158
▪ Right-click the appended filename input terminal and select This Connection Is» Required
from the shortcut menu.
▪ Now when you use this subVI in a main VI, the Run button of the man VI will be broken until
the appended filename input terminal is wired.
159
6. Create an icon, as shown in the figure below.
▪ Double-click the VI icon in the upper-right corner of the front panel to open the Icon Editor.
Search for delay and path and place the corresponding graphics onto the VI icon.
▪ Click the OK button when finished.
160
Use the SubVI in a Main VI
1. From the Project Explorer window, open the Main VI.
2. Examine the Open/Create/Replace File function on the block diagram.
Notice that its file path input is unwired, which means when you run the VI, this function will
launch a file dialog for you to specify the file path.
3. Use the Generate Timestamped Filepath subVI to output a timestamped filename in the same
directory as the current project file (.lvproj).
▪ Drag the Generate Timestamped File VI from the Project Explorer window to the block
diagram of the Main VI.
▪ Right-click the appended filename input and select Create Constant. Set the constant to
string value, such as MyData.
▪ Wire the timestamped relative filepath output of the Generate Timestamped Filepath VI to
the Open/Create/Replace File function.
161
Your Turn
Create a subVI that reads a temperature measurement, compares it to the set temperature threshold,
and returns if the threshold is exceeded or not.
The following figure shows how your completed Temperature Warning subVI could be used in an
example VI.
Note: For the answer, refer to the C:\Solutions\LabVIEW Core 1\11-1\[Your Turn] Create
SubVI directory.
On the Job
Is there code you will commonly reuse in your applications? Would the application benefit from putting
that code in a subVI?
___________________________________________________________________________________
___________________________________________________________________________________
____________________________________________________________________
Do you have any code that uses a lot of nodes but accomplishes one modular task (for example,
algorithm)? Would the top-level application be more readable if that code was put inside a subVI?
___________________________________________________________________________________
___________________________________________________________________________________
___________________________________________________________________
End of Exercise 11-1
162
Exercise 12-1: Grouping Related Data Using a Cluster
The goal of the exercise is to group weather-related data into a Weather Data cluster, create a subVI
with cluster input/output and pass cluster data into/out of a subVI from a main VI.
Goal
▪ Group related data into a new cluster.
▪ Create a subVI with cluster input/output.
▪ Pass cluster data into/out of a subVI from a main VI.
Scenario
Group weather-related data into a Weather Data cluster.
Another developer has created a VI that displays temperature warnings. This VI is part of a temperature
weather station project. Your task is to update this VI to use clusters instead of individual
controls/indicators for inputs and outputs.
163
Instructions
Determine Warnings SubVI
In this section, you will create a subVI that handles temperature warnings. All the weather-related data is
grouped together in a Weather Data cluster.
1. Open C:\Exercises\LabVIEW Core 1\Clusters\Weather Warning
Cluster\ Weather Warnings.lvproj.
2. From the Project Explorer window, open the Determine Warnings VI.
3. Place existing controls and indicators in a cluster named Weather Data, as shown in the
following figure.
1. Cluster – Drop a cluster control from the Data Containers 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.
164
4. Resize the cluster so that all the elements are visible and arranged vertically, as shown in the
following figure.
1. Autosize cluster – LabVIEW can rearrange and resize the cluster for you. Right-click the border of
the Weather Data cluster and select AutoSizing» Arrange Vertically.
165
5. Reorder the items in the cluster, as shown in the following figure.
▪ Right-click the border of the Weather Data cluster and select Reorder Controls In Cluster.
Verify that your Weather Data cluster order matches the order in this figurer.
166
6. Modify the VI to receive and return cluster data.
1. Weather Data In – <Ctrl>-click the Weather Data cluster and drag it to create a copy.
Rename the copy Weather Data In.
2. Weather Data Out – Right-click the original Weather Data cluster and select Change to
Indicator. Rename the indicator Weather Data Out.
167
7. Modify the block diagram, as shown in the following figure, to extract and modify data from the input cluster.
1. Unbundle By Name – Wire the Weather Data In cluster 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 an d
indicators into a single cluster, you must use the Unbundle By Name function to access each cluster element.
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 click to select the Warning and Warning Text elements. Connect the broken wires to the
inputs of Bundle By Name as shown.
Note: If the order of the elements in the Unbundle By Name or Bundle By Name functions is different than what you want, you can
click the elements to change the order.
168
8. Save the Determine 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 Out indicator displays correct values.
3. Save and close the VI.
169
1. Weather Data cluster constant as input to the Bundle By Name function.
2. Output of the Bundle By Name function.
3. Input and output terminals of the Determine Warnings subVI.
4. Weather Data indicator.
5. Input of the Unbundle By Name function.
6. Input terminal of the Log Warnings subVI.
170
Your Turn
Log SubVI
How would you modify the following subVI block diagram to use a cluster instead of 5 individual controls?
Note: To view the solution, open the Log Warnings subVI from Full Weather Warnings
Example.lvproj.
On the Job
1. In your own applications, what data should you group into a cluster? Sketch your potential cluster
data types below.
_____________________________________________________________________________
_____________________________________________________________________________
_______________________________________________________________________
_________
_____________________________________________________________________________
_____________________________________________________________________________
__
171
Exercise 13-1: Using Type Definition
Goal
▪ Create a weather data cluster type definition.
▪ Place the type definition in several places (e.g., subVI input/output, main VI controls/indicators).
▪ Update the type definition and save to propagate data type changes to all instances of the type
definition.
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.
As a developer, you must ask yourself the following questions:
▪ What should happen to the copies of the custom data types used in VIs that are already saved?
▪ Should the copies remain unchanged or should they update themselves to reflect changes to the
original?
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 Determine Warnings subVI in such a way that the changes to the
Weather Data type definition propagate through the application.
When completed, the Weather Station application monitors temperature and wind information.
1. Open C:\Exercises\LabVIEW Core 1\Type Def\Type Def.lvproj.
2. From the Project Explorer window, open the Determine Warnings VI.
3. Experiment with changing an existing cluster.
▪ Place a file path control in the Weather Data In cluster control.
▪ Notice that the Determine 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.
▪ Press <Ctrl-Z> to undo the addition of the file path control.
4. Make a type definition.
▪ On the front panel, right-click the border of the Weather Data In control and select Make
Type Def.
172
Notice in the Project Explorer window that this has created a new file on your hard drive marked
Control 1.
▪ On the block diagram, the Weather Data In terminal now has a black triangle on the upper-
left edge indicating that it is connected to a type definition.
▪ Right-click the Weather Data In control and select Open Type Def. to display the type
definition in a new window.
▪ The type definition window looks like the front panel of a VI but it does not have a block
diagram.
▪ Rename the cluster as Weather Data.
▪ Press <Ctrl-S> to save the type definition and name the type definition file as Weather
Data.
▪ In the Project Explorer window, move the type definition file into the support directory by
dragging the file.
▪ Close the type definition window when finished.
▪ On the block diagram of the Determine Warnings VI, notice the coercion dot on the Weather
Data Out indicator terminal. This shows that the indicator is not tied to the type definition.
173
5. Replace the Weather Data Out indicator with the type definition you just created.
▪ On the front panel of the Determine Warnings VI, delete the Weather Data Out indicator.
▪ Drag the Weather Data type definition item from the Project Explorer window to the front
panel.
▪ Right-click the border of the Weather Data type definition on the front panel and select
Change to Indicator. Rename the indicator as Weather Data Out.
▪ Go to the block diagram and notice that the Weather Data Out terminal has a black triangle
on the upper-left edge, which indicates that it is connected to a type definition.
▪ Update the VI connector pane to include the Weather Data Out indicator because the
indicator you previously deleted had been connected to the connector pane.
▪ The connector pane is located in the upper-right corner of front panel.
▪ Connect the second-from-the-top terminal on the right side to the Weather Data Out indicator,
as shown in the following figure.
Note: You can no longer add or remove elements to or from a type definition cluster
control/indicator on the front panel. You must open and edit the type definition file to
add or remove the element.
174
6. Edit weather Data type definition to include wind speed information.
▪ Right-click the border of the Weather Data In control and select Open Type Def. from the
shortcut menu.
▪ Modify the front panel as shown in the following figure.
1. Numeric Control – Place a numeric control in the cluster and rename it as Current
Windspeed.
▪ Apply the changes (File» Apply Changes) and Save the Weather Data type definition before
closing its window.
▪ On the Determine Warnings VI, notice that the Weather Data In control and Weather Data
Out indicator have been updated with the changes you made to the Weather Data type
definition. Arrange the front panel of the VI as shown in the following figure.
175
7. Run and save the Determine Warnings subVI.
176
Your Turn
1. In this project, update the Main VI and Log Warnings VI. Replace all instances (listed below) of
the cluster in these VIs to use the Weather Data type definition.
▪ Weather Data instances in the Log Warnings VI
▪ Weather Data In cluster
Note: Make sure you reconnect the new type definition to the connector pane
177
Your Turn
1. Create a new project and a new VI.
2. Create an enum that contains 3 items (e.g., Add, Subtract, and Multiply).
3. Convert the enum into a type definition.
4. Add the type definition to multiple places and VIs.
5. Modify the enum type definition to include a fourth item (for example, Divide). Save the
type definition.
6. Verify that all instances of the enum type definition update to include the new element.
On the Job
2. List all the clusters and enums that will exist in your own application.
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
3. Should you make these clusters and enums a type definition?
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
178
Exercise 14-1: Creating a State Machine
Goal
▪ Create a VI that implements a state machine using a type definition enum.
Scenario
You must design a VI for a user interface state machine. The VI acquires a temperature every half a
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 state machine to create the VI in this exercise. The state transition diagram in the following figure
describes the logic for this application.
Acquire Set time to zero and acquire data from the “Analyze”
temperature sensor
Analyze Read front panel controls and determine the “Log” if a warning occurs,
warning level “Check Time” if no warning occurs
Check Check whether time elapsed is greater than “Acquire” if time has elapsed,
Time or equal to 0.5 seconds “Check Time” if time has not
elapsed
179
Implementation
The figure below shows the front panel of the Weather Station UI VI that has been provided for
you. You will modify the block diagram to create a state machine for the weather station.
180
The following figure shows the starting point of the block diagram for the Weather Station UI VI. You will have to edit this block diagram to
implement a state machine for the weather station application.
1. These are the unused controls and indicators from the front panel. You will use these controls and indicators to program different
cases.
181
3. Create a new type definition to control the weather station application.
▪ Open the block diagram and create an enum constant to the left of the While Loop.
▪ Right-click the enum constant and select Edit Items to open the Enum Constant
Properties window. On the Edit Items tab, add the enum items, as shown in the following
figure.
▪ 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.
▪ Right-click the enum constant and select Open Type Def.
▪ Rename the label on the enum control to States.
▪ Apply the changes made to type definition (File»Apply Changes).
▪ Save the type definition as Weather Station States in the C:\Exercises\LabVIEW
Core 1\State Machine\Supporting Files directory.
▪ Close the Type Def window.
▪ In the Project Explorer window, drag the Weather Station States type definition to your
Supporting Files folder.
182
5. Place a Case structure inside the while Loop, as shown in the following figure. This is the part of
the State Machine design pattern.
183
6. Control the state machine with the type definition enum and update the frame work as shown in
the following figure.
1. Shift Register – Right-click the While Loop and select Add Shift Register.
2. Type definition enum constant – In the Properties window, enable the Show Label checkbox.
Rename the label as Beginning State. Wire the Beginning State constant to the shift register
to initialize the shift register to the Acquire state. Wire the shift register to the Selector input 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 – Drag the Weather Data type definition from the Project Explorer window to the
block diagram to create a type definition cluster constant.
5. Shift Register – Place another shift register on the While Loop and wire the Weather Data
constant to it.
6. Wire as shown.
Note: After you finish wiring the Acquire case in the following step, some tunnels are empty
because not all cases are wired yet.
184
7. Complete the Acquire state as show in the following figure.
185
8. Complete the Analyze case as shown in the following figure.
1. Upper Limit and Lower Limit – Move these controls into the Analyze state of the Case structure.
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
Determine Warnings subVI.
3. Determine Warnings – In the Project Explorer window, find Determine Warnings VI inside the
Supporting Files folder and drag it to the block diagram.
4. Unbundle By Name – Returns the values of specific items from the cluster.
5. Select – Determines which state to execute next depending on whether or not a warning occurs.
6. Weather Station States – Wire two copies of the Weather Station States type definition enum
renamed as Next State to the Select function. You can create these copies from the
Beginning State enum.
7. Warning – Move this indicator into the Analyze state of the Case structure.
8. Wire the DAQmx task and file reference through the case as shown.
186
9. Complete the Log case as shown in the following figure.
1. Log Warnings – From the Project Explorer window, find Log Warnings VI inside the Supporting
Files folder and drag it to the block diagram. This subVI logs weather data to file.
2. Next State – Create a copy of the Weather Station States type definition enum, label it Next
State, and set the next state to Check Time.
Wire the DAQmx task and Weather Data cluster through the case as shown.
187
10. Complete the Check Time case as shown in the following figures.
1. Next State – Wire two copies of the Weather Station States type definition enum to the Select
function.
2. Select – Determines which state to execute next depending on whether or not time has elapsed.
3. Wait (ms) – This function allows the CPU to do other tasks while this VI repeatedly executes the
Check Time case until the Elapsed Timer VI returns a TRUE value when 0.5 seconds have
elapsed.
4. Stop – Move the Stop button terminal from outside the While Loop. Wire the Stop button terminal
to the Or function outside of the Case structure.
5. Use Default if unwired – Right-click these tunnels and select Use Default If Unwired. These
Boolean tunnels will output a value of FALSE in cases where these tunnels are unwired.
Wire the DAQmx task, file reference, and Weather Data cluster through the case as shown.
188
Test
1. Run The VI.
▪ Name the log file Weather Warning Log.txt when prompted.
▪ Enter values for the Upper Limit and Lower Limit controls and observe the behavior of the
VI. Does it behave as expected?
2. Stop the VI.
3. Navigate to the Weather Warning Log.txt file and open it.
4. Notice the changes in the upper and lower limit values and the placement of tabs and line breaks.
5. Close the log file.
6. Save and close the VI and the project.
On the Job
1. Back at your job, can your application’s logic be described by a state transition diagram? If so,
then draw the state transition diagram below:
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
2. Will you use a state machine to implement your state transition diagram in LabVIEW code?
_____________________________________________________________________________
_____________________________________________________________________________
_____________________________________________________________________________
189