Upload
quy-nguyen
View
92
Download
6
Tags:
Embed Size (px)
Citation preview
Intermediate LabVIEW Tutorial June 27, 2011
Ayyappa Vemulkar, HMC 2013
This tutorial assumes that the user has programmed in LabVIEW before. If you haven’t used
LabVIEW before, it is advised that you first go through the following references:
1. Getting Started Manual on the National Instruments website -
http://digital.ni.com/manuals.nsf/websearch/EC6EF8DE9CB98742862576F7006B0E1E
2. Introduction to NI LabVIEW - http://www.ni.com/gettingstarted/labviewbasics/
The tutorial has been tested for LabVIEW 2009 and 2010, and may be done in teams of two.
Objectives
By the end of the tutorial the student will:
1) Learn how to install, test and use a Data Acquisition Device (DAQ) using the
Measurement and Automation Explorer (MAX) software
2) Review basic programming concepts in LabVIEW such as understanding the LabVIEW
environment; creating Sub Vis; using functions, loops and structures; and displaying and
working with different data types
3) Learn how to communicate with and control instrumentation over RS-232 and GPIB
Before you begin:
Create a New Folder in your Charlie directory for your LabVIEW work. You will save all
your VIs to this folder so that LabVIEW can find them.
Saving your VI frequently is good, but know that once you choose to save your VI, it
resets the ‘undo call’ (Ctrl-Z) and you will not be able to go back on any steps you made
before saving your VI.
Think node-to-node programming and not line-by-line.
Avoid crossing wires while connecting different objects on the block diagram. Crossed
wires can be confusing to read and follow at times.
When in doubt, DEBUG! Use the light bulb icon on the status toolbar on the block
diagram to highlight the path of the flow of data.
Place output indicators at multiple steps during the data flow path of your VI to keep
track of the output as it changes through the VI.
PLAN PLAN and PLAN! Plan out the various stages of your VI/Program prior to placing
objects on the block diagram. This will make it easier to end up with a clean picture of
code and will also allow you to pick out the functions that best suit your needs.
PRACTICE! The only way to get better at LabVIEW is to practice.
How to use this Tutorial:
Each section of this tutorial is divided into three parts: The Objectives, Background Information,
and Exercise. Each section addresses a “big picture idea.” The Objectives aim at telling the
reader the important topics that will be addressed within the section. The Background
Information acts as a resource, defining terms and attributes of LabVIEW you will need to
understand prior to doing the exercise and to fully comprehend the big picture idea of the
section. If you are not a beginner, it is advised you skim through the Background Information
and only read about topics you are not comfortable with. The Exercise is designed to be concept-
based as opposed to testing your programming skills. Apart from simply following directions, it
is advised, particularly through the later exercises, that you try thinking through the problem
statement at hand and planning how you might use LabVIEW as a tool to solve the problem.
Introduction:
LabVIEW, short for Laboratory Virtual Instrumentation Engineering Workbench, is a visual-
based programming environment created by National Instruments. LabVIEW is an industry
standard used for data acquisition (through DAQ devices), instrument control, laboratory
measurements, and industrial automation.
Bill of Materials
The following materials shown in Table 1 are required for the tutorial. They can all be checked
out from the stockroom and should all be available during the proctored lab session.
Component Description Supplier Manufacturer Part # Unit Price Quantity Total
Resistor (available in the stockroom)
220 Ω resistor, ¼ W, through-hole DigiKey P220CATB-ND $0.095 1 $0.095
Resistor 2.2 kΩ resistor, ¼ W, through-hole DigiKey 2.2KQTR-ND $0.074 1 $0.074
Capacitor Cap, Tantalum, 10 nF Capacitor, through-hole DigiKey 478-1832-ND $0.52 1 $0.52
Protoboard Solder less Breadboard DigiKey 438-1046-ND $13.82 1 $13.82
LED Through-hole LED DigiKey C4SMF-BJS-
CR0U0452TB-ND $0.27 3 $0.27
Photodiode Infrared through-hole, Dome shaped DigiKey. 751-1045-2-ND $0.95 1 $0 .95
Speaker Available in the stock room N/A N/A N/A 1 N/A
Ni-myDAQ Data Acquisition Device National Instruments
N/A $200 1 $200
GPIB to USB Cable
National Instruments
N/A $495 1 $495
Serial to USB Cable
RS 232 Port adapter National Instruments
N/A $135 1 $135
Agilent 33250A
Waveform Generator Agilent Technologies
N/A N/A 1 N/A
Hp/Agilent 54600A
Oscilloscope, 2 channel, 100MHz
Agilent Technologies
N/A N/A 1 N/A
HP E3620A DC Power Supply, 35 W, Triple Output
Agilent Technologies
N/A N/A 1 N/A
Elenco LCM-1950
Digital Mutlimeter Elenco N/A N/A 1 N/A
Table 1– Bill of Materials
Section 1 – Understanding your DAQ Device
Objectives: By the end of this section the student will learn how to:
1) Use MAX to self-test a DAQ device
2) Determine the input/output ports on a DAQ device
Background Information
A Data Acquisition (DAQ) device is the “means by which physical signals, such as voltage,
current, pressure and temperature are converted into digital formats and brought into the
computer”1. This section describes three key concepts: DAQ resolution, input configuration, and
the Measurement and Automation Explorer (MAX).
Resolution of a DAQ device: The resolution is the smallest increment of a signal that
can be determined by the device. One may determine the resolution of a device from the
number of bits in the A/D or D/A (digital/analog) converter and the full-scale range of the
device. For example: the resolution of a 16 bit device with a full-scale range of 0 to 10 V
is 10/(216
) V = 153 μV. (Note that noise may cause the device to have an accuracy that is
less than the resolution.)
Input Configuration: LabVIEW supports three input configurations of the channels on
the DAQ, as shown in Figure 1:
1. Differential: Typically used to measure small voltage differences between two input
voltages, especially if there is a possibility of a large common mode voltage. You
need 3 connections: a high side, a low side and a path to ground. The path to ground
is important; if the inputs are purely floating, the voltages may drift outside the valid
voltage range, a problem that is solved by connecting one of the input voltages to
ground using a resistor (usually valued around 10 kΩ). A typical application of this
configuration is for a thermocouple.
Note: When using the myDAQ, the preferred analog input connection is differential.
2. Referenced Single-Ended (RSE): This configuration is used when all measurements
are referenced to a common ground, usually the ground pin on the DAQ. You need
two connections, the input signal and a path to ground. The most common application
of RSE is for a power supply, oscilloscope, or waveform generator.
1 Source: Labview Measurements Manual
3. Non-Referenced Single-Ended Inputs (NRSE): Used if you don’t want to connect the
ground of the circuit to the ground of the DAQ. This setup is not very common in
practice.
Figure 1– Different input configurations based on the input signal type. The image was
taken from NI.com – Field Wiring and Noise Considerations for Analog Signals,
[http://zone.ni.com/devzone/cda/tut/p/id/3344]
MAX (Measurement and Automation Explorer): MAX is the software interface
provided by National Instruments that allows you to communicate with and test all
National Instrument Devices, without programming.
Equipment required for this section:
1. Agilent 33250A Waveform Generator
2. DAQ Device [NI-myDAQ]
3. LED
4. Resistor (220 Ω)
Exercise 1
Problem statement – Self-test a myDAQ device and test the Analog Input channels and the
Digital Output channels.
1. Plug the myDAQ into a USB port. If Windows detects the new device and prompts you for an
action, choose to take no action.
2. Launch MAX by double-clicking the icon on the desktop or by selecting
Start » Programs » National Instruments » Measurement & Automation.
3. Expand the Devices and Interfaces section to view the installed National Instruments devices.
MAX displays the National Instruments hardware and software currently available to the
computer.
4. The device number appears in quotes following the device name. The data acquisitions VIs
use this device number to determine which device performs DAQ operations. For example, your
hardware may be listed as NI myDAQ, as shown in Figure 2. If you are using LabVIEW 2010
and are unable to see your device, Expand the NI-DAQmx Devices section to view the installed
hardware that is compatible with NI-DAQmx.
Figure 2– The MAX window after selecting a device
5. Perform a self-test on the device by right-clicking on it and choosing Self-Test.
6. Check the pinouts for your device. Right-click the device and select Device Pinouts or click
“Device Pinouts” along the top of the center window. MAX will display the function of each pin
on the DAQ device. For example, the myDAQ has eight digital input/output (DIO) pins, two
differential Analog Input (AI) pin pairs, two Analog Output (AO) pins, and 5V, +15V, -15V, and
GND pins. The myDAQ case is already well marked with all the pin information displayed by
MAX, but some devices are not marked as well.
7. Open the test panels. Right-click the device and select Test Panels. With test panels, you can
test the inputs and outputs without doing any programming.
8. To test the Analog Input in differential mode, we will use an Agilent waveform generator.
Switch on the waveform generator. Caution: the DAQ channels are configured to handle at
most ±10 V. Ensure that the output button on the signal generator is switched on. Generate a 100
Hz sine wave with a peak-to-peak amplitude of 1 V. Ensure that the waveform generator is set to
drive an unterminated cable, by pressing Utility » Output Setup » High Z.
Be sure there is a pair of minigrabber clips attached to a BNC cable connected to the output of
the waveform generator. Using a straight-slot screw driver, attach wires to the 0+ and 0
- Analog
Input channels. Connect the positive output clip to the 0+ wire and the ground clip to the 0
- wire,
as shown in Figure 3. If you are using a different DAQ device, you will need to determine the
appropriate pinout for that device.
Figure 3– The schematic showing the setup for the Analog Input test
On the Analog Input tab of the test panels, change Mode to “Continuous” and Rate to “10,000
Hz” and leave the Configuration as “Differential”. Click “Start” and verify that the graph
matches your expectations. Vary the signal generated and check the results. Click “Stop” when
you are done.
9. To test the Digital Output, we will use an LED. Connect one end of the 220 resistor to the
+5V channel and the other end to the anode (positive terminal) of the LED (the positive side is
the longer lead). Then connect the cathode (negative terminal) of the LED to the DIO channel 0,
as shown in Figure 4.
Figure 4– The schematic showing the setup for the Digital Output test
On the Digital I/O tab, notice that initially the port is configured to be all input. Under Select
Direction click on the bubble above 0 along the output row. You will then see a slider switch
appear at zero in the Select State section. Hit start and watch the LED turn on because the slider
is set to 0. Toggle the switch to observe the LED turn on and off. Figure 5 shows what the test
panel should look like. Click “Close” to close the test panels.
Figure 5– Digital I/O Test Panel.
What to turn in:
1. Did the waveform match your expectation?
2. Did the LED light up when you toggled the switch?
Section 2 – LabVIEW working environment
Objectives: By the end of this section the student will:
1) Be familiar with the LabVIEW environment, creating sub VIs and llb libraries
2) Learn about different data types in LabVIEW and debugging techniques
3) Review properties of panels
Background Information
Unlike text-based programming, LabVIEW is a graphical programming language that uses icons
and node-to-node data flow programming. This section describes key concepts including the
LabVIEW environment, Data Types, Data Flow Programming, Debugging techniques, useful
shortcuts and tools, and the NI Example Finder in LabVIEW, which are addressed below.
The LabVIEW Environment: LabVIEW programs are called Virtual Instruments (VIs).
Controls provide the inputs and Indicators display the outputs. Each VI is made up of a
Front Panel that provides the user interface and a Block Diagram that represents the
program. Figure 6 shows a front panel and block diagram for a temperature sensor VI.
Figure 6– Example showing the front panel and block diagram windows. [E80 Lecture on March
5, 2008 - www.eng.hmc.edu/.../LabView%20and%20Matlab%20Lecture-S08-final-%20RM.ppt]
In LabVIEW, you draw a block diagram describing the relationship between controls and
indicators in your VI. Then you arrange these controls and indicators on a front panel.
You interact with the front panel when the program is running. You can control the program,
change inputs, and see data updated in real time. Controls are used for inputs such as adjusting a
slide control to set an alarm value, turning a switch on or off, or stopping a program. Indicators,
such as graphs, thermometers, and lights, display output values from the program.
Every front panel control or indicator has a corresponding terminal on the block diagram. The
block diagram also contains various functions connected by wires.
One has access to a number of tools and palettes in LabVIEW. The following figures from
National Instruments’ Introduction to LabVIEW tutorial describe the basic palettes and panels
one would use in LabVIEW.
Figure 7 – Controls Palette
Figure 8 – Functions Palette
Figure 9 – Tools Palette
Figure 10 – Status Toolbar
Data Types in LabVIEW: LabVIEW uses many data types, including Boolean,
numeric, arrays, strings, and clusters. The color and symbol of each terminal indicate the
data type of the control or indicator. Control terminals have a thicker border than
indicator terminals. Also, arrows appear on front panel terminals to indicate whether the
terminal is a control or an indicator. An arrow appears on the right if the terminal is a
control and on the left if the terminal is an indicator. Figure 11 shows the various data
types present in LabVIEW. Most basic data types such as integers and complex numbers
are self explanatory. Arrays group data elements of the same type. An array can have one
or more dimensions and as many as (231
) – 1 elements per dimension, memory
permitting. Clusters group data elements of mixed types.
Figure 11 – Common data types found in LabVIEW
Understanding Data Flow Programming: LabVIEW follows a data flow model for
running VIs. A block diagram node executes when all its inputs are available. When a
node completes execution, it supplies data to its output terminals and passes the output
data to the next node in the dataflow path. Thus it is important to program node to node
as opposed to “line by line”.
Common Debugging Techniques: When your VI is not executable, a broken arrow is
displayed in the Run button in the palette. Here are some common debugging techniques
that allow you to step through your block diagram and identify possible errors, also
described in figure 12.
1. Finding Errors: To list errors, click on the broken arrow. To locate the bad object,
click on the error message, or show error.
2. Execution Highlighting: Traces the flow of the data, allowing you to view
intermediate values. Click on the light bulb on the toolbar.
3. Probe: Used to view values in arrays and clusters. Click on wires with the Probe tool
or right-click on the wire to set probes.
4. Retain Wire Values: Used with probes to view the values from the last iteration of the
program.
5. Breakpoint: Sets pauses at different locations on the diagram. Click on wires or
objects with the Breakpoint tool to set breakpoints.
Figure 12 – Common debugging techniques in LabVIEW
Short-cuts and important tools: A few of the important shortcuts are listed below:
1. Ctrl-E: Allows you to shift between the front panel and the block diagram
2. Ctrl-B: Allows you to delete broken wire
3. Ctrl-U: Cleans up the block diagram. This re-orders functions, wires and other objects
on the block diagram in a cleaner, more organized manner. This is good for small VIs
but does not work too well for large VIs
4. Ctrl-Z: Undo
5. Ctrl-H: The Amazing Context Help Window displays basic information about
LabVIEW objects when you hover the cursor over each object, as shown in Figure
13. Objects with context help information include VIs, functions, constants,
structures, palettes, properties, methods, events, and dialog box components.
Figure 13 – Using the context help window
SubVI: After you build a VI, you can use it in another VI as a function. A VI called from
the block diagram of another VI is called a subVI. You can reuse a subVI in other VIs.
To create a subVI, you need to build a connector pane and create an icon.
Finding Examples in LabVIEW: LabVIEW offers a large number of Example VIs that
are saved on your computer with the installation of LabVIEW. These example VIs may
be used as a starting platform for many projects. You use the NI Example Finder, shown
in Figure 14 to find these examples. From the Getting Started screen, clicking on Find
Examples will lead you to the Example Finder. From the block diagram of a VI, clicking
on help and selecting Find Examples… will lead you to the Example Finder.
Figure 14 – The NI Example Finder
Exercise 2 – Getting familiar with the LabVIEW environment and creating a
sub VI
Problem statement – Create a sub VI that adds two inputs and outputs the sum.
1. Launch LabVIEW by double-clicking the icon on the desktop or by selecting
Start » Programs » National Instruments » LabVIEW 2009 » LabVIEW.
Open a new Blank VI from the Getting Started screen (<Ctrl-N> opens a new VI.)
2. Place the Add function on the block diagram. Right-click on the block diagram and navigate to
Programming (You may have to click on the double arrow at the bottom of the palette to
expand the menu) » Numeric » Add.2
2 It is a hassle to click on the double arrow each time you need a Programming element. To make
Programming show up by default, right click on the block diagram, click on the pin on the upper
left corner of the Functions palette, and select View » Change Visible Categories… Check the
Programming box and click OK.
3. Create controls and indicators by right-clicking on the adder icon and selecting Create »
Control or Indicator. To make the controls and indicators small, right-click on them and
remove the checkmark on View as Icon. To make the diagram neater, click on Edit » Clean Up
Diagram. Rearrange the front panel as you see fit. The block diagram and front panel should
resemble Figure 15.
Figure 15 –The block diagram and front panel describing what your VI should look like.
4. Now we will create the connector nodes of the subVI. On the front panel right-click the icon at
the top right and select Show Connector to reveal the connector pane. Then right-click the
connector pane and select patterns. Choose the pattern with two input terminals and a single
output terminal. Figure 16 and 17 shows the process
Figure 16 – Accessing the connector pane
Figure 17 – Selecting the required pattern
5. Assign icon terminals to the two controls and the indicator by first left-clicking on an icon
terminal on the connector pane and then clicking the desired control/indicator. The connector
will turn from white to orange in color.
Note: The general convention is to have controls as data inputs on the left side and indicators as
outputs on the right side of this icon.
6. Now we will change the icon representing the subVI to one that is more descriptive of its
function. Right-Click on the connector pane and select Edit Icon... This should open the icon
editor depicted in Figure 18.
Figure 18 – Accessing the icon editor
7. Modify the graphics to more accurately represent the function of the subVI, in this case
Addition as shown in Figure 19. Right-click on the connector pane and click Show Icon to see
the modified icon.
Figure 19 – Modified Icon
8. Save the subVI in a common Labview Library (LLB) in your LabVIEW folder. Click File »
Save. In the bottom right corner of the save dialog, click on New LLB. Name the new LLB
Tutorial. Name the VI adder.
If you wanted to use this subVI in another block diagram you would right-click on the block
diagram and select Select a VI… and choose your adder.vi from the Tutorial library. In Section
4 you will modify and add a more interesting subVI to your block diagram.
What to turn in
1. A print out of the Block Diagram.
Section 3 – Recap: Elements of typical programming
Objectives: By the end of this section the student will:
1) Review LabVIEW programming, such as loops, functions, decision making structures,
and File I/O
Background Information
This section describes key concepts including loops, functions, making decisions, and File I/O in
LabVIEW, which are addressed below.
Loops: Both the While and For loops are located on the Functions » Programming »
Structures palette. The For loop differs from the While loop in that the For loop
executes a set number of times. A While loop, on the other hand, executes the sub
diagram until the conditional input terminal receives a specific Boolean value. The
default behavior and appearance of the conditional terminal is Stop If True. Both loops
have an iteration output terminal, which contains the number of completed iterations. The
iteration count always starts at zero. During the first iteration, the iteration terminal
returns 0. Figure 20 shows how one would draw a loop in LabVIEW.
Figure 20 – Drawing loops in LabVIEW
One important property of loops is the Shift Register. The shift register allows a loop,
such as the For or While loop, to carry forward values from one iteration into the next. It
may be added to a loop by right-clicking on the right or left side of the loop/structure and
selecting Add Shift Register as shown in Figure 21. Adding a control or constant to the
left block of the shift register allows you to place an initial value for the first iteration.
Adding an indicator to the right block of the shift register allows you to view the entire
set of data carried forward after all iterations are done.
Figure 21 – Adding a shift register.
For most LabVIEW VIs you may develop, timing of loops will be important. The
following are a few common timing functions used in LabVIEW.
Time Delay: The Time Delay Express VI delays execution by a specified number of
seconds. For example when placed in a While loop, the while loop does not iterate
until all tasks inside of it are complete, thus delaying each iteration of the loop by the
specified timed delay. This function can be found at Functions » Programming »
Timing » Time Delay.
Wait Until Next ms Multiple: This function waits until the value of the millisecond
timer becomes a multiple of the specified millisecond multiple to help you
synchronize activities. You can call this function in a loop to control the loop
execution rate. However, it is possible that the first loop period might be short. This
function makes asynchronous system calls, but the nodes themselves function
synchronously. Therefore, it does not complete execution until the specified time has
elapsed. This function can be found at Functions » Programming » Timing » Wait
Until Next ms Multiple.
Functions: There are 3 Types of Functions in LabVIEW, illustrated in Figure 22.
Figure 22 – Types of Functions in LabVIEW.
LabVIEW 7.0 introduced a new type of subVI called Express VIs. These are interactive
VIs that have a configuration dialog box that helps the user customize the functionality of
the Express VI. LabVIEW then generates a subVI based on these settings.
Functions are the building blocks of all VIs. Functions do not have a front panel or a
block diagram.
The various types of functions that are available include, but are not limited to:
1) Signal and data simulation
2) Real signal acquisition using the DAQ
3) Instrument I/O assistant
4) Statistics
5) Signal processing
6) Basic math and logic
7) File I/O and writing to files
The SEARCH Button: The functions palette is filled with hundreds of VIs and
functions. The easiest way to identify a set of functions that may be useful for a particular
task you wish to perform is to click on SEARCH on the top row of the functions palette
and enter a particular keyword, as shown in Figure 23. You may then study the narrowed
list of functions, pick the one you desire, and click and drag it onto the block diagram.
You may also determine the palette of the function by double-clicking on it. The first
time you do a search, labVIEW takes a noticeable time to populate the list of functions to
search through.
Search does make it easy to locate VIs or functions with which one is familiar, however
if one were looking for VIs to suit a particular purpose, browsing through the palettes
narrowing down VIs by function would be a better option to using the Search feature.
Figure 23 – The Search Window
Making Decisions in LabVIEW: Often while programming one is required to develop
routines that allow for decision making. Two useful functions for decision making in
LabVIEW are listed below.
1. Case Structure: The case structure has one or more sub diagrams, or cases, one of
which executes when the structure executes. The value wired to the selector terminal
determines which case to execute and can be Boolean, string, integer, or enumerated
type. Right-click the structure border to add or delete cases. Use the Labeling tool to
enter value(s) in the case selector label and configure the value(s) handled by each case.
You may also rename cases by double-clicking on the label. Remember, if you have more
than two cases, it is important to name one of the cases as the ‘Default’ case. For example
if you had three cases that were to be controlled by the integers 1, 2, and 3, you would
have to have one default case that would execute if an unidentifiable control were
inputted into the selection tool. The Case Structure is found at Functions »
Programming » Structures » Case Structure.
2. Select: Returns the value wired to the t input or f input, depending on the value of s. If
s is TRUE, this function returns the value wired to t. If s is FALSE, this function returns
the value wired to f. It is found at Functions » Programming » Comparison » Select.
A few examples are shown in Figure 24.
Figure 24 – Decision making tools in LabVIEW.
• Example A in Figure 24: Boolean input - If the Boolean input is TRUE, the true case
executes; otherwise the FALSE case executes.
• Example B in Figure 24: Numeric input. The input value determines which box to
execute. If the input is out of range of the cases, LabVIEW chooses the default case.
• Example C in Figure 24: When the Boolean passes a TRUE value to the Select VI, the
value 5 is passed to the indicator. When the Boolean passes a FALSE value to the Select
VI, 0 is passed to the indicator.
File I/O or writing to a file in LabVIEW: In LabVIEW, you can use File I/O functions
to:
Open and close data files
Read data from and write data to files
Read from and write to spreadsheet-formatted files
Move and rename files and directories
Change file characteristics
Create, modify, and read a configuration file
Write to or read from LabVIEW measurement files
It is advisable to use the higher level of abstraction of File I/O functions, usually express VIs.
A few are:
Write To Spreadsheet File – Converts a 1D or 2D array of strings, signed integers,
or double-precision numbers to a text string and writes the string to a new csv file or
appends the string to an existing file. The created spreadsheet file may be opened
with Microsoft Excel. This function can be found at Functions » Programming »
File I/O » Write to Spreadsheet File.vi.
Read From Spreadsheet File – Reads a specified number of lines or rows from a
numeric text file beginning at a specified character offset and converts the data to a
2D double-precision array of numbers, strings, or integers. Can be used to read from
Excel files. This function can be found at Functions » Programming » File I/O »
Read From Spreadsheet File.vi.
Write To Measurement File – Express VI that writes data to a text-based
measurement file (.lvm) or a binary measurement file (.tdm or .tdms). This function
can be found at Functions » Programming » File I/O » Write to Measurement
File.vi.
Read From Measurement File – An Express VI that reads data from a text- based
measurement file (.lvm) or a binary measurement file (.tdm or .tdms) format. You can
specify the file name, file format, and segment size. This function can be found at
Functions » Programming » File I/O » Read From Measurement File.vi.
These functions are easy to use and excellent for simple applications. In the case where
you need to constantly stream to the files by continuously writing to or reading from the
file, you may experience some overhead in using these functions.
Exercise 3 – Using elements of typical programming
Problem statement – Create a VI that
1. Uses a bandpass filter to filter uniform white noise and generate a range of frequencies
2. Analyzes the filtered signal using an fft spectrum
3. Measures the dominant frequency of the filtered signal as a function of time
4. Writes the measured values to a spreadsheet file
This exercise is a contrived problem aiming to introduce you to the variety of functions available
in LabVIEW.
1. We will first generate white noise continuously. Draw a while loop on the block diagram.
Search for the Uniform White Noise Waveform VI using the Search button on the upper right
corner of the Functions Palette (which appears by right-clicking on the block diagram) or
through Functions » Programming » Waveform » Analog Waveform » Waveform
Generation » Uniform White Noise Waveform.vi. The White Noise function generates 1000
samples at 1 kHz by default. Generate uniform white noise continuously by placing the Uniform
White Noise Waveform VI in the while loop. To graph the result you will have to place a graphic
indicator (waveform) on the front panel of the VI, by right-clicking on the Front Panel and
selecting Graph Indicator. You may then connect the output terminal of the function you choose
to the graph on the block diagram.
2. Now we shall filter the signal generated by the Uniform White Noise Waveform.vi. Place the
Filter Express VI (Functions » Express » Signal Analysis » Filter) in the while loop. As it is an
Express function, a screen with various options regarding the VI should pop up when you place
the VI on the block diagram. You may access this screen at any time by double-clicking on the
VI. Create a 10th
order IIR Butterworth bandpass filter with a lower cut-off of 300 Hz and an
upper cut-off of 310 Hz. Also create a front panel control for user-configurable upper and lower
cutoff frequencies to override the defaults you just entered. You may encounter a LabVIEW bug
such that the upper cutoff node does not appear on the filter icon. If so, double-click on the
Filter Express VI, then choose OK and the node should appear. Your block diagram should look
similar to that in Figure 25. To graph the result you will have to place a graphic indicator
(waveform) on the front panel of the VI, by right-clicking on the Front Panel and selecting Graph
Indicator. You may then connect the output terminal of the function you choose to the graph on
the block diagram.
Figure 25 – The Filter Express VI with controls. The Brown wire represents the incoming
Uniform White Noise Signal and the Blue wire represents the filtered signal
3. We will now plot the FFT spectrum of the filtered signal. First place the Spectral
Measurements Express VI (Functions » Express » Signal Analysis » Spectral) shown in Figure
26 on the block diagram. On the properties screen of the Express VI, let the Selected
Measurement be Magnitude (Peak) and the Result be in dB. Use a Hanning window. Connect the
input to the filter output. Add another graph indicator to display the magnitude spectrum on the
Front Panel. Re-label the X-axis on the graph to “Frequency”.
Figure 26 – The spectral Measurements Express VI with a graphic indicator.
4. Next we will find the dominant frequency of the filtered data using the Tone Measurements
Express VI as shown in Figure 27. Search for the Tone Measurements Express VI using the
Search button on the upper right corner of the Functions Palette (which appears by right-clicking
on the block diagram) or through Functions » Programming » Waveform » Analog
Waveform » Waveform Measurements » Tone Measurements Express VI. Select frequency
as the single tone measurement. Also create an indicator for the output of the Tone
Measurements VI, by right-clicking on the output node and selecting Create » Numeric
Indicator.
Figure 27 – The Tone Measurements Express VI measuring the dominant frequency of the
Filtered Signal.
5. Now we shall compare the dominant frequency of the filtered signal to a user-input limit (307
Hz). Place an LED on the front panel by right-clicking on the front panel, selecting LEDs, and
choosing an LED of your choice. Next place the Greater? VI on the block diagram by right-
clicking on the block diagram and selecting Programming (you may have to click on the double
arrow at the bottom of the palette to expand the menu) » Comparison » Greater?
Now connect the output of the Tone Measurements VI to the upper node of the Greater? VI.
Create a control to the lower node of the Greater? VI by right-clicking on the node and selecting
Create » Control. Finally connect the output of the Great? VI to the LED. Thus if the frequency
is over that limit (307 Hz), the LED on the front panel will light up. If not, the LED stays off.
Your code should be similar to that in Figure 28.
Figure 28 – The spectral Measurements Express VI with a graphic indicator.
6. We will now write the dominant frequency to an array. First place the Build Array function
(Functions » Programming » Array » Build Array) on the block diagram, in the while loop.
Drag the bottom of the function down, so as to have two rows. Connect the output of the Tone
Measurements VI to the bottom row of the Build Array function. Now create a shift register by
right-clicking on the right edge of the While loop and selecting Add Shift Register. Now
connect the shift register on the left edge of the loop to the top row of the Build Array function.
Finally connect the output of the Build Array function to the shift register on the right edge of the
While loop. Your code should look similar to that in Figure 29.
Figure 29 – The Build Array function and the convert dynamic data VI .
Note: Usually when appending dynamic data to an array, LabVIEW will automatically use the
Convert from Dynamic Data.vi to convert dynamic data to a 1D array. If this doesn’t happen and
you don’t see the icon displayed above you should add the Convert from Dynamic Data.vi to
your block diagram and connect the dynamic data to the VI prior to appending it to the bottom
row of the build array function as seen in Figure 29.
7. Now write the array to a spreadsheet file using the write to spreadsheet VI. Search for the
write to spreadsheet VI (Functions » Programming » File I/O » Write to Spreadsheet File.vi)
and place the VI outside the while loop (ask yourself why?). Wire the output node of the shift
register on the right side of the loop to the 1D data node on the Write to Spreadsheet VI. Now
create a constant for the transpose? node on the Write to Spreadsheet VI and set the constant to
be T (True). Furthermore, you want the shift registers to start at zero every time you run the VI.
Therefore right-click the input node of the shift register on the left side of the loop and create a
constant, as shown in Figure 30.
Figure 30 – Shift register output node connected to the write to spreadsheet file VI and the input
node of the shift register connected to the initial value constant.
8. Attempt to Run the VI. You will see that you are unable to do so due to the broken Run arrow.
Debug the problem by clicking on the broken Run arrow. Correct the error by adding a control
to the conditional terminal of the While loop.
After correcting the error, click on the Light Bulb icon on the toolbar (Next to the Pause
Button). This will allow you to step through your code as it moves from node to node on the
block diagram. Now Run the VI. Once you are satisfied by the results you receive at each node
on the block diagram, de-select the Light Bulb icon and move to the front panel. On the front
panel you should see the LED flash on and off occasionally. After a bit stop the VI. When
prompted to save the results, save them as results3. Open the spreadsheet with MS Excel and
verify the various dominant frequencies recorded. Are they what you expected to see?
9. Save your VI in the folder you created for the tutorial in exercise 2.
What to turn in:
1. A print-out of the Block Diagram and the Front Panel.
2. Did the spreadsheet file contain values between 300 and 310 Hz?
Section 4 –Instrument Control
Objectives: By the end of this section the student will:
1) Control instruments through GPIB and Serial Ports
Background Information
LabVIEW provides device drivers to control a wide variety of commercial instruments over
GPIB, Serial, USB, and Ethernet ports. In this tutorial, you will generate a Bode plot for an RC
circuit using a signal generator and an oscilloscope controlled by LabVIEW. You will control
the signal generator over a serial port and the oscilloscope over the General Purpose Interface
Bus (GPIB).
Serial: The RS-232 serial communication port sends data one bit at a time over a single
communication line to a receiver. Therefore this method works best when data transfer
rates are low or when data must be transmitted over long distances.
The keys to successful serial communication are to match the physical and timing
interfaces. Despite the fact that only one wire is carrying data in each direction, standard
serial cables have either 9 or 25 pins. Moreover, they come in male and female flavors.
Worse yet, you may occasionally encounter a null-modem cable that swaps the transmit
and receive pins between the two ends. Take care to obtain the appropriate cable to
connect the device to your computer.
A data transmission consists of one start bit followed by 5-8 (usually 8) data bits
followed by an optional parity bit and 0-2 optional stop bits. Both the transmitter and
receiver must agree on how many data, parity, and stop bits to expect. Check the manual
for your device.
Serial links don’t use an explicit clock; instead, both sides agree on the speed, called the
baud rate, of communication. For example, 9600 baud indicates 9600 bits per second. If
the system is set to 1 start, 8 data, 1 parity, and 0 stop bits, then each character requires
10 bits, so the system transmits 960 characters per second.
Most computers today no longer have built-in serial ports. National Instruments sells
USB-to-RS232 cables like the one shown in Figure 31 with a built-in converter for
speaking to older devices with RS232 ports.
Figure 31 – The NI USB to RS 232 cable.
[http://sine.ni.com/nips/cds/view/p/lang/en/nid/12844]
The Art of Electronics by Horowtiz and Hill has a helpful section on troubleshooting
serial links.
GPIB: Stands for General Purpose Interface Bus as defined by the ANSI/IEEE standard
488.1-1987 and 488.2-1992. It is a common interface of communication used by various
instrumentation companies. Communication occurs through a digital 8-bit parallel
interface with transfer rates of 1 MB/s or more. For more information visit
http://en.wikipedia.org/wiki/IEEE-488. The cable you will use for the tutorial is shown in
Figure 32. GPIB is being replaced by Ethernet and USB in most new instrumentation but
is still widely found on older devices.
Figure 32 – GPIB to USB-B GPIB cable. [http://sine.ni.com/psp/app/doc/p/id/psp-354]
Bode Plots: In this section it is important that you understand how a first-order low-pass RC
filter works. Furthermore you will be required to understand the Bode plot (or at least the gain-
magnitude frequency response) associated with a first-order RC low-pass filter. Recall that a
first-order low-pass system has a transfer function of
H(j) = 1/(1+j)
where = RC is the time constant.
Some characteristics of the Bodeplot of a first-order low-pass filter are listed below and shown in
Figure 33.
1. The gain, in units of decibels (dB), is 20 log (Vin/Vout)
2. The corner frequency occurs at -3 dB
3. The slope of the drop off line is -20 dB/decade.
Although a Bode plot technically refers to both the gain and phase portions of the frequency
response, we will only consider the gain in this tutorial.
Figure 33 – Bode plot of a first-order RC Low-Pass Filter. The image was taken from
Electronics Tutorial: Passive Low Pass Filters - http://www.electronics-
tutorials.ws/filter/filter_2.html
Equipment required for this section:
1. Agilent 33250A Signal Generator
2. HP 54600A oscilloscope
3. Resistor (2.2 k)
4. Capacitor (10 nF)
5. Protoboard
6. The appropriate connectors
Exercise 4 – Controlling a signal generator and oscilloscope
Problem Statement – Design a VI that controls a signal generator and oscilloscope to make a
Bode plot of a first-order low-pass filter.
1. What is the theoretical cut-off frequency of the first-order RC filter shown in Figure 34?
2. Build the RC circuit on a protoboard and connect the signal generator and oscilloscope to the
respective terminals. Let channel 1 of the oscilloscope measure the unfiltered input to the RC
circuit and channel 2 measure the filtered output.
Input Signal Output Signal2.2 kW
10 nF
Figure 34 – Schematic of a first order RC filter.
3. Turn on the oscilloscope and the signal generator. Be sure the waveform generator is in High
Z mode. This can be found under Utility » Output Setup » Load » High Z. Plot both channels
on the oscilloscope and observe the amplitude of the waveforms as you increase the frequency.
Measure the peak to peak amplitudes of the waveforms at 1, 2, 5, 10, 20, 50, and 100 kHz and
draw a Bode plot by hand. If it does not match your expectations, debug until it does.
4. To automatically generate a Bode plot with LabVIEW, you will want to take measurements at
points logarithmically spaced between a start and stop frequency, in a manner analogous to the
Matlab logspace command. Since LabVIEW lacks such a function, we have written a subVI for
you. Copy Logspace.vi from \\charlie.hmc.edu\Clinic\Engineering\tutorials\LabVIEW to your
folder. Open a new VI in LabVIEW and add the Logspace.vi as a sub VI to the block diagram.
You may do this by right-clicking on the block diagram, selecting Select a VI… and choosing
Logspace.vi from your folder. Logspace.vi takes in the following inputs: upper bound and lower
bound of the frequencies in which you will measure the response of the filter and the number of
data points per decade. Create constants for the respective nodes. It is advisable that you choose
an upper bound of 100 kHz or higher and a lower bound of 100 Hz. Your code should look
similar to that in Figure 35.
Figure 35 – Logspace.vi with controls and an indicator.
5. You will now need to install the instrument drivers required for this exercise. Select Tools »
Instrumentation » Find Instrument Drivers or Help » Find Instrument Driver. Choose
Agilent Technologies as the manufacturer and then click Search. Choose the folder labeled
ag33xxx Instrument Driver and install the driver for LabVIEW 2009. You will have to register
on NI.com to be able to download the driver. One would repeat the same steps as above to obtain
the drivers for the oscilloscope, however as the updated drivers have errors we will use the old
drivers present in the Labview folder on Charlie. Copy the folder labeled hp546xxx on to your
desktop from \\charlie.hmc.edu\Clinic\Engineering\tutorials\LabVIEW.
6. Connect the waveform generator to the PC via the NI USB-232 Serial to USB adapter. Note
that you will need a 9-pin null modem gender mender that should come with the adapter.
Determine which COM port to which the waveform generator is connected by clicking on
Control Panel » System » Hardware » Device Manager and looking at the port assignments.
For instance the NI USB-232 may show up on COM4. Connect the oscilloscope to the PC via the
NI GPIB USB-B adapter. This will normally be assigned to port GPIB1::1::INSTR.
7. The block diagram will have three subsections:
control of the Signal Generator
control of the Oscilloscope
Bode plot calculations
8. You should save the VI, through the Save As option, in the folder you created for this tutorial
prior to proceeding.
Subsection 1 – Control of the Signal Generator
1. First we shall draw a loop to iterate through the frequencies outputted by the Logspace.vi.
Draw out a For Loop on the block diagram but do not include the Logspace.vi in the For
Loop.
2. Next we will draw a sequence that will divide the block diagram in the For loop into
three consecutive steps. Draw a Flat Sequence (Functions » Programming » Structures
» Flat Sequence) on the block diagram in the For Loop.
3. We will then convert a driver into a subVI that we can use in our VI. Right-click on the
block diagram and select Select a VI » My Computer » Local Disk (C:) » Program
Files » National Instruments » LabVIEW 2009 (2010 if that is the current version on
your laptop) » instr.lib » Agilent 33xxx Series » Examples » Generate Standard
Waveform.vi and place it in the flat sequence. You will notice that the example driver
does not have any nodes on it. Double-click on the Generate Standard Waveform.vi and
you will see the front panel of the driver open. We will now modify the subVI to include
three nodes. Right-click on the icon of the subVI present on the top right corner of the
window and choose Show Connector as shown in Figure 36. As you did in Section 2 of
the tutorial, create input connections for VISA Resource Name, Frequency and
Amplitude. Save the subVI and close the block diagram window of the subVI. Now if
you return to the main block diagram you will see the subVI has three nodes.
Figure 36 –Modifying the sub VI by first accessing the connector pins
4. Now we will provide inputs to the Waveform Generator subVI. Next we will identify the
Resource Name associated with the Waveform Generator. Create a Visa Resource Name
Control, by right-clicking on the VISA resource name node of the Generate Standard
Waveform VI and selecting Create » Control. Place the control outside the For loop and
then wire it to the Standard Waveform VI. Also create a control for the Amplitude node
of the Generate Standard Waveform VI, place the control outside the For loop, and set
the amplitude to be a constant of 5 V. Wire the frequency output node of the Logspace.vi
to the respective input node on the Standard Waveform VI.
5. Set the amplitude to 5 V on the front panel. Set the VISA Resource name to the COM
port representing the waveform generator. Now run the VI. You should see and hear the
waveform generator stepping through the frequencies you requested. Note: When
attempting to run your VI, LabVIEW may ask you to locate sub VIs required for the
Generate Standard Waveform.vi. Locate them in the folder Agilent 33xxx Series. Don’t
forget to search all folders within for the requested files. You may also obtain an error
stating that the dependency was loaded from a new path. You may ignore the error.
Subsection 2 – Control the Oscilloscope
1. First we will modify the block diagram by expanding the Flat Sequence. This will allow
us to accommodate the functions controlling the oscilloscope. Add two additional frames
to the flat sequence by right-clicking on the boundary of the flat sequence and selecting
Add Frame After. The second frame will be used to call the auto scale function of the
oscilloscope to scale the recorded signals. The third frame will be used to call a function
that reads the measurements made by the oscilloscope for each channel.
2. Add the HP546xxx Autoscale.vi to the second frame of the flat sequence from the
hp546xxx folder. Create a control for the VISA Session node and place it outside the For
Loop. On the front panel, set the VISA Session control to GPIB.
3. The third frame will contain two HP54600A/610B Measurement VIs to measure the
amplitudes of the filter input and output. The input amplitude should be 5 V, but it
doesn’t hurt to measure as a sanity check. Connect the VISA session nodes of the two
Measurement VIs to the same GPIB VISA session. Create controls for the source node
and function node of each measurement. The source node selects the oscilloscope
channel. The function node specifies the kind of measurement, such as peak to peak
voltage. Create an indicator for each function-reading output node.
4. On the front panel, you want to set the source of the first measurement to channel 1 and
the function to V p-p. Set the second measurement to channel 2 V p-p. Your code so far
should look similar to Figure 37
Figure 37 – The various subVIs your code should use to call measurements made by the
oscilloscope
5. Run the VI and observe the readings made by the oscilloscope.
Subsection 3 – Developing a Bode plot
1. First lay out the code required to calculate the Gain of the filter. Outside the flat sequence
(but in the For loop), determine the Gain of the system using the divide function
(Functions » Programming » Numeric » Divide). Determine the Log of the Gain by
using the Logarithm Base 10 function (Functions » Mathematics » Elementary and
Special Functions » Exponential Functions » log10). Multiply (Functions »
Programming » Numeric » Multiply) the output by 20 to obtain the Gain in dB. Your
code should look similar to that in Figure 38.
Figure 38 – Code describing the calculation of the gain in dB
2. Now we will group the Gain and Frequency results together so as to plot a Waveform
graph. Place the Bundle function (Functions » Programming » Cluster, Class &
Variant » Bundle) on the block diagram outside the For loop. Drag it down until you
have two rows. Connect the Gain to the bottom row of the Bundle and the output of the
Logspace.vi to the top row of the Bundle. The bundle allows you to combine two
variables, say X (top row) and Y (bottom row) into a single waveform prior to connecting
it to a XY graph.
3. Now we will build the Waveform graph. Shift to the Front Panel Window, right-click,
and place an XY Graph (Right-click » Graphic Indicators » XY Graph) on the Front
Panel. Right-click on the graph, select Properties » Scales » X-axis (on the drop down
menu) » Log (check the box). Also re-label the X-axis Name to frequency. (On shifting
back to the block diagram you might have to delete the express VI and keep the Graphic
indicator).
On the block diagram connect the Output Cluster (from the bundle) to the waveform
graph. Your code for this section should look like that in figure 39. Also remember on the
front panel you would like the graph to be in log scale.
Figure 39 – The code required to generate a Gain Magnitude frequency response plot
4. Run your VI. At what dB do you observe the cut-off frequency? Is it what you expected?
What is the slope of the line that drops off rapidly beyond the cut off frequency? Is it
what you expected?
What to turn in:
1. A screenshot of the Front Panel displaying the controls and the Bode plot, plotted using at
least 5 points per decade.
2. A printout of the Block Diagram.
Works Cited:
1. Two exercises were modified renditions taken from the NI tutorial. Furthermore a number of
slides present in the Background Information sub-part of each section were also grabbed from
the tutorial available at http://zone.ni.com/devzone/cda/tut/p/id/5247.
2. The shift register diagram was taken from
http://learnlabview.blogspot.com/2008/06/programming-labview-shift-register.html.
3. The pictures of the GPIB and Serial cable were taken from NI.com
http://sine.ni.com/psp/app/doc/p/id/psp-354 and http://sine.ni.com/images/products/us/ni-
9870_w_cable_l.jpg
4. E80 lecture Feb 5, 2008, www.eng.hmc.edu/.../LabView%20and%20Matlab%20Lecture-S08-
final-%20RM.ppt.
Good Reference Sources:
1. Bishop, Robert H. & National Instruments, LabVIEW 2009 Student Edition, Prentice Hall
2010, ISBN-10: 0-13-214129-9 ISBN-13: 978-0-13-214129-1
2. The LabVIEW youtube channel.
http://www.youtube.com/user/Labview#p/c/498405DC54786398/13/1KT98-7B2E8
3. The LabVIEW wiki
http://labviewwiki.org/Development_Environment
4. If you are interested in learning more about the Mathscript feature
http://techteach.no/labview/lv85/mathscript/index.htm
5. NI.com – It has EVERYTHING! (Well almost)
Feedback:
As this is the first time we are using tutorials as part of the clinic program, we would really value
your feedback.
How many hours did you spend on the tutorial?
Did you face any problems during the tutorial? Please explain
What would you like to see added to the tutorial? Please explain
What do you feel is not required in the tutorial? Please explain