Manual Practicas LabView
Manual Practicas LabView
Reler Lo thc Ni Tradenzarka and Logo Guidelines at ni com/trademar k s for more inkjrmation on Nauonal lnstrunients trademarks.
ARM, Keil, and jsVision are trademarks or registered of ARM ¡ .td or ita aubsidiaries.
LEGO, the LEGO logo. WF.I)O, and MINDSTORMS are trademarks of thc LEGO Group. 02013 The LEGO Group.
TETRIX by Pitaco isa trademark of Pitseo, Inc.02013
FIELDBUS 1:OUNl)A1iON and FOUNDA'1'ION' are trademarks of Ilie Fieldhus l"oundation.
EthcrCAT is a registered trademark of and liccnsed by I3eckhotT Automation Giubt 1.
CANopen Z ja a regiatered Community Trademark of CAN in Automation eV.
DeviceNct' aoci EtherNet/IP" are trademarks of ODVA.
Go!, SensorDAQ, and Vernier are registered trademarks of Vernier Software & 'I'echnology. Vernier Software & 'I'echnology and vernier.. core are trademarks or trade dresa.
Xilinx is the registered trademark of Xilinx. Inc.
Taptitc and Trilobular are registered trademarks of Rcscarch Engineering & Manufacturing Inc.
FireWire * is thc registered trademark of Apple Inc.
Linux is the restcred trademark of Linux 'l'orvalds in the U.S. and other countries.
Handle G raphicxa, MAllABa, Real-Time Workshopz, Simulink'. Stateflowv, and xl'C 'I'argctloxX are registered trademarks, and Targetl3ox" aoci 'larget 1 .anguage ('ompiler" are trademarks of The
MathWorks, Inc.
Tektronix 5 . Tek. and Tektronix, Enabling 'I'echnology are regiatered trademarks of 'tektronix. Inc.
Thc Bluetooth 5 word mark ix a regiatered trademark owned by the l3luetooth SIG, Inc.
The ExpressCard"' word mark and logos are owncd by PCMCIA and any use of auch marks by National Instrumcnts is under license.
The mark 1ahWindows ix u,sed under a license from Microsoft Corporation. Windows isa registered trademark of Microsoft Corporation in the United States and other countries.
Other product and company names mentioned herein are trademarks or tradc names of their respective companies.
Membera of thc National Instrumcnts Alliance Partner Program are huaincss entities independent from National tnstrumcnts and have no agency, partncrship, or joint-venture rctationship with National
lnstruments.
Patents
For patcnts covering National Instruments producta/technology, refer Lo the appropriate location: Help»Patents in your software, the parents. ext file on your media, or thc Nanonal Inst rumenis
Palen: Nozice at ni . com/pacents.
Worldwide Technical Support and Product Information
ni com
1
1
1
1
Contents
Student Guide
A. Ni Certification........................................................................................................................................................................................ Vil
B. Course Description ............................................................................................................................................................... . .................. Viii
C. What You Need to Get Started................................................................................................................................................................ix
D. Instaiiing the Course Software .............................................................................................................................. . ................................. X
1 E. Course Goals .......................................... . ............................................................... . ....................................................... . ........................ xi
Lesson 1
Navigating LabVIEW
Exercise1-1 Concept: Exploring a VI............................................................................................................................................1-2
1 Exercise 1-2 Concept: Locating Controis, Functions, and VIS ....................................................................................................... 1-7
Exercise 1-3 Concept: Using Tool Seiection .................................................................................................................................. 1_lo
Exercise1-4 Concept: Dataflow .................................................................................................................. . .................................. 1-18
Exercise 1-5 Simple AAP VI.......................................................................................................................................................... 1-23
Lesson 2
Troubieshooting and Debugging Vis
Exercise2-1 Concept: Debugging.................................................................................................................................................. 2-2
1
Lesson 3
Implementing a VI
Exercise3-1 Temperature Warnings VI ......................................................................................................................................... 3-2
Exercise3-2 Auto Match VI ......................................................................................................................................... ... ............... 3-10
1 Exercise 3-3 Concept: While Loops versus For Loops..................................................................................................................3-20
Exercise 3-4 Temperature Monitor VI—Average Temperature.....................................................................................................3-24
Exercise 3-5 Temperature Monitor VI—Piot Multiple Temperatures........................................................................................... 3-28
Exercise 3-6 Temperature Warnings VI—With Error Handling .................................................................................................... 3-33
1
Contenis nI.com 1 vi
Lesson 4
Developing Modular Applications
Exercise 4-1 Temperature Warnings VI- —As SubVI.....................................................................................................................4-2
Lesson 5
Creating and Leveraging Data Structures
Exercise 5-1 Concept: Manipulating Ari ays............................................................................................................. . ..................... 5-2
Exercise 5-2 Temperature Warnings VI- —Clusters........................................................................................................................5-13
Exercise 5-3 Temperature Wamings VI- —Type Definition ........................................................ . ................................................... 5-21
Lesson 6
Managing File and Hardware Resources
Exercise 6-1 Concept: Spreadsheet Exainple VI............................................................................................................................6-2
Exercise 6-2 Temperature Monitor VI—Logging Data..................................................................................................................6-6
Exercise 6-3 Concept: NI Measurement & Automation Explorer (MAX) ..................................................................................... 6-11
Exercise6-4 Using DAQmx ........................................................................................................................................................... 6-17
Exercise 6-5 Concept: GPIB Configuration with MAX ... . ............................................................................................................. 6-21
Exercise6-6 Concept: NI Devsim VI.............................................................................................................................................6-25
Lesson 7
Using Sequential and State Machine Algorithms
Exercise 7-1 Weather Station Project—State Machine VI ................................................. . ...................... . .................................... 7-2
Lesson 8
Solving Dataflow Challenges Using Variables
Exercise 8-1 Weather Station UI VI with Local Variables.............................................................................................................8-2
Student Guide
Thank you for purchasing the Lab VIEW Core ¡ course kit. You can begin developing an application soon after you complete the exercises in this manual. This exercise
manual and the accompanying course manual and software are used in the three-day, hands-on Lab VIE W Core 1 course.
You can apply the fuli purchase of this course kit toward the corresponding course registration fee if you register within 90 days of purchasing the kit. Visit
ni. com/ training for online course schedules, syllabi, training centers, and class registration.
A. Ni Certification
The Lab VIE W Core 1 course is part of a series of courses designed lo build your proficiency with LabVIEW and help you prepare for the NI Certified LabVIEW
Associate Developer exam. The following illustration shows the courses that are part of the LabVIEW training series. Refer lo ni . com/training for more
1 information about NI Certification.
LabVIEW Training Courses
LabVIEW Performance
Cartfltcatlons
Other Coursee
LabVIEW FPGA
LabVIEW Real-Timo 1
Coro coursos aro atrongly rocommonctod lo realizo maxlmum productivlty gama whenuslng LabVIEW.
1
Student Guide ni.com 1 viii
B. Course Description
The LabVIEWCore ¡ course teaches you programming conccpts. techniques, features, Vis, and functions you can use to create test and measurement, data acquisition,
instrument control, datalogging, measurement analysis, and rcport generation applications. This course assumes that you are familiar with Windows and that you have
experience writing algorithms in the form of flowcharts or block diagrams. The course and cxercise manuals are divided into lcssons, described as foliows.
• An introduction that describes the purpose of the lesson and what you will lcarn
• A summary quiz that tests and reinforces important concepts and skills taught in ihe lesson
• Sorne Iessons includc optional and challenge exercise scctions or a set of additional exercises to complete if time permits
Note For course and exercise manual updates and corrcctions, rcfer to ni . com/inf o and enter thc lnfo Code corel.
Severa] exercises use one of the foliowing National lnstruments hardware products:
• A plug-in multtfunction data acquisition (DAQ) device connected to a BNC.2120 containing a temperature sensor, function generator, and LEDs
If you do not have this hardware, you still can complete the exercises. Alternate instructions are provided for cornpleting the exercises without hardware.You also can
substitute other hardware for those previously mentioned. For example, you can use a GPIB instrumcnt in place of the NI Instrument Simulator, or another National
Instrument.s DAQ device connected to a signal source, such as a function generator.
1
Suggested Reading
The suggested reading materials ensure that all students have a minimum knowledge of key theories and concepts related to the Lab VIEW Core / course. To get the
most out of this course, complete all the suggested reading material.
1 To access each of the fohiowing suggested reading materials, refer to ni. coin/ mf o and enter the Info Code that corresponds to each topic:
Course Materials
Before you begin this course, ensure you have alt the folhowing items:
E A serial cable
1
1
1
Student Guide ni.com 1x
AGPlBcable
Directory Description
Exercises Folder for saving Vis created during the course and for conipleting certain course exercises; also includes sub VIs necessary
for sorne exercises and zip file (NI Instrument Simulator. zip) containing the LabVIEW instrument driver for the
NI instrument Simulator
1. lnsert thc course CD in your computer. The LabV1EW Core 1 Course Setup dialog box appears.
la Note Folder names in angie brackets, such as <Exercises>, refer to folders on the root directory of your computer.
1
E. Course Goals
This course prepares you to do the foliowing:
1 • Understand front paneis, block diagrams, icons, and connector panes
• Use the programming structures and data types that exist in LabVIEW
• Every built-in VI, function, or object; refer to the LabVIEW Help for more information about LabVIEW features not described in this course
• Developing a complete application for any student in the ciass; refer to the NI Example Finder, availabie by selecting Help»Find Examples, for example VIs
you can use and incorporate into Vis you create
1
e
e
e
e
e
e
e
e
e
1
e
e
e
e 1
e Navigating LabVIEW
1
e Complete the exercises in this lesson to reinforce the concepta you learn m Lesson 1 of LabVIEW Core 1.
e Exercises
e Exercise 1-1 Concept: Exploring a VI
e Exercise 1-2 Concept: Locating Controis, Functions, and Vis
Exercise 1-3 Concept: Using Tool Selection
e Exercise 1-4 Concept: Dataflow
Exercise 1-5 Simple AA? VI
e
1
e
e
e
e
e
e LabVIEW Coro 1 Exercises © National Instruments 1 1-1
e
e
e
e
e
e
e
e
e
e
Lesson 1 Navigatirig LabVIEW ni.com 1-2
Goal
As a class, identify the parts of an existing VI.
Description
You received a VI from an employee thai takes the seconds until a plane arrives at an airpori and converts the time into a combination of hours/minutcs/seconds.
You musi evaluate this VIto see if it works as expected and can display the remaining time until the plane arrives.
3. Qn the front panel, identify the foliowing items. How many can you find of each item?
t Controls j.
El Indicators
O Run button
o ¡con
o Connectorpane
4. Press <Ctrl-T> to view the froni panel and block diagram at thc same time or select Window»TiIe Up and Down or Window»TiIe Left and Right.
Tip To switch between the front panel window and thc block diagram without tiling the windows, press <Ctrl-E>.
1
e
e
1
1
1
e 5. On the block diagram, identify the foliowing items. How many can you find of
e Cl Indicators
•
D Constants
Q Free labeis
6. Use the Context Help Lo learn more about the items on the block diagram.
O Place your cursor over each of the different color wires to see which data type they represent.
O The Context Help window content changes to show information about the object that your mouse is over.
•
7. Get detailed help for the Quotient & Remainder function.
O Place your cursor over the Quotient & Remainder function. Read the Context Help window and click the Detailed Help link to launch the LabVJEWHeIp
and learn more about this function.
1
1
1
S. Refer to Figures 1-1 and 1-2 to verify that you identified ah items correctly.
a --.. Warning
e
Minutes
3
lvlessage
Seconds
e
e
e
e
e
1
1
1 Figure 1-2. Block Diagram Items
Seconda
60 seconda in a minute;
quotient is the number of minutes,
rernainder i, the remaining number of aeconds
1 Minutes
e M
M. - Hours
". -. . . . . . . . . . . . . . . . . . . . .
3,600 seconda in en hour;
n.
quotient is the number of hours, Warning
rernarnder is the remaining nurnber of seconda
Me ssage
e
Lesson 1 Navigating LabVIEW ni.com 1 1-6
9. Test the Seconds Breakdown VI using the values given in Table 1-1.
E For cach input, compare the given outputs to thc outputs listed in Tahle 1-1. Ifthc VI works correctly, they should match.
Description
1. Open a blank LabVIEW project.
O E Click the Create Project button in the LabVIEW Getting Started window and then click Blank Project.
E Click Finish.
E Right-click My Computer in the Project Explorer window and select New»VI from the shortcut menu.
3. Select View»Controls Palette from the menu of the VI front panel window.
Cl Select the foliowing palettes to add them to the Controis palette and click the OK button. Do not deselect any palettes.
- Silver
- Signal Processing
O Notice that the three palettes you just selected now appear in the Controis window.
Use palettes to locate controls and functions when you want to explore the options available to you or when you are not sure of the name of the control or function
you need.
O Click String Control (Silver) in the search results and drag it to the front panel window to place the object.
6. Open the block diagram and right-click anywhere on the block diagram to display the Fu nctions palette.
O Click the pin in the upper Ieft-hand comer to keep thc palette open.
() Tlp You can customize the Functions palette just like you customized the Controls palette.
- In the search results. double-click Cosme «Trigonometric Functions» to display the function on the palette.
- Douhle-click File I/O in the search results to display the File I/O palette.
- Drag the Write To Text File fund ion from the palette to the block diagram.
Use the Quick Drop feature when you know the name of the function or VI you want to use.
El Type Bundle By Naxne and double-click Bundle By Name in the search results. The cursor changes to a hand with the Bundle By Name function.
• Double-click the function in the search results and place the function on the block diagram.
1 9. Practice using the global search feature.
Cl Type Random in the Search bar in the upper right hand comer of the block diagram.
1J Note As you type, the global search automatically looks for matches in the LabVlEWJIeIp and LabVIEW palettes. It also searches for online material
related to your query.
o Hover the mouse over the first result in the Palette section, Random Number (0-1). You now see the foliowing three options:
- Drop—Allows you to place this function immediately on the block diagram
El Right-click the Add function and notice that Numeric palette is available from the shortcut menu.
O Practice placing funcuons from the Numeric palette on the block diagram.
11. (Jose the VI and LabVIEW project. You do not need save the files.
1
Lesson 1 Navigating LabVtEW ni.com 1 1-10
Description
During this exercise, you complete tasks in a partially built front panel and block diagram. These tasks give you experience using the automatic tool selection.
1. Openusing Temperature.lvproj iflthe<Exercises>\LabVIEW Core 1\Using Temperaturedirectory.
2. Open Using Temperature.vi from the Project Explorer window.
3. Select View»Tools Palette from the menu to display the Tools window.
Tip Press <Shift> and right-cick the front panel to open the Tools palette temporarily.
By default, LabVIEW selects tools for you based on the context of your cursor. You can disable automatic tool setection by clicking the Automatic Tool
Selection button in the Tools window.
Figure 1-3 shows an example of the front panel as it appears after your modifications. In steps 4 through 8 you increase the size of the waveform chart, rename the
numeric control, change the value of the numeric control, and move the knob.
e :1
Delay Mutipher
0.8 1
0. ).(
.:
0.4-. \ 4.6 24-:
1.8
0 100
02
Time
1 • Stop
1
Lessor 1 Navigaling LabVIEW ni.com 1 1-12
E Move the cursor to ihe right edge of the Chart waveform chart unul you see the resizing nodes appear around the chart.
E Move the cursor to thc middle right resizing node until thc cursor changes to a douhle arrow, as shown in Figure 1-4.
E Drag the repositioning node until the waveform chart is the size you want.
E Double-click the word Chart. LabVIEW highlights the word and automatically selects the Labeling tool in the Tools window.
• Complete the entry by c!icking outside thc control label or clicking the Enter Tcxt button on the toolbar.
E
E Notice that LabVIEW automatically reuurnsto the Positioningtool in the Tools window. The Positioningtool is the defaulttool. IfLabVIEW does not switch
back to thc Positioning tool, click thc Automatic Tool Selection button in the Tools window to enable automatic tool selection.
6. Rename the Numerie control to Number of Measurements using the Labeling tool.
S E Double click the word Numeric.
O EnterthetextNumber of Measurements.
Ó
O Complete the entry by clicking outside the control or clicking the Enter Text button on the toolbar.
7. Change the value of the Number of Measurements control to 100 using the Labeing tool.
•
E Move the cursor to the interior of the Number of Measurements control.
O When the cursor changes to the Labeling tool ¡con, click the mouse button.
o Complete the entry by pressing the <Enter> key on the numeric keypad, clicking the Enter Text button on the toolbar, or clicking outside the control.
8. Change the value of the Delay Multiplier knob using the Operating tool.
O When the cursor changes to the Operating tool ¡con, press the mouse button and drag to the value you want.
•
•
9. Change the color of the Delay Multiplier knob using the Coloring tool.
E Click the background square in the Set Color button and select a color from the color picker.
O When the cursor changes to a paintbrush, click the Delay Multiplier knob.
O Click the Automatic Tool Selection button again to turn on automatic tool selection.
1
Lesson 1 Navigating LabVIEW ni.com 1 1-14
10. Try changing the value of objects, resizing objects, and renaming objects until you are comfortable with using thcsc tools.
Figure 1-5 shows an example of the block diagram as it appears after your modifications. Steps 12 through 13 instruct you on how lo update the block diagram
to move the Number of Measurements terminal and wire [he terminal to the count terminal of [he For Loop.
Number cf Meurernent
LI
Delay Muttiplier
Wait tJntiI Next ms Multipie
Sta Button
12. Move the Number of Measurements terminal using [he Positioning tool.
E Move [he cursor over the terminal until thc cursor changes to an arrow.
E Click and drag the terminal to [he new location as shown in Figure 1-5.
13. Wire the Number of Measurements terminal [o [he coun[ terminal of the For Loop using the Wiring [ool.
U Move the cursor to the right of [he terminal, sopping when [he cursor changes [o a wiring spool.
1
e
O Move the cursor to the count (N) terminal of the For Loop.
14. Try moving other objects, deleting wires and rewiring them, and wiring objects and wires together until you are comfortable with using these tools.
Tip You can also select specific objects to clean up, such as wires or individual nodes. <Shift>-click to select multiple objects and then click the Clean Up
Diagram button. LabVIEW cleans up only the objects that you select and not the entire block diagram. Configure how LabVIEW cleans up objects by
selecting Tools»Options from the menu, clicking the Block Diagram category, and changing the options in the Block Diagram Cleanup section.
e
Lesson 1 Navigating LabVIEW ni.com 1 1-16
Note Boolean controls and indicators have Boolean tcxt labeis in addition to their control labels. Boolean text labcls change depending on the value of the
control or indicator. The label for the control or indicator does not change depcnding on the value of the control or indicator.
El Right-click the Stop Button terminal and sclect Properties from the shortcut menu. Set thc properties as shown in Figure 1-6.
Figure 1-6. Changing the Boolean Text for the Stop Control
Caption
' Visible L Visible
-Stop Outton
•Eoabied
Hezght Width
Ditabied
Disabied & gsayed
Off
Off teot
End 4
1 Control label—This text identifies the terminal of the Boolean control for programming purposes. This text does not appear on the front panel unless you select
Visible.
2 Boolean text—This text appears only on the front panel, and by default, appears in the center of the Boolean control.
O Right-click the Stop Bntton terminal and select Find Control from the shortcut menu. Notice the control label is Stop Button and the button text is End.
Tip You can also double-click the Stop Button terminal to find thc button control on the front panel.
1
•
1 The time required to execute this VI is equivalent to Number of Measurements times Delay Multiplier. When the VI is finished executing, the Temperature
Chart displays the data.
18. Close the VI and click the Don't Save - AH button. You do not need to save the VI.
•
• End of Exercise 1-3
••
••
••
••
•
• LabVIEW Core 1 Exercises © Nationa! lnstruments 1.17
••
••
•1
••
••
••
Lesson 1 Navigatng LabVIEW ni.com 1 1-18
la Note Nodes are objects on the block diagram thai have inputs and/or outputs and perform operations when a VI runs.
1. Which node executes first? Is there any dependency between the File Dialog function and the Simulate Signal Express VI?
3. Because a wire connecis the File Dialog function to ihe TDMS File Viewer VI, can the TDMS File Viewer VI cxecute before the TDMS Close function?
4. How many nodcs must execute before the TDMS Write function can execute?
File Dialog
1 LJ-.
TDMSOpen TDMS Write TOMS Close TDMS - File Viewer.vi
ente nr repiace
SinCWaVC 1
10.1 t-tz
Amplutude 1.0 F
1
5nlateSnal Sine Wav
1000 Snmplm per Second Sine Wave
6. In Figure 1-8, which Express VI executes Iast?
Figure 1 -8. Block Diaqram—Simple Acquire, Analyze, and Present Example
Aethnto Me
Ahet Meas'
Wavefcrm Graph
EZ
Wt Te
1 Meswn,t
e
e
1
e
e
e LnbVIEW Core 1 Exercises © Nahonal Iristrunieras 1 1-19
1
e
e
e
e
e
e
e
Lesson 1 NavIgaling LabVIEW ni.corfl 1 1-20
7. lo Figure 1-9 an error wire connecis the Express Vis. Which Express VI executes last?
Gph
--
[m5i
To
1
8. In Figure 1-10, which Tone Measurements Express VI executes !ast?
1 •
Li
1
Se wid UntIor+ Fvequecy
Frequency 5aIi
1 SrneWave with Naes
iILered Ampktude
No¡-,e Amplit d
1L.....r:
Tone
Me.suremu
t_,..i 2
Fittered Frequency
e Dataflow Discussion—Answers
1. Either the File Dialog function or the Simulate Signal Express VI can execute first. There is no data dependency between the two nodes so either of them can
execute first or they can execute simultaneously.
3. No. The TDMS File Viewer VI cannot execute before the TDMS Close function because the yellow error wire connecting the TDMS Close function and the
TDMS File Viewer VI forces data dependency. Remember, the data to alI inputs of a node must be available before a node can execute. Therefore, the
TDMS File Viewer VI must receive data from both the green Boolean wire and the yellow error wire before the VI can execute.
4. Three nodes must execute before the TDMS Write function can execute: File Dialog, TDMS Open, and Simulate Signal. The TDMS Write function also depends
on the Simulated Signal string constant, but that input is instantaneous.
5. Yes. A we!l-designed block diagram typical!y fiows from left to right. This makes it easier to see the flow of data on the block diagram. Fiowever, do not assume
left-to-right or top-to-bottom execution when no data dependency exists.
1
Lesson 1 Navigating LabVIEW ni.com 1 1-22
6. Either the Statistics Express VI or the Write to Measurement File Express VI executes last or they execute in parallel. The DAQ Assistant Exprcss VI cannot
execute last because both the Statistics Express VI and the Write lo Measurement File Express VI are dependent on the data signal from the output of the DAQ
Assistant Express VI.
ir— Note In LabVIEW, the flow of data, rather than the sequential order of commands, determines the execution order of block diagram elements. Therefore,
it is possible to have simultaneous operations.
7. The Write to Measurement File Express VI executes Iast. It has a data dcpendency on hoth the DAQ Assistant Express VI and the Statistics Express VI.
8. Either one of the Tone Measurement Exprcss VIs can execute last. Even though the Tone Measurements 2 Express VI has an extra dependency on the Filter
Express VI, the Filter Express VI might execute before the Tone Measurements 1 Express VI allowing the Tone Measurements 2 Express VI to execute before
the Tone Measurements 1 Express VI. Although it seems as if the Tone Measurements 1 Express VI would execute first, without an explicit data dependency
there is no way to know definitely it would execute first.
Scenario
You need to acquire a sine wave for 0.1 seconds, determine and display the average value, log the data, and display the sine wave on a graph.
Design
The input for this problem is an analog channel of sine wave data. The outputs include a graph of the sine data, a file that logs the data, and an indicator that displays
the average data value.
Flowchart
Tbe flowchart in Figure 1-11 ilustrates the data flow for this design.
Figure 1-11. Simple AAP VI Flowchart
DAQ Assistant The DAQ Assistant acquires data through a data acquisition device.
lnstrument I/O Assistant The Instrument I/O Assistant acquires instrument control data, usually frorn a GPIB or serial interface.
Simulate Signal The Simulate Signal Express VI generates simulated data, such as a sine wave.
1
2. Analyze: Circie the Express VI that is best suited to determining the average value of the acquired data.
1
Tone Measurements The Tone Measurements Express VI finds the frequency and amplitude of a single tone.
Amplitude and Leve¡ Measurements The Amplitude and Level Measuremenis Express VI performs voltage measurements on a signal.
Filter The Filter Express VI processes a signal through filters and windows.
1
Lesson 1 Nav;gating LabVIEW ni.com 1 1-26
3. Present: Circie the Express Vis and/or indicators that are best suited to displaying thc data on a graph and logging ihe data Lo file.
DAQ Assistant Thc DAQ Assistant acquircs data through a data acquisition device.
rswj
Write Lo Mcasurement Pile The Write lo Measurement File Express VI writes a file in LVM or TDM file formal.
EZ
Build Text Thc Build TexI Express Vi creates texI, usually for displaying on the front panel window or cxporting to a
w 1c
file or instrument.
Waveform Graph The waveform graph displays onc or more plots of evenly sampled measurements.
1. Acquire: Use the DAQ Assistant to acquire the sine wave from the data acquisition device.
2. Analyze: Use the Statistics Express Vito determine the average value of the sine wave. Because this signal is cyclical, you could also use the Cycle Average
option in the Amplitude and Level Measuremenis Express Vito determine the average value of the sine wave.
3. Present: Use the Write to Measurement File Express VIto log the data and use the Waveform Graph to display the data on the front panel window.
Implementation
Ó 1. Prepare your hardware to generate a sine wave. lf you are not using hardware, skip to step 2.
El Find the BNC-2120 and visually confirm that it is connected to the DAQ device in your computer.
El Using a BNC cable, connect the Analog 1n Channel 1 to the Sine Function Generator, as shown in Figure 1-12.
O Set the Frequency Selection switch and the Frequency Adjust knob to their lowest levels.
1
lo
1
2. Open LabVIEW.
3. Create a blank project. Save the project as Simple AAP. lvproj in the <Exercises>\LabVIEW Core l\Simple AAP directory.
1
4. Add a new VI to the project from the Project Explorer window and save the VI as Simple kA.p . vi in the <Exerci ses> \ LabVIEW Core 1 \ Simple AAP
directory.
In steps 5 through 6 you will build a front panel similar to the one in Figure 1-13.
Average Valuc
5. Add a waveform graph to the front panel window (o display the acquired dala.
El Type Waveform in (he text box and double-click Waveform Graph (Silver) in (he search resul(s lis(.
6. Add a numeric indicaor (o the front panel window to display thc average value.
• Type Nuxneric Indicator in (he text box and double-click Numeric Indicator (Silver) in the search results lisi.
1
Lesson 1 Navigating LabVIEW ni.com 1 1-30
DAQAssistit
dala
ir
- Note The terminals corresponding (o thc front panel window objects appear on the block diagram.
8. Acquire a sine wave for 0.1 seconds by following the instructions in Table 1-2. If you have hardware installed, follow (he instructions in the Hardware Installed
column to acquire the data using the DAQ Assistant. If you do not have hardware installed, follow the instructions in the No Hardware Installed column to
e simulate (he acquisirion using the Simulate Signal Express VI.
1 1. Press <Ctrl-Space> to open (he Quick Drop dialog box. 1. Press <Ctrl-Space> to open the Quick Drop dialog box.
e 2. Type DAQ Assist in the text box and double-click DAQ Assistant in the
search results list.
2. Type Simulate Signal in the text box and double-click Simulate
Signal in the search resulta list.
e 3. Place the DAQ Assistant on (he block diagram. 3. Place (he Simulate Signal Express VI on the block diagram.
e 4. Wait for the DAQ Assistant dialog box to open. 4. Wait for the Simulate Signal dialog box to open.
6. Select ail (analog input channel 1) for the physical channel. 6. Set the signal frequency to 100.
7. Click the Finish button. 7. In the Timing section, set the Samples per second (Hz) (o 1000.
S. In the Timing Settings section, select N Samples as the Acquisition 8. In the Timing section, deselect Automatic for the Number of samples.
Mode.
9. In (he Timing Settings section enter 100 in Samples To Read. 9. In the Timing section, set (he Number of samples to 100.
10. Enter 1000 in Rate (Hz). 10. In the Timing section, selectthe Simulate acquisition timing option.
11. Click the OK button. 11. Click the OK button.
e Tip Reading 100 samples at a rate of 1,000 Hz retrieves 0.1 seconds worth of data.
1
1
9. Use the Statistic Express VI to determine the average value of the data acquired.
E Type statistics in the text box and doublc-click Statisties INI_ExpressFull.lvlibI in thc search results usE.
E Place the Statistics Express VI on the block diagram to the right of the DAQ Assistant (or Simulate Signal Express VI).
U Type write to rneasurement in the texi box and double-click Write to Measurement File in the search results list.
• Place the Write to Measurement File Express VI on the block diagram bclow the Statistics Express VI.
• Wait for the Write lo Measurement File Express VI dialog box to open.
• Leave all configuration settings in the Write to Measurement File dialog box as defauli.
Note Future exercises do not detail the directions for finding specific functions or controls in the palettes. Use Ouick Drop, the paletEe search feature, or
the global search to locate functions and controls.
11. Wire the data from the DAO Assistant (or Simulate Signal Exprcss VI) to the Statistic.s Express Vi.
E Place the mouse cursor over the data output of the DAQ Assistant (or the Sine output of the Simulate Signal Express VI) at the location where the cursor
changes to thc Wiring tool.
E Place the mouse cursor over the Signais input of the Statistics Express VI and click the mouse button lo end the wire.
1
e
1
e
• 12. Wire the data to the graph indicator.
. 0 Place the mouse cursor over the data output wire of the DAQ Assistant (or the Sine output of the Simulate Signal Express VI) at the location where the cursor
changes to the Wiring tool.
• o Place the mouse cursor over the Waveform Graph indicator and click the mouse button to end the wire.
1 13. Wire the Arithmetic Mean output of the Statistics Express Vito the Average Value numeric indicator.
O Place the mouse cursor over the Arithmetic Mean output of the Statistics Express VI at the location where the cursor changes to the Wiring tool.
E Place the mouse cursor over the Average Value numeric indicator and click the mouse button to end the wire.
14. Wire the data output to the Signais input of the Write Measurement File Express Vi.
El Place the mouse cursor over the data output wire of the DAQ Assistant (or the Sine output of the Simulate Signal Express VI) at the location where Ihe cursor
changes to the Wiring tool.
o Place the mouse cursor over the Signais input of the Write Measurement File Express VI and click the mouse button to end the wire.
Note Future exercises do not detail the directions for wiring between objects.
1
Lesson 1 Navigating LabVIEW nicom 1 1-34
Test
1. Switch to the front panel window of the VI.
• Right-click the waveform graph and select X Scale»Autoscale X to remove the checkmark and disable autoscaling.
• Right-click the waveform graph and select Visible Items»X Scale to enable the X scale.
• Use the labeling tool to change the last number on the Time scale of the waveform graph to . 1.
3. SavetheVI.
The graph indicator should display a sine wave and the Average Value indicator should display a number around zero. If the VI does not run as expected, review the
implementation steps.
e
e
1
Troubleshooting and Debugging Vis
Mi-
e
e Complete the exercise in this lesson to reinforce the concepts you Icaro in Lesson 2 of LabVIEW Core 1.
e Exercises
e Exercise 2.1 Concept: Debugging
e
e
e
e
e
e
e
e
e
e
e LabVIEW Cora 1 Exercses © National Instrumonts 1 2-1
e
e
e
e
e
e
e
1
e
e
e
a
Lesson 2 Troubieshooting and Debugging Vis ru.com 1 2-2
Description
The Vis in this exercise check thc validity of a triangle and then calculate the arca. For a triangle to be valid, afl three sides must have a iength that is greater than
zero. The subVl in this exercise uses Heron's formula to caicuiate the arca of a triangle. You can use this method when you know the iengths of all three sides of a
triangie.
1-leron's formula
A = .Js(s—a)(s—h)(s—c)
where
a+b+c
2
The default values, which you will use to dcbug ancl test this Vi, are Side A = 6, Side B = 8, Side C = 10. Therefore the correct values are as foliows:
= 6+8+ 10 =
2 -
A = J12x6x4x2 = 24
You might want to reter to this caicuiation as you debug ihe VI.
Complete the l'oilowing sections to identify and fix ediL-time and run-time issues. Use single-stepping and execution highhighting to step through the Vi. Use
breakpoints and probes to determine if the caicuhations are corrcct and figure out where an error originaLes.
e
1
e
Edit-Time Errors
1 Locate and correct errors that prevent the VI from running.
1 0 Open Arca and Validity oía Triangle VI from the Project Expiorer
W1vdow
File EdIt Vlew Preject Ope,ile 1bolS
•e ptAp*ManFt 1 t ATEIJ
O
e
e
El Notice the Run button on the toolbar appears broken, indicating that the VI is broken and cannot run.
e
1
Lesson 2 Troubleshooiing and Debuggiog Vis rii.com 1 2-4
2. Display and examine the block diagram of Arca and Validity of a Triangle VI shown in Figure 2-2.
This VI takes input values for each of the three sides of a triangie, pas.ses the values into a subVi that determines thc arca, and checks that the values entered are
valid for a triangle.
Figure 2-2. Area and Validity of a Triangle VI Block Diagram
de A(cm)
1-
Areo of Triangle Al
Ateo of Triongle A
.*l
Sd.B(cm)
t,I1I VolidTriongle?
Click the broken Run button to display ihe Error iist window, which lists ah the errors.
El Sehect an error description in the Error Iist window. The Details section describes the error and in sorne cases recomrnends how to correct thc error.
Click the HeIp button to display a topic in the LabVIEW Help that describes the error in detail and includes step-by-step instructions for correcting the error
El Click the Show Error button or double-click the error description to highlight the arca on the block diagram that contains the error.
Note Doubie-click the Arca of a Triangle subVi to open it. In the Arca of Triangle VI, notice that the formula for calcuiating the arca of a triangle requires
the sum of the sides be divided by 2. Right-chick the y input of the Divide function and select Create»Constant and entcr a value of 2.
Run-Time Errors
identify and correct crrors that cause the Vito behave unexpcctedly and return incorrcct responses.
1. Test theVi.
E Use the dcfault values for each side. These values are valid measurements for a triangle.
1 E Run the VI.
E Notice that although the numbers you entered are valid, [he LED is not illuminated and [he Area of a Triangle indicator displays NaN.
O Click thc lIighlight Execution button on the toolbar to enable execution highiighting.
• O Click the Retain Wire Values button on the toolbar so you can see the last value passed on a wire.
•e
1
Lesson 2 Troubleshooting and Debuggtng Vis n.com 1 2-6
D Right-click each of the inputs to thc Compound Arithmetic Function and select Probe. This displays the Probe Watch Window.
fl Notice that one of the wire values is Falso as shown in Figure 2-3.
Figure 2-3. Probe Wires
II :. 'ro l3 15ptAppl,catiorilont-
Side A (cm)
5r23
ide e(cm) -••
PrabeWatchWindgw
tJ x1 jCPbDply
PL iL_... ..__.. .
Sido C (cm) Check that s¡de ieregi] Aseo and Volidity of o Tnangie.vi (Debug,
are greater tiran lees. FALSE
11 Probe True
121 Probe True
VoiidTriangie?
.................
' Cleani Up Wire
Creete Wire Branch
Driete Wire iirench
Visible. Itenir
Intrrt
Dooiean Palette
Cerote
Custorn Probe p
Beeokpotnt )
Debug.Ivoroj/Mv Cornpute - . . 1
e
E Because you are checking to see that all three sides of the triangle have positive !engths, either the input value is invalid or the logic is incorrect. The input
values were afl positive numbers, so that means the logic is incorrect.
Notice that the node returning a value of Falas is a Less than Zero? function, but this section of code should be checking to see if the value is greater
than zero.
E Right-click the Less than Zero? function and select Replace»Comparison Palette»Greater than Zero?.
o Display the front panel. Notice that the Valid Triangle? LED is illuminated, but the Area of Triangle indicator is still returning NaN.
El The area of the triangle is calculated in the subVl, so you must continue debugging in the Área of a Triangle subVl.
e o Click the Step Into button to start single-stepping through the VI. Execution highlighting shows the flow of data on the block diagram from one node to
another. Nodes b!ink to indicate they are ready to execute.
n
4 a
E Click the Step Over button after each node to step through the entire block diagram. Each time you click the Step Over button, the current node executes
and pauses at the next node.
e
e O When you get to the subV!, click the Step Into button to opon the block diagram of the Área of Triangle subVl. The subV! is paused.
1
1
e
1
Leseon 2 Troubeshooting and Debugging Vis ni.com 1 2-8
O Right-click the output of the Square Root function and select Brcakpoint»Set Breakpoint as shown in Figure 2-4.
Figure 2-4. Set Breakpoint
deA(cm)
S
de8(cm)
SdeC(crn)
@ - . . .............. . ........ .. .. L.__.
The breakpoint stops the VI after the Square Root riode executes and before the value is ouipui to the Area of Triangle indicator.
6. Click the red pause button to resume the execution of the VI.
El The VI continues executing until thc breakpoint and then pauses again.
O Move the cursor lo hover over the input wire of the Square Root function. You should see a tip strip with aval ue of -576. You cannot take the square root of
a negative number, which is why the Arca of Triangle indicator returns NaN.
Tip If you cannot see the tip strip, you can click the wire to open the Probe Watch window to see the value.
O Hover over other wires or use the Probe Watch window lo examine other intermediate values.
El Notice that the value on the (S-B) wire is also a negative number. If you look more closely, you notice that the inputs for the subtract function are reversed.
Tip Press <Ctrl> and click one of the inputs lo switch them. Whcn you press <Ctrl> and hover over an input, you see the cursor change.
1
8. Save the VI.
O Check the intermediate values as the VI runs or hover over the wires after it pauses at the breakpoint and verify that the values returned are correct. The square
root function should return a value of 24.
O Turn off execution highlighting in the Area of Triangle VI and the Area and Validity of a Triangle VI.
Test
1. Test the Aren and Validity of a Triangle VI using the val ues for Side A, Side B, and Side C in Table 2-1. For each set of test values, the VI should return the value
shown in the Area column.
24 30 18 216
12 12 12 62.35
15 20 25 150
1
Implementing a VI
3
Complete the exercises in this lesson to reinforce the concepts you learn in Lesson 3 of LabVIEW Core 1.
Exercises
Exercise 3-1 Temperature Warnings VI
Exercise 3-2 Auto Match VI
Exercise 3-3 Concept: While Loops versus For Loops
Exercise 3-4 Temperature Monitor VI—Average Temperature
Exercise 3-5 Temperature Monitor VI—Plot Multiple Temperatures
Scenario
You must create a portion of a larger project. The lead developer gives you the inputs of the VI, the algorithm, and the expected outputs. Your task is to create and
document a VI based on the given design.
Design
Use the following flowchart and input/output lisi to create a VI that displays temperature warnings, This VI is part of the temperature weather station project studied
throughout the course.
Flowchart
1 The flowchart in Figure 3-1 illustrates the data flow for this design.
1
Max Temp?
WamngText
Heatstroke 1 W
L: j~
arninamng
gT".
Warning _____
%TemP_
No
M in
e Ves
1xt.No ) No
Type
Numeric control
1_ Name
String indicator Warning Text 'Fhrcc potential values: lleatstroke Warning, No Warning, and Frceze Warning
Implementation
Complete the foliowing steps to create a front panel similar to Figure 3-2. The user enters the current temperature, maximum temperature, and minimum temperature
Then, the front panel displays the warning string and thc warning Boolean LED.
1. Create a new LabVIEW Project and add a new Vito the project.
O Select File»New from the LabVIEW menu and then select Project»Empty Project from the Create New tree.
O Save the new projectas <Exercises>\LabVIEW Core 1\Weather Warnings\Weather Warnings. lvproj.
O Right-click My Computer in the Project Explorer window and select New»Vi to open a blank VI.
O Savethe VI asTemperature Warnings .vi in the <Exercises>\LabVIEW Core 1\Weather warnings directory.
2. Create the front panel shown in Figure 3-2.
Current Temperature
o Warning?
Max Temperature
Warning Text
Min Temperature í -
1 Numeric Control—Right-click and select Representation»DBL to confirm that this numeric control is double precision.
2 Create copies of the Current Temperature numeric control by holding down the <Ctrl> key and dragging the Current Temperature control.
1 3 String indicator—Resize the indicator to accommodate longer strings.
4 Round LEO
Tip You can use this VI for Fahrenheit, Keivin, or any other temperature scale, as long as alt inputs to [he Vi use the same scale. Therefore, it is not necessary
[o add scate units to the labeis.
1
Lesson 3 Implemenflng a V ncorn 1 36
JHeatWoke W.tningj 1
Cw,erl Temperalur,
L Seect )
M.xTemprture
--- J
1
GreitirOrEqual?
1 \
--
No W tntng
Not Equa Warning?
MinTimpru(urt
1etOrEqual?
1 - L -t
1 Greater or Equal?—Compares input values and retums a TRUE value if Current Temperature is greater than or equal to Max Temperature.
2 Less or Equal?—Compares input values and returns a TRUE value if Current Temperature is less than or equal to Min Temperature.
3 String Constant—Create string constants br Heatstroke Warning, Freeze Warning, and No Warning.
4 Select—Returrts the Heatstroke warning string if Current Temperature is greater than or equal to Max Temperature; otherwise returns the No warning
string.
5 Select—Returns the Freeze warning strtng if Current Temperature is less than or equal fo Min Temperature; otherwise returns the No Warning Strirtg.
6 Not Equal?—Returns a TRUE value to the Warning? indicator ib the value Warning Text is something other than No Warriing.
4. Modify [he description and tip associa[ed with thc Warning Text indica[or to change [he content shown in [he Context Help window.
Select Window»Show Front Panel to open [he front panel of thc VI.
e
e
O Right-click the Warning Text indicator and seleci Description and Tip.
o EnterDisplays text string ind±cating Meatstroke Warning, Freeze Warning, or No Warning depending on weather
1 conditions in the Warning Text" Description text box.
Negk Note Text you enter in the "Warning Text" Tip text box displays in a tip strip. Tip strips are briefdescriptions that appear when you move thc cursor over
a front panel objcct while a VI runs.
Notice that the contents of the Context HeIp vindow changed to match the text you typed in the description fleld of thc Description and Tip dtalog box.
e
e
e
e
e
e
Lesson 3 ImpIemerting a VI ni.com 1 3-8
5. Document the block diagram using owncd labeis and free labeis.
Add owned labeis and free labels on thc diagram as shown in Figure 3-4.
Owned labeis are owned by a specific object. You can hide owned labeis and move them, but you cannot copy or deicte thcrn indepcndently of their owners.
Curent Temperture
[_
(i LHeatstroken1
Select
:::::::::»
1e Or Equel? Warning Teot
Mm Temperature
1 Owned Iabels—Right-click a function and select Visible ltems»Label from the shortcut menu to display the owned label for that function.
2 Move Iabel—Click the owned label of the Greater or Equal? function with the Positioning tool and move it beneath the function.
3 Move funclion—Use the positioning tool to move the function. Notice thaI the owned labei moves with the function.
4 Owned Iabel—Right-click the wire and select Visible ltems»Label from me shortcut menu. Move me label with the Positioning tool.
5 Free label—Double-clicka blank area of the block diagram and use the Labeling 1001 to create comments for the code. -
6. Document Ehe VI Properties, giving a general description of the VI, a list of inputs and outputs, your name, and the date the VI was creatcd. 'Fo acccss the
VI Properties dialog box. sclect FiIe»VI Properties and select Documentation from the Category pul]-down menu.
e Table 3-2 shows the expected Warning Text string and Warning? Boolean value for each set of input values.
Note The temperature range in the table is only an example of temperatures selected to indicate freeze or heatstroke warnings.
25 30 lO No warning False
What happens if you input a maximum temperature value that is less than ihe minimum temperature value? What would you expect to happen? You learn to
handle issues like this one in Exercise 3-6.
Scenario
Create a VI that continuously generales random numbers between O and 1000 until it generates a number that matches a number selected by the user. Determine how
many random numbers the VI generated before generating the matching number.
Design
Use the foliowing flowchart and input/output list to create the VI for this exercise.
e
e
e
e
e
e
e
e
e
e
e
e
e Flowchart
The flowchart in Figure 3-5 ilustrates the data flow for this ci esign.
e Figure 3-5. Auto Match Flowchart
e
e
e Generate a
e Random Number
Between O and 1
No
e
e Muttiply by 1000
e
e
e Round to Neareal D i splay Value
Vas
1 Addlto
Iteration
oN~
IntegerValue
e lo User
>
Terminal
e
e mr
ol Iteratlona
e
e
e
e
e LabVIEW Core 1 Euercises © Nalional Instrumenls 1 3-11
e
e
e
e
e
e
e
e
e
e
e
Lesson 3 Implementing a VI n.com 1 3-12
Numeric control Number to Match Double-precision, floating-point between 0 and 1000, coerce to nearest whole
number, default value = 50
1 m piementation
1. Create a blank project and save itasAuto Match. lvproj in the <Exercises>LabVIEW Core 1\Auto Match directory.
2. Create a new VI in the project and save it as Auto Match. vi in the same directory as the project.
e
e
3. Build the front panel shown in Figure 3-6.
e 5
1
Number of Iteratiora
o
1 Set the default value of the Number to Match control to 50—Enter 50 in the Number to Match control and then nght-click the control and select Data
Operatlons»Make Current Value Default.
2 Set Number of lterations ¡ndicator to output a slgned, long integer—Right-cllck the indicator and select Reprssentatlon»132.
4. Set the properties for the Number to Match control so that the data type is a 32-bit unsigned integer, the data range is from 0 to 1000, the increment value is 1,
and the digits of precision is 0.
ii Right-click the Number to Match control and select Representation»U32 from the shortcut menu.
e
Lesson 3 Implementing a VI ni.com 1 3-14
E Right-click [he Number to Match control and select Data Entry from [he shortcut menu. Set thc properties on thc Data Entry and Display Format [abs as
shown in Figure 3-7.
Appearance Dita Typ e Dala Intry Display Formal Documentahon Appearance Doto iype Dala lntsy DtOpIeyFOmiit Uunntatio,i
Current0bject
Nmc
E ......Numenc
Type Digita PrecisionTypi
Use DefauItL,rnits
O D g Os otpr,clalon
Minimum Responsetovituaoutsidelimit Scientific
E O Coerce Automotic fOrmatt,fl9 .,. -ltdo trailing zocos
Stnotation
Euponcrt in mi!tipie ratO
PMamum
Decimal tE Use minimum field width
Coerce ( HexdecimsI
Octsl
Binary Padw4$aípankft
[ncrement
1 1 Coerce ti> ne.rest
Poqr lize
00000
5. Set the data type of the Current Number indicator to an unsigned, 32-bit integer and set the digits of precision for the Current Number output to O.
O Right-click the Current Number indicator and setect Representation»U32 from the shortcut menu.
O Right-click the Current Number indicator and select Display Format. Set the properties as shown in Figure 3-8.
Figure 3-8. Current Number Iridicator Display Format Properties
1
DisplayFormet
1-
Numenc
P i '.'sth en left
..
1
Lesson 3 ImpIemerting a VI ni.com 1 3-16
Numberto Match
fncrement Number of iteratiorta
-- ............
iI
~,
4
Tip Coercion dots can cause a Vito use more mcmory and mercase its run time, so try fo keep data types consistent in the Vis you create.
e
E Right-click the wire coming from the Round To Nearest function and select Insert»Numcric PaIette»Conversion»To Unsigned Long Integer as shown m
Figure 3-10. This inserts the To Unsigned Long integer function on the wire.
Figure 3 10. Insertirtg the To Unsigned Long Integer Function on a Wire
-
Clean Up Wire
Create Wire Dranch
Delete Wire tranch
Visible (teme
Numeric Plette
O Crente
Probe
.Add
To Extended ... To Doubte Pr... To Single Pre.., To Fixed-Poiree
Converrion
El mil KP
NumeeicCo,. Fixnt
- tejumber To .,. Oootem Arre... Boolem Tcs (... To Time Sto...
I I jJ
DBL Numen., - - - , , , \lath Consta...
e
Lesson 3 Impementing a VI ni.com 1 3-18
8. Notice that converting [he output from the Round To Nearcst function rcmoves al¡ the cocrcion dots on [he block diagrarn, as shown in Figure 3-11.
Figure 3-11. Completed Auto Match VI
Current Number
rurnbetoMatch
Increment Number of Iterations
10. Right-click [he Current Number indicator and select Advanced»Synchronous Display.
Note If synchronous display is cnabled, then every time [he block diagram sends a value [o the Current Number indicator, [he block diagram stops
exccuting until [he front panel has updated thc value of [he indica[or. In [his exercise, you enable [he synchronous display, so you can see the Current Number
indicator gel upda[ed repea[edly on [he front panel. Typically, thc synchronous display is disabled [o increase execution speed since you usually do not need
[o see every single upda[ed value of an indicator on [he fron[ panel.
Test
1. Change thc number in [he Number [o Match control loa number tha[ is in [he data range, which is 0 [o 1000 with an incremen[ of 1.
3. Change the Number (o Match value and run [he VI again. Currcnt Number updatesa[every iteration of the loop because it is inside [he loop. Number of ltcrations
updates upon completion because it is ou[side the loop.
1
1
e
O On the block diagram toolbar, click the Highlight Execution button Lo enable execution highlighting.
O Change the Number to Match value to a number that is out of the data range, O
1 0 Notice LabVIEW coerces the out-of-range value to the nearest value in the data range you specified in step 4 of the Implementation section.
1
• 8. Close the VI.
••
e
••
•• LabVIEW Core 1 Exercises © National Instruments 1 3-19
•e
••
1
1
••
Lesson 3 lmplementing a VI ni.corn 1 3-20
Description
For the foliowing scenarios, decide whether to use a While Loop or a For Loop.
Scenano 1
Acquire pressure data in a loop that executes once per second for one minute.
1. If you use a While Loop, what is the condition that you need to stop the loop?
2. If you use a For Loop, how many iterations does the loop need to run?
Scenario 2
Acquire pressure data until the pressure is greater than or equal to 1400 psi.
1. If you use a While Loop, what is the condition that you need to stop the loop?
2. If you use a For Loop, how many iterations does the loop need to run?
e
1
Ó
Scenario 3
Acquire pressure and temperature data until both values are stable for two minutes.
1. Ifyou use a While Loop, what is the condition that you need to stop the loop? '
2. If you use a For Loop, how many iterations does the loop need to run? fl.0 /
Scenario 4
Output a voltage ramp starting at zero, increasing incrementally by 0.5 V every second, until the output voltage is equal to 5 V.
1. If you use a While Loop, what is the condition that you need to stop the loop?
2. If you use a For Loop, how many iterations does the loop need to run?
e
LabVIEW Core 1 Exerctses © National Instruments 1 3-21
Leason 3 Implementing a VI nicom 1 3-22
Answers
Scenario 1
Acquire pressure data every second for one minute.
Scenario 2
Acquire pressure data until the pressure is 1400 psi.
1. While Loop: Pressure = 1400 psi
2. For Loop: unknown
3. A While Loop. Although you can add a conditional terminal to a For Loop, you still need to wire a value to the count terminal. Without more information, you
do not know the appropriate value to wire to the count terminal.
e
Ó
Scenario 3
Acquire pressure and temperature data until both values are stable for two minutes.
1. While Loop: [(Last Temperature = Previous Temperature) for 2 minutes or more] and [(Last Pressure = Previous Pressure) for 2 minutes or more]
2. For Loop: unknown
3. A While Loop. Although you can add a conditional terminal to a For Loop, you still need to wire a value to the count terminal. Without more information, you
do not know the appropriate value to wire to the count terminal.
Scenario 4
Output a voltage ramp starting at zero, increasing incrementally by 0.5 V every second, until the output voltage is equal to 5 V.
Scenario
The Temperature Monitor VI acquires and displays temperature. Modify the Vito average the last five temperature measurements and display the running average
on the waveform chart.
Design
Figure 3-12 and Figure 3-13 show the Temperature Monitor Vi front panel and block diagram.
Figure 3-12. Tomperature Monitor Vi Front Panel
Temperature
Temperature Hotery
• Stop
30-
L)
25-
Cn
15- 3
o loe
Time (seconci)
e
Thermorneter (Demo).vi
Temperature Histoy
1
Wit Until Next ms Multi le
millisecond multiple
Stop8utton
IW
To modify this VI, you need to retain the temperature values from the previous four iterations of the While Loop and average the values. To accomplish this, you
modify this VI as foliows:
• Use a shift register with additional elements to retain data from the previous four iterations.
• Initialize the shift register with a reading from the simulated thermometer.
Implementation
1. Test the VI.
Run the VI. Notice the variation in the simulated temperature reading.
Compound Arithmetic
--..,-. ... - DMde/Temperature History
L.J StButton
T .. mi
1 Shift Registers—Stacked shift registers collect multiple temperature readings. Right-click the border of the While Loop and select Add Shift Register. Drag
the lower resizing handle of the shift register to display four shift registers.
2 Create a copy of the Thermometer (Demo) VI—Press <CtrI> while dragging the subVl outside the While Loop to create a copy. The Thermometer (Demo) VI
returns one temperature measurement and initializes the Ieft shift registers before the loop starts.
3 Compound Arithmetic—Retums the sum of the current temperature and the four previous temperature readings. Resize the function to have five terminais.
4 Divide—Returns the average of the Iast five temperature readings.
Note You can create stacked shift register terminais on thc left side of a loop to remember multiple previous iterations and carry those values to the next
iterations. This technique is useful for averaging data points. Stacked shift registers can occur only on the left side of the loop because the right terminal
transfers the data generated from only the current iteration to the next iteration.
During each iteration of the While Loop, the Thermometer (Demo) VI takes one temperature measurement. The VI adds this value to the last four measurements
stored in the left terminais of the shift register. The VI divides the result by five to find ihe average of the five measurements—the current measurement plus the
previous four. The VI displays the average on the waveform chart. Notice that the VI initializes the shift register with a temperature measurement.
1 2. Stop the VI by clicking the Stop button on the front panel.
1
Lesson 3 Implementing a VI ni.com 1 3-28
Scenario
Modify the VI from Exercise 3-4 to p101 both the current temperature and the running average on the same chart. In addition, allow the user to examine a portion of
the plot while the data is being acquired.
Design
Figure 3-15 shows the front panel for the existing Temperature Monitor VI and Figure 3-16 shows the block diagram.
Figure 3-15. Temperature Monitor VI Front Panel
'y y Temperature
Temperture Hitoiy
a stop 35-
; 30-
25H
20-,
15-
100
Time (5econd)
To allow the user to examine a portion of the piot while the data is being acquirecl, display the scale legend and the graph palette for the waveform chart. Also, expand
the legend to show additional plois.
Ó To modify the block diagram in Figure 3-16, you must modify the chart terminal to accept multiple pieces of data. Use a Bundle function to combine the average
temperature and the current temperature into a cluster to pass to the Temperature History terminal.
Compound Arithmetic
Divide Temperature Hitory
-
+
Wait
mifliseiond multiple
w
Implementation
Ji
1 Bundle—Passes the current temperature and average temperatura lo the Temperature History chart.
3. Modify thc froni panel so that it resembles Figure 3-18.
Figure 3-18. Temperature Monitor VI Front Panel—Plotting Multiple Temperatures
Current Terripertuie fl
Temperature Hitory
a Stop 1
25-
2O-
ls_ji
o ioo
1 Time (econd)
.4-
Ti me (second-)
'Degrees Celsius
1 Show both plots ir the piot egend—Use the positioning tool to resize the piot legend to show two objects. Double-click the label to edit the plot names. The order
of the plots usted in the piot legend is the same as the order of the items wired to the Bundle function on the block diagrarn.
1 2 Change the piot type of Current Temperature—Use the Operating tool to select the plot in the plot legend. Click the plot ¡con, select Common Plots from the
menu, and choose the plot you want.
3 Display Graph Palette—Right-click the Temperature History chart and select Visible ltemsi'Graph Palette.
4 Display Scale Legend—Right-click the Temperature History chart and select Visible items»Scale Legend.
1
L.aaon 3 ImpI.menting a VI ni.com 1 3-32
Test
1. Run the VI. Use the toots in the scale legend and the graph palette to examine the data as it generates.
Scenario
You created a VI where a user inputs a temperature, a maximum temperature, and a minimum temperature. A warning string generates depending on the relationship
of the given inputs. However, a situation could occur that causes the VIto work incorrectly. For example, the user could enter a maximum temperature that is less
than the minimum temperature. Modify the VI to generate a different string to alert the user to the error: Upper Limit < Lower Liinit. Set the Warning?
indicator to TRUE to indicate the error.
Design
Modify the flowchart created for the original Temperature Warnings Vi as shown in Figure 3-19.
1 Output
CurrentTemp No Current TempNo No Warning
Minp and
Vi
FALSE
Ves Ves
1
1
Output
Heatroke
1 1 Ou
Freeze Warning 1
Create Error
1 Warning and and 1
1 TRUE TRUE 1
Output
Upper Limit
<Lower Limit
1 andTRUE
1
L.esson 3 Implementing a VI ni.com 1 3-34
The original block diagram for the Temperature Warnings VI appears in Figure 3-20. You must add a Case structurc to the 1mperaturc Warnings Vito execute the
code if the maximum tcmperature is less than or equal to thc minirnum temperature. Otherwise, the VI does not execute the code. Instead, the VI gencrates a new
string and the Warning? indicator is set to TRUE.
itstroke Warningj
Current Teperatuvt Select
............
Max Temperature
1 Greater Or Equ.al?
Not EquaI 7- Warning?
r
» No Warning >>
INc wLnngi
Wdrningj
LesOrEquai? WarrungTt
Implementation
2. Open Temperature Warnings.'i from the Project Explorer window. You created the Temperature Warnings VI in Exercise 3-1.
3. Place an Error In and Error Out cluster on the front panel as shown in Figure 3-21.
Figuro 3-21. Temperature Warnings VI Front Panel with Error Clusters
CurrentTemperature
Warning?
Mex Tempereture
Warning Text
Min Temperature oWaming -
Error In
stebs code
.
:T]
lource
4. Open the block diagram and create space to add the Case structure.
D Select the Current Temperature, Max Temperature, Min Temperature, and Error In control terminais.
Ç) Tip To select more than one item press the <Shift> key while you select the items.
Zi While t.he terminais are still selected, use ihe left arrow key on the keyboard to move the controis to the left.
Tip Press and hoid the <Shift> key to move the objects in five pixel increments.
1
LabVIEW Core 1 Exercises © National Instruments 1 3-35
1
Lesean 3 Inlemenftng a VI ni.com 1 3-36
Tip Press the <CtrI> key and use the Positioning tool to drag out a region of the size you want to insert.
o Select the Warning?, Warning Text, and Error Out indicator terminals.
O Align the terminais by clicking the Align Objects»Left Edges button in the LabVEEW toolbar.
0 While the terminais are still selected, use the right arrow key on the keyboard to move the indicators to the right.
e
5. Modify the block diagram similar to that shown in Figure 3-22, Figure 3-23, an(l Figure 3-24. This VI is part of the temperature weathcr station project.
Figure 3-22. Temperature Warnings VI Block Diagram—No Error, False Case
c
ex' 81W
1 1
Herrr;okeWarnin9}
Greater Gr Equal?
Max tern1terat, NotEqual? Wam.ng?
l
q 1
Eq WarrnngTea
Min iemperature
Error lo Eçcr
1 Less?_Compares the Max Temperature and Min Temperature. Make sure the Less? function js outside the Case structure.
2 Case Structure—Do not include the Current Temperature, Max Temperature, Min Temperature, Error In, Warning?, Warning Text, or Error Out terminais
in the Case structure because these controis and indicators are used by both cases.
3 Set True and False cases—With the True case visible, right-click the border of the Case structure and select Make this Case False.
4 Case Structure—Wiro the Error In terminal to the selector terminal to create No Error and Error cases. By default, the Case structure has True and False cases.
These cases change to Error and No Error cases only after you wire Error In to the selector terminal.
CurrentTemperuture
MaTemperature Warning?
WarnwgText
¡Upperlimit<lowerLimtt
Min Temperature
1 *
1 True case-11` the Max Temperature is set lower than the Min Temperature, the True case executes. Click the case selector label to choose the True case.
2 True Constant—When the True case executes, the Warning? LED illuminates.
3 String Constant—lf the Max Temperature is set lowerthan the Min Temperature, the warning Upper Limit < Lower LirniL displays on the front panel
Enter the text in the String Constant.
1
1
1
1
6. Create the Error case in the outer Case structure so this VI can be used as a subVl.
1
1
1
1
1
1
1
7. Save the VI.
1
1
1
LabVIEW Core 1 Exercuses © MaSonal Instrumexxts j 3-39
1
1
1
1
.
Lesson 3 Implementing a VI ni.com 1 3-40
Test
1. Switch to the front panel of the VI.
2. Resize the Warning Text indicator to a length lo accommodate the new string.
3. Test the VI by cntcring values from Table 3-4 in the Current Temperature, Max Temperature, and Min Temperature controls and running the VI for each
set of data.
Table 3-4 shows the expected Warning Text and Warning? Boolean value for each set of data.
25 30 10 No Warning False
10 30 10 Freeze warning True
25 20 30 upper Limit < Lower Limit True
4. Test the Error case. To use this VI as a subVl, the VI must be able to handlc an error coming into the VI. Test the Error case to make sure that this VI can output
the error information it receives.
E On the front panel, use the Operating taol to click the status Boolean indicator inside the Error In cluster so that the indicator turns red and enter 7 in the
code control.
E Run the VI. The error information you entered passes through the Error case in the VI and is output in the Error Out cluster.
O Display the block diagram, select the No Error case, highlight execution, and then run the VI again to see the error pass through the Error case
E On the front panel, right-click the border of the Error Out cluster and scicct Explain Error to display information about the error that was rcturned.
e
e
e
e
e
e
e
e
e
e
e
e
Lesson 4 Developing Modular Applicatsons ni.com 1 4-2
Scenario
You have created a VI that determines a warning string based on the inputs given. Create an ¡con and a connector pane so that you can use this VI as a subVl.
Design
The Temperature Warnings Vi contains the foliowing inputs and outputs:
Inputs Outputs
Min Temperature -
Use the standard connector pane terminal pattcrn to assure room for future cxpansion.
Implementation
1. Openweather warnings.lvproj in the <Exercises>\LabVIEW Core 1\Weather warriingsdirectory.
2. Open Temperature Warnings VI from thc Project Explorer window. You created the Temperature Warnings VI in Exercise 3-1 and modified it in
Exercise 3-6.
3. Connect the inputs and outputs to the connector pane as shown in Figure 4-1.
TemperreWaiinq.vi
R Max Temperature
Min Ternperature
Error In
Waming Text
Error Out
1 Con nector Pane—Located in the upper right comer of the VI window, the connector pane displays potential terminais for the Vi. The connector pane shown hero
displays the standard pattem of terminais. Vou can right-click the connector pene and seiect Patterns to choose dlfferent terminal designs.
2 Connections—The Context HeIp window displays the connections for the VI.
1 • Using the Wiring tool, click the upper-left terminal of the connector pane.
• Click the connector pane terminal below the Current Temperature terminal.
• Continuc wiring the connector pane until alI controls and indicators are wired, and the Context Help window matches that shown in Figure 4-1.
4. Create an con.
Cl Use the tools in the Icon Editor dialog box to create an ¡con. Make the ¡con as simple oras complex as you want, however, it should be representative of the
function of the Vi. Figure 4-2 shows a simple example of an ¡con for Ihis VI.
Fije Operatsons 1,
Fije Structurrs c>
CT rF;
Fije Types
Hardwate
Image Manupulmuon
LVOOP Clres mcd Objects
M.tlnematucs
Product Nimes Identrfiers ql x
SL
Product Namesldenbfier 41_
Prngrammirrq
u,u,.,mi Pr o ce ss in &a °.9
SignaN 1 RO XO
SttChrts
IIH k Ip
Tip De uble-click thc Selection tool to select the existing graphic. Press the <Delete> key to delete the graphiL. Ihen, double-click the rectangle tool to
automati cally create a border for the ¡con.
Tip De uble-click thc Text tool to modify fonts. You can select Small Fonts to choose fonts smaller than 9 points in size.
1
Tip Select the Glyphs tab and filter the glyphs by the keyword thermometer, then draga thermometer glyph onto your ¡con. And then filter by the
keyword warning and drag a warning glyph onto your ¡con.
1
5. Click OK when you are finished to close the Icon Editor dialog box.
1 Test
Test the Temperature Warnings VI as a SubVI.
1. Add files to the Weather Warnings LabVIEW project as shown in Figure 4-3.
Figure 4-3. Weather Warnings Project
1
1J Wethr Wemings.lvproj * - Project EepL Li
r 51
1ten, Fila
Sh.red Ales
SubV! Tester.vi
TensperaturaWtnsngs.vi
ti Dtendeies
L BdSpecificatcne
Add an auto-populating folder to the Weather Warnings LabVIEW project. LabVIEW continuously monitors auto-populating folders and updates the folder
in the Project Explorer window according to changes made in the project and on disk.
- Right-click My Computer in the Weather Warnings project and select Add»Folder (Auto-populating) from the shortcut menu.
- Navigate to <Exercises>\LabVIEW Core 1 \Shared Fi les and click the Select Folder buuon.
The Sbared Files folder contains shared files that you use in this and future exercises.
- Navigate to <Exercises>\LabVIEW Core 1\Weather Warnings\Test VIs\SubVI Tester vi and click Add File.
2. Open the SubVl Tester VI and complete the block diagram as shown in Figure 4-4.
Figure 4-4. Test SubVI Block Diagram
Wait (MI)
- Th,tmo,neter
WanangTet
E)-
Max Ttn,peaataxe
- AL-
- Tmpe,atu: Wainng;vi
e C
Mix 7emWature
1"
siop=- ...--
El:
1 Thermometer (Demo)—Locate this VI in the Shared Files folder in the Project Explorer window, drag it lo the block diagram and wire it as shown. This VI
generales sample temperature values.
2 Temperature Warnings—Because of the modifications you made to Temperature Warnings VI, you can use it as a subVl. Wire the Temperature Warnings VI
using the connections you just created.
3 Enum Con stant—Right-click the Units (O:Celsius) input of the Thermometer (Demo) VI and select Create»Constant. Creating the enum constant from the
Thermometer (Domo) VI automatically populates the enum with the appropriate choices. Use the Operating tool lo select Celsius.
4 Or—Use the Or function lo stop the VI if the user clicks the Stop button or if the Temperature Warnings VI outputs an error in the Error Out cluster.
3. On the froni panel of the SubVI Tester Vi, entcr test values for the Max Temperature and Min Temperature controls.
The Thermometer (Demo) VI generales sample temperatures, which thc SubVl Tester VI displays on the Thermomcter indicator.
e
e
e
e
e
e
e
e
1
e
e 5. Notice how the string in the Warning Text indicator change as the temperature rises and falis.
6. After you have finished testing, save and close the VI.
1
e End of Exercise 4-1
e
e
e
e
e
e
e
e
e
e
e
e
e
e
e
© National Instruments 1
e LSbV!EW Core 1 Exercuses
e
e
1
e
e
e
e
e
e
e
e
e
e
e
e
e
e
e
e
e
e
e
e
e
e
Creating and Leveraging Data Structures
5
e Complete the exercises in this Iesson to reinforce the concepts you ¡cara in Lesson 5 of LabVIEW Core 1.
Exercises
e Exercise 5-1 Concept: Manipulaling Arrays
e Exercise 5-2 Temperature Warnings VI—Clusters
1
e
e
e
e
e
e
e LebV!EW Core 1 Exercises © Nallonal Instruments 1 5-1
e
e
e
1
e
e
e
1
e
e
Lesson 5 Creating and Leveraging Data Structures ni.com 1 5-2
Description
You are given a VI and asked to enhance it for a variety of purposes. The front panel of this VI is built. You complete che block diagram to practice several different
techniques lo manipulate arrays.
Implementation
1. Open Martipulating Arrays. lvproj in the <Exercises>\LabVIEW Core 1\Manipulating Arrays directory.
2. Open Array Manipulation VI from the Project Explorer window. The front panel, shown in Figure 5-1, is already built for you.
e
e
e
e
e
e
1
e
e
e
e Figure 5-1. Array Manipulation VI Front Panel
Cøratt,ate Channd Add/bct Channeli Wect a Cnra& Wavfom, Data .AJI Data Chann& Wa'afrna Sba:
Conctnated Data
e o-
e
e
O 200 4O 610 800 1000 120 1400 1600 1800 0000
Date Points
e
e •tp
e
e
e
e
e
e
e
LabVIEW Core O Exercises
(Ç) Natotal lOSirunlentS 1 5-3
e
e
e
e
e
e
e
e
e
Lesson 5 Creating anci Levoraging Data Siructures ni.com 1 5-4
3. Open the block diagram and complete cach of thc cases that correspond to the tabs on the front panel as shown in Figures 5-2 through 5-8.
Figure 5-2. Array Manipulation VI—Concatenate Channeis Case
lgJ-,
Gene,te 1000
date potnt3 lor
oach o,.oy
1 Build Array—Expand this node to accept two inputs, and then right-click and select Concatenate inputs from the shortcut menu.
2 Wire the sine wave and square wave outputs to the Build Array function to create a 1 D array with both waveforms.
4. Switch to the front panel and test the Concatenate Channels case.
Run the VI and notice that the sine wave is concatenated with a squarc wave.
6. Switch to the block diagram and sclect the Add/Subtract Channcls case.
1
e
e
e
1
1
7. Complete the Add/Subtract Channeis case as shown in Figure 5-3 and Figure 5-4.
Gener.te 1000
data pointfor
e .ch 4mv
e 1 Subtract?—Wire this to the case selector terminal so that the correct case executes when you cllck the Subtract? button on the 1 ront panel.
2 Case Structure—Place a Subtract function in the True case, so that the VI subtracts the elements of the array when the Subtract? button on the 1 ront panel is
p ressed .
e
e
LSbVIEW Core 1 Exercises © National tnstruments 1 5-5
1
1
e
e
.esson 5 Creating and Leveraging Data Structures ni.com 1 5-6
Note
:1
When me value of the Subtract? Boolean control is False, the array elements are added.
This case demonstrates polymorphic functionality by adding and subtracting elcmcnts of the array.
8. Switch to the front panel and test the Add/Subtract Channeis case.
LI Click thc Subtract? hution and observe the behavior of subtracting the square wave from thc sine wave.
9. Stop theVI.
10. Switch to the block diagram and select the Select a Channel case.
1
Generate 1000
Sin Channel of Data A""
each 4~
1 1
ONI
1 BulId Array—Combines the sine and square waves into one 21) array.
2 Index Array—Extracts row O or 1 1 rom the 21) array. The output from this function is a 1 D array and Is the waveform you select with the Select Channel control.
1 The waveform is displayed on the Single Channel of Data Waveform Graph and the Single Channel of Data Array indicator.
3 Select Channel—Wire lo the row input of the Index Array function.
4 Array Size—Because you are using a 1 D array, this function outputs a scalar value.
Note i'he Selecta Channel case uses a property node lo change the color of the graph piot. You learn about Property Nodes Lab VIEW Core 2.
12. Switch to the front panel and test the Select a Channel case.
• Switch between Channel O and Channel 1 and notice the different values shown in tite Single Channel of Data Array indicator.
14. Switch to the block diagram and selcct the Waveform Data case.
15. Complete the Waveform Data case block diagram as shown in Figure 5-6.
The waveform datatype is a speciai kind of cluster that contains additionai timing information about the waveform.
-- Figure 5-6. Array Manipulation VI—Waveform Data
ne
tnemte 1000 1
date porntsfo
e.ch w.y
Add—Uses the value 1 rom the Offset control to modify the value of the waveform in the waveform datatype. Notice the value from the Offset control must be
coerced lo be used with the waveforrn datatype.
Note Polymorphism is the ability of Vis and functions to automaticaliy adapt to accept input data of different data types, including arrays, scalars, and
waveforms. Vis and functions are polymoprhic to varying degrees.
16. Switch lo the front panel and test the Waveform Data case.
O Change the value of thc Offset control and notice the square wave move on the Waveform Data chart.
1
1
17. Stop the VI.
18. Switch to the block diagram and select the Al! Data Channel case.
19. Complete the Al! Data Channel case as shown in Figure 5-7.
Ginerate lotol
dita pomOs for
each orisy
e
1 Add—Modify the same data in one array by adding the value of the Channel 1 Offset to each element of the array. -
2 For Loop—Extracts each element of the array using auto indexing so that the Add functlon in the For Loop can add the scalar value.
3 Build Array—Takes the two 10 arrays and builds a 20 array. Each 10 array becomes a row In the 20 array.
4 Array Slze—Outputs a 10 array where each element shows the size of each dlmenslon. In this exercise, you have 2 elements of data for the number of rows
and columns.
1 5 Allí Data Channel and Data Channel Array indicators display the same data.
Note The polymorphic functiona!ity of LabVIEW functions allows you to perform the same operation on each element without extracting the array
elements, as you do with the two Add functions in the Al! Data Channe! case.
1
Les5on 5 Creaflng snd Leveragng O.Ia Structures nicom 1 5-10
20. Switch lo the front panel and test the Afl Dala Cliannel case.
El RuntheVi.
O Change the value of the Channel 1 Offset control and observe the behavior.
22. Switch to the block diagram and select the Waveform Subset case.
1
la
Gener.te 1000
datpoinbter
e,ch arroy
1 Array Subset—Extracts a subset of an existing array. In thls exercise, you use thls function to zoom In on a subset of the waveform you generated.
2 Numerlc Constant—These constants specify that the function extract the first two rows starting at element 0.
3 Start Value—Sets the stari index. The default value is set to start at element 0.
4 Length—Sets the number of elements to extract. The default value is set to output 1000 elements.
24. Switch fo the front panel and test the Waveform Subset case.
O Change value of the Start Value and Length sliders and notice that the Subset Data waveform graph x-axis starts at zero and finishes at the number of
1 elements in [he new array. The x-axis starts at zero because the VI creates a brand new array and the graph does not know where the data was located in the
original array.
Complete ihc foliowing steps to use the NI Example finder to locate example Vis thai demonstrate different ways to use ihe Array function.
4. Click one of the example Vis in the search results Iist and read the description.
6. Read through the comments on the front panel and block diagram [o lcarn more about what ihis exampie VI demonstrates.
7. Run the example, examine the different cases, and click the Stop buiton to cxii.
8. Close ihe Vis and the Ni Example Finder when you are finished.
:3
:
Mu, Temperature Max Temperature
o
Mio Ternperxture !.1!n Tempereture
Warning' arnng
No Wa r n i ng No Worrinrg
status
: cerle
o •
status
SOUrr.P
code
.o
source
Natona rrstu"o'nn 3
LabVIEW Core 1 Exercises
1
Lesson 5 Creahng and Leveraging Data Structures nLcom 1 5-14
3. Place exisung controis and indicators in a cluster named Weather Data as shown in Figure 5- 10.
T t
CtTnritu,
-----------
-------------
mTempe~ NO W44~9
In E' Ot a
$tWl ode codi
1 Cluster—Use the Cluster control from the Silver palette and chango the label to Weather Data.
2 Select controis and indicators to include in the cluster. <Shift>-click to select multiple objects.
3 Drag the controls and indicators into the Weather Data cluster.
4. Resize the cluster so that all the elements are visible and arranged vertically as shown in Figure 5-11.
Wether
Cutrent Temperture
MxTemperture
Min Temperatvme
Warning TtA
In Enor Out
seurce seurce
1 Autosize cluster—LabVIEW can rearrange and resize the cluster for you. Right-click the border of the Weather Data cluster and select AutoSizing»Arrange
Vertically.
[0=
1 Right-click the edge of the cluster and select Reorder Controis in Cluster.
2 Click the controis to toggie the order of the items in ttte cluster.
3 Click the Conflrm button to save the changes.
6. Modify the VI to receive and rcturn cluster data.
1 Figure 5-13. Temperature Warnings—Weather Data In and Weather Data Out Cksters
Í
1 Ede Edt Viev, 2reject Qp,ate ICM(S jnd u&p
2
Max Tetapetature tb. Taapeatuae
= o
ddarrnflg? Warning'
•
W,nng Tt Warning TrW
No i
Error In Erro, Out
e sOruce sourco
.e8tt Atining.hprOJMy
1 Weather Data—<Ctrl>-click the Weatheroata cluster and drag it to create a copy. Rename the copy Weather Data In.
2 Weather Data—Right-click the original cluster and select Change to Indicator. Rename the indicator Weather Data Out.
3 Wire connector pane—Wire the Weather Data In control to the top left comer of the connector. Wire Weather Data Out to the top right comer.
1
Lesson 5 Creattng and Leveraging Data Structures rti.com 1 5-18
7. Modify [he block diagram as shown in Figure 5-14 lo extract data from the input cluster.
[1 Move the Weather Data In cluster to the Ieft, outside the Case structures.
El Move (he Weather Data Out cluster to thc right outside the Case structurcs.
tpt
1
____ •____i
1
Wth,,D.t.O,,t
I l
1 Unbundle By Name—Wire the Weather Data In control and expand the Unbundle By Name function to display three items. Wire [he outputs of the Unbundle
By Name function te the broken wires ¡n [he order shown. Because you moved individual controls and indicators into a single cluster, you must use the Unbundle
By Name function to wire [he interna¡ controis and ¡ndicators ¡ndependentty of each other.
2 Bundle By Name—Wire [he Weather Data In cluster around the Case structure to [he input cluster of [he Bundle by Name function. Display two elements and
use the Operafing [001 te select Warning? and Warning Text elements. Connect the brokon wires te the Unbundle By Name inputs as shown.
Note If theorderof the elements in the Unbundle By Name and [he Bundle By Name functions is different (han what you want, you can use (he Operating
tool to change (he order.
Test
1. Use the SubVI Tester Vito test the modified Temperature Warnings VI as a subVl.
1
ED On the block diagram, delete the Thermometer, Warning?, and Warning Text indicators and any broken wires. Press <CtrI-B> to clean up al¡ broken wires.
El Modify the SubVl Tester VI lo work with the Temperature Warnings VI that now uses clusters, as shown in Figure 5-15.
Figure 5-15. SubVl Tester VI Block Diagram Modified to Work with Modified Temperature Warnings VI
1fltIIE
1 Weather Data—Right-click the Weather Dala Out output of the Temperature Warnings VI found on the block diagram of the SubVl Tester VI and select Create»
Indicator. Wire the output to the edge ol the While Loop, right-click the tunnel, and then select Replace wlth ShIft Register from the shortcut menu. The shift
register stores the cluster data from one iteration to the next.
2 Constant—Right-click the left shift register and select Create»Constant lo initialize weather data to values. Rename the constant Initialize Weather.
3 Bundle By Name—Wire the shift register from the InitIalize Weather constant lo the Input cluster of the Bundle By Name functlon. Expand the Bundle By Name
function to display three elements.
Wthr Data
Tmp
Maxiernp
25.9375
- MaxTemp
Min, Ternp 30
PAin Temí
Wming1
lo
Warning Tent
O Run the VI and verify that the Weather Data indicator displays correct values.
Scenario
As a LabVIEW developer, you can encounter situations where you need to define your own custom data types in the form of clusters and enums. A challenge
associated with using custom data types is that you may need to change them later in deveiopment. In addition, you may need to change them after they have already
been used in Vis. For example, you create copies of a custom data type and use them as controis, indicators, or constants in one or more Vis. Then you realize that
the custom data type needs to change. You need to add, remove, or change items in the cluster data type or the enum.
As a developer you must ask yourself the foliowing questions:
• What should happen to the copies of the custom data types used in Vis that are aiready saved?
• Should the copies remain unchanged or should they update themselves to reflect changes to the original?
1 Usualiy, you want all the copies of thc custom data type to update if you update the original custom data type. To achieve this you need copies of the custom data
types to be tied to a type definition, which is defined as foliows:
Type definition—A master copy of a custom data type that multiple Vis can use.
Implementation
In this exercise, you modify the Temperature Warnings VI that you revised in Exercise 5-2 in such a way that the changes to the Weather Data custom data type
propagate through the application.
When complete, the Weather Station application monitors temperature and wind information. This exercise modifies the Temperature Warnings VI. In the Challenge
exercise, you modify the Windspeed Warnings VI.
1
Lesson 5 Crealing and Leveraging Data Structures nicom 1 5-22
Place a File Path Control (Silver) in the Weather Data In cluster control.
• Notice that the Temperature Warnings VI is brokcn. This is because the Weather Data In and Weather Data Out clustcrs are no longer the same data type.
• Open the block diagram and notice the broken wire connected lo the Weather Data Out terminal.
O Right-click the bordcr of the Weather Data In control and select Make Type Def.
El On the block diagram, the Weather Data In terminal now has a black triangle on the comer indicating that it is connected to a type definition.
1
El Right-click the border of the Weather Data In control and select Open Tvpe Def to display thc Custom Control Editor window as shown in Figure 5-17.
The window looks like the front panel of a VI but it does not have a block diagram.
'IÍTOf
Wncow
[iL.
1
Weather Data 1n
Cunent Tnmperatur
MnxTrmperotun
Mn Temperiture
1
Womtng?
WmingT
NoW,orq
1 The control type is Type Def, which maintains the link between this file and the custom control copies used in Vis.
O Save the custom control as Weather Data. ct 1 in the <Exerc ± ses> \LabVIEW Core 1 \Weather warnings directory and close the control editor
window.
O On the block diagram of the Temperature Warnings VI, notice the coercion dot on the Wenttier Data Out indicator terminal. Ihis indicates that the indicator
is not tied to the type definition.
G Rigbt-click the border of ihe Weather Dita Out indicator on the front panel and select Reptace»Select a Control from the shortcut menu.
O Browse Lo and select the Weather Data. ctl file you just created.
Note You can no longer add or remove elements to or ftom the cluster control and indicator on the front panel. You must open the type definition and add
or remove the element from the control editor window.
O Right-click the border of the Weather Data In control and select Open Type Deffrom the shortcut menu.
1
O Modify the front panel as shown in Figure 5-18.
Wether Data te
1 Current Temperature
tlxt Teriperature
t1in 7 emperature
Temperature 'íarning?
e
temperatura warning tt
1 Nc Virnrt
Unitu
1 Enum (Siiver)—Place an enum in the cluster and rename It Units. Right-clickthe enum and salect Edit Items. Create en Item forcelsius and Fahrenheit.
O Save the Weather Data type definition and close the control editor window.
1
Lesson 5 Creating anci Leveraging Data Structures ni.com 1 5-26
El Notice that the Weather Data In control and Weather Data Out indicator on thc i'cmperature Warnings VI havc been updated with the changes you made
to the Weather Data type definition. Arrange the front panel of the VI as shown in Figure 5-19.
Nc No Warning
Unit5jjj Unmt
Celsius Celimu;
seucce
40
•
source
Test
1. Use the SubVl Tester VIto test the modified Temperature Warnings VI as sub Vis.
1
El Open the SubV! Tester VI from the Project Explorer window.
E On theel right-click the Weather Dita Out cluster and select Replace»Select a Control from the shortcut menu.
E Navigate to the Weather Data. ctl file in the <Exercises>\LabVIEW Core 1\Weather Warnings directory and select it.
E On the block diagram of SubVI Tester VI, delete the foliowing items:
Delete any broken wires. Press <Ctrl-B> to clean up alt broken wires.
1
Lesson 5 Crealng and Leveraging Dala Structures ni.com 1 5-28
Modify the SubVl Tester Vito work with the Temperature Warnings VI which now uses type definitions as shown in Figure 520.
Figure 5-20. SubVI Tester VI Block Diagram Modified lo Test Temperature Warnings SubVI
il- E , — Un ft
fem trA
Max 1 emperature '.. - l*a Ttwn it
Mn 1enperature Miri Terir ah
Wrather Data Out
Weather Data ln
...............................
Temperature Warnings.vi
I1 Stop
L
1 Initialize shift register—Right-click the Ieft shift register and select Create»Constant to ¡nitialize the shift register. Right-click the cluster and select View Cluster
as ¡con.
2 Bundle By Name—Expand the node to display four elements. Use the Operating tool fo select Units.
3 Wire the Units (0:Celsius) constani to the Unitseiernent of the Bundle By Name function.
1
e
El Arrange the front panel as shown in Figure 5-21.
ure 5-21. SubVl Tester VI Front Panel Modified with Type Def
e Weathr Data Out
Mal Tempereturt
Cturent Tanier.ture
- 30
: o
e Mm Temperatua
Temperature Wamifl9?
Temperatuee Waaning re
Nc Waming
1 • stop
Un:
2. Run the VI and verify that correct values are displayed in the Weather Data Out indicator.
3. Save and close the VI.
Challenge
In this challenge exercise, you modify the Windspeed Warnings Vito augment the Weather Station application. You then test the Windspeed Warnings VI asa subVl.
O In the Project Explorer window, nght click My Computer and select Add»FiIe from the shortcut menu.
O Navigate to <Exercises>\LabVIEW Core 1 \Weather Warnings\Support VIS and select Windspeed Warnings . vi.
e
1
e
Lesson 5 Creating and Leveraging Data Structures ni.com 1 5-30
3. Copy the Weather Data In cluster from the Teniperaturc Warnings Vito the Windspecd Warnings VI.
4. Right-click the Weathcr Data In cluster and scicct Open Type Deffrom thc shortcut menu.
5. Modify the Weather Data type definition with windspeed controis as shown in Figure 5-22.
Curient Tamperature
Max Temperatura
Mm Tempeaxture
Temperatume Warning: ,
0
Temperatura Warning Text
Currerrt 'ndxpeed
Max Wrndpeed
Wrndxpeed Warning?
0
Windspeexl Warrrrrrg Taxi
O
e
e
e
e
e
e
e
e
e 6. Modify tbe block diagram of the Windspeed Warnings Vito use the new Weatlier Data type definition instead of individual controis and indicators, as skown in
Figure 5-23.
e Figure 5-23. Windspeed Warnings VI Using Type Definitions
e
e End
e W~D.bl. WnsffierD.ta O*
e
e
e
e
e non .n (no ono( ti? Of 0(1!
e
O
e
e
e
e
e 1
e
© Nationat Instruments 5-3
L8bVIEW Core 1 Exercises
e
e
e
e
e
O
e
e
Lesson 5 Creasng and Leveraging Data Structures ni,com 1 5-32
7. Modify ihe SubVI Tester VI to work with the Windspccd Warnings VI, as shown in Figure 5-24.
Figure 5-24. SubVI Tester VI Block Diagram Modified to Test Windspeed Warnings SubVt
ICclsu 'i-fj
1
Mu Temputu, «-'« L
Weathe, nata duster ¡
ecnstanf ¡
ec L
Max
MX
L 1:oi; :
8. Run the SubVI Tester VI and verify thai correct values are displayed in the Weather Data Out indicator.
9. Save and close the VI and the project.
e
Managing File and Hardware Resources
Complete the exercises in this lesson to reinforce the concepts you learn in Lesson 6 of LabVIEW Core 1.
e Exercises
Exercise 6-1 Concept: Spreadsheet Example VI
Exercise 6-2 Temperature Monitor VI—Logging Data
e Exercise 6-3
Exercise 6-4
Concept: NI Measurement & Automation Explorer (MAX)
Using DAQmx
Exercise 6-5 Concept: GPIB Configuration with MAX
Exercise 6-6 Concept: M Devsim VI
1
1
e
Lesson 6 Managing File and Hardware Resources roi.com 1 6-2
Description
Complete the foliowing steps 00 examine a VI that saves numcric arrays 00 a file in a format you can access with a spreadsheet.
Tbbln
Sine
Sine Moise Cosme * Nene
0 0.00 0.04 LOO Casase
Wnveform Grnph
1 0.05 0.43 LOO
2 0.10 0.90 LOO
3 0.15 0.61 0.99
4 0.20 -0.23 0.98
5 0.24 0.75 0,07
O 0.29 -0.68 0.96
7 0.34 -0.53 0.94
8 0.38 0.40 0.92
9 0.43 0.59 0.90
10 0.47 0.01 0.98
11 0,51 -0.29 0.86 0 20 453 60 00 lIJO 10 148
12 0.56 -0.35 0.83
13 0.60 -0.92 0.80
4. Save the file, when prompted, as wave. txt in the <Exercises> \LabVIEW Core 1 \Spreadsheet Exajnple directory and click the OK button. You
examine this file later.
1 Sine Pattem.ji
Build Array Waveform Grph
Sine Pittern,vi
phase Number To Froctional
Table
• Sine Pattern VI—Returns a numeric array of 128 elements containing a sine pattern. The constant 90. 0, in the second instance of the Sine Pattern VI,
specifies the phase of the sine pattern which generates the cosme pauern.
Uniform White Noise VI—Returns a numeric array of 128 elements containing a noise pattern.
Build Array function—Builds the following 2D array from the sine array, noise array, and cosme array.
Sine Array
Noise Array
Cosme Array
1
Lesson 6 Managing Fi'e and Hardware Resources ni.com 1 6-4
• Transpose 2D Array function—Rearranges the elements of the 2D array so element [i, u becomes element Ej i] as foliows.
S N C
• Wrne To Spreadsheet File VI—Formats (he 2D array into a spreadsheet sring and writes (he string to a file. The string has the foliowing format, where an
arrow (-+) indicates a tab, and a paragraph symbol () indicates an end of une character.
S N C 1
—) ¶
• Numbcr To Fractional S(ring function—Converis an array of numeric values lo an array of srings thai (he table displays.
1
7. Open the wave txt file using a word processor, spreadsheet application, or text editor and view its contents.
• Open a word processor, spreadsheet application, or text editor, such as Notepad or WordPad.
• Open wave. txt. The sine waveform data appear in the first column, the random (noise) waveform data appear in the second column, and the cosme
1 waveform data appear in the third column.
1
LabVIEW Core 1 Exercises © Natlonal Instruments 1 6-5
1
Lesson 6 Managing File and Hardware Resources ni.com 1 6-6
Description
You have been given a VI that plots the current temperature and the average of the last three temperatures. Modify the Vito log the current temperature to an ASCII
file.
Implementation
1. Open Ternperature Monitor. lvproj in the <Exercises>\LabVIEW Core 1\Temperature Monitor directory.
2. Open Temperature Monitor.vi from the Project Explorer window. You created this VI in Exercise 3-5.
e
e
1
3. Modify the block diagram as shown in Figure 6-3.
milbs«c>nd rnuftiple
9i
1
C, L
2
Open/Create/Replace File—Creates or replaces an existing file for the data log. Right-cllck the operation input and select Create»Constant.
Set the constant to replace or create.
2 Format Into String—Formats temperature data into a string. Expand the node to accept two inputs.
3 End of Line Constant—Adds an end-of-line constant after each piece of data so that data values are separated by une breaks.
4 Write to Text FiIe—Wrltes the data to a file.
1 5 Or—Stops the VI when an error occurs or when the Stop Button is clicked.
6 Close File—Closes the data log file created or replaced when the VI started running.
7 Simple Error Handler—Indicates whether an error occurred. lf en error occurred, thls VI retums a description of the error and optionally displays a dialog box.
1
Lessori 6 Managirig File and Hardware Resources ni,com 1 6-8
AddNwOp
Formatinto Strin9 'i..i.:_. - Use tpecified preciriorn 3
Itemove fleo Operateon Formatlnto Stnng
OK Canc& Help 4-
1 Formal Into String—Double-click the Formal Into String function lo open the Edit Format String diabog box.
2 Use specified precision—Place a checkmark in Ihis checkbox and enter 3 in the text box lo specify that data have a floating point precision of three digits.
3 Corresponding format string -This text box automatically updates based Qn the configuration you specify. After you click the OK button in the dialog box, the
block diagram updates lo display the formal string.
4 HeIp button—CIick the Help button for more information about formal specifier elements, such as %3f, and conf iguration options for the Formal Into String
function.
o Click the Stop button after the VI has been running for a few samples.
Current remperature
23.590
23.590
23.590
23.590
23.590
24. 566
26.520
:27.984
Modify the Temperature Monitor Vito include the header Current Temperature.
Hints:
Because you write the header to the text file only once, you should write to the header outside the While Loop.
Use the functions on the Strings palette to manipulate and format a string for use ja a word processing or spreadsheet application.
e
Lessorl 6 Mariaging File and Hardware Resources ni.com 1 6-10
Note Portions of this exercise can only be completed with the use of a real device and a BNC-2120. Sorne of these steps have alternative instructions for
simulated devices.
1. Launch MAX by selecting Start»Programs»Nl MAX or by double-clicking the NI MAX ¡con on your desktop. MAX searches the computer for installed
National lnstruments hardware and displays the information.
2. If you have a DAQ device installed, skip step 3 and go to the Examining ihe DAQ Device Seuings section.
3. Create an NI-DAQmx simulated device to allow you to complete the exercises without hardware.
El Right.click Devices and Interfaces and select Create New from the shortcut menu.
o lo the Create New dialog box, select Simulated NI-DAQmx Device or Modular lnstrument.
• Click the Finish button.
• In the Create Simulated NI-DAQmx Device dialog box, select M Series DAQ»Nl PC] 6225.
1
Lesson 6 Managing File and Hardware Resources ni.com 1 6-12
2. Select the device that is connected to your machine. Green icons represent real devices and yellow icons represent simulated devices. You might have a different
device installed, and sorne of the options shown might be different.
MAX displays National lnstrurnents hardware and software in the computer. The device alias appears in quotes foliowing the device type. The Data Acquisition
VIs use this device alias to determine which device performs DAQ operations. MAX also displays the attributcs of the device such as the system resources that
the device uses. Figure 6-7 shows the simulated FCI-6225 device.
a Li My ysteni a
J Refresh Ccnfigurr_. )(. Delate ,Resat - SkaowHelp
Dita Neighborhood
l Desices aoci Interfaces Nenia Value
a
i) 4SRL3::1'ISTR "C0M3 Serial Number taO
• ASRIOO::INSTR LPT1
NI USB-6212 (Mess Termination) "De,2
LO Nl PCI-6225 Davl.
T.Sockat Nurnber
Bus Number
Driver Neme
taO
OnO
NI-DAQmx
NetworkDevices 2DriverVarsron 9.7.5b6
'4 Sales
B
• Software
IV! Desees
Remota S.ytems
1 Make sure the device you use is named Dcv 1. To rename a device, right-click the device and select Rename from the shortcut menu. You use Dey 1 in
Exercise 6-4.
Tip The Show Help/Hide Help button in thc top right comer of MAX is available for certain items. Click the Show Help/Hide Help hutton to hide anime
help or show the DAQ device inforrnation.
1
1
3. Select the Device Routes [ab at the bottom of MAX to see detailed information about the interna¡ signals that can be routed to other destinations on the device,
as shown in Figure 6-8. This isa powerful resource thatgives you a visual representation of the signais that are available to provide timing and synchronization
with componcnts that are on the device and other external devices.
O
&bsystem Uxed ber ove, veilto nee wtt, nne ss
Cavite 1
O
Lesson 6 Managing File and Hardware Resources ni.com 1 6-14
4. Select the Settings tab, as shown in Figure 6-9, to see information about the lasi time thc device was calibrated hoth internally and extcrnally. Not afl devices
contain calibration information.
U Iv1 Spten
H Refreh Configure... *a Reset 5 StIf-Test ( Show Help
La Data Neighborhood
ASRLIO::INSTR LPT1
Recornmended Seat
511012012 12:5951 AM
5110/2013 12:5951 AM
CaI,baat,or
Net..ork Devies
44 Scaies Temperature 342C
Software
Comments
lMDrwer
Pffi
.Remote 5yOemu .k.. -. ::;........................ _______
Self-Callbratlaar _________
- Settrng;
5. Ifyou are using a physical device, right-chick the NI-DAQmx device in the configuration tree and select Sdf-Cahibrate to update the built-in calibration constants
and cahibratc the DAQ device using a precision vohtage reference source. When the device has been cahibrated, information in the SeIf-Cahibration section
updates. Skip this step ifyou are using a simulated device.
1
1. Click the Self-Test button in MAX to test [he device. The device should pass the test because it is already configured.
2. Click [he Test Paneis button to test the individual functions of the DAQ device, such as analog input and output. The Test Panels dialog box appears.
O Use the Analog Input [ab to test the various analog input channels on the DAQ device. aick the Analog Input [ab. Click the Start button [o acquire data
from analog input channel 0 and click the Stop button when you finish.
- Ifyou are using the BNC-2 120. make sure the switch over the Al O connector is in the Temp. Re£ position to connect the temperature sensor to ajO.
Place your finger on the sensor to see the voltage rise.
- Ifyou are using a simulated device, a sine wave is shown on all input channeis.
O Use [he Analog Outpnt [ab to set up a single voltage or sine wave on one of the DAQ device anaiog output channels. Click the Anahog Output [ab.
- Select Sinewave Generation in the Mode drop-down menu and click the Start button. MAX generates a continuous sine wave on analog output
channel 0.
- Ifyou have hardware instalted, you can read the sine wave that channel O outputs. On [he BNC-2 120, wire Analog Out ChO to Analog In Chi. Click
[he Analog Input tab in the Test Paneis dialog box and select Devl/ail from the Channel Name drop-down menu. Click the Start button to acquire
data from anatog input channel 1. MAX displays the sine wave from analog output channel 0.
O Use the Digital 110 tab [o test the digital limes on the DAQ device. Click the Digital 110 tab.
1 - In the Select Direction section, set unes O through 3 as output as shown in Figure 6-10.
portOjneO7
!fpJt(i) óG•'O
*Zit(0) C,J
0
1
Lesson 6 Managing File and Hardware Resources ni.com 1 6-16
- Click Start to begin the digital output test, then toggle the switches in the Select State section shown in Figure 6-11. If you have a BNC-2120, toggling
the switches turns the LEDs on or off. Notice that the LEDs use negative Iogic.
poO/LeO:7
(I)
Loe (0 ) 90001111 1
O Use the Counter I/O tab to determine if thc DAQ device counter/timers are functioning properly. Click the Counter I/O tab.
- lfyou have hardware installed, you can verify counter/timer operations by selecting Edge Counting from the Mode drop-down menu and clicking the
Stari button. The Counter Value indicator incrcments rapidly. Click Stop to stop the counter test.
L ('lick the (lose button to close the Test Panel dialog box and return Lo MAX.
Scenario
Explore a DAQmx example program that continuously acquires a voltage signal on channel analog input 1 (Ah) of a DAQ device. Modify the Vito use a digital
trigger. The Vi begins measunng when the user sends a digital trigger to the device. In this exercise, the user sends a trigger by turning the Quadrature Encoder
knob on the BNC-2120. The VI stops measuring when the user ciicks the Stop button on the front panel of the VI.
Implementation
Externa¡ Connections
1. If you are using the BNC-21 20, connect the Sine/Triangle output on the function generator to channel Al 1 with a BNC cable, and make sure the switch on the
function gencrator is set to the sine wave. Also, ensure that there is a wire connecting the UPIDN screw terminal to the PFI 1 screw terminal in the Timing 110
section.
1 NCn Note The tJPIDN terminal on the BNC-2120 outputs a high or a low signal indicating the rotation direction of the Quadrature Encoder knob. When
you rotate the Quadrature Encoder knob clockwise, the UPÍDN terminal outputs a high signal. When you rotate the Quadrature Encoder knob
counterclockwise, the UP/DN terminal outputs a low signal. In this exercise, this signal triggers the VI to start acquiring data.
NCn Note If you cannot locate this DAQmx example in the NI Example Finder, you can also open the VI from the <Exercises> \LabVIEW Core 1\
Using DAQmX directory and skip to step 5.
4. Double-click Voltage-Continuous lnput.vi to open the example program. This VI demonstrates how to acquire a continuouS amount of data from a DAQ device.
5. Select File»Save Asto save the VI as <Exercises>\LabVIEW Core 1\Triggered Analog Input\Trigger Al Acquisition.vi . When
prompted, select Copy - Substitute copy for original.
Maxvoftoge
T
Sa leCiockSource
1 gMode
1 1
A volt lo9m j
A -- Actual Sample Rote -
1 DAQmx Create Virtual Channel VI—Click the pul¡-down menu and nolice it is set to Analog lnput»Voltage.
2 Press <CtrI-H> to open the Context Help window. Hover over each of the DAQmx functions to Iearn about each function.
3 Property Node—Gets or seis properties br a reference. You can Iearn more about Property Nodes in LabVIEW Core 2 or refer to the LabVIEW HeIp.
O Use the Frequency Selection switch and the Frequency Adjust knob un the 13NC-2120 to change the frequency of the generated and acquired signal.
1. Modify the block diagram as shown in Figure 6-13 to add trigger functionality. After you modify this VI, the VI waits for a trigger before acquiring data.
source
TOMS File Peth perLoop
1
Ste,t • Analog 10 Wfrn
c*IDi9italEd9e
H 1NChOONSOmP
1 DAQmx Trigger VI—Place to the right of the DAQmx Configure Logging VI. Delete the task out and error out wires from the DAQmx Configure Logglng VI
and then wire them through the DAQmx Trigger VI to the DAQmx Start Task VI.
2 Configure the trigger—Click the DAQmx Trigger VI pul¡-down menu and select Start»Dlgital Edge.
1 3 Create controls—Right-click the source input and the edge input of the DAQmx Trigger VI and select Create»Control.
4 Free label-Create a abel and enter Trigger Settings.
1
Lesson 6 Managing Fde and Hardware Resources ni.com 1 6-20
2. Modify the front panel and set the default settings as shown in Figure 6-14.
%ln.JPri1
0.2105
25025-1
0.200i0-
Ob.dCiu - 221005-
025
RO,
A tow O25l5-
2409-
:
Ø4999 .
1OD
52405-
0.24919-
Le9hlI SIUI.I,J
02497
Lo9m9Mods
0,24945
0.2494-, ,. . ,,
0 00
Move the Acquired Data group—Select al¡ the items in the Acquired Data group and shiti them lo the right. <Shift>-click lo select multiple items and press
<Shift-arrow key> to move them.
2 Create Trigger Settings group—Copy a container from another group, label the copy Trigger Setcings, and place the edge and source controls in it.
3 Select Rising in the edge control.
4 Select Devl/PFI1 in the source control.
3. SavetheVi.
4. Run the VI. Turn thc Quadrature Eneoder knob on the BNC-2120 counterclockwisc then clockwise lo begin the acquisition.
Description
El Set the configuration switch on the rear panel to CFG, as shown in Figure 6-15.
E Power on the NI Instrument Simulator using the power switch on the front of the unit.
O Verify that the PWR LED is lit and the RDY LED is flashing.
• Launch the NI Instrument Simulator Wizard from Start»All Programs»National Instruments»Jnstrument Simulator»Instrument Simulator Wizard.
• Click Next.
• Click Next.
• On the Select Interface page, select GPIB Interface and click Next.
1
1
o Click Update.
E Click OK when you get the message that the update was successful.
El Power off the NI Instrument Simulator using the power switch on the front of the unit.
E Expand the Devices sud Interfaces section to display the installed interfaces. Ifa GPIB interface is listed, the NI-488.2 software is correctly loaded on the
computer.
E Examine but do not change the seuings for the GPIB interface. S
4. Communicate with the GPIB instrument.
o Make sure the GPIB interface is still selected in the Dev ices and lnterfaces section. 1
O Click the Scan for Instruments button on the toolbar.
o Expand the GPIB interface selected in the Devices and Interfaces section. An mstrument named Instrument Simulator appears. 1
1
1
D Click Instrurnent Simulator to display information about it in the right pane of MAX. Click the Attributes tab. Notice the NI lnstrument Simulator
has a GPIB primary address.
O Click the Communicate with lnstrument button on the toolbar. An interactive window appears. You can use it to query, write to, and read from that
instrument.
O Enter * IDN? in the Send String text box and click the Query button. The instrument returns its make and model number in the String Received indicator
as shown in Figure 6-16. You can use this communicator window to debug instrument problems orto verify that specific commands work as described in the
instrument documentation.
1 (onF.ired
Strro Received: CMPL
Nalional lnstiments,instiument Simulatoi D.0 D
O Enter MEASURE VOLTAGE: DC? in the Send String text box and cick the Query button. The NI Instrument Simulator returns a simulated voltage
measurement.
O While Instrtunent Simulator is selected in MAX, click the VISA Properties tab.
O Enter devsim in the VISA Alias on My System field. You use this alias later in the course.
O Click Save.
Description
Instali the instrument driver for the NI lnstrument Simulator. After installation, explore Ihe VIs that the instrument driver provides and the example programs that are
added to the NI Example Finder.
NOMMMCIFO
4. If you do not have an ni. com profile, follow the onscreen instructions to create one at this time. Be sure to make a note of the user ID and password you create.
5. Altar you log in, click the Sean for lnstruments button. If you have an instrument connected, clicking this button detects the instrument and finds the correct
driver. In this case, it detects the lnstrument Simulator.
6. Double-click Instrument Simuiator in the list and click the Search button.
7. Select Version 2.0 of the instrument driver from the Driver list.
1
1
1
12. Close the NI lnstrument Driver Finder window and go to the Explore Insirumeni Driver section to continue this exercise.
1. If you have it opcn, close LabVIEW and then navigate to the <Exercises> \LabVIEW Core 1 \ Instrument Driver directory. This folder contains a zip
file with the LahVIEW Plug and Play instrumcnt drivers for the lnstrumcnt Simulator.
2. Right-click thc rip file and follow the wizard to extract ah files to the <Program Fi les> \National Instrumerits\LabVIEW 2013 \ instr. lib
directory.
1. Open National lnstruments lnstrument Simulator Acquire Single Measu remen t(DMM).vi from the Examples folder in the Project Explorer window of
the National lnstruments lnstrument Simulator project.
This VI reads a single measurement from the lnstrument Simulator.
2. Verify that the PWR and RDY LEDs are lit on thc Instrument Simulator.
3. Seleci devsim from the VISA Resource Name control on the front panel. You specified the VISA alias for this GPIB instrument as devsirn in step 5 of
Exercise 6-5, Concepl: GPIB Configuration ii-,th AL4X.
6. Open the Functions paiette and navigate to the instrument IIO»Instrument Drivers»National Jnstruments Instrument Simulator palette.
7. Explore the palette and subpaiettes using the Context Help window to familiarize yourseif with the functionality of functions on the paiette.
9. Open National Instruments Instrument Simulator Acquire Waveform(Scope).vi from the project. This VI reads a single waveform from the lnstrument
Simuiator.
10. Seiect the same VISA resource name you selected in step 3.
11. RuntheVI.
O To familiarize yourselfwith the VI's fünctionality, explore the block diagram using the Context Help window.
. O Open to the block diagram of the Read Waveform Vi. Notice that it uses VISA functions to commumcate with the instrument.
15. Close the Vis and project when you are finished. Do not save changes.
•• Complete Llie exercise in this Iesson Lo reinforce the concepts you Iearn in Lesson 7 of LabVIEW Core 1.
Exercises
Exercise 7-1 Weather Station Project—State Machine VI
e
e
e
e
e
e
e
e
LabVIEW Core 1 Exercises 1 \jIc'ia Insrrnens
•
e
e
1
0
e
O
Lesson 7 Uang Sequential and State Machine Algorlthms ni.com 1 7-2
Scenario
You must design a VI for a user interface state machine. The VI acquires a temperature every haif second, analyzes each temperature to determine if the temperature
is too high or too low, and alerts the user if there is a danger of heatstroke or freeze. The program logs the data ¡fa warning occurs. If the user has not cicked the stop
button, the entire process repeats. The state machine must also allow for expansion, because processes may be added in the future.
Design
Use the foliowing flowchart and states list to create the VI in this exercise.
e
e
e
e
e
e
e
e
e
e
e
e Flow Chart
The flowchart in Figure 7-1 illustrates the dais flow for this design.
e Figure 7-1. Temperature Warnings VI Flowchart
e
e
Ó
e
e
e
e
e
e
e Elapoed FALSE
and
Siop FALSE
e
e Stop TRUE
\'
e
e
e
e LabVIEW Coro 1 Exorcises © National Instrumente 1
e
e
e
e
e
e
e
e
e
Lesson 7 Usirg Sequential and State Machi rie Algorithms ni.com 1 7-4
State Transitions
The foliowing table describes the states in this state machine.
Acquisition Set time to zero, acquirc data from the temperature sensor Analysis
Analysis Read front panel controis and determine warning level Data Log ifa warning occurs
Time Check if no warning occurs
Data Log Log the data in a tah-delimited ASCII file Time Check
Time Check Check whcthcr time is greater than or equal to .5 seconds Acquisition if time has elapsed
Time Check if time has not elapsed
Implementation
/
1. Openweather Station.1roj in the <Exercises>\LabVIEW Core 1\Weather StationdirectO.
1 2. Open Weather Station tJI.vi from the Project Explorer window.
Figure 7-2 shows the front panel of the Weather Station UI VI that has been provided for you. You modify the block diagram to create a state machine for the
Weather Station.
Ternpereture [>
Ttmprture Histoy
- - 0.00
Temperature Riges (C)
323-
UpprLimit
30-
27.5-
LowerLimit
25-
22.5-
20-,
100
Ssmple
Wming
swp
Figure 7-3 shows the starting point of the block diagram for the Weather Station UI VI. You edit this block diagram to implement a state machine for the Weather
Station application.
Figuro 7-3. Weather Station UI VI Block Diagram Starting
1 You use titese controis and indicators to program dlfterent cases. --- -
• Open the block diagrain and create an Enum constant to the left of the While Loop.
• Right-click the constant and select Edit Items from the shortcut menu.
El Add the items shown in Figure 7-4 and click OK.
e 1
Figure 7-4. Weather Station States Type Def
Ó [d tern.
ppeaance Dote Te Display Format Ooumentation
tenn Inrt
Anaysts 1
Da" Loq -'-. ....
lime Check .
MoveDon
- Dsable!Lem
OK Can<tI: Hp
El Right-click the enum constant on the block diagram and setect Make Tpe Del'.
4. Modify the new type definition and add it to the Weather Station project.
1
e
Lesson 7 Using Sequential and State Machine Algorithms ni.com 1 7-8
In the Pruject Explorer window, notice that Weather Station States.ctl has been added to your Supporting Files foldcr because that folder is an
auto-populating folder.
5. Control the state machine with the type-detined enum and update ihe framcwork as showo in Figure 7-5.
Weither Data ln II
>Weither Data>
- - 4- >
3I
nrnnq State
--->P , Ac quisition
(22)-L - Next State'
1 Shift Register—Right-click the While Loop and select Add Shift Register.
2 Enum type defirtition constartt—Right-click and select Visible ltems»Label. Change the label to Beginning State. Wire the Beginning State constant to the
shift register to initialize the shift register to the Acquisition state. Wire the shift register to the case selector of the Case Structure.
(3 Add more cases—Right-click the Case structure and select Add Case For Every Value to create different cases br each value in the ertum.
4 Weather Data In—Drag Weather Data.ctl from the Project Explorer window to the block diagram to create a type definition cluster constant. Rtght-click the
cluster and select View Cluster As ¡con.
5 Shift Register—Place a shift register on the While Loop and wire the Weather Data In constartt to it.
Note After you finish wiring the Acquisition case in step 6, sorne tunneis are ernpty because not all cases are wired yet.
1
1
1 Y Thermometer or Thermometer (Demo)—Drag one of these Vis from the Shared Files folder in the Project Expiorer window to the block diagram. Drag the
Thermometer Vi if you have hardware and drag the Thermometer (Demo) VI if you do not have hardware.
2 /Temperature History—Move this indicator into the Acquisition state of the Case structure.
3 / Bundle By Name—Wire the Temperature Value output of the Thermometer Vito the Current Temperature input.
4,' Next State enum—<Ctri>-ciick the Beginning State enum and drag a copy into the Acquisition case. Rename this copy of the Weather Station States type
definition Next State. Set the enum to Analysis and wire it through a tunnel on the Case structure to the shift register on the While Loop.
5 /True Constant—Create a True constant and wire it through the Case structure to the Elapsed Time shift register. The True constant resets the Elapsed Time
counter every time the VI executes the Acquisition case.
1
Lesson 7 Using Sequenhiai arid State Machine Aigorithms ni.com 1 7-10
1 1 Upper Limit and Lower Limit—Move these controis from outside the While Loop.
1 2 Bundle By Name—Replaces the Max Temperature and Min Temperature items with the values from thc Upper Limit and Lower Limit controis. The Bundle
By Name function makes it possible to wire the Upper Limit and Lower Limit values to the Weather Data In input of the Temperature Warnings VI.
3 Temperature Warnings—Drag the Temperature Warnings VI from the Supporting Files folder in the Project Explorer window.
.4 4 Unbundle By Name—Returns the value of specific items from the cluster.
.i 5 Select—Determines which state fo execute next depending on whether or not a waming occurs.
6 Weather Station States—Me two copies of the Weather Station Stafes type definition to fhe Select function. You can create these copies from the Beginning
State enum.
7 Warning—Move this indicator from outside the While Loop.
8. Complete the Data Log case as shown in Figure 7-8.
•v'T Unbundle By Name—Returns the value of specífic Items from the cluster.
Tab Constant—lnserts a tab in the string. The 109 lile you create contains tabs between values.
I I'•13 End of Line Constant—lnserts a platform-specific end-of-line value at the end of the string. The log lile you create uses the End of Line constant to insert une
breaks between data.
•/
"4 Format Into String—Expand the node to accept elght inputs.
•/5 Wrlte to Text Fiie—Wrltes the text that you formatted into a 109 lile.
Next State—Create a copy ot the Weather Station States enum, label it Next State, and set the next state to Time Check.
4 1 Next State—Wire two copies of the Weather Staf ion States type definition fo the Select function.
2 Select—Determines which state fo execute next depending on whether or not time has elapsed.
4 3 Stop Button—Move the Stop Button terminal from outside the While Loop. Wire the Stop Button terminal to the Or function outside of the Case structure.
4 Next State wire—Wire the tunnel for the Next State wire to the shift register.
5 Use default if unwired—Right-click these tunneis and select Use Default If Unwired.
O Enter values for the Upper Limit and Lower Limit controis and observe the behavior of the VI. Does it behave as expected?
•
1
••
••
• LabVIEW Core 1 Exercises © National Instrumente 1 7-13
•
•
•
••
1
•
••
•
1
1
Solving Dataflow Challenges Using Variables
H
e Complete tlie exercise in this Iesson lo reinforce the concepts you lean in Lesson 8 of LabVIEW Core 1.
Exercises
e Exercise 8-1 Weather Station UI VI with Local Variables
e
e
e
e
e
e
e
e LabVIEW Core 1 Exercises © National Instrurnerrts
e
e
e
e
e
e
e
e
e
e
e
1
Scenario
You have a l.abVIEW projcct that implements a temperature weather station. The weather station acquires a temperature every haif a second, analyzes each
temperature to determine if thc temperature is too high or too low, then alerts the user if thcre is a danger of a heat strokc or freeze. The VI logs the data ¡fa warning
occurs.
Two front panel controls determine the setpoints—thc tcmperature upper limit and the temperature lower limit. 1-lowever, nothing prevents the user from setting a
lower limit that is higher than the upper limit.
Use a local variable to set the lower limit less than the upper limit if the user sets a lowcr limit that is higher than the upper limit.
Design
Your task is to modify the VI you created in Exercise 7-1 so that the lower limit is set less than the upper limit when necessarv.
State Definitions
The foliowing table describes the states in the state machine.
Acquisition Set time to zero, acquire data from the temperature sensor Analysis
Analysis Read front panel controis and determine warning leve¡ Data Log ifa warning occurs. Time Check if no warning occurs
Data Log Log the data in a tab-dclimited ASCII file Time Check
Time Check Check whcther time is greater than or equal to .5 seconds Acquisition if time has clapscd. Time Check if time has not elapsed
Changing thc value of the lower temperature lirnil control should happen after the user has entered the value but before the value determines the warning level.
Therefore, make the modifications to the VI in the Acquisition or Analysis state, or place a new state between thc two.
Before determining which option to use, review the content of the Acquisition and Analysis states:
O Review the contents of the Acquisition and Analysis states, which correspond to the Acquisition and Analysis cases of the Case structure.
Design Options
You have three different design options for modifying this project.
1 Insert a Case structure in the Acquisition state to reset the Poor design: the acquisition state has another task added, rather than
controis before a local variable writes the values to the cluster. focusing only on acquisition.
2 lnsert a new state in the state machine that checks the controis Ability to control when the state occurs.
and resets them if necessary.
3 Modify the Determine Warnings subVl to reset the controis. Easy to implement because functionality is already partially in place.
However, if current functionality is used, one set of data always is lost
when resetting the lower limit control.
Acquisition Acquire data from the temperature sensor on channel AlO Range Check
and read front panel controls
Range Check Read front panel controis and set the lower limit lo 1 less Analysis
than the upper limit ifthe upper limit is Iess than the lower
limit
Implementation
1. If the Weather Station. lvproj is not already open, open it from the <Exercises>\LabVIEW Core 1\Weather Station directory.
E Right-click the States control and select Edit Items from the shortcut menu.
E Insert an item and modify the item to match Table 8-2. Be careful not to add an empty listing.
Acquisition O
Range Check 1
Analysis 2
Data Log 3
Time Check 4
o On the block diagram of the Weather Station UI VI, right-click the state machine Case structure and select Add Case for Every Value from the shortcut
menu. Because the enumerated control has a new value, a new case appears in the Case structure.
1
LabVIEW Core 1 Exercáses © National Instrumente 1 8-5
1.
Lesson 8 Soving Datatlow Challenges Using Variables ni,com 1 8-6
3. Set the Next State enum in the Acquisition case lo Range Check as shown in Figure 8-1.
-- -- -] Acgueition
- ii-lIIJ
j... >Weather Datas ..- .-..-..-............,-,,,...... -,--..-..--,--......-.--..--,-................ ,-.,,....-,,, .-.--.,-..-...-..-,.,
Temperature History
El- FileRefnum>-
fl
Etipaed Time
IElapsed time sd te
D
4. Modify the Analysis case as shown in Figure 8-2.
W, .Ui,rD,ta ctwtsr
consbntvewed u Con
Weather Dato In
NextState
lowerLimit Be
StitO Dato Log
r.Acqusition- >NextState>-
Next Stite
Refnum>
1 Eltpied Time
El
1 Delete the Bundle By Name tunction and wire the Weather Data wire directly to the Temperature Warnings VI. Press <CtrI-B> to delete the broken wires from
1 the Upper Limit and Lower Limit controis.
2 Move the Upper Limit and Lower Limit corotrois outside the While Loop.
Figure 8-3. Weather Station UI VI wíth Local Variables—Range Check True Case
UpperLimtt
Ale Refnum>
re
________________ 1 1 upper fimit.
=
H
3 4 5 •6
1
IIap,,d time setto
0.5 ,,cor,d,.
If the Upper ¡,¡m ¡t control value is not less than or equal to the Lower Limit control value, the False case executes and the values are passed, unchanged, through
to the temperature cluster.
Figure 8-4. Weather Station UI VI with Local Variables—Range Check False State
1
Lesson 8 SoMng Dataflow Challenges Using Variables ni.com 1 8-10
Test
1. Run the VI.
O Enter a value in the Upper Limit control that is less than the value in the Lower Limit control. Does the VI behave as expected?