100% found this document useful (1 vote)
38 views

Labview Core2 Course Manual New

Labview Core2 Course Manual new

Uploaded by

mohamed.jaheen22
Copyright
© © All Rights Reserved
Available Formats
Download as PDF or read online on Scribd
100% found this document useful (1 vote)
38 views

Labview Core2 Course Manual New

Labview Core2 Course Manual new

Uploaded by

mohamed.jaheen22
Copyright
© © All Rights Reserved
Available Formats
Download as PDF or read online on Scribd
You are on page 1/ 135
SLNAWINULLSNI of Buuren woo “TWNOLLWN. jenuey| esuno9 é 9109 wMAIAIET LabVIEW™ Core 2 Course Manual Course Software Version 2011 August 2011 Edition Part Number 325292C-01 Conyrignt (©1993-2011 National Instruments Corporation. Al rights reserved Under the copyright laws. this pubication may not be reproduced or transmitted in any form, electronic or mechanical, ineluding photccopying, recording, storing inan informaton retriaval yster, or transtating, in whol orn part, without he prior wtten consant ‘of National Instruments Corporation, Nationa Instruments rspests the intallactual property of others, and we ask cur users todo the same. software is protected by copyright and cther intellectual property laws. Where NI sotware may be used to reproduca software o other matarils balonging te thers, You may use Ni sofware only to reproduce materia Inet you may reproduce in accordance with the terms of any apolicadle ene or other legal restriction. For components used in USI (Xerces G+, [OU, HOTS, b64, Stingray, and STLpor) the following copyright stipuations apply. Fora sting of the conditions and d'sclamars, refer to ae he USTCopyr ight s «chm orthe Cogyrights topc in your sofware Xerces Cer. This product insludes software that was developed bythe Apache Software Foundation (meeps //wwas.apachs.org/) GGopyright 1$99 The Apache Sofware Foundation. Al rights reserved. ICU. Copyright 1905-2009 International Business Machines Corporation and others. Alrights reserved, DFS, NCSA HDFS (Hierarchical Data Format 5) Software Library and Utiites Copytight 1998, 1999, 2000, 2001, 2008 ny the Board! Trustees ofthe Univers of Iinois. Al ight reserved. 164, Copyright © 2004-2006, Matthew Wilson and Synesis Software. All Rights Reserved. Stingray. This sotware includes Stingray software developed by the Rogue Wave Software division of Quovack. Inc Copytight 1995-2006, Quovadx, Inc. A Fights Reserved. STLport Copyright 1996-2008 Boris Forritchev Trademarks (OV, LabVIEW, National Instruments, NI, ri.cor, the National Instrumente corporate logo, and the Eagle logo are trademarks ot National Insvuments Corporation. Rete tothe Trademark informtion at ni . com/tredemazks for other National Instruments trademarks. “The mark LabWindows is used under a license from Microsoft Corporation. Windows isa registered trademark of Microsett Corporation inthe United States and other Counties. ter product and company names mentioned herein are trademarks or rade names oftheir respective companias, ‘Members of the National struments Aliance Partner Program are business entities independnt from Mational instruments and have no agency, pannership, or jpin-venture rdawonship with National instruments. Patents For patents cavering Natioral Instruments produtsechnology, refer tothe appropriate location: Help»Patents in your software, the patents. tact fle on your magia, or the Nationa instruments Patent Notice at ni .con/patents Worldwide Technical Support and Product Information Worldwide Offices Visit ni .com/niglobal 10 access the branch office Web sites, which provide up-to-date contact information, support phone ‘numbers, email addresses, and current events, Notional instruments Corporate Headquariers 11500 North Mopac Expressway Austin, Texes 78759-2504 USA Te: 512683 0100 For further support information, refer tothe Additional Information and Resources appendix. To corament on National Instruments documentation, eferto the National Insruments Web steal ni. com/in£o und enter the Info Cade feedback. Contents _—_— Student Guide NI Certification... Course Description . What You Need to Get Started Installing the Course Software. Course Goals Course Conventions. mmona> Lesson 1 Common Design Techniques A. Design Patterns B. Single Loop Design Patterns... C. Multiple Loop Design Patterns D, Timing a Design Pattern... Lesson 2 Synchronization Techniques A, Notifier onsen B. Queues... Lesson 3 Event Programming A. Events. B. Event-Driven Programming..... C. Caveats and Recommendations D. Event-Based Design Patterns Lesson 4 Error Handling Importance of Error Handling... Detect and Report Errors Errors and Warnings Ranges of Error Codes. Error Handle1 moow> Lesson 5 Controlling the User Interface ‘A. Property Nodes B. Invoke Nodes C. Vi Server Architecture D. Control References .. (© Nationa instruments Corporaton 8 LabVIEW Gore 2 Course Marua! ontents Lesson 6 File 1/0 Techniques A. File Formats B. Binary Files. C. TDMS Files. Lesson 7 Improving an Existing VI A. Refactoring Inherited Code B. Typical Refactoring C. Comparing VIs..... Lesson 8 Creating and Distributing Analcations A. Preparing the Files... B. Build Specifications C. Building the Application and Installer... Appendix A Additional Information and Resources Glossary LabWiEW Gore 2 Coors Aanuat » ‘com Student Guide ‘Thank you for purchasing the LabVIEW Core 2 course kit. You can begin developing an application soon after you complete this course, This course 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 corresponding course registration fee if you register within 90 days of purchasing the kit, Visitnni . com/ training 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 Certified 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 Exporionced User ‘Advanced Usor Courses LabVIEW Cove 1* LabVIEW Core 0° Maneging Software Engineering in LabVIEW {LABVIEW Cannectvty Advanced Architectures in LabVIEW LabVIEW Core 2° Object Oviented Design ‘nd Programming in LABVIEW LabVIEW Poriormance eats cae ae Catal anew Seite aE matin tosytian fy Guepertan acne cer Coors LabVIEW instrument Control LabVIEW Real-Time 1 LabVIEW Real-Time 2 LabVIEW FPGA LabVIEW DAQ and Signal Conationing Modular Instuments Serias “Core nurses are strongly commanded te rele maximum posucty gas wien using Labview. (© Rational instruments Corporation r LaDVIEW Gore 2 Course Maruat Student Guide B. Course Description 8 LaDVEW Core 2 Course Manual ‘The LabVIEW Core 2 course teaches you programming concepis, techniques, features, VIs, and functions you can use 10 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 | 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: ‘+ Anintroduction 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 topics + Some lessons include optional and challenge exercise sections or asset of additional exercises to complete if time permits For course and exercise manual updates and corrections, refer toni .com/into 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 temperature sensor, function generator, and LEDs, Ifyou 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 as a funetion generator. Ww icon ‘Student Guide 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 BN 120, wires, and cable LabVIEW Professional Development System 2011 or later DAQmx 9.3.5 or later oboaocad 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 in your computer. The LabVIEW Core 2 Course Setup dialog box appears. 2. Click Install the course materials. 3. Follow the onscreen instructions to complete installation and setup. Exercise files are located in the \LabvIEW Core 2\ folder, BZ Note Foldernamesin angle brackets, such as , refer to folders on the root directory of your computer. © Nation nsruments corporation w LaDIEW Cove 2 Course Manual Student Guide E. Course Goals This course prepares you to do the following: ‘+ Apply common design pattems that use notifiers, queues, and events ‘+ Use event programming effectively + Programmatically control user interface objects * Evaluate binary file I/O 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 I course + Every built-in V1, 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 NIExample Finder, available by selecting Help»Find Examples, for example VIs you can use and incorporate into VIs you create LabVIEW Gore 2 Course Manual vi com ‘Suc Guido F. Course Conventions monospace monospace bold Platform © Nationa fasiruments Corporation » The following conventions appear in this course manual: ‘The » symbol leads you through nested menu items and dialog box options to. final action, The sequence Tools»Instrumentation»Find Instrument Drivers directs you to drop down the Tools menu, select the Instrumentation item, and finally select the Find Instrument Drivers option, ‘This icon denotes a tip. which alerts you to advisory information. ‘This icon 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 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 toa key concept. Italic text also denotes text that is a placeholder for a word or value that you must supply. ‘eat in this font denctes text or characters that you should enter from the keyboard, sections of code, programming examples, and syntax examples. ‘This font is also used for the proper names of disk drives, paths, director 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 sereen. This font also emphasizes lines of code that are different from the other examples. Text in this font denotes a specific platform and indicates that the text following it applies only to that platform. LapviEW Gove 2 Course Manual Yee uUoveuUeVueaDaAeaaIISsT FTA Common Design Techniques Topics ‘You can develop better programs in LabVIEW and in other programming languages if you follow consistent programming techniques. Design patterns represent techniques that have proved themselves useful time and lime again. To facilitate development, LabVIEW provides templates for several common design pattems. This lesson discusses two different categories of programming design patterns—single loop and multiple loops. Single loop design pattems include the simple VI, the general VI, and the state machine. Multiple loop design patterns include the parallel loop V1, the master/slave, and the producer/consumer. Understanding the appropriate use of each design pattern helps you create more efficient LabVIEW VIs. A. Design Patterns B. Single Loop Design Patterns C. Multiple Loop Design Patterns D. Timing a Design Pattern (© National instruments Corporaton 4 Lane Gore2 Gourse Manvel Lesson t Common DesionTechnaues A. Design Patterns Application design patterns represent LabVIEW code implementations and techniques that are solutions to specific problems in software design. Design patterns typically evolve through the efforts of many developers and are fine-tuned for simplicity, maintainability, and readability. Design patterns represent the techniques that have proved themselves useful over time Furthermore, as paitern gains acceptance, it becomes easier to recognize—this recognition alone helps you to read and make changes to your code. Lab VIEW includes several built-in VI templates for several standard design patterns that you will learn about in later lessons. To access the design patterns, select File»New to display the New dialog box. The design patterns are available in the VI>From Template»Frameworks»Desiga Patterns folder. Listed helow are the different kinds of design patterns. + Master/Slave Design Pattern—Use this template to build a master/slave design pattern. The master loop alway’ executes, It notifies one or more slave loops to execute their code. The slave loop or loops continue executing until they complete, then wait for another notification. Contrast this with the producer/consumer pattern in which the consumer loops execute only when they have data in their queue. + Producer/Consumer Design Pattern (Data)—Use this template to build 4 producer/consumer design pattern. Use this template when you need to exccute a process, such as data analysis, when a data source, such as, triggered acquisition, produces data at an uneven rate and yon need to execute the process when the data becomes available. + Producet/Consumer Design Pattern (Events}—Use this template to build a producer/eonsumer design pattern with events to produce queue items. Use this design pattern instead of the user interface event handler patiern for user interfaces when you want (o execute code asynchronously in response to an event without slowing the user interface responsiveness. + Queved Message Handler—Use this template to builda queued message handler design pattern, in which each message handling code can queue any number of new messages LabVIEW Cove 2 Gourse Manual re icon Lesson} Common Design Techniques + Standard State Machine—Use this template to build a standard state ‘machine design pattern, Each state executes code and determines which state to transition to. Contrast this design pattern with the user interface event handler pattem, in which code executes in response to user actions, Contrast this design pattern also with the queued message handler pattern, in which each message handling code can queue any number of messages. + User Interface Event Handler—Use this template to build a user interface event handler design pattern, Use this pattern for dialog boxes and other user interfaces in which code executes in response to user actions. You also can create and execute user-defined events that the VI can handle the same way as user interface events. B. Single Loop Design Patterns You Jearned to design three different types of design patterns in the LabVIEW Core 1 course—the simple architecture, the general architecture, and the state machine, imple VI Design Patterns When performing calculations or making quick lab measurements, you do not need a complicated architecture. Your program might consist of a single ‘VI that takes a measurement, performs calculations, and either displays the results or records them to disk. The simple VI design patiern usually does not require a specific start or stop action from the user. The userjust clicks the Run button. Use this architecture for simple applications or for functional components within larger applications. You can convert these simple VIs into subVIs that you use 2s building blocks for larger applications. Figure 1-1 displays the block diagram of the Determine Warnings VI that was the course project in the LabVIEW Core 1 course. This VI performs a single task—it determines what warning to output dependent on a set of inputs. You can use this VI 2s a subVI whenever you must determine the warning level. Notice that the VI in Figure 1-1 contains no start or stop actions from the user. In this VI all block diagram objects are connected through data flow. ‘You can determine the overall order of operations by following the flow of data, For example, the Not Equal function cannot execute until the Greater Than or Equal function, the Less Than or Equal function, and both Select functions have executed. (© Rational asruments Corporation 13 LabVIEW Gore 2 Cowse Manus! Lesson + Common Design Technioies General VI Design Patterns A general VI design pattern has three main phases—startup, main application, and shutdown, Each of the following phases may contain code that uses another type of design pattern, Startup—lnitializes hardware, reads configuration information from files, or prompts the user for data file locations. Main Application—Consists of at least one loop that repeats until the user decides to exit the program or the program terminates for other reasons such as I/O completion Shutdown—Closes files, writes configuration information to disk, or resets /O to the default state, Figure 1-2 shows the general VI design pattern. Enter your code here Figure 1-2. General VI Design Patter {LADVIEW Gore 2 Course Maruat i] a.com Lesson? Common Design Tectniaues Tn Figure the error cluster wires control the execution order of the three sections, The While Loop does not execute until the Start Up VI finishes running and returns the error cluster data. Consequently, the Shut Down VI cannot run until the main application in the While Loop finishes and the error cluster data leaves the loop. @ Tip Most loops require a Wait function, especially if that Joop monitors user input on the front panel. Without the Wait function, the loop might run continuously and use all of the computer system resources. The Wait function forces the loop to run asynchronously even if you specify 0 milliseconds as the wait period. If the operations inside the main loop react to user inputs, you can increase the wait period to a level acceptable forreaction times. A wait of 100 to 200 ms is usually good because most users ‘cannot detect that amount of delay between clicking a button on the front panel and the subsequent event execution. For simple applications, the main application loop is obvious and contains code that uses the simple VI design pattern. When the application incudes complicated user interfaces or multiple tasks such as user actions, /O triggers, and so on, the main application phase gets more complicated. State Machine Design Pattern The state machine design pattern is a modification of the general design ‘pattern, It usually has a start up and shut down phase. However, the main application phase consists of a Case structure embedded in the loop. This architecture allows you to run different code each time the loop executes, depending upon some condition. Each case defines a state of the machine, hence the name, state machine. Use this design pattem for VIs that are casily divided into several simpler tasks, such as Vis that act as a user interface. A state machine in LabVIEW consists of a While Loop, a Case structure, and a shift register. Each state of the state machine is a separate case in the Case structure. You place VIs and other code that the state should execute within the appropriate case. A shift register stores the state that should execute upon the next iteration of the loop. The block diagram of a state machine VI with five states appears in Figure 1-3. Figure 1-4 shows the other cases, or states, of the state machine. © National Instruments Corporation 8 “LaDVIEW Gore 2 course wana Lesson t Common Design Tochniuee aos fa sxc sa 3 ae es o moe Figure 1-3. State Machine with Startup State [‘Idle", Default ~bP™ ae] Event 1 Code Here Nest State Event 2 Cade Here Net State Figure 1-4. Idle (Defautt), Event 1, and Event 2 States In the state machine design pattern, you design the list of possible tasks, or states, and then map them to each case. For the VI in the previous example, the possible states are Startup, Idle, Event 1, and Event 2. An enumerated LabVIEW Core 2 Course Manual 1 com Lesson Common Design Teteues constant stores the states, Each state has its own case in the Case structure. The outcome of ane case determines which case to execute next. The shift register stores the value that determines which case to execute next. The state machine design pattern can make the block diagram much smaller, and therefore, easier to read and debug. Another advantage of the state machine architecture is that each case determines the next state, unlike Sequence structures that must execute every frame in sequence. A disadvantage of the state machine design pattern is that with the approac in the previous example, it is possible to skip states. If two states in the structure are called at the same time, this model handles only one state, and the other state does not execute. Skipping states can lead to errors that are difficult to debug because they are difficult to reproduce. More complex versions of the state machine design pattern contain extra code that creates queue of events, or states, so that you do not miss a state. Refer to Lesson 2, Synchronization Techniques, for more information about queue-based state machines. C. Multiple Loop Design Patterns ‘This section describes the following multiple loop design pattems—parallel loop, master/slave, and producer/consumer data. Parallel Loop Design Pattern Some applications must respond to and run several tasks concurrently. ‘One way to improve parallelism is 10 assign a different loop to cach task. For example, you might have a different loop for each button on the front panel and for every other kind of task, such as a menu selection, 1/O trigger. and so on. Figure 1-5 shows this parallel loop design pattern. Batupst * Magers son. Process 1 Code Here a a Process 2 Code Here i Figure 1-5. Parallal Loop Design Pattern © Natal nsuments Corporation "7 LaOMEW Core 2 Course Manu’ lesson 1 Common Desion Techies This structure is straightforward and appropriate for some simple menu VIs, where you expect « user to select from one of several buttons that perform different actions, The parallel loop design pattern lets you handle multiple, simultaneous, independent tasks. In this design pattern, responding to one action does not prevent the VI from responding to another action. For example, if a user clicks a button that displays a dialog box, parallel loops can continue to respond to VO tasks, However, the parallel loop design pattern requires you to coordinate and communicate between different loops. You cannot use wires to pass data between loops because doing so prevents the loops from running in parallel Tnstead, you must use a messaging technique for passing information among. processes. Refer to Lesson 2, Synchronization Techniques, for messaging techniques using notifiers and queues. Master/Slave Design Pattern LabVIEW Gore 2 Course Manual ‘The master/slave design patiem consists of multiple parallel loops. Each of the loops may execute tasks at different rates. One Joop acis as the master, and the other loops act as slaves. The master loop controls all the slave loops and communicates with them using messaging techniques, as shown in Figure 1-6. Figure 1-6. Master/Siave Design Pattern Use the master/slave design pattern when you need a VI to respond to user imerface controls while simultaneously collecting data, For example, you want to create a VI that measures and logs a slowly changing voltage once every five seconds. The VI acquires a waveform from a transmission line and displays it on a graph every 100 ms. The VI also provides a user interface that allows the userto change parameters for each acquisition. The master/slave design pattern is well suited for this acquisition application. For this application, the master loop contains the user interface. The voltage acquisition occurs in one slave loop, while the graphing occurs in another slave loop. 18 scom Lisson} Common Design Tectieves Using the standard master/slave design pattern approach to this VI, you ‘would put the acquisition processes in two separate While Loops, both of them driven by a master loop that receives inputs from the user interface controls. This ensures that the separate acquisition processes do not affect each other, and that any delays caused by the user interface, such as displaying a dialog box, do not delay any iterations of the acquisition processes. Vis that involve control also benefit from the use of master/slave design patterns. Consider a VI where a user controls a free-motion robotic arm using buttons on a front panel. This type of VI requires efficient, accurate, and responsive control because of the physical damage to the arm or surroundings that might occar if control is mishandled. For example. if the user instructs the arm (0 stop its downward motion, but the program is ‘occupied with the arm swivel control, the robotic arm might collide with the support platform. Apply the master/slave design pater to the application to avoid these problems, In this case, the master loop handles the user nirol ‘a loop. Because each controllable section of the arm has its own loop and its ‘own piece of processing time, the user interface has more responsive control of the robotic arm, With a master/slave design pattern, itis important that no two While Loops write to the same shared data, Ensure that no more than one While Loop may write to any given piece of shared data. Refer to Lesson 2, Synchronization Techniques, for more information about implementing an application based on the master/slave design pattern. The slave must not take too long to respond to the master. Ifthe slave is processing a signal fiom the master and the master sends more than one message to the slave, the slave receives only the latest message. This use of the masterislave architecture could cause a loss of data. Use a. master/slave architecture only if you are certain that each slave task takes less time to execute than the master loop. Producer/Consumer Design Pattern ‘The producer/consumer design pattern is hased on the master/slave design patiern and improves data sharing among multiple loops running at different rates, Similar to the master/slave design pattem, the producer/consumer design pattern separates tasks that produce and consume data at different rates, The parallel loops in the producer/consumer design pattern are separated into two categories—those that produce data and those that consume the data produced. Data queues communicate data among the loops. The data queues also buffer data among the producer and consumer loops. © National instruments Copoataon 18 LAD VIEW Core2 Course Marua! Lesson 1 Common Desian Techniaves @ Te Abuiferis a memory device that stores temporary data among two devices, or in this case, multiple loops. that accepts data while processing the data sets in the order they were received. The producer/consumer pattern is ideal for this type of VI because queuing (producing) the data occurs much faster than the data can be processed (consumed), You could put the producer and consumer in the same Joop for this application, but the processing queue could not receive additional data until the first piece of data was completely processed. The producer/consumer approach to this VI queues the data in the producer loop and processes the data in the consumer loop, as shown in Figure 1-7. Q Ti Queve functions allow you to store a set of data that can be passed among multiple loops running simultaneously or umong Vis. Refer to Lesson 2, Synclronization Techniques, for more information about queues and implementing applications using the producer/consumer design pattern, farpacainas fetiencas ra ren ae Saal eyo e jor oi TE rams x ‘OD D>} Toa a pee TE [tins the usu Figure 1-7. Producer/Consumer Design Pattern This design pattern allows the consumer loop to process the data at its own pace, while the producer loop continues to queue additional dats. LabVIEW Gore 2 Course Manual 10 icon Lesson Common Design Techniques: You also can use the producer/consumer design pattern to create a VI that analyzes network communication. This type of VI requires two processes to ‘operate at the same time and at different speeds. The first process constantly polls the network line and retrieves packets. The second process analyzes the packets retrieved by the first process In this example, the first process acts as the producer because it supplies data to the second process, which acts as the consumer. The producer/consumer design pattern is an effective architecture for this VI. The parallel producer and consumer loops handle the retrieval and analysis of data off the network, and the queued communication between the Wo loops allows buffering of the network packets retrieved. Buffering can become important when network communication is busy. With buffering, packets can be retrieved and communicated faster than they can be analyzed. D. Timing a Design Pattern Execution Timing ‘This section discusses two forms of timing—execution timing and software conttol timing, Execution timing uses timing functions to give the processor time to complete other tasks. Software control timing involves timing a real-world operation to perform within a set time period. Execution timing involves timing a design pattern explicitly or based on events that occur within the VI. Explicit timing uses a function that_ spccifically allows the processor time to complete other tasks, such as the ‘Wait Lintil Next ms Multiple function. When timing is based on events, the design pattem waits for some action to occur before continuing and allows the processar to complete other tasks while it waits se explicit timing for design patterns such slave, _producer/consumer, and state machine, These design patterns perform some type of polling while they execute. Tip Polling is the process of making continuous requests for data from another device. Tn LabVIEW, this generally means that the block diagram continuously asks if there is data available, usually from the user interface. For example, the master/slave design pattern shown in Figure 1-8 uses a While Loop and a Case structure to implement the master loop. The master ‘executes continuously and polls for an event of some type, such as the user clicking a button. When the event occurs, the master sends a message to the slave, You need to time the master so it does not take over the execution of the processor. In this case, you typically use the Wait (ms) function to regulate how frequently the master polls. (© hationat instruments Corporaron rt Labinew Gave 2 Coors Maruat lesson 1 Contman Design Techniques Q Th Always use a timing funetion such asthe Wait ms) funetion or the Wait Until Next ms Multiple function in any design pattern that continually executes and needs to be regulated. If you do not use a timing function in a continuously executing structure, LabVIEW uses all the processor time, and background processes may not run. cotati, fearon ce nC a] [emcee sere | Kp leet ia opr eae eco te Figure 1-8. Master/Slave Design Pattern Notice that the slave loop does not contain any form of timing. The use of Synchronization functions, such as queues and notifiers, to pass messages provides an inherent form of timing in the slave loop because the slave loop waits for the Notifier function to receive a message. After the Notifier function receives a message, the slave executes on the message. This creates an efficient block diagram that does not waste processor cycles by polling for messages. This is an example of execution timing by waiting for an event, When you implement design patterns where the timing is based on the occurrence of events, you do not have to determine the correct timing frequency because the execution of the design pattem occurs only when an event occurs. In other words, the design pattern executes only when it receives an event. LaDVIEW Gore 2 Course Manual we com Software Control Lesson} Common Design Techniues Timing Many applications that you create must execute an operation fora specified amount of time. Consider implementing a state machine design pattern for a temperature data acquisition system. If the specifications require that the system acquire temperature data for 5 minutes, you could remain in the acquisition state for 5 minutes. However, during that time you cannot process any user interface actions such as stopping the VI. To process user interface actions. you must implement timing so that the VI continually executes for specified time. Implementing this type of timing involves keeping the application executing while monitoring a real-time clock In the LabVIEW Core 1 course, you implemented software control timing to ‘monitor the time until the VI should acquire the next piece of data, as shown in Figure 1-9, Notice the use of the Elapsed Time Express VI to keep track of a clock. or a Tyee tifa mF = tee @. a. * © Nationa Instruments Corporation Figure 1-9. Use of the Elapsed Tima Express V Ifyou use the Wait (ms) function or the Wait Until Next ms Multiple function to perform software timing, the execution of the function you are timing does not occur untij the wait function finishes, These timing functions are not the preferred method for performing software control timing, especially for VIs where the system must continually execute. A. rag LDVIEW Core 2 Course Mansa! essen Common Desin Tashiaves Figure 1-10. Software Timing Using the Get Date/Time In Seconds Function Q Tip Always use the Get Date/Time In Seconds function instead of the Tick Count (ms) function for this type of comparison because the value of the Tick Count (ms) function can rollover to 0 during execution. LabVIEW Core 2 Course Manual He rican Lesson 1 Common Design Techniques: Self-Review: Quiz 1,_The state chine is an example of a design pattern. hb. False 2. Which of the following are reasons for using a multiple loop design pattern’? ‘a,_Execute multiple tasks concurrently b. Exccute different states in a state machine c,_Execule tasks al different rates d. Execute slart up code, main loop, and shutdown code 3. Software control timing allows the processor time to complete other tasks, a. True © Ration instruments Corporation 115) LaDvIEW coe 2 couse Manual wevu Yo o a 2 o9goa3097 Lesson? Common Design Tectniaues Self-Review: Quiz Answers (© Rational nsrunents Corporation ‘The state machine is an example of a design pattern a. True b. False Which of the following are reasons for using a multiple loop design pattern? a, Exeeute multiple tasks concurrently b. Exccute different states in a state machine c. Execute tasks at different rates d. Execute start up code, main loop, and shutdown code Software control timing allows the processor time to complete other tasks. a True b. False tr LabWIEW Gore2 Cows Marua! Lesson | Common Design Techniques Notes LabVIEW Core 2 Gourse Mana com Synchronization Techniques Variables are useful in LabVIEW for passing data between parallel processes. However, when using variables it is often difficult to synchronize data transfers and you must take care to avoid race conditions. This lesson introduces noiifiers and queues as alternative methods for pussing data ‘between parallel processes, Notifiers and queues have advantages over using variables because of the ability to synchronize the transfer of data. Topics A. Notifiers B. Queues © Natona insrumerts Gorporatan at Lab MEW Core 2 Course Marua! Lessan2 Synchronization Techniques A. Notifiers A more effective implementation of the master/slave design pattern uses notifiers to synchronize data transfer. A notifier sends data along with a ‘notification that the data is available, Using a notifier to pass data from the ‘master to the slave removes any issues with race conditions, Using notifiers also provides a synchronization advantage because the master and slave are timed when data is available, providing foran elegant implementation of the master/slave design pattern, Figure 2-1 shows the master/slave design pattern using notifiers. EHO So _ Sane, tae |.2) x") wwhececte| 1 sre i avec Aare] a po | (es tinale_ Poneto nica tsa a aT a] =a a ctatcin be any tps) ‘te LDWEW Gore 2 Course Manual Figure 2-1. Master/Slave Dasign Pattern Using Notifies, ‘The notifier is created before the loops begin using the Obtain Notifier function, The master loop uses the Send Notification function to notify the slave loop through the Wait on Notification function. After the VI has finished using the notifiers, the Release Notifier function releases the aotifiers, The following benefits result from using notifiers in the master/slave design pattem: + Both loops are synchronized to the master loop. The slave loop only executes when the master loop sends a notificatio 22 icon B. Queues Lesson SynciraniationTestniques + You can use notifiers to ereate globally available data, Thus, you can send data with a notification, For example, in Figure 2-1, the Send Notification function sends the string instruction. + Using notifiers creates eificient code. You need not use polling to determine when data is available from the master loop. However, using notifiers can have drawbacks. A notifier does not buffer the data. If the master loop sends another piece of data before the slave loop(s) reads the first piece of data, that data is overwritten and lost ‘Queues are similar to notifiers, except that a queue can store multi Hews ‘of data, By default, queues work in a first in, first out (FIFO) manner. ‘Therefore, the first piece of data inserted into the queue is the first piece of data that is removed from the queue. Use a queue when you want to process all data placed in the queue. Use a notifier if you want to process only the current data, ‘When used, the producer/consumer design pattern, queues pass data and synchronize the loops. sate te ay ty} hae] ea pemesenar faxtarcamns a ES ce Z Ts x Fal a 13] ‘a isa yol ease BRITT Figure 2-2. Producer/Consumer Design Pattern Using Queues (© Waioral instruments Corporation 23 LabVIEW Core 2 Course Maaual lesson? — Syrchroization Tecniques ‘The queue is created before the loops begin using the Obtain Queue function. The producer loop uses the Enqueue Element function to add data to the queue. The consumer loop removes data from the queue using the Dequeue Element function. The consumer loop does not execute until data is available in the queue. After the VI has finished using the queues, the Release Queue function releases the queues. When the queue releases, the Dequeue Element function generates an error, effectively stopping the consumer loop. This eliminates the need to use a variable to stop the loops. ‘The following benefits result from using queues in the producer/consumer design pattern: Both loops are synchronized to the producer loop. The consumer loop only executes when data is available in the queue. You can use queues to create globally available data that is queued, removing the possibility of losing the data in the queue when new data is added to the queue. Using queues creates efficient code, You need not use polling to determine when data is available from the producer loop. Queues are also useful for holding state requests in a state machine, In the implementation of a state machine that you have learned, if two states are requested simultancously, you might lose one of the state requests. A queue stores the second state request and executes it when the first has finished. To practics the concepts in this section, complete Exercise 2-1. Case Study: Weather Station Project Lav ViEW Core 2 Course Mana ‘The weather station project acquires temperature and wind speed data, and analyzes it to determine if the situation requires a warning, If the temperature is too high or too low, it alerts the user to « danger of heatsiroke or freezing, It also monitors the wind speed to generate a high wind warning when appropriate. The block diagram consists of two parallel loops, which are synchronized using queues. One loop acquires data for temperature and wind speed and the other loop analyzes the data. The loops in the block diagram use the producer/consumer design pattem and pass the data through the queue. Queues help process every reading acquired from the DAQ Assistant, Code for acquiring temperature and wind speed is placed in the producer loop. Code containing the state machine for analysis of temperature-weather conditions is within the no error case of the consumer loop. The code using 2 queue is more readable and efficient than the code using only state machine architecture. The Obtain Queue function creates the queue 24 rican ssson2—Synchrontation Techniques reference. The producer loop uses the Enqueue Element function to add data obtained from the DAQ Assistant to the queue. The consumer loop uses the Dequeue Element function to get the data from the queue and provide it 10 the state machine for analysis. The Release Queue function marks the end ‘of queue by destroying it, The use of queues also eliminates the need for a shared variable to stop the loops because the Dequeue Element function stops the consumer loop when the queue is released, Figure 2-3 shows the block diagram consisting of a producer and a consumer loop. Data transfer and synchronization between the loops is achieved by the queue functions. Figure 2-3. Data Transfer and Synchronization of Parallel Loops Using Queues © fatonal nsiurments Corporation 29 LabVIEW Core 2 Course Marua\ Pee uuvuenevuevyvuYOO9027D 32 397903990 Self-Review: Quiz Lesson 2 Synebroniaton Techniques 1. Which of the following buffer data? a. Notifiers b_Queues ¢. Global Variables d. Local Variables 2. Match the following: Obtain Queue * a Get Queue Status Enqueue El = nt Destcoys the queue reference signs the data type of the queue (dds an element to the back of the queue Desermines the number of elements currently in the queue 3. Which of the following are valid data types for Queues and Notifiers? a. Suing ». Numeric b c. Enum a Array of Booleans e. Cluster of a String and a Numeric So (© atonal instruments Corporation 27 LaDMEW Core 2 Course Manual , 2 Peru vruUUYVeUUYEyYUVVOoDSsI2BIDF7FDt Lesson 2 Synchronization Techniques Self-Review: Quiz Answers 1, Which of the following buffer data? a. Notifiers b. Queues cc. Global Variables d. Local Variables 2. Match the following: Obtain Queue Assigns the data type of the queue ti Get Queue Status Determines the number of elements 7 currently in the queue th Release Queue Destroys the queue reference Enqucue Element Adds an element to the back of the queue 3. Which of the following are valid data types for Queues and Notifiers? a. String b, Numeric c. Enum 4. Array of Booleans e. Cluster of a String and a Numeric © Nationa Instruments Corporation 29 Lavmew Gore 2 course Marua! Lesson 2 Synchronization Techniues Notes LabVIEW Core 2 Course Mansal 20 ‘com Event Programming Event-based design patterns allow you to create more efficient and flexible applications. Event-based design patterns use the Event structure to respond directly 0 the user or other events. This lesson describes event-driven programming using the Eveat structure and design patterns that use the Event structure. Topics Events Event-Driven Programming Caveats and Recommendations pane Eyent-Based Design Patterns © Rational nstuments Corporation a LanviEW Gore 2 Course manuas esson3 Bret Programming A. Events LabVIEW is a dataflow programming environment where the flow of data determines the execution order of block diagram elements. Event-driven programming features extend the LabVIEW dataflow environment o allow the user's direct interaction with the front pancl and other asynchronous activity to further influence block diagram execution BY Note _Event-criven programming features are available only in the Lab VIEW Full and Professional Development Systems. You can run a VI built ith these features in the Lab VIEW Base Package, but you cannot reconfigure the event-handling components. What Are Events? Why Use Events? LabVIEW Cove 2 Course Manual Anevent is an asynchronous notification that something has occurred, Events can originate from the user interface, external /O, or other parts of the program. User interface events include mouse clicks, key presses, and so on. External I/O events include hardware timers or triggers that signal when data acquisition completes or when an error condition occurs. Other types of events can be generated programmatically and used to communicate with different parts of the program, LabVIEW supports user interface and programmatically generated events, LabVIEW also supports ActiveX and -NET generated events, which are external /O events. In an event-driven program, events that occur in the system directly influence the execution flow. In contrast, a procedural program executes in a pre-determined, sequential order. Event-driven programs usually include a loop that waits foran event to occur, executes code to respond to the event, and reiterates to wait for the next event. How the program responds to each. event depends on the code written for that specific event. The orderin which an event-driven program executes depends on which events occurand on the order in which they occur. Some sections of the program might execute frequently because the events they handle occur frequently, and other sections of the program might not execute at all because the events never occur. Use user interface events in LabVIEW to synchronize user actions on the front panel with block diagram execution, Events allow you 10 execute a specific event-handling case each time a user performs a specific action. Without events, the block diagram must poll the state of front panel objects inaloop, checking to see if any change has occurred. Polling the front panel requires a significant amount of CPU time and can fail to detect changes if they occur too quickly. By using events to respond to specific user actions, you eliminate the need to poll the front panel to determine which actions the user performed. Instead, LabVIEW actively notifies the block diagram each 32 ico Lesson’ Event Powamming time an interaction you specified occurs. Using events reduces the CPU requirements of the program, simplifies the block diagram code, and ‘guarantees that the block diagram ean respond to all interactions the user makes Use programmatically generated events to communicate among different parts of the program that have no dataflow dependency. Programmatically generated events have many of the same advantages as user interface events and can share the same event-handling code, making it easy to implement advanced architectures, such as queued state machines using events. B. Event-Driven Programming In Lesson 1, Common Design Techniques, you learned how event-driven programming extends the LabVIEW dataflow environment to allow user interaction with the front panel. You also learned ahout programmatically-generated events allow for easy implementation of advanced architectures, such as queued state machines. Event Structure Components f(D Application Exit? *P} Use the Event structure, shown as follows, to handle events in a VI. ‘The Event structure works like a Case structure with a built-in Wait on Notification function. The Event structure can have multiple cases, each of which is a separate event-handling routine. You can configure each case 10 handle one or more events, but only one of these events can occur at a time. ‘When the Event structure executes, it waits until one of the configured ‘events occur, then executes the corresponding case for that event. The Event structure completes execution after handling exactly one event, It does not implicitly loop to handle multiple events. Like a Wait on Notification function, the Event structure can time out while waiting for notification of an event. When this occurs, a specific Timeout case executes. The event selector label at the top of the Event structure indicates which events cause the currently displayed case to execute. ‘View other event cases by clicking the down arrow next to the case name and selecting another case from the shorteut menu ‘The Timeout terminal at the top lefi comer of the Event structure specifies the number of milliseconds to wait for an event before timing out. © national instruments Corporation 3 LaDVIEW Gore 2 Gowrse Manus! lesson 3 Event Programming ‘The default is —1, which specifies to wait indefinitely for an event to occur, If you wire a value to the Timeout terminal, you must provide a Timeout case. ‘The Event Data Node behaves similarly to the Unbundle By Name function, ‘This node is attached to the inside left border of each event case. The node identifies the data Lab VIEW provides when an event occurs. You can resize this node vertically to add more data items, and you can set cach data item in the node to access any event data element. The node provides different data elements in each case of the Event structure depending on which event(s) you configure that ease to handle. If you configure a single case to handle multiple events, the Event Data Node provides only the event data elements that are common to all the events configured for that case. aa ‘The Event Filter Node is similar to the Event Data Node. This node is attached to the inside right border of filter event cases. The node identifies the subset of data available in the Event Data Node that the event case can modify. The node displays different data depending on which event(s) you configure that case to handle. By default, these items are inplace to the corresponding data items in the Event Data Node. If you do not wire a value to a data item of an Event Filter Node, that data item remains unchanged. Refer to the Norify and Filter Events section of this lesson for more information about filter events. B The dynamic event terminals are available by right-clicking the Event structure and selecting Show Dynamic Event Terminals from the shortcut menu. ‘These terminals are used only for dynamic event registration, Refer to the Dynamic Event Registration topic and the Modifying Registration Dynamically topic of the LabVIEW Help for more information about using these terminals. FY Note Like a Case structure, the Event structure supports tunnels. However, by default you do not have to wire Event structure output tunnels in every ease. All unwired tunnels use the default value for the tunnel data type. Right-click a tunnel and deselect Use Default If Unwired from the shortcut menu to revert to the default Case structure behavior where tunnels must be wired in all cases. You also ean configure the tunnels to wire the input and output tunnels automatically in unwired cases. Refer to the LabVIEW Help for information about the default values for data types. LaDVieW cor 2 Course Manval a nicer Lesson Even! Programming Notify and Filter Events Notify events are an indication that a user action has already occurred, such as when the user has changed the value of a control. Use notify events to respond toan cvent after ithas occurred and LabVIEW has processed it, You can configure any number of Event structures to respond to the same notify event on a specific object. When the event occurs, LabVIEW sends a copy of the event to each Event structure configured to handle the event in parallel. Filler events inform you that the user has performed an action before LabVIEW processes it, which allows you to customize how the program responds to interactions with the user interface. Use filter events to participate in che handling of the event, possibly overriding the default behavior for the event. In an Event structure case for a filter event, you can validate of change the event data before La VIEW finishes processing it, or ‘you can discard the event entirely to prevent the change from affecting the VI. For example, you can configure an Event structure to discard the Panel Close? event, which prevents the user from interactively closing the front panel of the VI. Filter events have names that end with a question mark, such as Panel Close?, to help you distinguish them from notify events. Most filter events have an associated notify event of the same name, but without the question mark, which LabVIEW generates after the filter event if no event case discarded the event. Forexample, you can use the Mouse Down? and Shorteut Menu Activation? filter events to display a context menu when you left-click a control. To perform this action, modify the data retuned by the Button event dats field of the Mouse Down? filter event. The value of the left mouse button is |,and the value of the right mouse bution is 2. In order to display the context menu when you left-click a control, change the Button event data field to 2 so that LabVIEW treats a left-click like a right-click. Refer to the Lefi-click Shortcut Menu VI in the Labview\examples\general directory for an ‘example of using filter events. As with notify events, you can configure any number of Event structures (0 respond to the same filter event on a specific abject. However, LabVIEW sends filler events sequentially to each Event structure configured for the event. The order in which LabVIEW sends the event to cach Event structure depends on the order in which the events were registered. Each Event structure must complete its event case for the event before LabVIEW can notify the next Event structure. If an Event structure case changes any of the event data, LabVIEW passes the changed data to subsequent Event structures in the chain. If an Event structure in the chain discards the event, LabVIEW does not pass the event to any Event structures remaining in the © Nationa! instruments Corporaton 38 LabVIEW Core 2 Course Manual

You might also like