You are on page 1of 34

Introduction to Labview

Peter Powers

Chautauqua Program
University of Dayton
May 21-23, 2012

1
Contents

Basic Operation.............................................................................................................................................. 3 
Controls and indicators .............................................................................................................................. 4 
Introduction to programming ..................................................................................................................... 5 
Displays, charts .......................................................................................................................................... 7 
Formula node ............................................................................................................................................. 8 
Interfacing with the outside world ................................................................................................................. 9 
Low-level programming: A/D setup ........................................................................................................ 11 
Express A/D ............................................................................................................................................. 13 
Analog output........................................................................................................................................... 15 
Loop structures, arrays, and displays ........................................................................................................... 15 
Arrays....................................................................................................................................................... 18 
Shift Registers .......................................................................................................................................... 21 
Debugging ................................................................................................................................................ 22 
Saving Data .................................................................................................................................................. 22 
Sub-vi’s ........................................................................................................................................................ 23 
Waveform data ............................................................................................................................................. 25 
Recording multiple points from the A/D card ............................................................................................. 26 
Array statistics ......................................................................................................................................... 27 
Sequences and cases ................................................................................................................................ 27 
Sequence locals and local variables ......................................................................................................... 29 
Bells and whistles (just a few) ..................................................................................................................... 30 
Interfacing with a variety of instruments ..................................................................................................... 32 
Exercises .................................................................................................................................................. 33 

2
Basic Operation
We’ll work through the first few exercises together. The goal is to become comfortable
navigating Labview and get started with basic programming.
Navigate to and open the Labview program from the Start menu. The screenshot below is the
first screen to appear after starting Labview. From the Files area you will see “New”, from this
block of functions select and click on “Blank VI”. Also visible is the “Open” block of
commands. This block consists of recently written programs and is convenient for quickly
opening up old programs. The term VI stands for virtual instrument.

click this

Note: different versions of Labview basically look the same.

After clicking, Blank VI, you should see the following two windows pop up. If there are other
windows that open, don’t worry about them now.

The two windows, Front Panel and Block Diagram, are where all the action occurs. In the rest
of the document the block diagram is referred to as the Back panel. We switch between the front
panel and back panel by using the short-cut CTRL-e. Alternatively from the menu bar select
Window and then select front or back panel. The Front Panel is where we place inputs to the
program and where the program displays information. The Back panel is where the program is

3
“written,” that is, it is where we operate on the inputs from the front panel and it’s where we
generate results to display to the front panel.

Displaying inputs and outputs as well as programming are visually oriented in Labview. To add
elements to either window we start by opening tool boxes. To access these, go to the View menu
item and select Control Pallet and then also select Tools Pallet.

Tip: To switch between the Front Panel and Back Panel (block diagram) type CTRL-e.
Tip: A quick way to access control pallet or tool pallet is to right click on the active window.

When green light is on,


the mouse is in “smart These are the objects you place on the
mode” and automatically front panel
picks the tool you need

These are tools to


manipulate front panel
objects (pan, label, color, These open up other pallets
etc)

Controls and indicators


Now let’s use an example to get a feel for working with Labview. Let’s write a program to
simulate Ohm’s law. In this program, we input a current and resistor value and then a voltage is
displayed based on Ohm’s law. First we’ll set up the Front Panel inputs and output. From the
controlsmodernnumeric Pallet, select the Numeric Control icon. The numeric control
represents an input to the program while a numeric indicator displays results of the program.

Using this panel (see above), drag and drop two Numeric Controls and one Numeric Indicator to
the Front Panel, and label them as in the following picture. To label the boxes, double click on
the label area and enter the desired text.

4
You can enter numbers into the Current and Resistance boxes, or click on the up and down arrows
to change the values. You cannot enter anything into the Voltage box since this is an indicator as
apposed to a control. The VI is now set up for data entry and display. To manipulate the inputs,
we go to the Block Diagram. Note that when we switch to the back panel, the control pallet
changes and is completely different than the front panel.

Introduction to programming

In the back panel we see three orange boxes. The color of the boxes indicates the data type. The
orange color indicates double precision (DBL), and also note that the boxes have the label DBL,
which indicates that the variable is double precision. In Labview, colors in the Back Panel are
always tied to a particular data type. Floating point numbers are orange, integers are blue,
boolean is green, and so on. As we work more with programming these colors will be more
apparent.
In the current example, the data types for the controls and indicator happen to be correct, but in
other programs we might want a different data type. To change the type of number we are
working with, right click on one of the boxes and select Representation (see below). Here you
will see a host of choices for the different data types. The top row are floating-point, the next row
are integers, the next unsigned integers, and the last are complex (as in numbers with the square
root of -1). If you move the mouse over the items, you will see a fuller description show up on
the top of the window. For example, move the mouse to the CDB box and you will see Complex
Double show up in the description bar. For now let’s leave the representation as double precision.

Back to the program; all it does at this point is take in the two numbers and then does nothing
with them! To execute the Ohm’s law algorithm, we would like to multiply the current times the
resistance. To do so, go to the View menu and open the Functions pallet and the Tools pallet
(alternatively, and my preference is to simply right-click anywhere in the back panel to access the
5
various pallets). The Functions pallet shows many options for manipulating data, as seen in the
next figure.

click me to get …

Clicking on an icon opens up a separate window with various operations. In our case, we simply
want to multiply, so click on the Numeric block to show what numeric operations we can
perform. Now drag the Multiply object to the Back Panel. After doing so you will need to
somehow tell Labview what you want to multiply. This is done by “wiring” the two inputs to the
multiply object. Simply pass the mouse over one of the inputs and you will see a wiring icon
appear, click and drag over to the multiply object and then unclick and you should be able to get
the following.

A few notes: The left hand side of the multiply object is input and the right is the resultant output.
The second note is that the wires are orange showing that the data type going through the wires
are DBL.

Now the program is done. We go back to the Front Panel and press the Continuous Run button,
then enter values for Current and Resistance to see the resultant “voltage” displayed.

continuous run
button

run once button

To stop the continuous-run execution, click on the red stop sign. At this point you may want to
save your program, or in the parlance of Labview, save your VI. Next let’s explore the various
ways to display data.

Tip: Right clicking on various objects displayed is a good way to bring up menus and
display information about an object.

6
Displays, charts
Next we’ll look at graphical displays of data such as gauges and charts. From the Front Panel try
adding other Numeric Displays (the figure below shows one example). Be sure to wire the
displays up in the back panel, which can be done in parallel with the previous display. That is,
you can send the result of the multiplication to several displays at the same time by adding more
wires. Similarly, the controls have different displays such as rotating knobs. Replace one of the
controls to a knob and then change the inputs to see how the different displays work. I used the
“Silver” pallet to find the controls shown below.
Back Panel program

Labview has several graph-type displays and the first we’ll look at is the Waveform Chart (think
chart-recorder). As an example of this display, we’ll modify our existing program. Delete the
Current input from the Front Panel and delete all Voltage displays. You should now see a broken
run arrow to indicate that the VI has problems. In the Block Diagram go to the
functionsprogrammingnumeric pallet and drag a Random Number and hook this up in
place of the old current input. We’ll pretend this random number is our measurement of current.
Now instead of visualizing a single value at a time, let’s display a whole history. To do so, go to
the Front Panel and select Waveform Chart from the Controls ModernGraph pallet. From
the Block Diagram, wire up the output of the Multiply object to the Graph icon. You should have
something that looks like the following snapshot.

The front panel now shows a chart. Run the VI to display values. You will see a rather rapid
update of values, so stop the program and set the minimum value to 0 (x-axis scale) and the
maximum to 500. Now run the program again and the updating should occur at a less frenetic
pace.

7
Formula node
In some cases it is much more efficient to use line-code to enter formulae. Consider the equation
for the temperature dependence of a thermistor,
1
T
A  B ln R  C  ln R   D  ln R 
2 3

where T is in K and R is in k.

“Wiring” up such a program is somewhat cumbersome, so another approach is to include a code-


snippet using a formula node.

Formula node

Under the Structures pallet, select the Formula Node icon (see above) and create a code-box as
shown below. Each line in the box is terminated by a semicolon. The code can have local
variables (A, B, C, and D in this case) as well as external inputs and outputs. The local variables
have to be declared as floating point or as integers, for example float A declares A as floating
point and int I declares I as an integer. The local variables are entered as shown below. We right
click on the left hand side of the box and click “Add Input” to add an input port. When this port
is created, we type in the variable name, in this case lnR. Note that the variable name can be
anything we choose; in this case I chose “lnR” so that the code is clear. Now we can access this
variable (lnR, or whatever we decide to call it) within the code box. Note the variable is case-
sensitive. Similarly, we right click on the right hand side of the box and click “Add Output” to
add the output port. Add the code into your program and after that we’ll address how to access
elementary functions such as the natural logarithm.

Labview has so many commands available, that it is oftentimes difficult to navigate to the
appropriate sub-pallet. In such cases I find it convenient to use the search icon, see figure below.

Click here to search for


Logarithm

8
Type in “logarithm” in this search window. By clicking on “natural logarithm” Labview will bring up the
sub-pallet where the ln function resides. The search is complemented by a context-help. As you may
have noticed, Labview has a seemingly infinite number of possible data manipulation blocks, and in many
cases the icon is not particularly helpful in determining its function. We can access context-help by
opening the help menu and selecting Context Help. Now open the function pallet and move the mouse
over various icons. You should see a change in content as the mouse is passed over each icon.
Tip: you can type control-H to toggle context-help on and off

Context help changes as


you move the mouse over
various icons

Use this to find


functions you are
looking for

Interfacing with the outside world


Now let’s switch gears and look at using Labview to make measurements and analyze data. We start by
using a National Instruments tool to check to see what devices are present on the computer and to see if
they are functioning properly. This tool, “Measurement and Automation Explorer” (MAX) may be found
under the StartNational InstrumentsMeasurement & Automation. After opening it up, the screen
shown below should be visible

9
Most of the devices we need to see are under the “Devices and Interfaces” section (circled in red above).
Open this item to show the devices present on the computer, and it should look something like what is
shown below (different devices will be present depending on which computer you have),

In the above, the Devices and Interfaces is expanded to show what is available on my computer. This is
the area where we look for devices that we installed on the computer. In the above, a GPIB card, NI
ELVIS, as well as serial ports show up. When these devices show up in MAX then they are accessible to
Labview. From MAX it is possible to open up the device and test it out. Below is a screen-shot after
opening up the NI ELVIS device, which shows its various properties including how many and what type
of channels. By pressing start we can test the device. Similarly, we can test GPIB and serial port devices
if they are hooked up.

10
In this class we will spend a lot of time with the ELVIS boards. These are analog-to-digital cards that are
connected to a break-out panel that allows us to easily access the different input and output channels on
the A/D card. The ELVIS board comes with several input and output configurations that we won’t use
such as an oscilloscope mode and DMM mode, but feel free to open up the ELVIS software (found under
StartNational Instruments) to see pre-programmed functionality.

In brief, an A/D card takes an external analog voltage and converts it to a digital number. In almost all
cases, the cards also have a digital to analog output that allows us to convert a digital number to a real
voltage. There are a huge range of such cards differing by resolution, speed, cost, etc. Most cards have an
optional break-out boxes to easily access the different channels (such as ELVIS).

Low-level programming: A/D setup


We start with a low-level approach and after completing this step, we’ll use wizard based approaches
(Labview Express). Why bother with this low-level stuff you might ask? It gives you a behind-the-scenes
look at what the Express wizard is doing, and it shows you that what is behind it is not too difficult. It
also helps us understand a few key points about the A/D card setup and a few general Labview
programming details.

To make a measurement with the A/D card we first need to configure it – determine which channels
should be active and so on. You can access the A/D functions from the Measurement I/O >>NI-
DAQmx pallet.

11
Drill down and open
the NI-DAQmx pallet

Select the Create Channel icon and drop it into your Block Diagram. This icon has several inputs to
configure an A/D channel. A very useful Labview technique is to let Labview do the work for connecting
the right type of input. If you move the wire tool over one of the inputs, right click on it. From the menu
select Create (see next page). Now you will see three options: Constant, Control, Indicator. In the case
of the A/D setup we will be using the same setup as we run the program, so select constant. If you select
Control, Labview will place a control on the front panel. If you select Indicator you will get a broken wire
(the Icon is expecting an input).

Wire up your Block Diagram to look like the screen-shot below. It consists of a set-up icon and a read-
board icon. The read icon is found in the same pallet as the Create Channels icon. The numbers in the
orange block are for the A/D voltage range. Both the Create Channel and Read icons are polymorphic.
This means that the same icon can perform many different tasks depending on how you set it up. In our
case we click on the purple box below the icon to select the options in the figure below. For the Create
Channel icon we are telling it to set up an analog input that reads 1 voltage measurement (double
precision). For the read icon we are telling it to read one channel for a single analog, double precision
number.
This is connected
to the “Physical
Channels” input
This is labeled as the READ icon in
the NI-DAQmx pallet.

Now we are ready to measure external world voltages. I have pre-wired a photo-resistor circuit so that the
voltage across the photo-resistor is measured by channel 0 (ai0). When you run the program in
continuous-run mode, you should see the voltage go up and down as you wave your hand to cast a shadow
on the detector – congratulations you are now interfacing to the external world with the computer!

12
Express A/D
The preceding exercise shows a low-level program that communicates with the A/D card. This gives a
taste of how Labview is interfacing with the A/D card, and shows that we can address individual channels
on the card. Another easier approach is to let Labview write the program for us using an “Express” vi.
Let’s recreate the above exercise using the Express approach. Within the NI-DAQmx pallet is an icon
called DAQ Assistant. Drag and drop this icon into the back panel of a new vi and double click it to open
the window shown below.

Here, we see several input/output options and for now we select Analog Input. This selection brings up
another menu from which we select Voltage. Afterwards other windows open up allowing us to configure
the channel(s). We’ll configure one of the analog inputs:

choose ai0

13
Various options present
themselves here.
Desired voltage range,
terminal configuration,
data collection mode (1
sample, N samples), and
triggering.

All of these properties


along with the channels
they refer to make up a
“task.”

Change from “N
Samples” to “1 Sample
(on demand)” and then
click OK.

The following icon shown below on the left should now appear in the back panel,

The colored arrows are inputs we can set and outputs we can use. Note that by dragging down on the
double arrow, we can expand the options out as shown on the right above. The output we want is the
data line, which sends out the measured voltage. Note that we can later go back and reconfigure the DAQ
Assistant by double clicking on it if needed. Because the DAQ Assistant is so flexible, the output data is
in a form called “dynamic data” that can accommodate single point measurements, N-point measurements,
multiple channels, etcetera. If all we want to do is display the data, then we simply wire the output of the
data line to an indicator, which automatically configure themselves for the specific data coming in to it.
14
However, if we would like to manipulate the data, we need to extract it. (In a sense, this is the price we
pay for using the Express vi. ) Go to FunctionsExpressSignal Manipulation and select “From
DDT”. When you drop this icon in the back panel it brings up a window asking you how the data should
be displayed. In the present case, select single scalar. Create an indicator and wire up the program as
shown below and test it to see that it displays voltages going into the A/D card.

If you would like to see the programming behind the express vi, right click on the express icon and select
“Generate NI-DAQmx code.” This action converts the express icon into the low-level steps like we set up
in the first place. This approach can be a good way to learn how to program the lower-level functions.

Analog output
In this section we’ll continue to work with the DAQ Assistant, but now we’ll configure it to send voltages
as outputs.
Most A/D cards have a digital-to-analog and digital outputs, and our cards are no exception. The analog
and digital outputs are a great way to control external devices. For example, we might want to make a
temperature controller where we set the current to a heating element based on a temperature recording.
The possibilities are endless. For now we look at how to implement this function.

The input and outputs to a given A/D card are handled using two tasks, one for inputs and one for outputs.
That is, we can’t double click on the Express icon and configure both inputs and outputs from the same
icon. Using the same program we just wrote, add another Express DAQ Assistant icon to the back panel.
Click on the icon and follow the steps to configure an analog output (for channel AO0). During this
process, be sure to select “1 sample (on demand).” The other options are not compatible with the A/D
card we use in this course. Your program should look something like that shown below. Save this
program as we will use it again, I’ll refer to this program later as “Two-channel read write.”

Notice the red dot going into the data input. This indicates a type mismatch and the value is being coerced
to the right type of input. If we would like to get rid of the red dot, add a “To DDT” conversion from the
FunctionsExpressSignal Manipulation pallet. To test the program, we can physically wire the
A/D card’s input (AI0) to the output (AO0). Put the program in continuous-run mode and verify that the
value entered into the “data” control shows up on Channel 0.

Loop structures, arrays, and displays


In the above exercises we use continuous run to make a series of measurements, but this has limitations.
For example, what if we would like to compare a previous measurement with the current one? In the
continuous run mode, we basically lose the past history. All programming languages have a means to
15
repetitively execute code. “For loops”, “While loops”, “Do loops”, etc may be familiar to you – if not,
they are all very simple constructs. For example, the “While loop” executes certain operations while a
certain condition is true. In Labview, loop structures are found under the Functions  Structures pallet
(Block diagram only). Open a new vi and go to the Back Panel and select the while loop and place it on
the back-panel. Within the while-loop structure is a stop sign. Right click on the stop sign and select
Createcontrol, which places a button on the Front Panel . The button sends a False signal if left alone
and True when pressed. This type of data is called Boolean, ie it has two values – True or False. The
green wire indicates a Boolean data type. Also notice the blue i inside a blue block. This is a loop
counter, which you can use for display or in a loop calculation (it starts at 0 and counts up).

Now let’s return to the program above that communicated with the A/D card. We’ll modify it so that it
steps the output voltage in a ramp and sends that voltage to the analog output on the A/D card.
Go back to the “Two-channel read write” VI you wrote earlier and add a while-loop as shown below. We
 i 
obtain a voltage ramp that runs from 0 to 5 by writing the remainder of   /5 to the data input. By
 100 
dividing i by 100, we obtain a finer step size in the ramp. If you like, change the 100 to a front-panel
control so that you can control the step size. Note that in addition to a single-value indicator, the vi
includes a Waveform Chart. The chart shows up on the front panel and it lets us see the voltage ramp.
Remainder and quotient icon is
found in same pallet as multiply,
divide, etc.

The numeric constants are also


found in the same pallet. You
can change the data type
representation by right clicking
on the constant and selecting
representation.

Front Panel:

Note that we have created a function generator! We could change the ramp to another waveform by
replacing the remainder icon with a trig-function (see
functionmathematicselementarytrigonometric pallet). In fact, we have the ability to write
arbitrary waveforms that are limited only by the speed and voltage characteristics of the A/D card. Of
course, timing in our present example is completely uncontrolled, but we’ll address this issue later.

16
Since we are on the topic of loops, let’s
convert the While loop above to a For loop.
A For loop executes the loop a
predetermined number of times. The For
loop structure is found within the same
pallet as the While loop, but we can also
switch between the two once they are
created. Right click on the While loop’s
boundary and select “replace with for
loop.” This repacement preserves the
contents of the loop, but note that a few
broken wires are present. The For loop
does not need the Stop button, so it can be deleted. The number of iterations of the For loop is given by
wiring an integer to the “N” from the outside of the loop.

To store values measured during a While or For loop’s operation, we can put the values into an array.
Any looping structure in Labview allows arrays to be automatically created by wiring from inside the
While loop to the boundary (see left). Once connected, right click on the terminal at the loop boundary
and select enable indexing. The enabled index creates an auto-sizing array where an element is added for
each execution of the While loop. After the loop is completed, we hook up a wire to the outside of the
loop and the whole array is accessible. In the case shown to the left, we wire the array up to a Waveform
Graph. This graph icon is added to the Front Panel from the same pallet as the Waveform Chart icon.
Run the program and verify that a history of measurements are recorded (try running the program for
different number of steps and verify that the number of points in the array is different).

While we’re on the topic of waveform graphs, we’ll spend some time learning how to display multiple
data sets on the same graph, and how to plot a Y vs X type plot. The Waveform Graph can display more
than one array of data by building a two-dimensional array where each element corresponds to an array of
data to display. We take the above example and create another array of data based on what we send to the
A/D and then send both arrays the Waveform Graph, see below. Now we can compare graphically what
we send out to what we measure on the A/D.
Note thick orange line indicates
array of DBL numbers

Build Array function found in


functionsarray pallet. Note that
it initially shows up as a single
input icon. To obtain two inputs,
click on the bottom of the icon to
resize it.

Notice output is double-line


indicating 2-D array

Front panel on next page

17
Front Panel:
Another way to display data is with the XY Graph, which plots a Y-array versus an X-array. Labview
creates such a plot using x and y data that are “bundled” together. In our case we bundle the x-array and
the y-array together and send the data to the XY Graph, see below. For an x-array, this example just uses
the loop count number, i. The bundle icon is found in the functionsclusters and variant pallet.
Bundles are also used to combine all sorts of data and objects. For example, we can bundle an array of
100 complex numbers with an array of 20 Booleans and a string variable. Such an option is not possible
with arrays since an array must have elements with the same data type.

x-array

bundle icon

y-array

Arrays
All programming languages have the ability to group objects together in arrays and Labview is no
different. We already saw how to automatically create an array using the “enable indexing” with a For or
While loop. In that exercise, we created an array and then displayed it using the Waveform Graph as well
as using two arrays with the XY graph. Typically we would like more functionality, that is the ability to
access specific elements, modify elements, use a subset, etcetera. Labview has a pallet of functions
dedicated to arrays that gives these various functionalities, see below.

18
As a first example of working with the array pallet, let’s create an array. We have already seen one way
as mentioned above, and there are two more ways within the Array pallet as well. We can create an N-
element array with the “Initialize Array”

With this function, we need to tell Labview how many elements the array will have, and what the value
for each element should be. The output is sent to an indicator using the createindicator approach.
Using the create indicator step automatically creates a front panel array indicator. Duplicate the above
and inspect the front panel array indicator. Note that we can resize the array indicator to show multiple
elements.

Note the array indexing on the indicator starts at zero. Also note that the array does not have to contain
numbers. Below is a string array with every element of the array initialized to the string “Peter.”

19
The second way to build an array using the Arrays pallet is via the “build array” icon,

This allows us to directly write each element of an array and it lets us concatenate two arrays. To use this
tool, drop it onto the back panel and then resize it to the appropriate number of elements. The inputs to
the array can be numbers, strings, or “objects”. The only rule is that each element must be the same type.
Below shows a few examples

Most of the time, the build array is used to concatenate (Labview terminology) or append two arrays to
each other. When concatenating , the two arrays must be of the same type as seen below

Another option is to build an array of arrays. To do so, right click on the build array tool and de-select
concatenate inputs

With arrays, each element must be of the same type. With numeric arrays, we can use a mixture of
different types of numbers such as DBL and INT, but when we do this, labview will coerce all of the
elements to be DBL.
We worked with the Bundle objects with the XY graph. In many cases the bundle looks a lot like an array
in that it contains many objects. The big difference is that in bundles, the objects don’t all have to be of the
same type. For example, below is shown a bundle (or sometimes called a cluster) of a 100 element array
bundled with a string and a Boolean control.
20
As a further example of arrays note that we can create an array of bundles like so:

Shift Registers
When using a loop-structure it is convenient to have a quantity based on the action of a previous loop
iteration. A classic example is a program for generating a factorial, ie N!=N*(N-1)*(N-2)….*1. Labview
has a construct called the shift register, which is used with For-loops and While-loops. A shift register is
thought of as a stack of objects where, upon each iteration of the loop, a value is added to the top of the
stack (register) pushing all the other elements down one level. The object in the bottom-most register is
kicked out to make room. I use the word object because the shift register handles a variety of data types –
single numbers, arrays, and even character strings. A shift register is added to a While loop or a For loop
by right clicking on the left or right wall of the loop and selecting add shift register. The down-arrow on
the left is the value the loop uses on the current iteration and the up arrow on the right is where the value
for the next iteration is written. The register needs to be initialized at the start of the loop – hence the value
1 wired in from outside the loop below. Beware, if you do not initialize the register you lose control of the
starting value of the register. What usually happens is that a value of 0 is written in, but I have learned the
hard way that this is not always the case!

21
A vi for the Fibonacci sequence is shown below. The Fibonacci sequence follows the pattern: 1, 1, 2, 3, 5,
8, 13,… ie the Nth number in the sequence is equal to the sum of the previous two values. Also, the ratio
of any two numbers in the sequence converges to the golden ratio for largish N (note the sequence grows
rapidly and for N>40 it cannot be represented with double precision). In the vi below, the shift register is
resized so that it is “two elements high.” For a given iteration of the loop, we access the two register
values and when the iteration is done, the top value is pushed down to the lower element and the top value
is replaced by the value sent to the up arrow. You can resize the shift register by clicking on it and
dragging down (be careful to not just create a second independent shift register). An interesting fact about
Fibonacci sequences is that the golden ratio is always obtained independent of the starting values. We can
verify this by changing the inputs to the shift registers.

Light-bulb for debugging

Debugging
Labview has an excellent debugging tool that allows us to watch the program run in slow-motion. From
the back-panel of the Fibonacci vi select the light-bulb and then press the run-button. As the program
executes, we can observe the data and order of operations. A problem with the light-bulb mode is that it
slows everything down. In some cases, all we care about are a few values. Labview allows us to observe
these values by right-clicking on a wire and selecting Probe. When the program executes and gets to the
probe point, it displays the value. Note that the wire can be any type so the probe can look at single-
values, arrays, bundles, and so on. Finally, note that when we right-click on a wire another option is
“custom probe.” The custom probe allows us to use graphical displays such as Waveform graphs to
visualize a particular data stream.

Saving Data
Labview has a a pallet devoted to file input output function, found in functionsprogrammingfile I/O.
We will save data using the “save to spreadsheet file” icon, shown below.

The inputs to the icon to pay attention to are the format, file path, and transpose. The format follows
Fortran conventions (I think) where %.3f stands for floating point, 3 digits. Note that unfortunately
%.3f is the default format. If we don’t wire in a different value, the saved data will only keep three
digits – very annoying! My preference for a format string is %g, which is automatic formatting. Other
format strings may be found by searching the help files under “format specifier examples.” The file path
input is typically left unwired, which then results in a dialog box opening up asking for file name and
location to save. The transpose input is used to arrange horizontal arrays into vertical columns, which is

22
Build-array creates a header
array. The headers are created
using string constants found in
more compatible with spreadsheet programs like Excel. In the example below we add the save to spread
sheet icon and we also add headers to the columns of data.

Sub-vi’s
The icons in Labview represent subroutines that accomplish specific tasks. Labview lets us create our
own subroutines or in Labview parlance, sub-vi’s. We’ll build a sub-vi and use it in a subsequent program
to illustrate the point.

In the following we’ll create a vi that takes an array of data and subdivides it into N segments, create a
spectrum of each segment, and store the spectrums in an array that we display. In addition to learning
about how to make a sub-vi, we’ll also learn some more array operations.

We start by creating an input where the array of information starts. Go


to the front panel and add an array element (see left). Next select a
Numeric control icon and drop it inside the array box on the front panel.
This procedure results in a numeric array object. Note that if we want to
create a Boolean array or string array, we would have added a Boolean
or string control to the array box.

Next we go to the back-panel, where we see that the array object is


present (see also screen shot below). Note that we have not assigned a
length to the array, but we will take care of this detail later on. Our
goal is to divide the array into sub-arrays that have a prescribed length,
which we’ll call “Number of points per segment” or Ndiv for short.
Within the array pallet are a host of array utilities, and one of them is
Array Size. Array size divided by Ndiv is the number of sub-arrays.
Instead of dividing, we use the Remainder and Quotient icon (in the
same pallet as the divide icon), which gives an integer result for the division. The vi shown below uses
the Array Subset to select out sequential segments of the total array. The two inputs to Array Subset are
index (starting point) and length. The output of the Array Subset is sent to the Auto Power Spectrum icon
(magnitude squared Fourier transform), which is another built-in Labview function. dt is delta-t (in
seconds), which we provide via a front-panel control, and df is a display that shows the frequency spacing
for the spectrum. Wire-up the vi and save it.

23
Array subset

Array size Remainder


and quotient df

For subsequent display purposes, we would like to have the frequency output as an array, and so we have
yet another excuse to introduce another Labview concept. Add another For loop as shown below. In this
example, when we bring an array into a For loop and enable indexing on the input side, the For loop
figures out how many elements are in the input array and will loop for that number, so we don’t need to
connect an input to N. On each execution, each array element is delivered to the For loop, but in this case
we are not using those elements instead we just use it to match array lengths (there are other ways to
accomplish the same result).

This vi requires three inputs and yields two outputs. In a stand-alone mode, we would manually enter the
values in the front-panel and then run the vi to see the resultant outputs. However, that is not our current
intention. We would like another program to input the values and then access the resulting outputs. We
accomplish this task by turning the above into a sub-vi. To do so, go to the Front Panel and right-click on
the icon in the upper-right corner of the Front Panel. Select Show Connector. These are connectors that
you can hook up to items on your Front Panel. Since the program has three inputs and two outputs, we
need to select a pattern with five connectors. Right click on the icon showing the connectors and select
Patterns, see below.

24
After selecting a pattern, when you click on one of the connector panes, the wiring tool activates.
Clicking on either a control or indicator wires the given pane to that control or indicator. Futhermore,
note that one of the options from the drop-down menu above is Edit Icon… This option allows us to create
a unique icon graphic to identify our sub-vi. When we save the vi it is ready to be called from within
another vi. To test our sub-vi, we start with a new vi where we’ll create an array of data, and then we’ll
use the above sub-vi to analyze the results.

Waveform data
Labview has a special data type called Waveform, which is an array of data along with specific
information about the waveform such as its starting time and point spacing in time (delta-t). The
waveform data type is a convenient way to make sine-waves, square-waves and so on. From the
ProgrammingWaveformAnalogWaveformWaveformGeneration Pallet (yikes!) select the
BasicFunctionGenerator icon. This function allows us to create one of several types of waveforms.
Right-click on each of the Frequency, SignalType, and SamplingInfo inputs to create controls for these
inputs. We access the waveform data by splitting out it’s various components using the GetComponents
icon (ProgrammingWaveformAnalogWaveform pallet). Wire up the vi as shown below.

The above exercise gives us an array of data that has a known waveform. Now we’ll feed this array into
our previously written sub-vi. We find the sub-vi by right-clicking in the back panel and choosing
functionsselect VI… Here we can navigate to the previously written vi and add it to the back panel,
see below (my sub-vi is called Get Spectr.). To display all the spectra on the same plot, we can use an
intensity graph. The intensity graph is added via the front panel. The input to the Intensity Graph is a 2D
array, and it displays the 2D array as an image where the color for a given “pixel” is determined by the
value of the 2D array at that location. Run the VI and try different waveforms to see its operation. In the
next section we replace the “fake” signal with a real-world audio signal.
25
Recording multiple points from the A/D card
Collecting sequential data using a While or For loop is fine for applications where timing is not critical.
If we require precise timing, then these loop structures have problems in that the timing of each iteration
of the loop may change and we have no idea how long a given iteration takes. A/D cards have a built-in
clock that allows us to set the timing and record the data all from the card itself. There is, however, a limit
to how much data we can collect – the card has on-board memory that fills up. If this happens the vi
usually freezes and to fix the problem we reduce the number of data points recorded, which we control via
labview.

We will modify the above vi to input an audio signal as shown below. Here, we use the express DAQ
Assistant and configure the analog input to acquire N points. For the sampling rate and number of points,
we recycle the bundled “sampling info” from the previous vi. To access the rate and number of points we
unbundle the data. There are two choices for unbundling: unbundle and unbundle by name. In the figure
below unbundle by name is used so that we see that the top element is Fs (Rate) and the bottom is #s
(number of points). Wire up the vi and test it by making sounds into the microphone on the provided
breadboard. I will show you where to place the wire for the audio signal.

Open the DAQ Assistant and select


N Samples. We’ll be able to change
the samples to read and the Rate
after we are done.

26
Array statistics
A handy pallet for calculating various properties such as mean, standard deviation and so on may be found
in functionsmathematicsprobability and statistics. For example, if we would like to cut out the
DC component of the spectrum we can just subtract off the array’s mean value:

Notice that the subtraction is between an array and a single number. In such cases the number is
subtracted from every element of the array. Also note that I added a logarithm to get what I think is a
better image.

Sequences and cases


Our programs so far have been somewhat short, but you can imagine that the size can grow quickly.
Furthermore, the sequence of events in a given program is not always clear. The sequence structure is a
construct that helps to keep the program size manageable and it also sets up a specific order of events.
The sequence icon is found in the functionsprogrammingstructures pallet. Its borders are set up to
look like frames of a movie film strip, and it acts in the same way. One frame is executed followed by the
next and so on. Open a new vi and add a “stacked sequence” structure to the back panel. Next, right click
on the top of the frame and select “add frame after.” The resultant vi should have something similar to
what’s shown below.

In the stacked sequence, frame 0 is executed followed by frame 1. As an example, consider a situation
where we want to write 2.5V to the analog output AO0 before we read a value from the analog input AI0.
In our previous examples with both analog read and write, the order of operation is not clear. We force
the order by adding a DAQ Assistant to frame 0 (write a voltage to AO0) and then adding a DAQ
Assistant to frame 1 (read a voltage AI0).

27
Add “wait until done” to the task, which can
be found in functionsmeasurement
I/ONI DAQmx pallet.

If no output is requested from the given icon


then Labview moves on and executes the
next frame even if the internal workings of
the present icon aren’t finished.

The analog read is configured to read N


samples (1000 points is the default).

Within the same pallet as the sequence, while loop, and for loop are several other structures. In this
Chautauqua class the final structure we consider among this pallet is the case structure. Which frame of
the case structure executes depends on the input value. In the example below, a Boolean control (added to
the front panel) is the input. If the Boolean is true the value 2.5 is sent out of the case structure and into
the DAQ Assistant. However, if the Boolean value is False then the other frame (see second snapshot)
executes. Within the other frame is a separate number (0, for example) that is sent out of the case
structure when the False case is selected. Add the case structure to your vi and verify its action by
monitoring AO0 with AI0 (that is, wire the output and inputs of the A/D to each other). No changes are
made to the second frame (frame 1).
Note difference

28
The case structure is not limited to Boolean inputs. The example below shows how to have 5 voltages
sent to the ouput. To make the vi, delete the Boolean control and then wire in the blue-wire as shown.
When the blue wire is connected, the labeling on the case changes to 0,1 instead of False,True. By right
clicking on the 0,1 we can add cases to the structure. In the program below we need to have cases 0, 1, 2,
3, and 4 to account for the possible values generated from the remainder operation. Wire this vi up and
run it in light-bulb-mode from the back panel to see how the case is evaluated and executed.

Sequence locals and local variables


An obvious question here is how to pass data from one frame to the next in a sequence. For example, we
might want to base a calculation in frame 1 on a particular value in frame 0. The first way to pass data is
using a sequence local. We’ll start with a new vi as shown below. The program creates a cosine wave
and then calculates its mean and standard deviation. We display the result in a Waveform Graph (labeled
cos-wave below). Build the vi by first creating a stacked sequence structure. Next right click anywhere
on the sequence structure and select “add sequence local.” By doing so, a yellow square is added to the
sequence, which we can wire to. The square represents a tunnel from one frame to the next (it’s a one-
way tunnel, however).

In the above, the data is leaving the frame as indicated by the arrow. Notice that the next frame in the
sequence has a sequence local with an arrow pointing in the opposite direction, which indicates that data is
entering the frame. The measurement in the second frame (frame 1) takes the array and calculates mean
and standard deviation (see functionsmathematicsprobability and statistics pallet).

As the program grows in size and more data is passed from one frame to the next in a sequence, the
sequence locals tend to clutter the diagram. Another way to pass data is using a local variable. A local
variable is based on a control or indicator somewhere in the program. In our case, we can use the cos-
wave indicator in the above program. If such an indicator is not present we can create an indicator where
needed by right clicking on the wire of interest and selecting create indicator. To create the local variable,
right click on the cos-wave icon indicator and select createlocal variable. Place the resulting icon in
frame 1 of the sequence as shown below. After placing it in the frame, right click on the local variable
29
and select “change to read.” This action lets us read from the local variable. The program now gives the
same result as our previous one with local variables.

Note that we can read or write to the local variable. Consider a case where we generate a graph (like cos-
wave’s front panel indicator) and later on we want the contents of the graph to change. The local variable
lets us write a new value to the object and then any front-panel indicator associated with it will reflect the
change. Add two frames to the sequence (right click on the sequence number and select add frame after).
In frame 2 add a delay of 1 second using the wait icon found in functionsprogrammingtiming pallet
(see below). In frame 3 we convert the cos-wave into a square wave using a greater-than (>) comparison
from the functionsprogrammingcomparison pallet. The output of the comparison is Boolean, so
we convert it to 0’s and 1’s using a conversion icon from the same pallet as the > operation. Note that we
use two local variables here, one is read from and the other is written to. We can copy and paste a given
local variable to make more copies. Be sure that the local variable on the left in frame 3 is set to Read and
the one on the right is set to Write. When the program executes, we should see a cosine-wave and then
shortly thereafter it turns into a square wave.

Bells and whistles (just a few)


Chances are that a right-click on an object will bring up options to display the particular object in the way
you would like. One right-click option in particular brings up a host of possibilities. Right click on the
“cos-wave” icon in the previous example and select “create property node.” When you do this, a list of
possible attributes are listed.
Visibility: One I find particularly useful is “visible.” When this property node is created, we can make a
particular front panel object appear or disappear programmatically. This is useful for scenarios where
you want to control what a person can access at a particular time during program execution.
Cursors information: The other option I particularly like is to access cursor coordinates on a waveform
graph. In the example shown below, I created a waveform graph on the front panel, then I right clicked on
it and selected “Visible items””cursor legend.” This brings up a cursor box, which if we right click in it
we can select “create cursor.” The graph can have an arbitrary number of cursors, so the way Labview
deals with extracting this information is by creating a “cursor list” which is an array of bundles. The array
size is automatically set to be equal to the number of cursors on the graph. Each bundle contains all the
cursor information such as x-position, y-position, and so on. To access the cursor list, go to the Back
Panel and right click on the Waveform Graph icon. Then select createproperty nodecursor list. The

30
output of this property node is the array of bundles. As seen below, we access each cursor by using the
index array icon to pick out particular array elements.

Sub-vi creation: We have learned to make a stand-alone program into a sub-vi, but in some cases we
write a program and then decide that a portion of that program would make a good sub-vi. Or, we might
be working with someone else’s program and would like to make a portion of their code into a sub-vi.
Labview allows us to create sub-vi’s by selecting the appropriate code and then go to EditCreate Subvi.
When we perform this action, the selected code is turned in to a sub-vi, see below:
1) select code:

2) Select EditCreate Subvi

3) Code is now a sub-vi

Code snippets: In the above, step 2, note that under Edit, we can select Create VI Snippet from Selection.
When we choose this option, Labview will save the selected code to a .png file, which when pasted into
Labview will automatically be converted to Labview code. To paste it into Labview, go to the directory
where the png file is saved, select the file and then drag it to the back panel. A powerful use of this
snippet approach is that when the png’s are posted to a website, the image can be cut and pasted directly
into labview.

31
Diagram clean-up: The screen shot of the program below shows a messy diagram that is nearly
impossible to understand. Labview will automatically clean it up for you by going to EditClean Up
Diagram.
Before auto-clean-up:

After auto-clean-up:

We can also highlight a portion of the code and select “clean up selection” and Labview will rearrange
that part of the diagram.
Wire cleanup: Sometimes the whole diagram doesn’t need cleaning up, but just one wire does. In such a
case, select the wire, right click and select “clean up wire.”
web publishing: Labview converts any vi into an html document accessible via the web. From the menus
bar select ToolsWeb publishing. This selections brings up a wizard that steps us through the web-
publishing process.

Interfacing with a variety of instruments


So far we have used the A/D card as our main interface with the outside world. These cards are a good
introduction to both acquisition and control applications, but are only one of a host of devices that we
encounter in laboratory classes and in research labs. Other types of devices fall into roughly two
categories: 1) devices that reside within the computer (usually attached to the PCI bus) and 2) external
stand-alone devices. Labview treats the first category in a similar fashion to A/D cards, that is, Labview
uses function calls for the device that have built in the communication to the device without us doing
anything. Labview is such an industry standard that most companies that sell third party devices provide
Labview drivers, which include the basic function calls to the device. In most cases these functions are
provided by the device manufacturer. Labview has a considerable library of devices that it will
automatically communicate with such as web-cams, mouses, keyboards, and joy-sticks.

The second category, stand-alone devices, are in most cases accessible via serial port, general purpose
interface bus (GPIB), ethernet, or USB. The majority of these devices such as oscilloscopes, function
generators, and so on are controlled using ASCII commands (ie commands using normal text characters).
The ASCII commands are sent to the device via serial port, GPIB, etc. Labview uses a flexible
communication format (VISA) that allows us to use the same programming for any of these
32
communication connections. This is particularly helpful for devices that are sold with different
connection options because a particular vi that communicates with the device will work for all the
different connection types.

When working with VISA, we initialize the particular type of communication port at the beginning of the
program using a VISA Open (Instrument I/O-->VISA) and after that we use VISA Read and VISA Write
to communicate with the device. On the VISA Open we select the particular instrument by right clicking
on “VISA Resource Name” and then selecting create control. On the front panel the Visa Resource Name
control automatically updates with every serial device connected to the computer. At this point we then
select the appropriate device, which is passed to the VISA Read and Write by wiring VISA Resource
Name from the VISA Open to the VISA Read and Write. Similar to internal devices, most stand-alone
devices come with Labview vi’s that show us how to communicate with the device. Many of these
programs may be found at the National Instruments website under Instrument Driver Network.

Because of the limited number of GPIB devices (and GPIB-to-USB converters) available for this course, a
station is set up demonstrating GPIB programming. Additional stations are set up that illustrate different
Labview capabilities from video capture to joy-stick feedback. We will cycle through these stations and
then our last activity is more loosely defined. Below I have several application examples that you can use
to test your new-found Labview knowledge. In addition to these examples, feel free to define your own
application or interface with a device you have brought along.

Exercises
The following exercises are intended to show you useful Labview skills and also give you a chance to try
programming without a step-by-step guide. As you work through examples of interest to you, I will be on
hand to help.

Loop progress monitor: A handy loop skill is some way of displaying how far along a program has
progressed. Write a vi with a For loop that executes N times and use a front-panel display to show the
progress. For example, you can take i/N and plug it into a “vertical progress bar” that is scaled from 0 to
1.

Averaging: Create an array with values that give a square wave consisting of roughly 1000 points and
roughly 10 periods. Add random noise to the square wave using the random number generator used
earlier. Use this routine within a loop-structure and average N waveforms and display the average result.
I suggest using a shift-register to help.

Histograms: Use the functionsignal processingsignal generationpoisson noise to create an


array with Poisson noise statistics. Use this array to create a histogram of the distribution. Change the
noise type to see what effect the given generator has on the distribution.

Enhanced resolution mode: We can improve the bit resolution of a given A/D card by sacrificing speed
for resolution. Write a vi that takes in an array of data and averages “m” adjacent points to give a single
point. Hence an original array of length N becomes an array of N/m, where each point has higher bit-
resolution.

FFT’s: Instead of using the auto-power spectrum vi that only gives the magnitude squared of an FFT,
write a vi that displays the magnitude and phase of the signal. See the functionssignal
processingtransforms pallet. Note that the output of an FFT is a complex-valued array.

33
Sound-card A/D: Labview has access to the computer sound-card’s microphone input. Note that
although this input is intended for an audio input, it is possible to send in voltages from other sensors.
Select functionsprogramminggraphics and soundsound pallet and then select the input wizard.
You should be able to set up the microphone. Try using this audio-A/D input in the 3D visualize program
we wrote earlier.

Digital functions: So far we have only used the analog functions on the A/D card. Write a program that
sends out a digital pulse train with a variable number of pulses. Note that our cards are only capable of
sending out a single value at a time, so you will need to use some sort of loop with the digital write inside
to create the pulse train. Monitor the pulse train with the analog input (ai0).

Triggering: In our previous audio-spectrum program we had to manually synchronize the start of the
program with the sounds we made into the microphone. Another approach is to continuously monitor the
input and when the voltage goes above a certain level, then we start recording. Modify the previous
program to include triggering. You can take this a step further to include a pre-trigger capability.

Box-car integrator: Write a vi that collects N samples from the A/D channel 0, but then integrates only a
portion of the array. Note that the integration is performed by simply adding array elements.

34

You might also like