You are on page 1of 103
SLNAINNULSNI of Sujuenswootw ‘TWNOLLWN. SOSIDIOXJ € 9109 wMAIAIET LabVIEW™ Core 2 Exercises Course Software Version 2011 August 2011 Edition Part Number 325293C-01 Copyright © 1993-2011 National instruments Corporation. Al ights reserved Under the copyright laws, this publication may not be reproduced ortransmitad in any form, eectronic or mechanical, ncluting PPhotocorying, recording, staring in an information retrieval system, or translating, in whole or in pat without the prior wrten consent (of National instruments Corporation. National instrurnents respects the intelectual property cf athers, and we ask cur users to do tha same. Ni software Is protacied by ‘copyright and otter intllstual property laws. Whare NI seftware may de used to reproduce software or cther materia belonging to ‘others. you may use NI software only fo reproduce materials that you may reproduce in accordance withthe terms of any applisabla license o other egal restraton. For components usec in USI (Xoreos C+, ICU, HOPS, b64, Stingray, and STLpar}), the following copyright stipulations apply. Fora listing ofthe conditions and disclaimers, reer to either the uszCopyights «chm orthe Copyrights topic in your software. Xereas C++. This produit includes software that was developed by the Apache Software Foundation (ht to: //imev-apachs.ora/'). ‘Copyright 1990 Tha Apache Software Foundation. All rights reserved. CU. Copyright 1995-2009 International Business Machines Corporation and others, All rights reserved. HFS. NCSA HOFS (Hierarchical Data Forma §) Software Library and Utilities Gopyrighi 1998, 1898, 2000, 2001, 2008 by the Board of Trustees ofthe University of lina. Al rights re ‘64, Copyright © 2004-2006, Matthew Wison and Symesis Soitwara. all Rights Reserved ‘Stingray, This software includes Stingray software developed by the Rogue Wave Software dvision of Quovack, In. Copyrigt 1995-2008, Quovads, Inc. Al Rights Reserved. ‘STLport. Copyright 1998-2008 Boris Foritchey ned Trademarks LabVIEW, National Instruments. NI n.com, the National instruments corporate logo, and the Eagle toga are tradamarks of National Instruments Corporation. Relertothe Trademark informationat ns .com/ rradenarks tor otter National Instruments trademarks. Other product ard company names mentioned herein are trademarks or trade names oftheir respactive companies. ‘Mambers of the National rstruménts Aline Partner Program are business anttis independent from National instruments and have ne agency, partnership, or joint-venture relationship with National instruments. Patents For satents covering Nationa Instruments produststectnology, refer tothe aparapriate location: Help»Patents in your sotuare, the patents. tse fleon your media, or the National Instruments Patent Notice a m5 .com/patents, ‘Worldwide Technical Support and Product information Worldwide offices Visitnd .com/ni global access the branch office Web utes, wich provide up.1o dete contact information, support phone umber, eal addresses, and current evens. National Instruments Corporate Headquarters 1500 Nomth Mopac Expressway Austin, Texas 78759-3504 USA ‘Tel: 5126830100 For further support information, refer tothe Additional Informatica and Resources appendix. To cornmient‘on National Instruments documentation, refer ta the National Instruments Web site at ni -com/ia fe and entacthe Info Code feedback. Contents —— Student Guide NI Certification Course Description «cusses: What You Need to Get Started ... Installing the Course Software.. Course Goals. Course Conventions. mmoap> Lesson 2 Synchronization Techniques Exercise 2-1 Concept: Comparing Queues With Local Variables... Lesson3 Event Programming Exercise 3-1 Concept; Experiment with Event Structures , Exercise 3-2 Create a Print Queue Consol Lesson 4 Error Handling Exercise 4-1 Updating the Print Console With Etror Handling ... Lesson 5 Controlling the User Interface Exercise 5-1 Display Temperature and Limits Exercise 5-2 Customizing the VI Window Exercise 5-3 Set Plot Name: Lesson 6 File 1/0 Techniques Exercise 6-1 Bitmap File Writer VI Exercise 6-2 Read TDMS Files... Lesson 7 Improving an Existing VI Exercise 7-1 Concept: Refactoring a VI Lesson 8 Creating and Distributing Applications Exercise 81 Preparing Files for Distribution Exercise 8-2 Creating a Stand-Alone Application © NetionalIsturens Corporation 0 Labinew Gore 2 Erescses Contents Appendix A Setting Up Your Hardware Appendix B Additional Information and Resources LabVIEW Core 2 Erreses com Student Guide ee Thank you for purchasing the LabVIEW Core 2 course kit. You can begin developing an application soon after you complete this course. This exer manual and the accompanying software are used in the two-day, hands-on LabVIEW Core 2 course. ‘You can apply the full purchase of this course kit toward the comesponding course registration fee if you register within 90 days of purchasing the kit. Visit 2i -com/craining for online course schedules, syllabi, training centers, and class registration, A. NI Certification ‘The LabVIEW Core 2 course is part of a series of courses designed to build your proficiency with LabVIEW and help you prepare for the NI Cestitied LabVIEW Associate Developer exam. The following illustration shows the courses that are part of the LabVIEW training series. Refer to ni com/ training for more information about NI Certification, New User Experisnoed User Advanced User Courses LabVIEW Gore 1" Managing Software peeat aes Engineering in LabVIEW LabVIEW Connectivity Advanced Nehitectures ‘Object Orented Design in LabVIEW ‘ang Progtemming in Labview Labview Pevformance ‘Carifiad LabVIEW Developer Exam, ified LabVIEW chive Exar LabVIEW instrument Control LABVIEW RealTime 1 LabVIEW Real-Time? LabVIEW FPGA LABVIEW DAG and Signal Conditioning Modular instruments Series “Core cours are sana ecemmanded wo reatze maxtrum producti Guns when ising LabVIEW, (Nationa astuments Corporation v Labview core 2exeres ‘Stutect Guide B. Course Description 8 LAVIEW Core 2 Beraises The LabVIEW Core 2 course teaches you programming concepts, techniques, features, VIs, and functions you can use to create test and measurement, data acquisition, instrument control, datalogging, ‘measurement analysis, and report generation applications. This course assumes that you are familiar with Windows; that you have experience writing algorithms in the form of flowcharts or block diagrams; and that you have taken the LabVIEW Core I course or have equivalent experience. The course and exercise manuals are divided into lessons, described as follows. In the course manual, each lesson consists of the following: + An introduction that describes the purpose of the lesson and what you will learn + A description of the topics in the lesson + A summary quiz that tests and reinforces important concepts and skills taught in the lesson In the exercise manual, each lesson consists of the following: + Asset of exercises to reinforce those topies + Some lessons include optional and challenge exercise sections or set of additional exercises to complete if time permits Note For course and exercise manual updates and corrections, refer to ni . com/info and enter the Info Code core2. Several exercises use.a plug-in multifunction data acquisition (DAQ) device connected to a DAQ Signal Accessory or BNC 2120 containing a tomperature sensor, function generator, and LEDs. If you do not have this hardware, you still can complete the exercises. Alternate instructions are provided for completing the exercises without hardware, Exercises that explicitly require hardware are indicated with an icon, shown at left. You also can substitute other hardware for those previously mentioned. For example, you can use another National Instruments DAQ device connected to a signal source, such asa function generator. Ww icon Studer cule C. What You Need to Get Started Before you use this course manual, make sure you have all of the following items Windows XP or later installed on your computer; this course is optimized for Windows XP o Multifunction DAQ device configured as Dev using Measurement & Automation Explorer (MAX) DAQ Signal Accessory or BNC-2120, wires, and cable LabVIEW Professional Development System 201 | or later DAQms 9.3.5 or later coco LabVIEW Core 2 course CD, from which you install the following folders: Directory Description Exercises Contains Vis used in the course solutions Contains completed course exercises D. Installing the Course Software Complete the following steps to install the course software. 1, Insert the course CD ia your computer. The LabVIEW Core 2 Course Setup dialog box appears. 2. Click Install the course materi: 3. Follow the onscreen instructions to complete installation and setup, Exercise files are located in the \LabvTEW Core 2\ folder. PZ Note Foldcrnamesin angle brackets, such as , referto folders on the root directory of your computer. © Nationa! Instuments Corporation i LanVIEW Core 2 Enrases ‘Stem Buide E. Course Goals LabVIEW Gore 2 Exercises This course prepares you to do the following: + Apply common design patterns that use notifiers, queues, and events + Use event programming effectively + Programmatically control user interface objects * Evaluate binary file 1/0 formats and use them in applications + Modify existing code for improved usability + Prepare, build, and deploy stand-alone applications You will apply these concepts as you build a project that uses VIs you create throughout the course, While these VIs individually illustrate specific concepts and features in LabVIEW, they constitute part of a larger project built throughout the course. This course does not describe any of the following: + LabVIEW programming methods covered in the LabVIEW Core 1 course + 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 class; refer to the NI Example Finder, available by selecting Help»Find Examples, for example Vis you can use and incorporate into VIs you create vi icon ‘Suident ove F. Course Conventions italic monospace monospace bold The following conventions appear in this course manual The » symbol leads you through nested menu items and dialog box options to a final action, The sequence Tools»Instrumentation»Find Instrument Drivers directs you to drop down the Tools menu, select the mn item, and finally select the Find Instrument Drivers This icon denotes a tip, which alerts you to advisory information. ‘on denotes a note. which alerts you to important information, This icon denotes a caution, which advises you of precautions to take to avoid injury, data loss, or a system crash. This icon indicates that an exercise requires a plug-in DAQ device. Bold text denotes items that you must select or click in the software, such as menu items and dialog box options. Bold text also denotes sections of dialog boxes and hardware labels. Italic text denotes variables, emphasis, a cross-reference, or an introduction toakey concept. Italic text also denotes text that is a placeholder fora word ‘or value that you must supply. Text in this font denotes text or characters that you should enter from the keyboard, sections of code, programming examples, and syntax examples. This fontis also used for the proper names of disk drives, paths, directories, programs, subprograms, subroutines, device names, functions, operations, variables, filenames, and extensions, Bold text in this font denotes the messages and responses that the computer automatically prints to the screen. This font also emphasizes lines of code that are different from the other examples. (© Notional istuments Corporation ® Labiew aore 2 Cewcises eeUeuUevVervovOovuUDdoeocose st PIB, Synchronization Techniques Exercise 2-1 Concept: Comparing Queues With Local Variables Goal In this exercise, you run and examine a prebuilt producer/consumer design pattern VI that tra s data generated by the producer loop to e consumer loops using local variables and qui Description 1. Open S vs Local V les.vi inthe and clears reference to the queue. fH ‘The Simple Error Handlerto the right of the Release Queve function reports Hy any error at the end of execution. Local Variable’s Consumer Loop ‘The Producer Loop generates sine wave data and writes it to a local variable while the Local Variable’s Consumer Loop periodically reads out the sine ‘wave data from the same local variable. The Points Difference VI inside the Local Variable’s Consumer Loop outputs the number of missed points or number of duplicate points read out. Switch to the front panel of this VI 1. Select the loop time speed of the Local Variable’s Consumer Loop and observe the Local Variable’s Consumer Loop waveform graph and the results generated on the Duplicate Points indicator. Ensure that the Loop Speed selected is Same as Producer Loop and observe the waveform graphs for both the Producer Loop and the Local Variable’s Consumer Loop. A race condition may occur resulting in missed points or duplicated data. (© Nationa/ instruments Corporaton 23 LabUIEW Core? Berises Lesson 2 Snetrontaton Tectnoues Select Maximum Speed from the pull-down menu of the Loop ‘Speed control and observe the waveform graph of the Local Variable’s Consumer Loap. A race condition occurs because data is consumed faster than itis produced, allowing the local variable to read the same value multiple times. Select 1/2.as Producer from the pull-down menu of the Loop Speed control and observe the waveform graph of the Local Variable’s Consumer Loop. A race condition occurs because data is produced faster than itis consumed. The data changes before the local variable has a chance to read it. Select the remaining options available from the pull-down menu of the Loop Speed control and observe the data retrieval. y Stop the VI. Data transfer between two non-synehronized parallel loops using local variables causes a race condition. This occurs when the Producer Loop is writing a value to a local variable while the Local Variable’s Consumer Loop is periodically reading out the value from the same local variable, Because the parallel loops are not synchronized, the value can be written before it has actually been read or vice versa resulting in data starvation or data overflow. Queue's Consumer Loop 1. Run the VI. Select the loop time speed of the Queue’s Consumer Loop and observe the Queue’s Consumer Loop waveform graph and the results generated on the # of elements in queue indicator. \W Ensure that the Loop Speed selected is Same as Producer and observe the value of the # of elements in qucuc indicator. The value should remain zero, Hence with queues, you will not lose data when the producer and consumer loops are executing at the same rate, Sclect Maximum Speed from the pull-down menu of the Loop ‘Speed control and observe the value of # of elements in queve. The value should remain zero. Hence with queues, you will not lose data if the consumer loop is executing much faster than the producer Loop. Labview Gore 2 beercses at com lesson 2 Synenronzation Yecinques O Select 1/2 as Producer from the pull-dowa menu of the Loop Speed control and observe the value of # of elements in queue. The data points will accumulate in the queue. You will need to process the accumulated elements in the queue before teaching the maximum size of the queue to avoid data loss. 2 Select the remaining options available from the pull-down menu of the Loop Speed control and observe the synchronization of data transfer between the producer loop and the consumer loop using queues. Stop the VI, When the Producer Loop and Queue’s Consumer Loop mun at the same speed, the number of elements in the queue remains unchanged. When the Queue’s Consumer Loop runs slower, the queue quickly backs up and the Producer Loop must wait for the Queue Consumer ILoop to remove the elements, When the Queue’ Consumer Loop runs faster, the queue is quickly emptied and the consumer loop must wait for the Producer loop to insert elements. Hence queues synchronize the data transfer between the two independent parallel loops and thus avoid loss or duplication of data. 3. Close the VI. Do not save changes. End of Exercise 2-1 © Nationa tnstuments Corporation 2 anew Gore2 bxeroses Lesson2 — Synotronzation Tetniques Notes Lab eW Core? Eros 26 icon Event Programming Exercise 3-1 Concept: Experiment with Event Structures Goal Experiment with the operation of the Event structure in a VI. Description Use and modify a VI that contains an Event structure. (© Nationa’ insturertsGorporanon Open the NI Example Finder. U Select Help»Hind Examples. Open the New Event Handler VI example. Navigate to Building User Interfaces» Acquiring User Input» General and double-click New Event Handler.vi. . Close the NI Example Finder, Enable execution highlighting on the block diagram. Run the VI. Observe the operation of the VI when you click the buttons on the front panel. Stop the V1. Disable execution highlighting. Modify the VI to respond to a Value Change event with a new control on. the front panel, Switch to the front panel of the VI Create a copy of the Boolean button on the front panel 1 Change the button text and label of the button to New Button. o Right-click the new bution and verify that the Mechanical Action is set to Latch When Released. + LabVIEW Core? Exercises Lesson Even Progamming Switch to the block diagram of the VI. Right-click the border of the Event structure and select Add Event Case from the shortcut menu to open the Edit Events dialog box. O Select New Button in the Event Sources section and select Vs ‘Change in the Eyents section as shown in Figure 3-1. |Wote: Handing 2 Value Changed event an a Laced Boolean wilnct adtomancally tans its ‘eda orn. You tread he Boseas Tend More Tort coecly rece Coo) Coon) Ce] a0vieW Gore2 exercises Figure 3-1. New Button Value Change Event Click OK to create the new Event case structure, Q Place the New Button control in the New Button event case, Q Adda One Button Dialog function in the New Button event case and wire a string constant to the message input. Set the string constant to New Event Case, Wire the Time Waveform daia through the case. Q. Wire a False constant to the Boolean tunnel. a2 icon Lesson 3 Event Propranning U Run the V1 und click New Button. A dialog box should open and display the New Bvent Case message. A Stop the VI. 10. Modify the Event structure to add a Filter Event to discard the Panel Close event. Right-click the Event structure and select Add Event Case from the shortcut menu to open the Edit Events dilog box. D Select in the Event Sources section. Select Panel Close? from the Events section and click the OK button. Wire a True constant to the Diseard? Event Filter Node in the Panel Close? case. G1 Wire the Time Waveform data through the case 2 Wire a False constant to the Boolean tunnel. 11. Run the VI 12, Attempt to close the VI by closing the front panel, 13, Click the STOP button to stop the VI 14, Open the NI Example Finder. 15, Open the Old Event Handler VI example. 1 Navigate to Building User Interfaces» Acquiring User Input» General and double-click Old Event Handler.vi. 16, Enable execution highlighting on the block diagram, 17, Run the VI 18, Observe the operation of the Old Event Handler VI and compare and contrast the operation with the New Event Handler VI. 19, Close all Vis without saving changes. End of Exercise 3-1 (© Nite instruments Corporation cd Labiiew Gore Brecises Lesson Event Pogramming Exercise 3-2 Goal Scenario Design Create a Print Queue Console Use the Produces/Consumer (Event) template to ereate a print queue console that submits print jobs to 4 printer and monitors the print queue, ‘You must create a print console VI that controls print job submissions and monitors the processing status of the print jobs. Each time the userclicks on the Queue Eyent bution, a print job will be seat to the printer. You will monitor the number of print jobs in the queve using a vertical bar. LEDs will indicate the print processing status. The print process for each job includes two steps—an initialization stage with a fixed duration of 300 ms and a print stage with a varying duration based on the size of the job. ‘The controls and type definition enums necessary for this project are already created. Your task is to use the Producer/Consumer design pattem template that ships with LabVIEW to create the print console VI. Table 3-1 lists the controls and indicators used in the front panel of the print console VI, Table 3-1. Front Panel Controls/Indicators and Descriptions Controls/Indicators Description ‘Queue Event button Each time the user clicks on this button, « print job is sent to the printer. ‘Queued Print Jobs bar | This bar displays the number of print jobs that are currently in the print queue. Bach time a print job is sent to the printer, a new job is added to the queue. When the printer starts a new job, the print job is removed from the queue, Waiting LED This LED is tumed on only when there are no print jobs in the queue. Initializing LED ‘This LED is tumed on for the duration of the setup stage for each print job. Printing LED ‘This LED is turned on for the duration of the print stage for each print job Stop Button This button stops the VI. LabVIEW Core? Exercises a com Lesson Eve Progamming Table 3-2 lists the Event cases you will implement in the producer loop. Table 3-2. Producer Loop Event Cases Event Case Case Deseription Engueue Element!0: Value Change In this case, you use the Enqueue Element function to queue a string constant with the value of print job Stop: Value Change In this case, you stop the While Loop. Timeout In this case, you use the Get Queue Status function to get the number of elements in the queue. You pass the value to the Queued Print Jobs bar. ‘Table 3-3 lists the states you will implement in the consumer loop state machine. Table 3-3. Consumer Loop States State State Description Wait ‘You perform the following tasks in this state. Use the Dequeue Element function to wait for a queued print job. Set the Dequeue Element function to timeout for 100 ms. Set the next state to be the Wait state, if the Dequeue Element function times out, Set the next state to be Initialize Setup, if the Dequeue Element function does not time out. Set the Waiting LED to True. Initialize Setup | You perform the following tasks in this statc. Set the Waiting LED to False. Set the Initializing LED to True. ‘Transition to the Setup state, Setup ‘You perform the following tasks in this state, Simulate print setup with a 300 ms wait, Set the Initializing LED to False. Print state. Transition to the In © national mstumerts Corperavon 3 LabVIEW Core? Exercises lasson3 Event Programming Table 3-3. Consumer Loop States (Continued) State State Description Initialize Print] You perform the following tasks in this state. + Set the Printing LED to True ‘+ Transition to the Print state Print ‘You perform the following tasks in this state. + Simulate the print job using a variable wait time * Set the Printing LED to False. + Transition to the Wait state, Implementation BZ Note To reinforce the development skills you have learned so far, you are given limited instructions to create the application, LatVvEW Core 2 Bercises Create a New Vi From a Template 1. Open Print Console. vproj inthe \ uabVIEW Core 2\print Console directory. 2. Create a new VI using the Producer/Consumer Design Pattern (Events) design pattern & Select File»New to open the New dialog box. Select From Template» Frameworks»Design Patterns» Producer/Consumer Design Pattern (Events) and click OK. 3. Select Files VI Properties»Documentation. In the VI description section, replace the template documentation with a concise description of your application. 4, Create « meaningful icoa for the VI. 5. Save the VIas Print Coneele.vi in the \ LabVIEW Core 2\Print Console directory, Confirm that the new Vlis added to the Print Console. Ivpred project. 6. Save the Print Conole.1vproj project. 38 com Lesson 3 Bien Programming Create the Front Panel Create the front panel as shown in Figure 3-2 using the Queued Print Jobs.cti and the Print LEDs.cti available in the Print Console. 1yproj project. 1 _ Already created in Print Console Ivproj Figure 3-2. Print Console Front Pane! Producer Loop Complete the block diagram by first modifying the producer loop and then modifying the consumer loop. The producer loop responds to front panel events. Each time the user clicks the Enqueue Element button, a print job is added to the queue. The producer loop is also responsible for updating the Queued Print Jobs bar with the number of elements in the queue. © Netiona nstumets Corporation w Labview Core 2 Exercises ‘Lesson 3 Event Programming Figure 3-3 and Figure 3-4 are examples of the completed producer loop Figure 3-3. Producer Loop—Enquaue Element Case 1. Inthe Enqueue Element case, replace the element string with print job in the Engueve Element function. 2. Add a Timeout case to the Event structure, The Timeout case updates the Queued Print Jobs bar by reading the number of elements in the queue. Select in the Event Sources section and select ‘Timeout in the Events section, BZ Note 1 the Event Data Node label is invalid (black tex1), right-click the label and select avalid one. BZ Note Because the Timeout case is an application event, the Event Selector label at the top of the Timeout case differs from other events associated objects. The label name only specifies the event and does not include the associated object. LabVIEW Core 2 Borcises 38 aloo Lesson 3 vent Programming queue Rope the convurve feos) x at Queues Pt obs — Figure 3-4. Producer Loop—Timeout Event Case 7 Add a Get Queue Status function to read the number of elements in as the queue. @ Set the Event structure to time out every 100 ms by wiring a constant value of 100 to the Timeout terminal. EY Note You do not need to make any changes to the Stop case as it already exists in the template. Consumer Loop ‘The consumer loop simulates the print process and updates the LEDs. Implement the print process using a state machine. The Wait state receives print jobs. When a print job is received, the state machine initiates a series of steps to simulate the print process. The Print LEDs update after each state. Therefore, the Initializing LED turns on after the Initialize Setup state and turns off after the Setup state. Similarly, the Printing LED tums on after the Initialize Print state and turns off after the Print state, (© National rstiments Corperation 39 Labview cone 2 Breese Lesson Even Programming Figures 3-5 through 3-9 are examples of the completed consumer loop. 1, Create a state machine in the consumer loop by starting with the Wait state. The Wait state receives print jobs using the Dequeue Element function. If the Dequeue Element function receives a queue element within the specified 100 ms timeout the state mac! transitions to the Initialize Setup state. If the Dequeue Element function times out, the state machine stays in the Wait state: [This ep 8 consumerlowp. aa J Thepintquene twesou) Elbiitee Soy Drei tDs 1 Already created in Print Console lupro) Figure 3-5. Consumer Looo—Wait Case The print processing states type definition enum is created for you. Select and drag the Print Processing States.etl from the Project Explorer window onto the block diagram. O Wire the Print Processing States.ctl to the Case selector to associate the Case structure with the enum values. =e O Move the Dequeue Element function into the Case structure, Use the timed out? output of the Dequeve Element function to determine if the next state is the Wait state or the Initialize Setup state. Add a Bundle by Name function to set the Boolean state of the Waiting LED. Drag the Print LEDs.ctl from the Project Explorer window onto the block diagram to create a Print LEDs cluster constant on the block diagram. LABVIEW Core 2 Bercises #0 com Lesson Even Progamming 2. Refer to Figure 3-6 10 create the Initialize Sewp case. Figure 3-6, Consumer Loop—tnitialize Setup Case 1 To create cases associated with each of the enum values, right-click the edge of the Case structure and select Add Case for Every Value. @ Th _Atematively. you can also create new cases by duplicating existing cases. ‘To duplicate a case, right-click the edge of the Case structure and select Duplicate Case. Be careful when duplicating cases that include front panel terminals as this will result in duplicated fromt panel objects. Right-click on the error tunnel and select Use Default if Unwired. 3. Referto Figure 3-7 to create the Setup state. [irubte prntsep [its ed 300s watts Figure 3-7. Consumer Loap—Setup Case Simulate the initialization duration with a 300 ms wait, © National isturvents Corporation on LadEW Gore? Braces Lesson Even Programming 4, Refer to Figure 3-8 to create the Initialize Print state. Figure 3-8. Consumer Loop—initialize Print Case 5, Refer to Figure 3-9 to create the Print state. [oH als [Srubeevenina pant dortar] Est nang wate Figure 3-8. Consumer Loop—Print Case G To simulate a varying print duration, generate a random wait time between 300 ms and 1500 ms. Use the Random Number in Range Vi found in your print Console. 1vproj tw seta random wait duration for a print job. 6. Save the VI and save the Print Console. 1vproj project. LabVIEW Core 2 cses a2 com Lesson 3 Event Programing Test 1. Ran the VI to confirm that it behaves correctly. Each time you click the Queue Event button, a new print job is submitted to the print queue. If you submit several print jobs in succession, you will see a backlog of print jobs in the Queued Print Jobs bar. Notice that after you stop queueing the print jobs, the print process continues to execute. Notice that the consumer loop stops only when there is an error. This ‘occurs when the producer loop stops and the Release Queue function destroys the queue reference. Without a valid queue reference, the Dequcue Element function in the consumer loop returns error code 1122 with an explanation of Refmum became invalid while node waited for it orancrrorcode 4 with an explanation of An input parameter is invalia (if there are elements left in the queue when you press stop). Stopping a consumer loop on ertor is relatively easy to implement but isnot recommended when ereating professional applications that are scalable and maintainable. A better approach is to shut down gracefully and report all errors to the user- 2. Close the VIs and project. Save any changes. End of Exercise 3-2 (© aon stuns Corporation a8 LabVIEW Care 2 Exercises Lesson Bett Pogtaniming Notes LaNVIEW core 2 Brercses a4 com Error Handling Exercise 4-1 Goal Scenario Design Updating the Print Console With Error Handling Update a VI to report errors and include a shutdown state You begin with « Print Console VE that simulates the control of print job submissions and monitors the status of the print jobs being processed. Each time you click the Queue Event button, you send a print job to the printer. You monitor the number of print jobs in the queue using a vertical bar. You use LEDs and a numeric indicator to monitor the process of the print jobs. The Print Console VI does not report errors. You must update the VI to report potential errors and warnings. You must also complete a shutdown procedure after the last print job. ‘To implement error reporting, you must do the following. Use shift registers to monitor and track errors and warnings for all loop iterations. Use the Merge Errors funetion to obtain error information from both the producer and consumer loops, Use the Simple Error Handler V1 to display both errors and wamings. Q_ Use an error handling VI that causes the state machine to execute the shutdown case when an error occurs or when the producer loop sends a shutdown message. © nétionalinstuments Corporation # Lavo w Core? Exercises Lesson ror Henating Implementation “LatVIEW Core 2 bxeroses 1, Open Print Console with Error Handling. 1vpros in the \LabVIEW Core 2\Error Handling directory. Figure 4-1. Front Panel of Print Console 2. Open and run the Print Console V1. The front pane! of this VI is shown, in Figure 4-1, (Each time you click the Queue Event button, you add a print job to the queue. The Queued Print Jobs bar displays the backlog of print jobs. (1 When there are no print jobs in the queue, the Waiting LED is turned ‘on, When each print job is processed the Job Number indicator is updated to show the number of print jabs that have been processed. The Initializing LED is turned on during print initialization and the Printing LED is turned on during the print operation. D1 Click the Stop button. 3. Examine the block diagram. Notice that none of the errors are reported to the user, (Notice that the consumer loop stops only when there is an error. This, ‘occurs when the producer loop stops and the Release Queue function destroys the queue reference. Without a valid queue reference, the Dequeue Element function in the consumer loop retums error code 1122 with an explanation of Refnum became invalid while node waited for it. lesson 4 kiror Ranting Error Handling in Consumer Loop 1. Modify the block diagram as shown in Figure 4-2 to report errors. a ‘avec Figure 4-2. Block Diagram with Error Handing in Consumer Loop % Wire the error cluster of the Obtain Queue function to the consumer at While Loop. Replace the error tunnel on the While Loop with a shift register. Wire the error cluster from the left shift register to the error in input of the Dequeue Element function, Wire the right-side error tunnel to the right shift register. In the Initialize Setup case, wire the left-side crror cluster tunnel to the error in terminal of the Scan from String function. 3. Forall the remaining cases, wire the lefi-side error cluster tunnel to the right-side error cluster tunnel (© netionatistuments Corporation + anew Core? Exercises Lesson 4 roy Handing Merge and Report Errors Ee 1. Add a Merge Errors function. ea 2. Add a Simple Error Handler VI. Right-click on the type of dialog terminal of the Simple Error Handler VI and select Create»Constant. Select OK Message + warnings. EY Note By defauli, the Simple Error Handler VI only displays a dialog when an error occurs. To report both wamings and errors, change the dialog selection to OK Message + warnings. 3. Complete wiring the Merge Errors function and the Simple Error Handler VI as shown in Figure 4-3, ra | ena ———1 Iecomee oon ag 5) Gant Figure 4-3. Block Diagram with Merge Errors Function and Simple Error Handler VI LaDVIEW Core 2 Exercises 44 com tesson4 — Evor Handing 4, Run the VL Notice that the VI does not stop when you click the Stop button. You must stop the VI using the Abort button. 5. Examine the block diagram. 1 Notice that the Merge Errors function cannot execute until both the producer and consumer loops terminiate. Therefore, the Release Queue function cannot destroy the queue reference that the consumer Loop relies on to stop the loop. Moving the Release Queue function before the Merge Errors function will cause the consumer Joop to stop. However, relying on an error to stap the loop will cause the Simple Error Handler VI to report an error every time the VI runs, You will fix this when you modify the Shutdown siate in the consumer loop. Add an Error Handler VI 1, Modify the diagram as shown in Figure 4-4 so that the consumer loop executes the Shutdown case when the producer loop stops or when there is an error in the consumer loop. a Figure 4-4. Block Diagram with Printer Error Handler VI (© Nasioainstraments Corporavon 45 LabeW Gere 2 Exercises Lessond Eno Handing Modify the producer loop to include a shutdown element at the front of the queue when the user clicks on the Stop button, — In the Stop event case, add an Enqueue Element At Opposite i End function. ~ Right-click the element input of the Enqueue Element At Opposite End function and select Create»Constant from the shortcut menu. — Type Shutdown in the string constant, FQ Note The text in this string constant is case sensitive. Lab MEW Gore? beercses np ~ Wire the Stop event case as shown in Figure 4-4. Modify the consumer loop to stop after executing the Shutdown case. ~ Delete the error wire from the right-side error tunnel to the While Loop conditional terminal — Add a true constant to the Shutdown case diagram, — Wire the True Constant to the While Loop conditional terminal. — Right-click on the Boolean tunnel and select Use Default if Unwired. Modify the consumer loop to execute the Shutdown case when it receives the Shutdown element in the queue. — Drag the Printer Error Handler VI from the subvis folder of the Print Console with Error Handling LabVIEW project and place it in the consumer loop. — Wire the consumer loop as shown in Figure 4-4, Double-click the Printer Error Handler VI to open the VI. Examine the block diagram of the Printer Ervor Handler VI. Q Notice that the Next State is the same as the State In, except when the error in cluster contains an error or the Queue Data value is equal to Shutdown. IF there is an error ora Shutdown match, the neat state is Shutdown. 46 ico Test (Optional) Lisson 4 Error Manns 4. Close the Printer Error Handler V1. 5. Switch to the front panel of the Print Console VI. 6. Save and run the Print Console VI. Notice that the VI stops when you click the Stop button and no error is reported Although the VL appears to work as you expect, you should force errors and warnings to test your error handling. Time permitting, try inserting errors and warnings in your code and running the V1 to test the error handling. You can force errors by breaking one of the error wires and replacing it with an Error Code Constant that has the status and code values set for an error or warming. Do not save your VIs with forced errors. End of Exercise 4-1 (© Nationa mscements Coxporaion 7 Lan VIEW oor 2 Exercises asso Bron Henaing Notes LatVEW core 2 Bxrcses “8 incom Controlling the User Interface Exercise 5-1 Display Temperature and Limits Goal Use Property Nodes to change the properties of front panel objects programmatically: Scenario Complete a V1 that records temperature to a waveform chart. During execution, the VI performs the following tasks: + Set the Ax value of the chart to the user-defined value, * Clear the waveform chart so it initially contains no data. * Change the color of a plot if the data exceeds a certain value. * Blink an alarm indicator if the data exceeds a certain value. Design ‘Add the following Property Nodes to an existing VI: Type ‘Name Property Waveform Chart ‘Temperature | XScale.Multiplier Waveform Chart Temperature | History Waveform Chart Temperature | Active Plot O»Plot.Color Boolean Indicator (LED) | Over Limit | Blinking (© Navona nstuments Corporation st LaDVIEW Core2 Exercises Lesson Cantoling ine User nertace Implementation t.vi located in the \ ature Limit directory, The front panel is 75 wo Ke 190 175 20 Figure 5-1. Temperature Limit Front Pane! 2. Open the block diagram of the VI. A portion has heen created for you Figure 5-2 shows an example of the final block di >_< Figure 5-2, Temperature Limit Block Diagram 3. Modify the VI so thatitsets the Ax value of the chart to the Ar (ms) value input by the user 1 Right-click the Temperature indicator and select Create» Property Node>X Scale»Offset and Multiplier» Multiplier from the shortcut menu to create a Property Node. LatneW Care 2 Exerc 4 Lesson'5 —Gontotiog the User nertace Place the new Property Node to the left of the While Loop. Right-click the Temperature Property Node and select Change All a To Write from the shortcut menu. Divide delta t (ms) by 1000 to determine the X-Scale Multiplier, as shown in Figure 5-2. Modily the Vito clear old data from the Temperature chart before starting the temperature acquisition. Tip To clear a waveform chart from the block diagram, send an empty array of data to the History Data property. (© niaonalrsteumerts Corporaion Resize the Property Node to two terminals, oa o o a Select the History Data property in the second terminal Verify that the History Data property is set to Write. Right-click the History Data property and select Create»Constant from the shorteut menu. Wire the Property Node as shown in Figure 5-2, Modify the VI so that when the VI acquires data, it turns the Data trace red and the Over Limit LED blinks when the temperature exceeds the limit value. a oo o @ a Right-click the Temperature indicator and select Create» Property Node»Active Plot from the shortcut menu to create another Property Node. Place the new Property Node in the True case of the Case structure. Res ze the Property Node to show two terminals. Click the second terminal and select Plot»Plot Color. Right-click the Property Node and select Change All To Write from the shortcut menu, Wire a numeric constant with a value of 0 to the Active Plot property to select the first plot on the Temperature chart, Wire the Red color box constant to the Plot Color property to set the plot color to red when the data rises above the High Limit. +8 LabieW Gore 2 Creveses Lesson Contoling te Use inetace Create a copy of the Property Node by pressing while selecting and dragging the Property Node. @ Tip Donor use the clipboard (Edit»Copy or ) to create a copy of the Property Node. This creates a different type of Property Node that you lear about in the Control References section of Lesson 5, Conirolling the User Interface, in the LabVIEW Core 2 Course Manual. Test anviEW Gore 2 bxercses Place the copy of the Property Node in the False case of the Case structure, as shown in Figure 5-3, Wire a numeric constant with a value of 0 to the Active Plot property to select the first plot on the Temperature chart Wire the Green color box constant to the Plot Color property to set the plot color to green when the data is helow the High Limit Figure 5-3, False Case in the Temperature Limit VI 6. Modify the VI so that when the VI acquires data, the Over Limit LED blinks when the temperature exceeds the limit value. QO Right-click the Over Limit indicator and select Create»Property Node»Blinking from the shorteut menu. Place the new Property Node inside the While Loop. OD Right-click the Property Node and select Change All To Write from the shortcut menu. Q Wire the Property Node as shown in Figure 5-2. 7. Save the VL 1, Run the VI to confirm that it behaves correctly. 2. Close the VI. End of Exercise 5-1 cS ‘icon Exercise 5-2 Customizing the VI Window Goal Lessons controling te User mertace Affect the attributes of a VI by using Property Nodes and Invoke Nodes. Scenario You can set the appearance properties of a VI statically by using the VI properties page. However, robust user interfaces often must modify the appearance of a front panel while the program runs. ‘You must create a VI that can perform the following tasks on demand: «Show or hide its title bar + Show or hide its menu bar + Become transparent so that objects behind the VI can be seen + Move to the center of the sereen Design Inputs and Outputs ‘Type Name Default Value Push Button | Show Menu Bar? “True Push Button | Show Title Bar? ‘True Push Buton | wake VI Transparent? ‘True OK Button center False Stop Button | stop False Tip Use the Push Buttan controls because their default mechanical action is Switch ‘When Pressed. Use the OK bution because its default action is Latch When Released. © national nsteuments Corporation 24 LADVIEW Core 2 Exercises Lesson’3 Contig the User mertace Properties Use the following properties and methods on the VI class: + ShowMenuBar—When this property is true, the menu bar of the VI is Bie Edt Wew Project Operate Tooe Window Help] Figure §-4. Vi Menu Bar + TitleBarVisible—When visible. property is true, the title bar of the VI is eles) |G Front Panet Properties.vi Front Panet Figure 5-5, VI Title Bar + RunViTransparently—When this property is true, the transparency of the VI can vary. The default value of this property is false, so you must write a true value to this property before varying the transparency of the VI. + Transpareney—This property varies the transparency of the VI. The property accepts any value between 0 and 100. A value of O makes the Vi completely opaque (normal behavior), and a value of 100 makes the ‘Vicompletely transparent (invisible). For this exercise, you set the value to 50 when the Make VI Transparent? button is clicked, Methods Unlike properties, a method has an effect every time you call it, Therefore, you should call methods only when you want to perform an action. For example, if'you call the Fp.Center method during each iteration of a loop, the VIis continually centered, thereby preventing the user from moving it. You can use a Case structure to control calling the method in a given iicration of a loop. Use the following method on the VI class: + Center—Each time this method is called, the VI moves to the center of the screen. @ Tip Use the Context Help window to view descriptions of each property and method. LaOvIEW Gore 2 Bxrases VI Structure ‘The V1 polls the front panel controls every 50 ms and sets the value of the properties based on the current value of the controls. A Case structure controls the execution of the Center method. 26 nico Lesson Coating the User Iertoco Implementation 1. Open the Customize VI Window VI from \ LabVIEW Coxe 2\Customize VI Window directory. The front panel of this VI is shown in Figure 5-6, Figure 5-6. Customize V| Window VI Front Panel Complete the following steps to create the block diagram as shown in Figure 5-7. Figure 5-7. Customize VI Window Block Diagram a —_ Figure 5-8. False Case for Center Method 2. Add a While Loop around the terminals, 3. Create a reference to the VI. een G Add a VI Server Reference to the block diagram to the left of the While Loop. Set the VI Server Reference to This VI if it is not already. ‘© patina astureas Corporation or LABVIEW Core? Gercises Lesson 5 Contoling tte User netace JB Nete_Using the This VI reference you can access all the methods and properties ofthe current VI without having to explicitly open and close a reference. aoview Gove 2 Erercises 4. Create a Property Node with the RunTransparently property. A Right-click the This VI reference and select Create»Property for VI Clays>Front Panel Window»Run VI Transparently from the shortcut menu to create a Property Node. A Move the Property Node to the right of the This VI reference, outside of the While Loop. Right-click the Property Node and select Change All to Write fram the shortcut menu. OF Right-click the FP:RunTransparently property and select Create» ‘Constant from the shortcut menu. Change the value of the constant to True. Create a Property Node with the ShowMenuBar, TitleBarVis, and ‘Transparency properties. C1 Right-click the This VI reference and select Create»Property for YI Class»Front Panel Window»Show Menu Bar from the shortcut menu to create another Property Node. Expand the Property Node to show three elements. Q Click the second item in the Property Node and select Front Panel WindowTitle Bar Visible. Click the third item in the Property Node and select Front Panel Window»Transparency, OF Right-click the Property Node and select Change All to Write from the shortcut menu, Move the Property Node inside the While Loop. Adda Select function inside the While Loop. Q Add two numeric constants with values 0 and 59 10 the left of the Select function. Wire the 0 numeric constant to the f input of the Select function. Q Wire the 50 numeric constant to the t input of the Select function, Wire the Boolean controls to the appropriate properties, as shown in Figure 5-7. 38 neon Test Lesson 8 Gontantg he User mteitace 6. Create an Invoke Node with the Center method. 1 Right-click the This VIreference and sclect Create»Method for VI Class»Front Panel» Center from the shortcut menu to create an Invoke Node, 7, Add a Case structure around the FP.Center Invoke Node. 8. Add a SO ms wait to the loop. Q Add a Wait (ms) function to the While Loop. Q Right-click the milliseconds to wait input and select Create» Constant {rom the shortcut menu. Q Enter 50 in the constant. 9. Set the While Loop to stop when the user clicks the Stop button or when an error oceurs. O Add an Unbundle By Name function to the While Loop. Add an Or function to the While Loop. 10, Wire the diagram as shown in Figure 5-7 and Figure 5-8. Make sure to replace the error cluster tunnel with a shift register: 11. Display any errors that may occur to the user. Add a Simple Error Handler VI to the right of the While Loop. Q Wire the Simple Error Handler VI to the error cluster output shift register from the While Loop. 12, Save the VI. 1. Switch to the front panel window of the VI. 2. Runthe VI. 3. Try each of the buttons and observe the results, End of Exercise 5-2 © nesta! rstauments Corperaton 9 Lab VEW Core? Erecses Lasso § Ganong te User Inetace Exercise 5-3 Goal Scenario LabVIEW Core 2 Ererises Set Plot Names Use control references to create a subV1 that modifies graph or chart properties. Create a subVI that allows you to assign a list of plot names to a chart or graph. The subVI should resize the plot legend as necessary to display all of the plots. Inputs and Outputs Type Name Default Value Control Reference toa GraphChart | Graph N/A object Reference 1-D Array of Strings Control Plot Names | Empty Array Entor Cluster Control Error In No Envor Error Cluster Indicator Error Out No Error Control References Both the Waveform Chart and the Waveform Graph are objects in the GraphChert class, To write a subVI that can accept references to both charts and graphs you must use a weakly typed control reference of the GraphChart class. However, this class also contains other charts and graphs, such as the XY Graph. This subVI generates an error if the user wires any type of graph other than a Waveform Chart or a Waveform Graph. You can determine if the user has wired the correct type by using the ClassName property to control a Case structure. If the correct class is wired, use the ‘To More Specific Class function to get a reference to the appropriate subclass, After you have a reference to a WaveformChart or a WaveformGraph you ean set the properties to modify plot names. o10 i.com Implementation Lesson 5 Contoting the User Iretace Properties Graphs and charts do not have a single property to set all of the plot names. Instead you must use a combination of properties to set cach plot name. In this exercise, use the following properties: + ClassName—This property retums a string indicating the control class of the object that the property is called on, You can access this property for any control. + LegAutosize—This property controls whether the Graph Legend automatically resizes to accommodate the plot names within it. Before modifying the plot names you should set this property to False. Otherwise, the legend may resize in such a way that it is separated from the graph or covers the graph or other controls + LegNumRows—This property controls the number of rows visible on the Graph Legend, When adding your legend to the front panel, remember to leave room for the legend to expand when you set this property. The legend expands downwards, + ActPlot—Properties affecting a plot act on one plot at a time. This property controls the active plot. Any time a plot property is set or read it applies to the active plot. The plots are numbered sequentially as they are created, starting with zero. + Plot.Name—This property sets the name of the active plot. 1, Opena blank VI. Save the Vas Set Plot Names.vi in the \ LabVIEW Core 2\set Plot Names directory. 3. Create the front panel window. Add a control refiaum to the front panel window. Q Name the control refnum Graph Reference. O Right-click Graph Reference and choose Select VI'Server Class» Generic»GObject»Control»GraphCharb»GraphChart from the shorteut menu, Add an array to the front panel window. Name the array Plot Names. (© Auton nstourents Corporation on LABVIEW Core 2 Gercses Lesson Contig the User interface ie 4 Place a string control to the empty Plot Names array. Add an error in cluster. O Add an error out cluster. [FF] Q Arrange the controls as shown in Figure 5-9. Figure 5-9. Set Plot Names Front Panel @ Tip. Because the front panel of this subVI is not displayed to the user, you do not have 10 put as much effort into making it visually appealing. You should always organize your front panels logically. However, you should not spend too much time on panels that the user does not see, 4. Switch to the block diagram. 5. Identify the class of the control reference and generate an error if it has an invalid class. Use the Class Browser to find and drop the ClassName Property Node. — Open the Class Browser dialog by selecting View»Class Browser, — Select VI'Server for the Object Library. = Select Generic»Generic for the Class. @ — Click the Search button to open the Class Browser Search dialog box. LaDViEW Core 2 ereses ae incom Lassan'5Contreling te User irises SS yp tbe mo sed For sane seahrenuts ene Geshe SS ebictetedipley % spervtta eration Rethotsy tore Search scope Ocenmtecas OA cavesin be Server Figure 5-10. Class Browser Search Dialog = TypeClass Name in the search field. Class Name should be the only item in the Search results. — Select Generic class in the Search Scope section, (© Nata lstnuments Copraion 513 LabVIEW Core 2 varios Lessons Contoting te User taetase Click OK toreturn to the Class Browser dialog box. Class Name is highlighted in the Properties and Methods tree. ca dens os 8a Properties ancethods ‘Gass Specir Cora es = Prorertes a (eel Coe) oe Figure 5-11. Class Browser Dialog Box Click the Create button and then move your mouse to an empty area on the block diagram. Click on the block diagram to drop the ClassName Property Node, — Close the Class Browser dialog box. LavVEW Core 2 Bxerses it nico a Lesson Gortraling the User imetace ‘Wire Graph Reference to the reference input of the Property Node. (© National testurnents Corporation Figure §-12. Default Case Add a Case structure to the block diagram, as shown in Figure 5-12. Wire the ClassName output of the Property Node to the case selector of the Case structure. Switch to the False case of the Case structure, 2 Delete the False text in the case name so that the case mame resembles Figure 5-12, The Default case of the Case structure is selected if the class of the control reference dogs not match one of the other cases. In this case, If the default case executes, then the control reference passed to this subVIis not a WaveformGraph or a WaveformChart, Remember for a Case structure, the case selector label is case sensitive. Q Add an Error Cluster From Error Code VI to the Case structure. Q Right-click the error code input of the Error Cluster From Error Code VI and select Create»Constant from the shortcut menu. Enter 1057 in the constant. Error code 1057 corresponds to the message Object cannot be typecast to the specified type. This is the appropriate error to generate if the caller of the subVI passes a control reference of the wrong class. Wire the block diagram as shown in Figure 5-12. 515 Lab MEW Core? Brercio sson’S Centon te User erase 6. Handle the WaveformGraph references. SisphReferance f=womn 9 faaraa mee fon Figure 6-13. WaveformGraph Case Switch to the True case of the Case siructure. (0 Change the ‘True text in the case name to WavefornGraph so that the case name resembles Figure 5-13. LX Caution The text entered the case selector label must exactly match the input string, including spaces and case, For this example, enter Waveformsraph. U2 Add a To More Specific Class function to the Case structure. Right-click the target class input of the To More Specific Class function and select Create» Constant from the shorteut menu, (2 Click the constant you created in the previous step and select the Generic» GObject»Control»GraphChart» WaveformGraph> WaveformGraph class. Use the Class Browser window to find and drop the Legend: Autosize Property Node inside the Case structure. Object library: VI Server ~ Class: Generio»Generic ~ Select All classes in the VI Server library in the Seareh Scope section — Search string: Legend: Autosize — Select the Legend: Autosize entry with class type of ‘WayeformGraph LadVIEW Core 2Erercses #16 com © Nationa instruments Corporation a ess0n 5 ontattg te User ttertace Wire the specific class reference output of the To More Specific Class function to the reference input of the Property Node. Expand the Property Node to display two properties. Click the second property in the Property Node and select Legend Number of Rows. Right-click the Property Node and select Change All To Write from the shortcut menu. Right-click the LegAutosize property and select Create»Constant from the shortcut menu. Verify that the value of the constant is False. Add an Array Size function to the Case structure. Add a For Loop to the Case structure. Add a Property Node to the For Loop. a Expand the third Property Node to di ‘Use the Class Browser window to find and drop the Active Plot Property Node inside the For Loop. = Object library: VI Server — Class: Generie»Generie — Select All classes in the VI Server library in the Search Scope section — Search string: Active Plot — Select the Active Plot entry with class type of WaveformGraph Wire the reference out output of the second Property Node through the border of the For Loop to the reference input of the third Property Node, lay two properties. Click the second property in the Property Node and select Plot» Plot Name from the lis. or LatvViEW Gore 2 Exercises Lesson Gontoting te User ttertace 1 Right-click the third Property Node and select Change All To Write from the shorteut menu, 1 Wire the block diagram as shown in Figure 5-13. Use shift registers Wwhen wiring the error wires through the For Loop. Confirm that auto indexing is enabled on the Plot Names tunne! on the For Loop. 8. Handle WaveformChart references. ash Reference pai peace wrt § pe wrchae 8 examine ere) | | Ssesione of Te} Teasitosoe acta ti Figure 5-14. WaveformChart Case O Right-click the border of the Case structure and select Duplicate Case from the shortcut menu. O Enter waveformchert in the case name. AX Caution The text entered in the case selector label must exactly match the input string, including spaces and case. For this example, enter tiaveformChart. Click the WayeformGraph reference constant and select Generic» GObject»Control»GraphChart»WaveformChart. EY Note When you change the class of a control reference, all Property Nodes and Invoke Nodes using the reference become invalid because the properties refer to a class that does ‘not matci the reference. Notice that all the property names change to black when you change the class reference and that the run arrow is broken. Leave the broken wires alone, because the wires reconnect as you reselect the properties. © Click each of the four properties and select the correct property again, The four properties are Legend»Autosize, Legend» ‘Number of Rows, Active Plot, and Plot»Plot Name. The resulting ‘lock diagram appears as shown in Figure 5-14. LabVIEW Cone 2 ecse8 8 icon Test Lesson 3 containg tne Use tertace 9, Create the icon and connector pane for the subVI. Figure 5-15 shows an example icon and connector pane. ‘Set Pot Names ech Refrense reine ena Hi Conneciions Connector Fane Figure 5-15. Connector Pane Connections for Set Plot Names VI Switch to the front panel of the VI 1 Right-click the connector pane and select Patterns from the shortcut menu to choose a pattern, Wire the connector pane. Right-click the icon and select Edit Icon from the shortcut menu, Use the tools in the Icon Editor to create an icon. Close the Ieon Editor when you are finished. 10, Save the VI. 1. Test the VI using a Waveform Graph. oe Figure 5-16. Set Plot Names Test O Create a blank VI. Add a Waveform Graph to the front panel window. ‘© neionat insures Corporation s19 LABVIEW Gore ? Crecises Lesson 5 Conirouay the User itertace a Qa a (Open the block diagram. Right-click the Waveform Graph indicator and select Create» Reference from the shortcut menu. Add the Set Plot Names VI to the block diagram of the new VL. Q Tip ifthe Sct Plot Names VI is open, you can drag the icon from upper right corner of its front panel to the block diagram of the new VI a a a Wite the WaveformGraph reference to the Graph Reference input of the Set Plot Names VI Right-click the Plot Names input of the Set Plot Names VI and. select Create»Control from the shorteut menu. The block diagram should resemble Figure 5-16. Switch to the front panel window of the new VI. ‘Type one and wo as items in the Plot Names array. Move the Plot Legend to the right of the graph so that you ean expand the legend. Run the VI. One and Two appear in the legend. 2. Test the VI using a Waveform Chart. Qa a u Right-click the waveform graph and select Replace»Graph» Waveform Chart from the shortcut menu. ‘Type Three as another item in the Plot Names array, Run the VI. Three appears in the legend of the chart 3. Testthe VI with an XY Graph. a a a Labine Core 2 Exercises Right-click the waveform chart and select Replace»Graph»> XY Graph from the shortcut menu. Add Four as another item in the Plot Names array. Run the VI. A typecasting error oveurs. Lesson 5 Contain te User Inertace B]_— Note The errors displayed because the conteol reference of the XY Graph isnot supported in the subVI. 4. Close the VI. You do not need to save the VI used for testing the Set Plot Names V1 End of Exercise 5-3 (© Netona irsruments Gaxporation set LabVIEW Core 2 Beroses Lesson’ Contoling ie User ntertace Notes LabVIEW ore? beercses eae icon File 1/0 Techniques Exercise 6-1 Goal Scenario Design Bitmap File Writer VI Use Binary File 1/0 to write toa file using a specified format. Write a file storage routine to store image files for an existing LabVIEW-based Drawing Pad, The drawing pad VI returns a drawing as a 2D array of red, green, and blue (RGB) values. Save the data as. a 24-bit bitmap file. You can use binary file 1/0 to write or read data in any file format, assuming that you have a specification that tells you the file layout for that format. The following section describes the format for a 24-bit Windows bitmap 24-bit Bitmap File Layout Bitmaps (. imp) files are a format for storing image data, Bitmaps come in multiple varieties, with differences such as the number of bits used to representa pixel and the level of image compression used. The easiest type of bitmap file to understand and create is a 24-bit uncompressed bitmap file. Table 6-1 describes the format of a 24-bit uncompressed bitmap file. Table 6-1. 24-Bit Bitmap File Layout Section Name Size (bytes) Notes BITMAPFILEHEADER 4 Data is provided. Write data to the file. BITMAPINFOHEADER 40 Data is provided. Write data to the file. Image Data 3 x Number of Pixels Stored in BGR order, Image is inverted. BITMAPFILEHEADER—Contains information about the file such as the file type and file size. A subVI calculates the data for this segment. The subVI returns an array of US numeries that you must write to the file. © Niort instumems Corperation or LaDMEW Core? Exercises Lesson 6 Fle VO Techniques BITMAPINFOHEADER—Contains information about the image such as. the height, width, compression level, and number of bits per pixel, A subVI calculates the data for this segment. The subVI retums an array of U8 numerics that you must write to the file, Image Data—For a 24-bit image, three bytes represent each pixel in the image. The three bytes represent the RGB values for the pixel and are stored in reverse order, BGR. The pixel array you are given is a 2D array of clusters. Each cluster has an RGB value in it. The rows in the Image Data are stored from bottom to top, and the first pixel stored is the lower left corner of the image Inputs and Outputs The main VI for this program contains no inputs or outputs. Dialog boxes control all user interaction. The Drawing Pad VI displays a dialog box that allows the user to draw a picture. When the user clicks Save, the application prompts the user to enter a save location by using a File Dialog VI Program Flow 1. Call the Drawing Pad VI to create a picture. Note ‘The Drawing Pad VI returns the picture as a 2D array of clusters, each containing RGB values, The 2D array has a width that is a multiple of four and is inverted in preparation for writing wo file, 2. Display a file dialog box to the user to select a location and filename and open the selected file for writing, 3. Call the BITMAPFILEHEADER YI and pass the dimensions of the pixel array to it. 4. Write the 1D array of unsigned integers returned by the BITMAPFILEHEADER VI to the open file, EY Note Disable the prepend array or string size option when you call the Write to Binary File function, otherwise LabVIEW inserts the array size at the beginning of the data, which invalidates the file layout. LanVEW Gore 2 ereses 5. Call the BITMAPINFOHEADER VI and pass the dimensions of the pixel array to it, 6, Write the 1D artay of unsigned integers returned by the BITMAPINFOHEADER VI to the open file. 02 com Lesson 6 Fe V0 Tectniques 7. Process each pixel in the array by using a pair of For Loops to remove the values from the cluster in BGR order and build them into an array. BZ Note Use a 3D amay to store the processed pixel data, because it allows you to use For Loop auto-indexing and simplify the program. The number of dimensions in the array is not important, because the File I/O functions auiomatically reformat the array to write to the file. 8. Write the processed pixel array to the open file 9. Close the file and handle any exrors, Implementation 1. Display the drawing pad, D Open a blank VI. Savethe Vias Bitmap File Writer.vi inthe \ LabVIEW Core 2\Bitmap File Writer directory. 2 Open the block diagram. 2 Add the Drawing Pad VI, located in the \LabviEW Core 2\Bitmap File Writer directory, to the block diagram. Right-click the Drawing Pad VI and select SubVI Node Setup from the shorteut menu. Check ihe Show Front Panel when called and Close afterwards if originally closed boxes. Click OK to exit the SubVI Node Setup dialog box. Note The subVI node setup lets you specify how to call a subVI, Checking the Show Front Panel when called box instructs the VI to show its front panel, even if the VI properties would otherwise prevent it from doing so. Run the V1 and observe the drawing pad, Click the Save button to exit. Currently, the program ends when you click Save, because you have not yet implemented the file 1/0. 2. Open anew binary file. Add a File Dialog Express VI to the block diagram. cs Click OK toexit the Configure File Dialog dialog box. The default values allow the user to select a single new or existing file (© nations astuments Corporation 68 LARVIEW Core 2 Exercises Lesson Fle ¢0 Tennigaes LU Expand the File Dialog Express V1 to show the selected path, error out, error in, prompt, pattern label, and pattern (all files) terminals by expanding the node and then clicking each terminal to select an input or output, Right-click the prompt input of the File Dialog Express VI and select Create»Constant from the shortcut menu. Q EnterSelect File to Save in the string constant. Right-click the pattern label input of the File Dialog Express VI and select Create»Constant from the shortcut menu, 2 EnterBitmap Files in the string constant Right-click the pattern (all files) input of the File Dialog Express V1 and select Create>Constant from the shortcut meau. Enter * bmp in the string constant. 5 Add an Open/Create/Replace File function to the block diagram. (Right-click the operation input of the Open/Create/Replace File function and select Create»Constant from the shoricut menu, Select replace or create as the value of the constant, Q Wire the block diagram as shown in Figure 6-1 Tre tosaa}- > eonnt is eal PGi een SIF] Figure 6-1. Open Binary File 3. Create bitmap headers. Add the BITMAPFILEHEADER YI located in the \LabVIEW Core 2\Bitmap File Writer directory to the block diagram, Lavview core 2 brcises 4 tieom Lesson 8 File V0 Techlques Add the BITMAPINFOHEADER VI located in the \LabVIEW Core 2\Bitmap File Writer directory to the block diagram. u Add an Array Size function to the block diagram. o Add two Write to Binary File functions to the block diagram. o Right-click the prepend array or string size terminal of cach Write to Binary File function and select Create»Constant from the shortcut menu, Q Set the constant values to False. Q Wire the block diagram as shown in Figure 6-2. FZ Note You do not need to specify little-endian or big-endian for the byte order input of the Write to Binary File function because the array data type is only one byte 4. 2 Nasio tnstrumerts Comperaion Eebeseee] | o- a 4 | oO wo [2] Fie Disiog pater iste asa] 99 ie Fb Figure 6-2. Write Bitmap Headers Write image data. (Add a For Loop to the block diagram Adda second Far Loop inside the first For Loop. o Add an Unbundle by Name function to the inner For Loop. o Add a Build Array function to the For Loops. o Wire the Image Data array through the For Loop borders to the Unbundle By Name function. os LabiEW Gere 2 Excite Lesson Fle 00 Teotmques Expand the Unbundle by Name function so that three elements are shown. OO Choose Blue, Green, and Red, in order, for the elements. FZ Note The bitmap file definition specifies that pixels must be stored in blue, green, red order. Storing the pixels in another order causes the colors in your image to be incorrect. Q Add a Write to Binary File function to the block diagram. UW Right-click the prepend array or string size input of the Write to Binary File function and select Create»Constant from the shorcut menu, Set the constant value to False. 5. Close the file and handle the errors. Add a Close File function to the block diagram. @ 2 Add a Simple Error Handler VI to the block diagram. Q Wire the block diagram as shown in Figure 6-3. 6. Save the VI. | FieDia eleced path a a Facatcw sn [iieep Fes Figure 6-3. Completed Block Diagram LaDiEW Core 2 Eereses 68 ‘nicom Lesson @ File 0 Techniques Test 1, Run the V1. Switch to the VI front panel window. Rum the VL ou Draw a picture in the drawing pad, oO Click Save. vu Select ¢:\Exexcices\LabVIEW Core 2\Bitmap File Writer\My Image lmp as the file to save. Open the image in an image viewer. O Open the c:\Exercises\LabVIEW Core 2\Bitmap File Writer directory in Windows Explorer. Double-click the image to open it in your default image viewer. ‘Verify that the image displayed is the picture you created. 3. Close the VI End of Exercise 6-1 (© Netra estar Corporation or LabMeW Core? xeroses Lesson Fle VO Technigues Exercise 6-2 Goal Scenario Read TDMS Files Log data to a’TDMS file and read the same TDMS file to access information about a specific channel. You are given a TDMS Logger VI that generates measurement data for any number of units under test (UUTS). The UUT measurement data consists of a time domain waveform and the power spectrum of a waveform, Run the TOMS Logger VI that accepts UUTs identified by seyial numbers. The TDMS Logger V1 retrieves the measurement data from the Generate Data V1, and logs the UUT data and additional properties to a TDMS file. ‘The TDMS file contains the author, timestamp, and two channel groups—Time Data and Power Spectrum Data. Each group contains a channel for each UUT. The serial number of the UUT names each channel and contains the matching signal data. Saving data to a file serves no purpose unless you also can access the data, Create a reader VI to access data from the TDMS file you generated, The reader should return either time data or power spectrum data for a particular UUT serial number, BZ Note Optionally, if you have Microsoft Excel installed on your system you ean use the the TDM Excel Add-In too! to load the TDMS file into Microsoft Excel. Design LaQWIEW Core 2 Exercises TDMS File Reference Information ‘+ File Level Information — Time Stamp—contains the cument time, ~ Author—contains the test operator name, acquired through a front pane! control, — The file contains two channel groups, one for time data and one for the power spectrum data. * Channel Group Level Information — Name—contains Time Data or Power Spectrum Data. This identifies the channel group. — Each channel group should contain a channel for each UUT. 8 a.com Lesson ® Fle U0 Tectlques + Channel Level Information = Name—contains the UUT Serial Number, which associates the numeric data with a particular unit, = Signal—contains an array of floating-point numeric data, — Several other properties, stich as the signal minimum and maximum will automatically be calculated and added to the file. TDMS Reader Inputs and Outputs Table 6-2. TOMS Reader VI Inputs and Outputs Type Name Properties File Path Control TOMS File Path | Default Value = \LabVIEW Core 2\ ‘TOMS Logger\Test Data. TDMS String Control Serial Number _ Combo Box Data set Waveform Graph Indicator | Channel Data = String Indicator Test Operator = Time Stamp Indicator Tine of Test = National estumerts Corperation 9 Your VI should begin by opening the TDMS fie and reading the author and time stamp file properties. Then read the time data or power spectrum data for the specified UUT and display the data on the Channel Data waveform graph, tabineW cere? Exercises Pecnaues Implementation TDMS Logger 1, Open rom: TOMS Li Figure 6-4. ‘2pH/s03 Figure 6-4, TDMS Logger Front Panel 2. Run the TDMS Logger VI. C1 Verify that the default value of the TDMS File Path control is Data .tdins. Enter your name in the Test Operator field Enter A001, a 0 and 003 in the UUT Serial Numbers control ood Run and test the TDMS Logger VL. View the logged data in the TDMS File Viewer window. The graphs on the front panel of the TDMS Logger VI should also display a plot for each serial number you enter Latview Gon Lessee 6 Fle WO Tectiaves Click Quit to close the TDMS File Viewer window. Examine the block diagram. Close the TDMS Logger VI. Do not save any changes TDMS Reader VI 1. Create a blank VI 2. Save the Vlas \LabVIEW Core 2\TDMS Reader\ Tous 3. Build the VI front panel. juan. Figure 6-5. TOMS Reader Front Panel Create the TDMS File Path control with a default value of \L Test Data.tdms Core 2\TDMS Logger\ o Create the Serial Number string control. Create the Time of Test time stamp indicator bo Create the Test Operator string indicator. u Create the Channel Data waveform graph o Place a combo box contral on the front panel. Label the combo box Data ‘nsrumeats Corporation or LabVIEW Gore? Exercises Lesson Fi 10 Techniques gcoaoogoogo oo o a Right-click the Data Set control and select Edit Items from the shorteut menu. Click Insert. Enter Power Spectrum in the ems list Click Insert Enter‘Time Data in the Items list. Deselect the Allow undefined values at run time box. Click OK. Select Time Data from the drop-down menu of the Data Set control. Right-click the Data Set control and select Data Operations» Make Current Value Default from the shortcut menu. Arrange the front panel as shown in Figure 6-5. 4, Open the TDMS file. im a a a Add a TDMS Open function to the block diagram. Right-click the operation input of the TDMS Open function and select Create»Constant from the shortcut menu, Select open (read-only) as the value of the constant, FZ Note Opening a file with the open (read-only) option increases the speed of reads in the file, Also, it does not lock the file so that other programs can use it at the same time, a a a Qa LaOVIEW Core 2 Bereses Wire the TDMS File Path control to the file path input of the ‘TDMS Open function. Read the Author file property. Adda TDMS Get Properties function to the block diagram. Right-click the property name input of the TDMS Get Properties function and select Create»Constant from the shorteut menu. Enter author in the string constant. 12 com © National nstrumerts Cxparation Lesson'@ File V0 Techniues Wire an empty string constant to the data type input of the TOMS Get Properties function, Wire the property value output of the TDMS Get Properties function to the Test Operator string indicator . Read the Time Stamp file property. i Add a TDMS Get Properties function to the block diagram, Right-click the property name input of the TDMS Get Properties function and select Create»Constant from the shorteut menu, Enter-rime stamp in the string constant. Wire a time stamp constant to the data type input of the TDMS Get Properties function 1. Wire the property value output of the TDMS Get Properties function to the Time of Test indicator. . Read the time data or power spectrum data for the specified UUT and display the data on the Channel Data waveform graph. Q Add a TDMS Read function to the block diagram. Q Wire the Data Set control to the group name in input of the TOMS Read function. Q. Wire the Serial Number control to the channel name(s) in input of the TDMS Read function. Q. Wire the data output of the TDMS Read function to the Channel Data indicator Close the file and handle errors, G1 Add a TDMS Close function to the block diagram. 615 LabVIEW Core 2 Brercites Lisson @ Fe (0 Teciaues Add a Simple Error Handler VI to the block diagram, a the block diagram as shown in Figure 6-6. mea O00 PM eas — & | Saris Numba “TonsFile Path Geteh | GmeSare a cS ene oni] | Testopertor Time of Test Channel Dats ie =) Figure 6-6. TOMS Reader Block Diagram 9. Save the VI. 10, Set the attributes and time stamp properties of the waveform graph. On the front panel, right-click the Channel Data graph and select Ignore Attributes. BZ Note You must ignore the attributes of the waveform, otherwise the waveform name attribute would overwrite the labels you set. This option is available only after you wire a waveform to the graph Test 1. Read and display the time domain data. G1 On the V1 front panel, ensure that the default TDMS File Path matches Table 6-2 and the Data Sct is sct to Time Data. © Enter A002 in the Serial Number control. FY} Note A001 was one of the serial numbers you entered when you ran the TDMS Logger VI. Run the VI. A sine wave should display in the Channel Data graph. (1 Change the Serial Number to 2002. O Run the VL A different sine wave should display. LatWEW Gore 2 Exess aM com 3. Lesson Fle VO Tecniues Read and display the power spectrum data. Change the Data Set control to Power Spectrum. Run the VI, Power spectrum data should display in the Channel Data graph. Close the VI. TDM Excel Add-In (Optional) BZ Note This exercise requires Microsoft Excel version 2003 or 2007 and the TDM Add-in Tool available on ni com. 4 . Launch Microsoft Excel. Click the Add-Ins tab and select the TDM Importer : Import a TDM(S) File icon in the Custom Toolbars section. Browse to find the TDMS file you created earlier: \ LabVIEW Core 2\TOUS Logger\Test Data. tems. The property information is displayed on the first worksheet. The Time data and Power Spectrum data are displayed on separate worksheets, Exit Microsoft Excel and return to LabVIEW. End of Exercise 6-2 (© retina rstuments Corporation 619 labiitw cere 2 Brercises Lesson fle 0 Tecaniques Notes LabineW Core 2 xercses 6 ‘moo Improving an Existing VI Exercise 7-1 Concept: Refactoring a VI Goal Improve an existing VI that is poorly designed. Description You receive a V1 that is used as a subVI in a larger project. You must improve the VI for readability and user friendliness. Evaluate the VI I. Openthe Determine Warning Bad One.vi located in the \LabVIEW Core 2\Determine Warnings directory. Figure 7-1 shows the block diagram of this VI. © Ran this VI with a variety of input values and observe the varying warning text Use the following list to evaluate the V1. Place a checkmark forall issues that apply. UW Disorganized block diagram Overly large block diagram Poorly named obj cts and poorly designed icons Unnecessary logic Duplicated logic Lack of dataflow programmi couodg Complicated algorithms (© national rstunerts Corporation a Lab MEW Core? Bxecses lesson? tnprowng an Esty VI Figure 7-1. Poorly Designad Block Diagram Improve the VI Improve the VI in stages. Begin with the first checkmark: The block diagram is too disorganized, 1. Use the following tips to help you organize the block diagram: fe a a Figure 7-2. Reorganized Block Diagram Q Move all controls to the left of the block diagram. Move alll indicators to the right of the block diagram. Use the Align Objects and Distribute Objects toolbar buttons to arrange the controls and indicators. LanViEW core 2 Everio 7 com Lesson? improving an basting v1 1 Rearrange wires so that they do not overlap. Rearrange wires so that no input wires are running from right to left. Reduce the number of bends in wires. Do notallow wires to run under objects 2, After the block diagram is better organized, rename controls and indicators using names that are more descriptive. * The purpose of this VI is to determine whether the current temperature and wind speed are at a level requiring a warning to generate. The V1 also lights an LED if a warning occurs, * Suggested input names ae Current Temperature, Low Temp, High Tomp,Current Wind Speed, andHigh Wind Speed + Suggested output names are Warning Text and tarning? 3. Remove any unnecessary logic from the block diagram. Figure 7-3 shows the last few functions in the block diagram. er] Ld Figure 7-3, Unnecessary Logic (© nana Instruments Corporation rs LavMleW Core? Cercses Lesson? Improving an Estng Vi Notice that the Equal’ function is followed by a Not function. One approach is to replace this with a Not Equal? function as shown in Figure 7-4. Figure 7-4. Unnecessary Logic Simplitiad Notice you can reduce unnecessary logic even further by removing the Not Equal? function and inverting the Boolean input of the Select function, as shown in Figure 7-5. Wiaening Text is) Warsing? LaOViEW Core 2 Berises Figure 7-5. Unnecessary Logic Simplified Further Refer to Figure 7-6 for assistance with wiring this duplicated function that occurs near the end of the VI. Delete the Equal? function. Delete the input wire io the Not function. Q Wire the input of the Not function to the input wire of the Select, function. Test the edited VI to be sure the functionality has not changed. 4 neon Lesson 7 Improving an sting VE aoe * Figure 7-6. Well-Named Controls and Unnecessary Logi Removed 4, Save the Vi as Determine Wernings Good one. vi Optional 1. Replace duplicated logic on the block diagram with subVIs. Figure 7-7 shows an example of the algorithm in the VI that is repeated. You can replace this algorithm with a subVL. L. Edad Figure 7-7. Repeated Algoritam Gi Select the repeated algorithm by drawing 4 selection box around the objects Select Edit»Create SubVI. Q Double-click the new subVI to open it. Rat the new subVI as necessary. Some things to consider: create an appropriate icon, recreate the connector pane, and rename the controls and indicators. Q Save the subV1. 1 Close the subVI. (Nationa! instruments Corporation ro LabMEW are? tvercies Lesson 7 Improving an Extsing Bz Note ifthe subV1 is dimmed, right-click the sub icon on the block diagram and select Relink to SubVI from the shortcut menu. Delete the duplicated logic in other locations and replace with the new subVI. © Test the edited VI 2. Remove unnecessary local variables and wire to the appropriate control or indicator instead. size roa af Figure 7-8. Duplicated Logic Placed in a SubV/I and Local Variables Removed 3. Save the Vias Determine Warnings Good One.vi. anview core 2 Eseries re com Lessin 7 proving an Exiting V0 Challenge: Simplify Algorithm If you have time remaining in this exercise, try to determine a way to simplify the algorithm and rewrite the code so that is easier to modify later, An example solution is shown in Figure 7-9 using a state machine. The states contained are: Healsiroke, Freeze, High Wind, and Generate Warning. You can explore altemate solutions in the \LabVIEW Core 2\ Exercise 7-1 Challenge directory. = a — = Figure 7-9. Alternate Algorithm that is Readable and Maintainable End of Exercise 7-1 (© Nationa Ieswrments Corporation nm LaDVIEW Gare2 Exercises Lesson 7 Improungan Busing Vi Notes LanveW core 2eurcises 78 toon Creating and Distributing Applications Exercise 8-1 Preparing Files for Distribution Goal Review the Building Applications Checklist and prepare VIs to build a standalone application. Scenario Review the Building Applications Checklist to assist you in the build process before creating a standalone application or installer. Stand-alone applications in LabVIEW have the Window Appearance set to ‘Top-level application to enable the front panel to open when the VI runs. A VI that is running as a stand-alone executable remains in memory when the application finishes running, Therefore, it is necessary to call the Quit LabVIEW function in order to close the application when the application finishes executing. Placing the Quit LabVIEW function on the block diagram can make editing the application more difficult in the future because LabVIEW exits each time the application finishes. With the use of the App Kind property, you can specify that LabVIEW exits only when executed within the run-time system Design + Modify the VI Properties to prepare to build a stand-alone application. + Modify the application to call the Quit LabVIEW function when the code is executed in the run-time system. + Modify the application to specify a log path relative to the standalone executable. (© National instruments Corperauon er LabEW Core 2 Ereises Lesson Creating and Oistrbiti ptications Implementation Before you build an application, you first prepare the code sothat it executes reliably when compiled into an application. Review the Building Applications Checklist L 3 Select Help»LabVIEW Help to open the LabVIEW Help. Select Fundamentals»Building and Distributing Applications Building Applications Checklist. Review the Preparing Files checklist items. Set Top-Level Application Window FZ Note If you have hardware installed and you have not already set up your hardware as part of a LabVIEW Core | exercise, refer to Appendix A, Setting Up Your Hardware. BZ Note tf you do not have hardware installed, use the files located in the \ LabVIEW Core 2\Weather Station\No Hardware Required Version directory. LabVIEW Core 2 Bentises Open the Weather Station UI VI. Open Weather Station. 1vprod in the \ LabVIEW Core 2\Weather Station directory. In the Project Explorer window, double-click Weather Station ULvi 82 too . | so wm 40 30 eb 7 L song tube Wind Seed Hetery Pie a (iced 5 ea Tae Ta Sonole cor Figure 8-1. Front Panel 2. Select File» VI Properties to display the VI Properties dialog box 3. Select Window Appearance from the top pull-down mena. 4. Give the window a name, such as Weather Station. the front panel a 5. Select Top-level application window, This gi professional appearance when it opens as an executable. 6. Click OK. 7. Save the VI es IONE Core? Exercises Nato Lesson 8 Creating a Oisttouray Appcatiens 8 Call the Quit LabVIEW Function Open and modify the block diagram to call the Quit LabVIEW function when the application finishes. Tontmesaer 7} ‘isp ie Figure 8-2. Adding the Quit LabVIEW Function to the Block Diagram Add the Quit LabVIEW function to the block diagram so that itis the last function that exceutes. This function quits LabVIEW and quits the application after it has executed. Enclose the Quit LabVIEW funetion in a Case structure. (Using the settings below in the Class Browser window create the Application: Kind propery. — Object library: VI Server — Class: Application — Properties and Methods: Properties»A pplication» Kind Wire the Property Node-as shows in Figure 8-2, Use the labeling tool to replace the text in the case label with Run Time system, Note Enum values that you wire to a case selector terminal are case sensitive. 2 Lanview core 2 exerts In the Project Explorer window, select File»Save All to save all the VIs, o4 ‘com Lesson creating snd Bstibuting Agoteations Specify a File Path Relative to the Executable I, Instead of prompting the user to specify a log file, modify your code to specify a file path relative to the application executable. Tupper — § ‘ed Speee of Wind poe iit ‘Appiction Dneceryst but Path Wea aoe rorestet — a enocout | TS | ae Figure 8-3. Additional Build Path Function Open the Initialize Weather Station.vi from the Project Explorer window. Q Switch to the block diagram. G2 Add « Build Path function to the block diagram. Right-click the name or relative path input and select Create» a (© Nesina inscurests Corporation Constant from the shortcut menu. Type weather. txt in the string constant. Add an Application Directory VI to the block diagram. Wire the block diagram as shown in Figure 8-3. 65 LabMew core 2 Exercises Lesson Grainy ana Distloutng Aypicaions Save and close the VI. From the Project Explorer window, open and run the Weather Station ULvi. When you click the Stop button, the VI stops but does not quit LabVIEW. (1 Open the \LabVIEW Core 2\ileather station directory in the Windows Explorer. Verify that the weather. tse file exists and contains the log information. BZ tote te you do not have hardware installed, the weather ext file is located in the \LabVIEW Core 2\Weather Station\No Hardware Required End of Exercise 8-1 LaOvIEW core 2 Excses 36 ‘nicom Exercise 8-2 Goal Scenario Implementation Q Tp You do not need to create the directory, LabVIEW creates any direct specify. (© nitional stunts Corporation “7 Lesson @ Creating an Distituting Apptzatons Creating a Stand-Alone Application Create a build specification and build a stand-alone application (EXE) in LabVIEW. Creating a stand-alone application and an installer simplifies deploying an application on multiple machines, After you have prepared your files, you create an Application (exe) Build Specification and then create an Installer Build Specification Use the Application (EXE) Build Specifications to create a stand-alone application for the Weather Station application. Use the Installer Build Specifications to create an installer for the Weather Application (EXE) Build Specification 1. Open Weather Station. Ivproj in the \ LabVIEW Core 2\Weather Station directory. 2, Right-click Build Specifications in the Project Explorer window and select New» Application (EXE) from the shortcut menu. 3, Modify the filename of the target and destination directory for the application in the Information eategory. © Select the Information category. © Change the Target filename to Weatherstation exe, QO Enter \LabVIEW Core 2\Weather Station\ Executable in the Destination directory. that you LabMEW Core? Exeros08 Lesson 8 Creating and Distrtng Aopteatons Lanview core 2 Berises 4, Specify the top-level VI. Select the Source Files category. G2 Select the Weather Station ULviin the Project Files tree. O Click the right arrow next to the Startup VIs listbox to add the selecied VI to the Startup VIs listbox O Click OK. 5. In the Project Explorer window, right-click the My Application build specification that you just created, and select Build from the shortcut menu. 6. Click Done in the Build status window. 7. Navigate to \LabVIEW Core 2\Weather station\ Executable in Windows Explorer and run WeatherStation.exe Stop when done. 8. Verify thatthe application closed when you stopped the application and that the weather . tact was created next f0 the executable, Review the Building Applications Cheel 1. Open the LabVIEW Help by selecting Help»LabVIEW Help. 2. Select Fundamentals»Building and Distributing Applications» Building Applications Checklist. 3. Review the Configuring Build Specifications checklist items. Installer Build Specification |. Right-click Build Specifications in the Project Explorer window and select New» Installer from the shortcut menu. Modify the Installer destination in the Product Information category. Select the Product Information category. OD Type \LabVIEW Core 2\Weather Station\ installer as the Installer destination. Specify the Executable Build Specification. Click the Source Files category. Select the My Application build specification. oe cam Lesson 8 Creating ana Cistibutng Agrcaions © Select the Weather Station directory in the Program Files in the Destination View tree. f=) © Click the right arrow nexi to the Project View tree to place the Lazy executable and the executable support files under the Program Files in the Weather Station directory as shown in Figure 8-4. 0 inser besaten: ras Dae eapT aenats ILebATW 65 Erompie Sian 4 Dialog narmaon Reaty, hse 202 ctumer Ores) Sew ries ects ||| ES | SERRiateren ees a (Sev ima oe : Sivan iy banca | Shee (S Prroxam es Common Progen ie) =) a, DS tWindows} Oo ; on a Figure 8-4. Installer Source Files Category 4. Add the NI LabVIEW Run-Time Engine to the installer by modifying the Additional Installers category. © Select the Additional Installers category. © Select the NI LabVIEW Run-Time Engine 2011 installer. Q Click OK. 5. Inthe Project Explorer window, right-click the My Installer build specification and select Build from the shortcut menu. 6. Click Done. © Nations struments Carpration 9 LABVIEW Core 2 Exercises Lesson 8 Greaing and Oisnbuting Anpcations Test 1, Run the setup .exe file in the \LabVIEW Core 2\ Weather Station\Installer\volume directory. You are guided through a setup process. The executable is created inside the \Weather Station directory. 2. Torun the application, select Start»Programs»Weather Station» Weather Station. End of Exercise 8-2 LaDViEW Care 2 erdses #10 com Lesson & creating and Dismtutig Apeavons Notes © Netionlistiuments Copwraton an LatiEW Cote? Bxerose5 Lesson Creating and Distributing Appicaions Notes LEW Core 2 rere 12 com Setting Up Your Hardware This appendix contains instructions on setting up your hardware. FZ Note Complete this setup only if you have hardware installed and have not already completed hardware setup on your system as part of a LabVIEW Core I course exercise. L. Launch MAX by selecting Start»Programs»National Instruments» Measurement & Automation or by double-clicking the MAX icon on your desktop. MAX searches the computer for instalied National Instruments hardware and displays the information. 2. Create a custom scale for the temperature sensor on the DAQ Signal Accessory. The sensor conversion is linear and uses the following the formula Voltage x 100 = Celsius Sa ne ees File View Toot Help = 1 hy Spe j “

You might also like