Vous êtes sur la page 1sur 12

Introduction to LabVIEW Programming

January 31, 2008

1 Fundamentals

LabVIEW is an application that lets you interface a computer with an experiment. It is


extremely powerful, allowing you to generate and measure analog and digital voltages as
well as control the timing of such operations. In order to be such a powerful application,
there is a huge amount of flexibility in what you can program. This makes it a little more
difficult to get started, but once you become familiar with the procedures you will enjoy an
amazing capability. After a description of the general features of the application, you will
be prompted to write four basic programs, each of which performs one operation. Following
that, you will write two programs that are more complicated. Finally, you will have the
chance to browse the library of example programs and then write a program of your own
choosing.
The computer is equipped with a National Instrument PCI-6221 Multifunctional I/O
board. This board is capable of (1) generating an analog voltage (D/A conversion), (2)
measuring an analog voltage (A/D conversion), (3) generating and measuring digital volt-
ages (digital I/O), and (4) timing the various operations. The D/A and A/D conversions
have a resolution of 16 bits, meaning that the voltage range (-10 to +10 V) is divided into
216 = 65536 levels. The spacing between levels is therefore 0.3 mV if the voltage range is
-9.99756 to 10.00000 V. You can choose ranges/resolution among some standard settings
(±10V , ± 5V , ± 1V , ± 0.2V ). Every generated or measured analog voltage will be one of
these 216 values. There are 2 analog output channels for generating voltages and 8 analog
input channels for measuring voltages. The 8 analog input channels can be set up to use
the same ground connection as the reference (this is called RSE or Referenced Single Ended
– there is also differential input, but we aren’t going to use this). The 2 analog output
channels have a common reference ground. There are 3 digital channels, each of which has
8 lines that can be low/false (0 V) or high/true (5 V). Each digital channel can be used
either to generate a digital voltage (digital out) or measure a digital voltage (digital in),
but clearly not both at the same time! The PCI-6221 board has been designated device

1
number 1 for all LabVIEW programming.
The LabVIEW programming environment utilizes two windows. The first is called the
Front Panel and is how you enter and obtain information from the program (please keep
in mind that we will use capital letters to identify all of the various names of LabVIEW
items).

The second is called the Block Diagram, which is where you write the actual program
by wiring objects together. A program is called a Virtual Instrument (VI) by LabVIEW,
and when a VI is saved both windows are saved. The front panel is shown when a VI is
opened. To see the block diagram, sometimes you must select it from the menu. When
programming, it is useful to have both the Front Panel and Block Diagram open at the
same time. However, the tool palettes and menu selections are different depending on
which window is the active “front window”, so keep in mind which window you are “in”
while working.
Objects for the Front Panel are dragged over from the Controls Palette (this palette can
be opened from the View menu as long as the Front Panel widow is active and it disappears
when the Block Diagram is selected). Controls supply the VI with data and Indicators
display data from the VI. When a control or indicator is dragged on to the Front Panel,
an object corresponding to it automatically appears on the Block Diagram. Objects for
the Block Diagram are dragged over from the Functions palette (which becomes available
when the Block Diagram is active). Once all the required objects have been dragged on to
the Front Panel and Block Diagram, wiring them together so all the proper operations are
performed is all that remains. Each object on the Block Diagram has one or more input or
output terminals, and it is good programming practice to make sure each is wired properly,
even if the program runs with a terminal left unwired. Wiring is done by dragging and
clicking the wiring tool from terminal to terminal. Dragging the tool creates the wire,
while clicking tacks down the wire at that point and lets you continue the wire in another

2
direction. Once the wiring is completed, the VI is saved in the usual way (with .vi as the
extension).
One complication is that there are many different data types, and each object produces
and expects certain ones. LabVIEW uses labels and colors to make this easier, but it is a
part of the programming that needs careful attention. The types you will be using at first
are 16 bit signed integers (I16), single and double precision real floating point numbers
(SGL and DBL), Boolean states (e.g., true or false), and I/O name controls (Channel
Types, which we’ll have LabVIEW generate for us). Remember to save your VI before
running it the first time. After testing a VI out thoroughly, print out a copy of the Front
Panel and the Block Diagram for your notebook.

2 Simple Analog Output Program

Start the LabVIEW 8.2 application and click on the Blank VI button in the New box.
Both the Front Panel and Block Diagram windows are open, you can see both at the same
time. Select the Front Panel to be the active window. We will generate Front Panel objects
a couple of different ways: 1) from the Controls pallette and 2) from menu items in the
Block Diagram. First let’s make a control from the Front Panel.
Select the Front Panel to be the active window, go to the Controls palette to
set up a numeric control.

• Click once on a Numeric Control object in the Controls palette, move the cursor to
to the Front Panel, click somewhere to place the icon, and label it Voltage.

• Now right click (control click on a Mac) on Voltage, go to Representation, and choose
double precision floating point (it may already be chosen, so you’re just double check-
ing).

Select the Block Diagram to be the active window, go to the Functions palette
to set up the calls to the interface card.

• Find the Measurement I/O menu item, then the NI-DAQmx icon and “pin” it to the
window for safekeeping.

• Click once on the DAQmx Create Virtual Channel icon and then click on the Front
Panel to add it to your program. There is a popup menu that opens when you click
on the box at the bottom of the icon, choose Analog Out → Voltage.

3
• By putting the cursor near the left edge of the Create Virtual Channel icon, you
will see that there are many terminals that can used to control the interface and the
nature of each is given by a name. To get more info, choose the Show Context Help
item in the Help menu and hold the cursor over an icon. Connectors in bold type
must be “wired up”, that is, connected to some control or another icon in order to
receive the proper information. The others are optional or have a default setting.
• Hold the cursor over the Physical Channel connector and right-click on it once. A
pop-up menu appears, go to Create, and choose Control. You have now created a new
Front Panel control. The wonderful thing about this method of generting controls
is that LabVIEW knows exactly what data type to use. Otherwise, you’d have to
look it up in some manual. When you return to the Front Panel, there will be a new
object that controls the physical channel of the data acquisition card.
• Similarly, right click on the Output Terminal Configuration terminal, but this time
choose Create Constant instead. A box appears in the Block Diagram only, which
allows you to wire a value or setting from inside the program (not from the Front
Panel). On the right side of the constant is a little triangle, which opens a popup
menu after you click on it. Choose RSE from the item list (sometimes you want to
use differential signals, not referenced to ground, but not here, not now).
• Next, put a DAQmx Write icon next to the Create icon. The wire connections from
icon to icon are in a left-to-right flow design, so place the Write icon to the right of
the Create icon (you don’t have to, it just makes the wiring neater).
• Next put a Clear icon to the right of the Write icon.
• Now you are going to “wire” together terminals from various icons. The cursor should
change to a “wiring tool” when you hold the cursor over a terminal (it looks like a
spool). Click on the terminal once and move the cursor to the destination terminal,
click on it and the wire should connect (as long as the data types are compatible
from one terminal to the other, otherwise you’ll get a broken/bad wire). If you want
to bend the wire to make a neat path, click once and you can make a 90◦ turn.
• Wire the Task Out of the Create icon to the Task In of the Write icon. Do the same
for the Write to the Clear.
• Wire the error out to error in of the three icons.
• Finally, wire the Data terminal on the Write icon to the numeric control icon that
you created (this is “wired” to the front panel).

Your Block Diagram is now completely wired, we are ready to set values on
the front panel and run the program.

4
• Click once on the Front Panel.

• On the right side of the Physical Channel box you will find a popup menu that lists
the possible channels, in this case Dev1/ao0 and Dev1/ao1, choose channel 0.

• Set the voltage on you Front Panel control to a value between -10 and +10 volts.

• Connect a voltmeter to pin J22 (AO 0, or analog output channel 0) and pin J55 (AO
GND or analog ground) of the interfacing connector block.

Run your VI by clicking on the arrow button at the top of the Front Panel. If everything
is working correctly, the voltage you specified should be what is measured by the voltmeter.
Try a bunch of voltages to see how well the voltmeter readings agree with what you specify
in the VI. See if you can check the resolution. You can change the resolution by wiring
values to the Max and Min terminals on the Create Virtual Channel icon. The default
values are ±10V , but try higher resolutions by using another one of the prescribed values
(±5V , ± 1V , ± 0.2V ). LabVIEW won’t accept other values, the actual amplifier gain must
be preset in hardware.
Programming Basics
Now that we have basic control of an output connector pin voltage, try a few program-
ming operations. To make repeated Write commands, for example, to write a sequence
of voltages, you can call the Write operation repeatedly by surrounding it with a loop
structure. A more sophisticated way of doing this is to write a waveform (we’ll do that
later).

• Select the Block Diagram Panel and chose a While Loop from the Functions Palette.

• Click and drag a box around the Write icon, but not the others. Make it big enough
to add a few more icons to the interior of the While Loop box.

• Drag the Voltage icon inside the box and choose Remove Bad Wires from the Edit
menu (wires break easily).

• Rewire the Voltage to the data terminal.

• You will notice that the Run Arrow is broken. If you click on it, a window will open
with a list of your errors. The While Loop stop condition has not been set yet, right
click on the little stop sign that is in a corner of the While Loop, and create a Front
Panel control.

5
3 Simple Analog Input Program

Now put together a VI that measures an analog voltage. You will follow a set of similar
operations as in the first exercise, except use Read instead of Write, Numeric Indicator
instead of Control, etc.
Select the Front Panel as the active window, go to the Controls palette to set
up a numeric indicator.

• Put a Digital Indicator object in the Front Panel and label it Voltage.

• Make the Voltage indicator double precision.

Select the Block Diagram to be the active window, go to the Functions palette
to set up the calls to the interface card.

• Place a Create Virtual Channel icon in the Block Diagram.

• Choose the Analog Input → Voltage setting on the Create Virtual Channel and create
the Physical Channel Control by right clicking on the terminal, and create a Output
Configuration constant, set it to RSE.

• Choose the Read icon, Clear icon and wire them up as before, but this time wire the
output data from the read operation to the digital indicator.

• Choose Dev1/ai0 from the popup menu on the Physical Channel box (Front Panel).

Connect a voltage source to pin 68 (AI 0 or analog input channel 0) and pin 67 (AI
GND or analog input ground). For safety, insert a 1KΩ resistor between the power supply
and pin 68 to match the high impedance of the card and protect it from too much current
in case you attach a power supply to the wrong pin. Run the VI and the Voltage indicator
should read the voltage being supplied by the voltage source. Vary the voltage and see
how well the indicator tracks it.

4 Simple Digital Output Program

In this next VI, you are going to output True or False, 5 V or 0 V, respectively, on one
line of an 8 line digital channel (called P0.0 - P0.7 for port 0, bit 0 - 7). On the Front
Panel, you will need a Digital Control, usually in the form of a button or a toggle switch
chosen from the Boolean set of objects on the Controls palette. In the Block Diagram, put

6
a Create Virtual Channel icon in place and choose Digital Output from the popup menu.
Notice that the terminal labeled “lines” is in the same location as the “physical channel”
terminal when you did analog signals. This terminal changes depending on your choice
of task. As before, right click on the “lines” terminal and create a control. Put a Write
icon in place and choose Digital → Single Channel → Single Sample → Boolean from the
popup menu. Wire all task and error terminals and wire the digital control to the Write
icon’s terminal.
On the Front Panel, click on the popup menu in the Lines box and choose Dev1/port0/line0.
Connect a voltmeter to pin 52 (line 0 of port 0) and pin 53 (digital ground). Now run the
program several times with the state switch both High/True and Low/False to see if the
voltmeter reading follows.

5 Simple Digital Input Program

As the final basic VI, use a Digital Input to read whether the voltage between pins 52 and
53 is 0 V or 5 V. The only change on the Front Panel is that you should use a Round LED
indicator instead of a button or toggle switch control. The wiring of the Block Diagram
is very similar to the previous program. Connect a power source set at either 0 V or 5 V
through a 1kΩ resistor (for current protection) to the P0.0 and D GND terminals and see
if your VI works.

6 Square Wave Generator with Software Jitter

Now that you have mastered the basic input and output features of LabVIEW and the
data acquisition board in the computer, its time to turn to a program that requires a loop.
So the task this time is to use a For Loop together with the digital output features of
LabVIEW to generate a square wave with a low level of 0 V and a high level of 5 V. There
are many ways to do this. One is described here, but feel free to try a different algorithm
if you so desire.
The general idea is to use a For Loop to give the time cycle of the square wave. We
will use the For Loop Index to get an alternating high and low value and then we’ll use
this to set the digital output of the square wave.
Build the Block Diagram in the same way that you built the Digital Output except that
you don’t need the button. Select a For Loop (under Structures) to the Block Diagram,
surrounding the Write icon, leaving a little room inside the loop. Notice that there is a N
in the upper left corner of the loop. This sets the number of times the loop will repeat.

7
Drag over a Numeric Constant from the palette, wire it to the square around the N, and
set its value to something large such as 10000, or create a constant /control (right click on
the N). The square with the i in it represents the index that will increase by 1 with each
iteration.
You will try two methods to generate the input to the Digital Line Out that alternates
between low and high (that is, digital 0 and 1 or Boolean True or False). First, you will
use the index counter to generate a binary number in the form of a Boolean array and
then you select the least significant bit. Read that line again and make sure that you
understand what we are doing. So drag over a Number to Boolean Array (under Boolean
Functions) and Index Array (under Array) to your Block Diagram. Wire the index box
(with the “i” in it) to the input of the Number to Boolean Array, then wire that output
to the n-dimensional array input of the Index Array. Since you want to select the least
significant bit, drag over a Numeric Constant, set it to 0, and wire it to the index n-1
terminal of the Index Array. Now you can wire the element or subarray output of the
Index Array to the Line State input of the Digital Line Out.
The final step is to drag over a Wait(ms) (under Time & Dialog) to your Block Diagram
and create a control for the millisecond input. On the Front Panel, call it Half Period (ms).
Remember to save your VI.
Go to the Front Panel and set the inputs to the required values (set the Half Period
(ms) to something line 50 to get a 10 Hz square wave). Save your program, hook an
oscilloscope to the proper pins, and run your program.
The second way to generate an alternating T/F (or a 0 and 1) is to pass a boolean
(number) variable from one iteration of the loop to the next. This uses a “shift register”
in the loop structure (there is a similar object in the sequence structure which is called a
sequence local, but it functions the same). Right-click on the side-border of loop frame,
choose Add Shift Register, and two boxes appear in the frame, The box with an arrow
pointing up (on the right) is for output to the next iteration of the loop and the box
pointing down (on the left) is for input from the previous iteration. These boxes allow
you pass numbers from one iteration to the next, like a local variable. So, to make an
alternating T/F/T/F sequence, just put a Not operation (from the Boolean palette) inside
the loop, wire its output to the output shift register, and wire its input to the input shift
register. The Not’s output is the desired data.
Notice that the scope trace is not that stable, there is a lot of jitter in the waveform.
This is due to the computer’s operating system doing its usual business and causing delay
in the execution of LabVIEW code. The moral to the story is that computers are terrible
at doing things with precise timing or with some kind of synchronization. An external
clock or one that is onboard the data acquisition card should work better.

8
7 Acquire a Waveform

To illustrate how LabVIEW allows you to do more complicated tasks, you will figure out
how to get the computer to wait until the voltage on one of the digital lines goes high and
then to acquire a time series of measurements on one of the analog input channels. It’s
easy to have LabVIEW display the acquired waveform, so that will be part of the exercise.
The important new feature is a sequence structure. In the first frame of the sequence,
the program repeatedly measures the state of one of the digital input channels. As soon as
a high state is detected, it moves to the second frame of the sequence in which it acquires
the waveform. It is not unusual for values to be passed from one frame to another, so you
will do that to see how it is done.
To get the first frame going, wire up a Digital Input as before. Now drag over a While
Loop (under Structures) and surround the Read icon (leave some room around the While
Loop). Right click on the symbol in the lower right of the While Loop and change it to Stop
If True. Wire the data output of Read icon to both the Front Panel LED indicator (call
it Trigger) and Stop if True symbol. Drag over a Wait (ms) (under Time & Dialog) and a
Numeric Constant and wire them together so the While Loop iterates once per second.
Now drag a Stacked Sequence Structure (under Structures, it looks like a film strip)
to the Block Diagram, surrounding your entire program (all of the icons) with the frame.
Right click on this frame and select Add Frame After. You will now see at the top of
the frame numbers and arrows that allow you to step from one frame to another. With
the second frame in view, create an Analog Input like before, but now select the Single
Channel, Multiple Samples, 1D DBL option in the popup window on the bottom of the
Read icon. On the Front Panel, drag a Waveform Graph (under Graphs) and arrange the
items so everything is visible. On the Block Diagram, wire the Graph to the data output
off the Read icon. When everything on both frames looks correct, save your VI.
Connect a power supply to the proper pins for the digital input and a function generator
to the proper pins for the analog input. Set the Number of Points equal to 1000. With
these values you can acquire a 100 Hz waveform and see a number of cycles. You might
notice that there is no indication of a time rate. At this point we don’t have any control of
timing, the computer acquires the data at a fixed rate (can you figure out what that rate
is?). We will gain control of timing is Section 9.

8 Writing to File

Once you have acquired data on a computer, you generally need to save it to file, if
only for safekeeping. While analysis can be done in Labview, other programs such as

9
Kaleidagraph, Mathematica, Igor, Matlab, etc. are more flexible, interactive, ... better.
The most common format for transporting numerical data from one program to another is
ascii code. In this scheme, each digit in a number is represented by its ascii character. So
the number 256, for example, is not represented by the binary 10000000 but by the ascii
character for 2 (00110010 or 32 in hexadecimal) followed by the ascii for 5 (35 hex), followed
by the ascii for 6 (36 hex). Spaces, line feeds and carriage returns are all represented by
their ascii code numbers, too (20, 0A, and 0D hex, respectively). Writing these files used to
be cumbersome, but in the end it was easier to deal with files than hard copy of numbers.
Labview makes these tasks fairly simple, but it is always a good idea to keep the basic
structure of a data file in mind when you are troubleshooting a program.
We are used to seeing data represented in columns and rows, like in Kaleidagraph or
Matlab. It is useful to see how these data are actually stored in a file so that we can make
files that are easily read by programs like Kaleidagraph. Use the “Acquire a Waveform”
program that you wrote to collect a list of numbers over some time interval. The wire
going from your Read to the Graph can be passed to another frame using the Sequence
Local in a film strip. Right click on the frame and select Add Sequence Local. Wire the
data to box that forms on the frame.
Before we start writing to disk, it is a good idea to have the program ask the user if
they want to save to file. You don’t want the program make dozens of files when they are
not needed. Sometimes you want to save data, sometimes you don’t, so having a procedure
that asks or even a switch that disables data saving is useful. So, make a frame after
the Analog Input routine and put into it a Two Button Dialog from the Dialog & User
Interface menu in the Functions Palette. This will cause your program to stop everything
and wait for you to click on a button. You can put any message you want in the box and in
each button by right-clicking in the text inputs (pink wire) and choosing Create Constant.
Have fun with that. Now make a Case Structure (found in Structures) and wire the dialog
output to the little box on case border (it should have a question mark). This is like the
if-then-else structure of standard languages, but can also be extended to choices besides
True and False. Right now we only need the True frame, so set the box on the top of the
Case Structure to True (it should come up that way).
Now we are ready to write to disk. In the True frame of the Case Structure, put in
a Write to Spreadsheet File, which can be found in the File I/O menu of the Functions
Palette (ha ha, it has a picture of a floppy disk, remember those?). This VI has a lot of
inputs, but you only need one right now, the 1D Data input. In order to access the data
wire from the previous frame, create a Sequence Local by right-clicking on the frame of the
Sequence Structure, a little box should appear “inside” the frame. Go to the frame where
the data is acquired (frame 2?) and wire the data to the little Sequence Local box. Go
back to the frame with the Write to Spreadsheet routine and wire the Sequence Local to
the 1D data input. That should do it for starters.

10
(Note - In case you have a Waveform Data instead of numerical data, it is a little
more complicated. Waveforms have more than a list of numbers, they also has information
about the time intervals and the start time. You can see this by right-clicking on the
waveform wire and choosing Create Indicator. When you run your program, this indicator
will display the data array (a few numbers at a time), the time interval (1/rate), and the
start date. To extract data from this structure, use the Get Waveform Components from
the Waveform menu of the Functions Palette. The three outputs are t0 , dt, and y. The y
output is a 1D array of numbers and you can wire this into the Write to Spreadsheet VI. )
Collect data as before and write to file. Make sure you keep track of the location that
the file gets sent so that you can find it. It should end up in your Documents folder. Open
this with notepad and notice the structure. You can control the data format in the Write
to Spreadsheet VI with a format string. It uses formatting commands like in “C”, where
%3f (the default format) is a floating point number with 3 digits after the decimal point.
Try changing the f to an e and see what you get, put in a \n after the number, try \t
before the number.
The last task is to make another column of data that represents time. Make a For
Loop (Structures palette), and wire Number of Samples to the N-box. Put a Multiply VI
(Numeric menu) in the For Loop and wire the index box to one of its inputs. Wire the time
interval into the other Multiply input and the output is the time. Here is an important
step. When you wire the Multiply output, or any output, from a loop structure, you can
turn it into an array by choosing Enable Indexing at the box that forms on the loop wall.
Now we have to combine these arrays into a 2D array so that we can wire it into the 2D
array input of Write to Spreadsheet. Use the Build Array (Array palette) and “pull down”
on the bottom part of its edge to make two inputs (you can make multidimensional arrays
this way). You can always look at the file to see if you are getting what you want. To make
a file that Kaleidagraph can read into two, properly formed columns, set the Transpose
terminal to True on your Write to Spreadsheet command.

9 Time Control

To get control of timing that is better than using the computer’s jittery Wait routines, you
must use clocks that are on the I/O card or external to the computer. Like before, we will
start with a simple digital waveform.

• Put the following routines in a new Block Diagram, from left to right; DAQmx Create
Task, Timing, Write, Start Task, Is Task Done (find this in the Task Config/Ctrl sub-
palette), and Clear Task.
• On the Create Task, choose Digital Output in the pull-down menu and create a Front

11
Panel control by right-clicking on the Lines terminal.

• The Timing routine is complicated. Create the following Front Panel controls by right
clicking on Source, Rate, Sample Mode and Samples Per Channel. The pull-down
menu on the bottom should read Sample Clock.

• On the Write icon, choose from the pull-down menu Digital→Single Channel→Multiple
Samples→ 1D U8 (port format). Create a Front Panel control for the Data terminal.

• Wire up all of the Task and Error terminals.

• Surround the Is Task Done routine with a While Loop and wire the done? output to
the Stop icon. Make sure the stop is set to Stop If True by right-clicking on it.

• On the Front Panel, set the Lines to Dev1/port0. You might not see that option at
first, so right-click on the box, choose I/O Name Filtering and choose Port Only on
the right side menu list.

• On the Front Panel, set the Source to 100kHz Timebase. You might not see that
option at first, so right-click on the box, choose I/O Name Filtering and check the
box next to Include Advanced Terminals.

• On the Front Panel make some digital data 1, 0, 1, 0 by pulling down on the border
of the data control icon.

• On the Front Panel set the Sample Mode to Finite Samples.

• Set the Samples Per Channel to 10 and the Rate to 10. Actually, I haven’t figured
out what the rate does.

Vary the number of points and see what kind of output you get. Check by hooking the
oscilloscope to P0.0 and trigger on it (set the scope’s trigger mode to Normal so a single
trace of the scope is displayed, not written over). Other sources can be used for timing.
Try the 10MHz clock and an external clock, such as the function generator. The input is
PF0.0, pin 11. Also try continuous mode.

12

Vous aimerez peut-être aussi