LabVIEWTM Core 2. Course Manual. Course Software Version August Edition. Part Number C LabVIEW Core 2 Course Manual. Materials used in the instructor-led course; Printed course concepts manual; Printed exercise procedure manual; Exercise solutions on CD. Overview; Pricing . The LabVIEW Core 2 course teaches you programming concepts, techniques, features, VIs, and In the course manual, each lesson consists of the following.
|Language:||English, Spanish, Japanese|
|Genre:||Business & Career|
|Distribution:||Free* [*Registration Required]|
Get this from a library! LabVIEW. Core 2: course manual. [National Instruments ( Firm)]. A Steve Jobs keynote presentation is an extraordinary expe- rience, and he. a passionate perfectionist and a visionary Reiki 2 Manual - Free Reiki. View Test Prep - LabVIEW-Core cehalfperbfamsce.gq from ELECTRICAL 1 at Rajiv Gandhi Proudyogiki Vishwavidyalaya. TM LabVIEW Core 2.
Rename the duplicate case Snapshot. LabVIEW deletes the corresponding button from the front panel. Cleanup the front panel of the VI as shown in Figure To create the look of a histogram in the chart. Notice how changing the Signal and Bins values changes the look of the histogram. You may also want to remove the line interpolation by clicking the plot legend and selecting Interpolation from the shortcut menu.
A file dialog box displays so you can save the histogram file. Click the Snapshot button. Open the saved text file and review the contents to see the bins and values of the histogram.
Save and close the Histogram project. Scenario You need to create an application in which some features are not available to all users. You create a finite number of user access levels and assign an appropriate user level to various users. You use a functional global variable design pattern to check for different access levels.
Get Current Access Level Retrieves the access level from memory so that the application can determine if a user has access to a certain feature. Action Description Read User Access Level File Reads information about authorized users and their access levels from a specified file and stores this access information in memory.
In this exercise. Set Current Access Level Sets the access level of the current user in application memory. Design The following table describes the different actions you need to handle so you can implement user access control. Create a type-defined enum control and modify the front panel as shown in Figure By making this terminal required.
Save the enum as User Level Cmd. Add the three actions listed in the Design section of this exercise to the User Level Cmd type definition as shown in Figure Tip Use the Add Case for Every Value option when you know that each case diagram is significantly different. When the cursor changes to a wiring tool. After you duplicate a case. Create the framework for the functional global variable design by completing the block diagram as shown in Figure Small white triangles inside the input and output tunnels indicate the link.
If cases contain similar subdiagrams. Creating the Functional Global Variable Design Framework 3 2 5 1 5 4 1 Case selector—Wire the Error In cluster to the case selector of the outer case structure to set the error and no error cases.
In this case. Click the left side of the While Loop to complete the shift register. Get Current Access Level Case Wire the Error Case as shown in Figure This VI takes a user name you input. It has already been placed on the block diagram. You can add additional user names and levels if you want. From the project.
This file contains the names of authorized users and their access levels. Save and close the project. Value Change Event 5. Run the VI with the following user names and verify the user level is correct by clicking the Test Access Level button. Value Change event case as shown in Figure Change the color of a plot if the data exceeds a certain value. Scenario Complete a VI that records temperature to a waveform chart.
Design You build this VI in four stages. During execution. Open Temperature Limit. Lesson 3 Controlling the User Interface ni. Temperature Limit Front Panel 2. Ctl Props directory. Run the VI and then click the Start Acquisition button.
You can change the values on the controls while the VI runs. Modify the block diagram as shown in Figure to disable the controls when the VI is running. Right click the property node and select Change All to Write.
Run the VI a second time. Run the VI and click the Start Acquisition button.
The Delta t ms and High Limit controls are disabled and grayed out. Lesson 3 Controlling the User Interface Test 1. Set different values for the controls and click the Start Acquisition button.
Modify the block diagram as shown in Figure to enable the controls each time you run the VI. Run the VI and notice that the controls are enabled again before you click the Start Acquisition button. Notice that the data displayed on the chart starts from where it stopped the last time you ran the VI.
Part 4—Challenge: This creates a cluster with values of 0 to initialize the temperature chart to 0 when the VI starts running. Modify the block diagram as shown in Figure to clear old data from the chart each time you run the VI. Notice that the chart clears before you click the Start Acquisition button and new data is written to it.
You can use a Case structure to control calling the method in a given iteration of a loop. Tip Use the Context Help window to view descriptions of each property and method. Center method during each iteration of a loop. After you implement the changes to the VI. Use the following method on the VI class: Methods directory. Modify the block diagram as shown in Figure to hide the scrollbars.
Implementation Part 1—Set Appearance Properties 1. Each pane can have its own scrollbars. Note Notice that the scrollbar visibility properties apply to the Pane class. The front panel can be split into multiple panes using the horizontal splitter bar or vertical splitter bar. When you wire a False constant to each of the properties. Expand the node to display two properties. You must wire the reference from the VI property node before setting this method. Verify that the scroll bars.
Modify the block diagram as shown in Figure to export the data displayed on the Temperature chart to Excel. View the data in the Excel file. The Export Data to Excel method creates a temporary Excel file with the data from the Waveform chart. Click Stop. SubVIs directory. The block diagram. Open the subVI. Right-click the copy and select Change to Indicator and change the label.
Connections for the other controls and indicators should already be created. On the Temperature Limit VI. Set Dialog Properties Code to Highlight. SubVI directory. Wire the reference and error wires through the Error case. Open the subVI you just created and modify the front panel as shown in Figure Save and close all open VIs and the Temperature Limit project.
Run the Temperature Limit VI and verify that it behaves as expected. Goal Modify a VI to programatically create a folder if none exists or to replace it if it already exists. Open the Create folder and file. Right-click Create folder and file.
Notice the files in the folder and notice that there is no folder called Logged Data. Open Create Data File. Examine the block diagram, as shown in Figure Application Directory—Returns the path to the directory containing the application. This is useful because you are using a subVI to create the data file. Check that the filename includes the date and time formatted components created using the codes used in the VI.
The error code 10 Duplicate Path is returned because the folder already exists. Modify the code to check if the Logged Data folder already exists as shown in Figure Only if the folder does not exist, create it.
Therefore, you enclose the Create Folder function in a Case structure. Modify the block diagram to conditionally create the folder. The folder is created only if it does not already exist. Save the VI and run it again. Notice that a new. Excel prefers data in columns. LabVIEW arrays store channels in rows and text files typically store channel data in columns for example. Operator Name. This VI uses several subVIs in order to modularize the code and make it more readable.
You can remove the spaces in the Corresponding format string section of the dialog box. LabVIEW adds a space between each one by default. This VI uses the Create Data File VI that you used in Exercise to programmatically create the Logged Data directory and the data file in the same directory containing the application. Add the Logged Data directory to your project. Save and close all open VIs. Read the data file.
Challenge A Goal Create a VI that takes the property name as input and returns the associated property value. Scenario Suppose your file header includes a variable number of property names and values.
The VI should take an array of strings as input. Your subVI should write the strings to file so that a tab separates each string and the line is terminated by an end-of-line character. You want to create a channel header for each channel of data.
Challenge B Goal Create a VI that creates tab delimited column headers for an arbitrary number of channels. If the property name isn't found. After reading in the file. Since the number of channels is arbitrary. Then use the row index to return the property value. For the file to be formatted correctly. Description After reading the spreadsheet string into memory. The TDMS file contains the author.
This identifies the channel group. The UUT measurement data consists of a time domain waveform and the power spectrum of a waveform. The serial number of the UUT names each channel and contains the matching signal data. Note Optionally. Each group contains a channel for each UUT. Saving data to a file serves no purpose unless you also can access the data.
The reader should return either time data or power spectrum data for a particular UUT serial number. Then read the time data or power spectrum data for the specified UUT and display the data on the Channel Data waveform graph. This VI is pre-built for you as shown in Figure When you save the TDMS file. Do not save any changes. The front panel is shown in Figure Open and examine the block diagram as shown in Figure Figure A different sine wave should display. Power spectrum data should display in the Waveform Graph.
Read and display the power spectrum data. Read and display the time domain data. The following information is displayed on the front panel: The Time data and Power Spectrum data are displayed on separate worksheets. Browse to find the TDMS file you created earlier: The property information is displayed on the first worksheet. Launch Microsoft Excel. Look over each option and choose one or two to complete during the time allotted in class.
The options for code to practice refactoring are listed from easiest to hardest. Refactoring Inherited Code This exercise consists of five VIs that you will evaluate for ways to improve. The researchers must perform experiments at very low temperatures. Test Test your refactored code to ensure that it works as the original application did. Also ensure that the refactored application generates errors if the user tries to convert invalid temperatures.
No temperature below Absolute Zero is allowed. The materials are tested in a chamber that contains four temperature sensors spread throughout the chamber. Note The Kelvin scale defines Absolute Zero as the lowest temperature possible.
The customer has recently decided to monitor more than four temperatures. He is worried that every time he increases the number of temperatures he would have to update the VI that does the conversion. You also will make the VI more readable and maintainable.
Due to the low temperatures involved. You should build your refactored application to generate errors if the user tries to convert invalid temperatures.
In this exercise you will refactor the conversion VI to make it more scalable. Scenario Your customer is a research facility that is doing experiments on superconducting material. Open Separate Array Values. Hints Conditional auto-indexing allows you to conditionally build an array within a For Loop. Test the VI. Notice that the input array contains a mix of positive and negative values. Lesson 5 Improving an Existing VI ni. After running. You notice that the Block Diagram of the VI is built in such a way that adding more features makes it grow.
Calculate the FFT of the waveform that is. You are asked to add a feature to calculate the Standard Deviation of the Time Series. Polling to Events Goal To take an existing VI that uses outdated techniques and refactor it to be more readable.
Calculate the Max and Min values of the Waveform. The waveform and spectrum are displayed in separate Waveform Graph indicators as are the Max and Min values. Description A lot of existing LabVIEW code was written using practices which were standard and accepted in the past but which were discovered to be less than ideal in terms of readability.
Acquire a waveform as a Time Series. Open Format Gas Params. You can add parameters without changing the VI if all the parameters are of the same data type.
Description The Format Into String function is very versatile: Hints If an additional parameter needs to be added to the Result string later. In addition to time and date information. You must update the code to change the order and prepare for future scalability of the cluster elements.
The challenge is to create two parallel arrays. You can then use a For Loop to process each cluster element. Your manager wants to re-order the name-value pairs so that Date and Time appear first.
Use that to build an array of names. Because the file is expected to be loaded into Excel. You can then get access to the Label names of the cluster elements.
The cluster element names and values are used in the name-value pairs. In the future you may want to expand the number of elements in the File Header Data cluster from 3 elements to 10 elements.
Scenario You inherited some code that creates a file header and includes a series of name-value pairs for your test data. Separate the name and value using a Tab constant and terminate with the End of Line constant. Set Top-Level Application Window 1. Review the Building Applications Checklist 1. Open the Histogram Main VI. Kind property. By using a Property Node with the App. Scenario Review the Building Applications Checklist to assist you in the build process before creating a stand-alone application or installer.
A VI that runs as a stand-alone executable remains in memory when the application finishes running. Implementation Before you build an application. Review the Preparing Files checklist items. Kind output to the case selector terminal and then right-click the Case structure border and select Add Case for Every Value. In the Project Explorer window. Select Window Appearance from the Category pull-down menu. Select Top-level application window to give the front panel a professional appearance when the VI opens as an executable.
Lesson 6 Creating and Distributing Applications ni. Click the Customize button to view the various window settings that LabVIEW configures for top-level application windows. You can leave the other cases empty or delete them 2. Enter a name. Run the Histogram Main VI to ensure that it is working.
Save the VI and the project. The Application Directory VI creates a path relative to the stand-alone application when you call the VI from a stand-alone application. LabVIEW creates any directories that you specify. Tip You do not need to create the directory. Optional Place a checkmark in the Do not prompt again for this operation checkbox and click the OK button if you receive a prompt about SSE2 optimization.
Modify the filename of the target and destination directory for the application in the Information category. After you prepare your files. Specify the top-level VI for the application.
Click Done in the Build status window. Enter localhost in the Machine name or IP address text box. Running the Application Executable 1. Include code to allow debugging of the executable. Run HistogramData.
Debugging the Executable on the Same Computer 1. Verify that the application closed when you stopped the application and the application created a text file in the Logged Data folder within the Executable folder. Stop the application by clicking the Stop button in the debugging window. Select HistogramData. Start debugging the running application. Click the Connect button to create the debugging connection.
As a challenge. After you have prepared your files. Review the Configuring Build Specifications checklist items. Specify the Executable Build Specification. Implementation Review the Building Applications Checklist 1. Scenario Creating an installer simplifies deploying an application on multiple machines.
Creating an Installer Build Specification 1. Modify the installer destination in the Product Information category.
Installer Source Files Category. Some installer files. Run the setup. Challenge If you have internet access during class. Note If you include additional installers in your build. Verify that classroom has internet access. By default. Follow the instructions on-screen to install the application. For other installer files. If you are completing this exercise in a classroom environment. On the Development computer. Select the executable from the Application or shared library drop-down menu.
Run the application on the Destination computer. MAX searches the computer for installed National Instruments hardware and displays the information. 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 1 course exercise. Flag for inappropriate content. Related titles. Jump to Page. Search inside document. Worldwide Technical Support and Product Information ni.
Contents Student Guide A. Exercise Create Folder and File Goal Modify a VI to programatically create a folder if none exists or to replace it if it already exists. Run the VI to test the functionality. Admir Berbiu. Student Guide In the course manual. If you do not have this hardware. Alternate instructions are provided for completing the exercises without hardware.
For example. You also can substitute other hardware for those previously mentioned. This icon denotes a tip. Follow the onscreen instructions to complete installation and setup. Insert the course CD in your computer. Installing the Course Software Complete the following steps to install the course software. Note Folder names in angle brackets. Course Conventions The following conventions appear in this course manual: Click Install the course materials.
Course Goals This course prepares you to do the following: This icon denotes a caution. Platform Text in this font denotes a specific platform and indicates that the text following it applies only to that platform. This font is also used for the proper names of disk drives.
Italic text also denotes text that is a placeholder for a word or value that you must supply. Student Guide This icon denotes a note. Bold text also denotes sections of dialog boxes and hardware labels.
This font also emphasizes lines of code that are different from the other examples. This type of communication between nodes is referred to as synchronous communication. LabVIEW is a dataflow language where the flow of data determines the execution order of block diagram elements. The movement of data through wires and nodes determines the execution order of the VIs and functions on the block diagram. A block diagram node executes when it receives all required inputs.
When a node executes. Queues C. Topics A. Asynchronous Communication B. Enqueue Element Adds an element to the back of a queue. Queues have advantages over using variables because of the ability to synchronize the transfer of data.
By default. Table describes the queue operations functions you use in this course. This lesson introduces queues as alternative methods for passing data between parallel processes.
Queue Operations Use the queue operations functions to create and use queues for communicating data between different sections of a VI and different VIs. A queue can hold data of any type and can store multiple pieces of data. Table Use a queue when you want to process all data placed in the queue. In this lesson you learn two important techniques for communicating asynchronously—queues for communicating between parallel loops and events for communicating between the user interface and the block diagram.
Enqueue Element at Opposite Adds an element to the front of a queue. End ni. Further more. Figure Release Queue Releases a reference to a queue. Obtain Queue Returns a reference to a queue. The consumer loop uses the Dequeue Element function to get the data from the queue and provide it to the state machine for analysis. You need not use polling to determine when data is available from the producer loop.
The producer loop uses the Enqueue Element function to add data to the queue. If the temperature is too high or too low. In the implementation of a state machine that you have learned. The block diagram consists of two parallel loops. Code for acquiring temperature and wind speed is placed in the producer loop. The consumer loop only executes when data is available in the queue.
It also monitors the wind speed to generate a high wind warning when appropriate. The consumer loop does not execute until data is available in the queue. The consumer loop removes data from the queue using the Dequeue Element function. Case Study: Weather Station Project The weather station project acquires temperature and wind speed data. After the VI has finished using the queues. When the queue releases. The Release Queue function marks the end of queue by destroying it. This eliminates the need to use a variable to stop the loops.
The Obtain Queue function creates the queue reference. 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. Code containing the state machine for analysis of temperature-weather conditions is within the no error case of the consumer loop. Queues help process every reading acquired from the DAQ Assistant.
The code using a queue is more readable and efficient than the code using only state machine architecture. A queue stores the second state request and executes it when the first has finished. Queues are also useful for holding state requests in a state machine. One loop acquires data for temperature and wind speed and the other loop analyzes the data. NET generated events. User interface events include mouse clicks. In contrast. Event-driven programs usually include a loop that waits for an event to occur.
How the program responds to each event depends on the code written for that specific event. Data transfer and synchronization between the loops is achieved by the queue functions. LabVIEW supports user interface and programmatically generated events. Event-Driven Programming Event-driven programming is a method of programming where the program waits on an event to occur before executing one or more functions. Events can originate from the user interface.
Other types of events can be generated programmatically and used to communicate with different parts of the program.
In an event-driven program. Events What Are Events? An event is an asynchronous notification that something has occurred. The order in which an event-driven program executes depends on which events occur and on the order in which they occur.
It does not implicitly loop to handle multiple events. LabVIEW actively notifies the block diagram each time an interaction you specified occurs. Event Structure Components Use the Event structure. Using events reduces the CPU requirements of the program.
The event selector label at the top of the Event structure indicates which events cause the currently displayed case to execute. Events allow you to execute a specific event-handling case each time a user performs a specific action. Polling the front panel requires a significant amount of CPU time and can fail to detect changes if they occur too quickly. You can configure each case to handle one or more events.
By using events to respond to specific user actions. The Event structure completes execution after handling exactly one event. View other event cases by clicking the down arrow next to the case name and selecting another case from the shortcut menu.
When the Event structure executes. Programmatically generated events have many of the same advantages as user interface events and can share the same event-handling code. Use programmatically generated events to communicate among different parts of the program that have no dataflow dependency.
When this occurs. Without events. The Event structure works like a Case structure with a built-in Wait on Notification function. Like a Wait on Notification function. The Event structure can have multiple cases. Lesson 1 Moving Beyond Dataflow might execute frequently because the events they handle occur frequently.
Refer to the Notify and Filter Events section of this lesson for more information about filter events. This node is attached to the inside right border of filter event cases. If you configure a single case to handle multiple events.
If you wire a value to the Timeout terminal. If you do not wire a value to a data item of an Event Filter Node. The dynamic event terminals are available by right-clicking the Event structure and selecting Show Dynamic Event Terminals from the shortcut menu. Note Like a Case structure. The default is —1. All unwired tunnels use the default value for the tunnel data type.
The node provides different data elements in each case of the Event structure depending on which event s you configure that case to handle. You can resize this node vertically to add more data items. These terminals are used only for dynamic event registration. 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. This node is attached to the inside left border of each event case. Dynamic event registration avoids the limitations of static registration by integrating event registration with the VI Server. LabVIEW supports two models for event registration—static and dynamic. Static registration allows you to specify which events on the front panel of a VI you want to handle in each Event structure case on the block diagram of that VI.
The reference to the object that generated the event is strictly typed to the VI Server class of that object. Dynamic registration provides more flexibility in controlling what events LabVIEW generates and when it generates them.
To avoid generating unwanted events. LabVIEW generates user interface events only as a result of direct user interaction with the active front panel. In many cases. Events are grouped into classes according to what type of object generates the event.
Lesson 1 Moving Beyond Dataflow behavior where tunnels must be wired in all cases. You cannot statically configure an Event structure to handle events for the front panel of a different VI.
LabVIEW does not generate events. Configuration is static because you cannot change at run time which events the Event structure handles. The time stamp is a millisecond counter you can use to compute the time elapsed between two events or to determine the order of occurrence.
Note In general. Each event is associated with a control on the front panel of the VI. You also can configure the tunnels to wire the input and output tunnels automatically in unwired cases. If a single case handles multiple events for objects of different VI Server classes. Since the user already knows text entry is needed. If you register for the same event on both the VI and Control class. Note Clusters are the only container objects for which you can generate events.
If the Lock front panel defer processing of user action until this event case completes option is enabled. You cannot turn off front panel locking for filter events. LabVIEW does not generate further events. Caution If no Event structure executes to handle an event and front panel locking is enabled. If this occurs. If the Event structure case for a VI event or for a Control event on a container object discards the event.
If the Lock front panel defer processing of user action until this event case completes option is disabled. LabVIEW places a copy of the event into each queue registered for that event. You can disable front panel locking by right-clicking the Event structure and removing the checkmark from the Lock front panel defer processing of user action until this event case completes checkbox in the Edit Events dialog box.
When an event occurs. Front panel locking does not affect certain actions. Because the Event structure handles only one event each time it executes. An Event structure handles all events in its queue and the events in the queues of any Register For Events functions that you wired to the dynamic event terminals of the Event structure. LabVIEW locks the front panel that contains the object that generated that event.
The Value Change event generates the event on an element in the cluster. LabVIEW uses these queues to ensure that events are reliably delivered to each registered Event structure in the order the events occur. While the front panel is locked. LabVIEW does not process front panel activity but places those interactions in a buffer and handles them when the front panel is unlocked.
Specify an event source in the Event Sources pane. When you run a VI. Right-click the border of the Event structure and select Edit Events Handled by This Case from the shortcut menu to display the Edit Events dialog box to edit the current case. You also can select Add Event Case from the shortcut menu to create a new case. When you click an item in this list. When the top-level VI finishes running. Select the event you want to configure for the event source.
Optional If you want to configure the Event structure to handle a user event.
If you have registered for events dynamically and wired event reg refnum out to the dynamic event terminal. Select the event source. Value Change. Configuring Events Before you configure events for the Event structure to handle. Complete the following steps to configure an Event structure case to handle an event. You can repeat steps 3 and 4 to redefine each event or click the X button to remove the selected event.
This is the same event you selected when you registered the event. If you want to add additional events for the current case to handle. When you select a dynamic event source from the Event Sources list. Use the Edit Events dialog box to configure an Event structure to handle a statically registered event. Select a specific event the event source can generate. Edit the case to handle the event data according to the application requirements. The Event Specifiers section at the top of the dialog box lists all the events for the case to handle.
In order to display the context menu when you left-click a control. Use filter events to participate in the handling of the event. Wire a value to the Timeout terminal at the top left of the Event structure to specify the number of milliseconds the Event structure should wait for an event to occur before generating a Timeout event.
Click the OK button to save the configuration and close the dialog box. Notify and Filter Events Notify events are an indication that a user action has already occurred. Repeat steps 1 through 6 for each event case you want to configure. Most filter events have an associated notify event of the same name. In an Event structure case for a filter event.
If an Event structure in the chain discards the event. LabVIEW sends a copy of the event to each Event structure configured to handle the event in parallel. Filter events have names that end with a question mark.
The default value for the Timeout terminal is —1. To perform this action. If an Event structure case changes any of the event data. You can configure any number of Event structures to respond to the same notify event on a specific object.
The value of the left mouse button is 1. When the event occurs. The order in which LabVIEW sends the event to each Event structure depends on the order in which the events were registered. The event cases you configured appear as selection options in the event selector label at the top of the Event structure and the Event Data node displays the data common to all events handled in that case.
As with notify events. Optional You can use a Timeout event to configure an Event structure to wait a specified amount of time for an event to occur. If you do not wire a value to the data item of the Event Filter Node. Note National Instruments recommends you use filter events only when you want to take part in the handling of the user action.
The ItemTag returns the menu item that was selected and the MenuRef returns the refnum to the menubar. This VI uses the Event structure to capture menu selections made using the user-defined menu named sample. A case can handle multiple notify events but can handle multiple filter events only if the event data items are identical for all events. This information is passed to the Get Menu Item Info function. If you only want to know that the user performed a particular action.
You can change the event data by wiring new values to these terminals. Lesson 1 Moving Beyond Dataflow completes processing the user action which triggered the event only after all configured Event structures handle the event without discarding it.
Event structure cases that handle filter events have an Event Filter Node. Tip In the Edit Events dialog box.
Note A single case in the Event structure cannot handle both notify and filter events. In any given VI. When you trigger an event on a Boolean control configured with a latching mechanical action. When an event occurs in this configuration. If you place two Event structures in a single loop. You must read the terminal inside the event case for the mechanical action to work correctly. National Instruments recommends that you place only one Event structure in a loop. If you have enabled front panel locking for the Event structures.
True b. Events c. Numeric c. Local Variables 2. Array of Booleans e. Queues b. Quiz 1. Enum d. Cluster of a String and a Numeric 4. Match the following: Obtain Queue Destroys the queue reference Get Queue Status Assigns the data type of the queue Release Queue Adds an element to the back of the queue Enqueue Element Determines the number of elements currently in the queue 3.
Which of the following buffer data? Which of the following are valid data types for queues? String b. The Event structure handles only one event each time it executes. Obtain Queue Assigns the data type of the queue Get Queue Status Determines the number of elements currently in the queue Release Queue Destroys the queue reference Enqueue Element Adds an element to the back of the queue 3. Quiz Answers 1. Generating Error Codes and Messages F. Error Handlers E. LabVIEW provides templates for several common design patterns.
This lesson discusses two different categories of programming design patterns—single loop and multiple loops. Single loop design patterns include the simple VI. Timing a Design Pattern G. Design patterns represent techniques that have proved themselves useful time and time again.
Multiple loop design patterns include the parallel loop VI. Design Patterns B. Implementing Design Patterns 2 You can develop better programs in LabVIEW and in other programming languages if you follow consistent programming techniques. Multiple Loop Design Patterns D. Simple Design Patterns C. To facilitate development. You can use this VI as a subVI whenever you must determine the warning level.
Your program might consist of a single VI that takes a measurement.
Use this architecture for simple applications or for functional components within larger applications. This VI performs a single task—it determines what warning to output dependent on a set of inputs. You can convert these simple VIs into subVIs that you use as building blocks for larger applications. Simple VI Architecture ni. Notice that the VI in Figure contains no start or stop actions from the user.
Design patterns represent the techniques that have proved themselves useful over time. You can determine the overall order of operations by following the flow of data. Design patterns typically evolve through the efforts of many developers and are fine-tuned for simplicity.
Design Patterns Application design patterns represent LabVIEW code implementations and techniques that are solutions to specific problems in software design. The simple VI design pattern usually does not require a specific start or stop action from the user.
In this VI all block diagram objects are connected through data flow. The user just clicks the Run button. Each of the following phases may contain code that uses another type of design pattern.
Figure shows the general VI design pattern. In Figure , the error cluster wires control the execution order of the three sections. 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 loop 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 for reaction times. A wait of to 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. State Machine Design Pattern Polling 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 pattern for VIs that are easily divided into several simpler tasks, such as VIs that act as a user interface. 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 Figure shows the other cases, or states, of the state machine. State Machine with Startup State. In the state machine design pattern, you design the list of possible tasks, or states, and then map them to each case. An enumerated constant stores the states. Each state has its own case in the Case structure. The outcome of one 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 approach 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 a queue of events, or states, so that you do not miss a state.
Refer to Lesson 1, Moving Beyond Dataflow, for more information about queue-based state machines. Use the Create Project dialog box to create a project from a template or sample project.
Templates provide common architectures that you can modify to accomplish specific goals. If you need multi-rate or parallel tasks. Refer to the Single Shot Measurement sample project.
Sample projects demonstrate how a template can be modified to accomplish specific goals. When a user clicks a button. The application is based on the event-based state machine design pattern. This subdiagram initiates a transition to the appropriate state. Because this combination is so useful for a wide range of applications. This state contains an Event structure that waits for front panel changes. Lesson 2 Implementing Design Patterns State Machine Design Pattern Event-Based The polling-based state machine design pattern monitors front panel activity using standard dataflow techniques.
Only one state executes at a time. An event-based state machine combines the powerful user interaction of the user interface event handler with transition flexibility of the state machine. LabVIEW provides a project-based template. The Simple State Machine template is a customizable application which is in the form of a.
The template includes ample documentation on how to modify the code to build a customized state machine application.
The Wait for Event state is the only one that recognizes user input. The state machine must be in this state for any user input to be accepted. Therefore, each state should be quick so the code can return to the Wait for Event state. Use the user interface event handler for detecting when a user changes the value of a control, moves or clicks the mouse, or presses a key.
The standard user interface event handler template consists of an Event structure contained in a While Loop, as shown in Figure Configure the Event structure to have one case for each category of event you want to detect. Each event case contains the handling code that executes immediately after an event occurs. Because the event handler loop wakes up precisely when an event occurs and sleeps in between events, you do not have to poll or read control values repeatedly in order to detect when a user clicks a button.
The user interface event handler allows you to minimize processor use without sacrificing interactivity. A common problem when using the user interface event handler is that it computes the While Loop termination before the Event structure executes. This can cause the While Loop to iterate one more time than you expected.
To avoid this situation, compute the While Loop termination within all your event handling code. The event handler code must execute quickly, generally within ms. Anything slower can make it feel as if the user interface is locked up. Also, if the event handler code takes a long time to execute, the Event structure might lock. By default, the front panel locks while an event is handled.
You can disable front panel locking for each event case to make the user interface more responsive. However, any new events that are generated while an event is being handled will not be handled immediately. So, the user interface will still seem unresponsive. Any code that is in an event case cannot be shared with another Event structure case.
You must use good code design when using the Event structure. Modularize code that will be shared between multiple Event structure cases.
The Event structure includes a Timeout event, which allows you to control when the Timeout event executes. For example, if you set a Timeout of ms, the Timeout event case executes every ms in the absence of other events. You can use the Timeout event to perform critical timing in your code.
Multiple Loop Design Patterns There are several multiple loop design patterns, some of which are beyond the scope of this course. Data queues communicate data among the loops. The data queues also buffer data among the producer and consumer loops. Tip A buffer is a memory device that stores temporary data among two devices, or in this case, multiple loops.
Suppose you want to create a VI that accepts data while processing the data sets in the order they were received. You could put the producer and consumer in the same loop for this application, but the processing queue could not receive additional data until the first piece of data was completely processed.
Tip Queue functions allow you to store a set of data that can be passed among multiple loops running simultaneously or among VIs. This design pattern allows the consumer loop to process the data at its own pace, while the producer loop continues to queue additional data. 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 parallel producer and consumer loops handle the retrieval and analysis of data off the network, and the queued communication between the two 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. The first process acts as the producer because it supplies data to the second process. Queues have the ability to transfer any data type. A string is not the most efficient data type for passing data in design patterns. A more efficient data type for passing data in design patterns is a cluster consisting of state and data elements.
The data type transferred in Figure is a string. Lesson 2 Implementing Design Patterns they are received. The parallel producer and consumer loops handle the retrieval and analysis of data off the network. Figure shows how you can use Synchronization VIs and functions to add functionality to the design pattern.
Queuing producing the data occurs much faster than the data can be processed consumed. The Wait ms in Consumer Loop slider simulates intensive processing time in the consumer loop.
The Event structure enables continuous response to user interaction. While the consumer loop executes. With this implementation. The front panel includes a button that controls when the Data to Enqueue sting value is added to the queue. The queue retains each element and executes them in order after the simulated processing of the element in the consumer loop.
This demonstrates the effect on the overall program execution. The consumer loop of this pattern responds as events occur. Data directory. The user interface is completely responsible for determining the actions taken in the consumer loop. Event directory. Even if there is a backlog of normal priority queue elements. Because the producer loop uses an Event structure.
The front panel includes buttons to enqueue either a normal priority message or a high priority message.
When a Normal Priority Message is enqueued. While the consumer loop is busy. When the user clicks on the Stop button. The consumer loop is implemented with a 1 second wait to demonstrate the effect of intensive processing time. Job Aid Use Table to determine the best uses for the design patterns described in this lesson. When a High Priority Message is enqueued. Unable to return to a run. The State to Execute indicator shows the current state being executed in the Consumer Loop.
Error Handlers By default. If you plan to create a stand-alone application. The user might be unable to continue running the application or fix the problem.
Automatic error handling is convenient for quick prototypes and proof-of-concept development. Lesson 2 Implementing Design Patterns Table By manually implementing error handling.
Figure shows a state machine error handler that sets the next state to be the Shutdown state when an error in status is TRUE. If you rely on automatic error handling your application might stop in a critical section of your code because of an error dialog box. Another common error handler is a VI that redirects code to a cleanup or shutdown routine when an error occurs so that your application exits gracefully.
You can implement other error handlers that are customized for your application. An error handler is a VI or code that changes the normal flow of the program when an error occurs. Some techniques involve adding an additional communication channel—such as an additional queue.
There are many techniques for communicating error information between the two loops. Another technique is to use the existing queue cluster to execute a Shutdown case in the Consumer loop. In addition to passing commands and data between loops. Since you want to re-use this same Error Handler VI in the consumer loop. Lesson 2 Implementing Design Patterns Figure The next node does the same thing.
At the end of the execution flow. As the VI runs. Just as data values flow through a VI. The Consumer Shutdown? LabVIEW tests for errors at each execution node. One approach. If an error occurs in the consumer loop. If you have multiple custom errors you want to use in the Error Ring. Instead of the generic error message. Check for empty arrays or empty strings before processing.
If an input is invalid. Generate Warning. Include Call Chain. Defining a Custom Error Code Creating a custom error code is useful if you want to define a single error code or overwrite a single built-in error code. If the value is negative. You also can toggle the error type and call chain options by right-clicking the Error Ring and selecting Generate Error. An example might be checking to see if an input is a positive value before attempting to take the square root of the number.
There are many situations where you might want to report an error condition that you detected with your code. As a VI developer. In this situation. Error Ring After you select the error. You can configure the ring to return a built-in error message or you can create a custom error message for a one-time use. Figure shows a configured error ring. Below are a few examples for setting or overriding error codes and messages: Execution timing uses timing functions to give the processor time to complete other tasks.
Explicit timing uses a function that specifically allows the processor time to complete other tasks. LabVIEW uses all the processor time. Timing a Design Pattern This section discusses two forms of timing—execution timing and software control timing.
In this case. Execution Timing Execution timing involves timing a design pattern explicitly or based on events that occur within the VI. Tip Always use a timing function such as the Wait ms function or the Wait Until Next ms Multiple function in any design pattern that continually executes and needs to be regulated. You need to time the producer so it does not take over the execution of the processor.
The producer executes continuously and polls for an event of some type. Tip Polling is the process of making continuous requests for data from another device. If you do not use a timing function in a continuously executing structure. Software control timing involves timing a real-world operation to perform within a set time period. When timing is based on events. This creates an efficient block diagram that does not waste processor cycles by polling for messages.
The use of queues to pass data and messages provides an inherent form of timing in the consumer loop because the consumer loop waits for the Queue function to receive an enqueued element. 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.
After the Queue function receives a queued element. Synchronization functions and the Event structure both include a Timeout feature. With an infinite timeout. The Dequeue Element function in the consumer loop waits until an item is placed in the queue. The Event structure in the producer loop controls when the producer loop executes. If the specifications require that the system acquire temperature data for 5 minutes.
Lesson 2 Implementing Design Patterns Specifying a timeout value allows functionality to be executed at regular intervals. The consumer loop executes every 50 ms even if the queue is empty. In Figure To process user interface actions.
Wiring a millisecond value to the timeout terminal of an Event structure wakes the Event structure and executes the code in the Timeout case.
Consider implementing a state machine design pattern for a temperature data acquisition system. Implementing this type of timing involves keeping the application executing while monitoring a real-time clock. These timing functions are not the preferred method for performing software control timing. The Functional Global Variable is one such design pattern. Before you can understand this new design pattern. Race Condition Example Both loops modify a local variable during each loop iteration.
If the difference in these two times is greater or equal to the wait time. Some design patterns. Race conditions are a common problem for programs that execute multiple tasks in parallel and share data between them. Since both loops are running at the same speed. Read-Modify-Write Race Conditions A race condition occurs when the timing of events or the scheduling of tasks unintentionally affects an output or data value.
One loop increments the counter while the other loop decrements the counter. Some other design patterns are useful components in larger applications. If you run this VI.
Consider the example in Figure Depending on when you ni. Loop 2 writes the decremented value to the local variable. Loop 2 reads the local variable. Loop 1 reads the local variable. Loop 2 decrements the value it read. Notice that both of the loops perform the following operations: On a single processor computer. The way tasks interact with each other and the operating system. The best way to avoid race conditions is by using the following techniques: Race conditions are difficult to identify and debug.
Loop 1 writes the incremented value to the local variable. The race condition in this example occurs when the switch from one task to the other occurs at a certain time.
Loop 1 increments the value it read. If the local variable started out with a value zero. In this example. This generates a race condition. This explains why this VI might run accurately for short periods and only loses a few counts for longer periods.
In this particular example. Protecting Critical Sections A critical section of code is code that must behave consistently in all circumstances. Allowing a resource to be altered from multiple locations often introduces the possibility for a race condition. In general. Lesson 2 Implementing Design Patterns Controlling and Limiting Shared Resources Race conditions are most common when two tasks have both read and write access to a resource.
Figure shows a solution to the race condition using semaphores. If all shared resources have only a single writer or controller. When dealing with race conditions. Most race conditions only occur when a resource has multiple writers. To remove the race condition. Within each loop.
You can prevent critical sections of code from interrupting each other by enclosing each between an Acquire Semaphore and Release Semaphore VI. This involves only a single read and a single write to a shared resource and eliminates the possibility of a race condition. When you use multi-tasking programs. Each loop in Figure contains a critical code section.