LabVIEW Core 2 Exercise Guide
LabVIEW Core 2 Exercise Guide
TM
Exercises
Patents
For patents covering National Instruments products/technology, refer to the appropriate
location: Help»Patents in your software, the patents.txt file on your media, or the National
Instruments Patent Notice at ni.com/patents.
Support
Worldwide Technical Support and Product Information
ni.com
Worldwide Offices
Visit ni.com/niglobal to access the branch office websites, which provide up-to-date
contact information, support phone numbers, email addresses, and current events.
For further support information, refer to the Additional Information and Resources appendix.
To comment on National Instruments documentation, refer to the National Instruments website
at ni.com/info and enter the Info Code feedback.
Exercise 1-1 Weather Station UI VI with Local Variables
Goal
Use a local variable to write to and read from a control.
Scenario
You have a LabVIEW project that implements a temperature weather station. The weather station acquires a temperature every half a second, analyzes each
temperature to determine if the temperature is too high or too low, then alerts the user if there is a danger of a heat stroke or freeze. The VI logs the data
if a warning occurs.
Two front panel controls determine the setpoints—the temperature upper limit and the temperature lower limit. However, nothing prevents the user from
setting a lower limit that is higher than the upper limit.
Use a local variable to set the lower limit less than the upper limit if the user sets a lower limit that is higher than the upper limit.
Design
Your task is to modify a VI so that the lower limit is set less than the upper limit when necessary.
State Definitions
The following table describes the states in the state machine.
Acquisition Set time to zero, acquire data from the temperature sensor Analysis
Analysis Read front panel controls and determine warning level Data Log if a warning occurs, Time Check if no warning occurs
Data Log Log the data in a tab-delimited ASCII file Time Check
Time Check Check whether time is greater than or equal to .5 seconds Acquisition if time has elapsed, Time Check if time has not elapsed
Changing the value of the lower temperature limit control should happen after the user has entered the value but before the value determines the warning
level. Therefore, make the modifications to the VI in the Acquisition or Analysis state, or place a new state between the two.
Before determining which option to use, review the content of the Acquisition and Analysis states:
3. Review the contents of the Acquisition and Analysis states, which correspond to the Acquisition and Analysis cases of the Case structure.
Design Options
1-10
Lesson 1
You have three different design options for modifying this project.
|
ni.com
Using Variables
1 Insert a Case structure in the Acquisition state to reset the Poor design: the acquisition state has another task added, rather than
controls before a local variable writes the values to the cluster. focusing only on acquisition.
2 Insert a new state in the state machine that checks the controls Ability to control when the state occurs.
and resets them if necessary.
3 Modify the Temperature Warnings subVI to reset the controls. Easy to implement because functionality is already partially in place.
However, if current functionality is used, one set of data is always lost
when resetting the lower limit control.
Acquisition If you have hardware installed, acquire data from the temperature Range Check
sensor on channel AI0 and read front panel controls.
Otherwise, simulate this acquisition.
Range Check Read front panel controls and set the lower limit to 1 less than the Analysis
upper limit if the upper limit is less than the lower limit.
Data Log Log the data in a tab-delimited ASCII file Time Check
Time Check Check whether time is greater than or equal to .5 seconds Acquisition if time has elapsed
Time Check if time has not elapsed
Implementation
1. Open Weather Station.lvproj from the <Exercises>\LabVIEW Core 2\Weather Station directory.
a. In the Project Explorer window, navigate to Supporting Files and open Weather Station States.ctl.
b. Right-click the States control and select Edit Items from the shortcut menu.
c. Insert an item and modify the item to match Table 1-4. Be careful not to add an empty listing.
Acquisition 0
Range Check 1
Analysis 2
Data Log 3
Time Check 4
Note The Run arrow is broken as there as some unwired terminals. You complete the wiring of these terminals in the following steps.
f. On the block diagram of the Weather Station UI VI, right-click the state machine Case structure and select Add Case for Every Value from the
shortcut menu. Because the enumerated control has a new value, a new case appears in the Case structure.
Lesson 1
Figure 1-1. Weather Station UI VI with Local Variables—Completed Acquisition State
|
ni.com
Using Variables
4. Modify the Analysis case as shown in Figure 1-2.
1 Delete the Bundle By Name function and wire the Weather Data wire directly to the Temperature Warnings VI. Press <Ctrl-B> to delete the broken
wires from the Upper Limit and Lower Limit controls.
2 Move the Upper Limit and Lower Limit controls outside the While Loop.
Lesson 1
When the Upper Limit control value is less than or equal to the Lower Limit control value, use a local variable to write the value, upper limit - 1, to the
|
Using Variables
Figure 1-3. Weather Station UI VI with Local Variables—Range Check True Case
8 3 4 5 6 7
If the Upper Limit control value is not less than or equal to the Lower Limit control value, the False case executes and the values are passed, unchanged,
through to the temperature cluster.
Figure 1-4. Weather Station UI VI with Local Variables—Range Check False State
Test
1. Run the VI.
3. Enter a value in the Upper Limit control that is less than the value in the Lower Limit control. Does the VI behave as expected?
Description
The following sections describe how the Queues vs Local Variables VI does the following.
• Creates a queue.
• Uses local variables to read and display data from the producer loop.
Lesson 2
1. Open Queues vs Local Variables.lvproj in the <Exercises>\LabVIEW Core 2\Queues versus Local Variables directory.
|
ni.com
2. Double-click Queues vs Local Variables.vi in the Project Explorer window to open the VI. The front panel of this VI is shown in Figure 2-1.
3. Run the VI. The Producer Loop generates data and transfers it to each consumer loop using a local variable and a queue. Observe the behavior of the
VI when the consumer loops are set to the same speed as the producer loop.
Lesson 2
You create the queue with code shown in Figure 2-3. This code is located to the left of the producer loop.
|
ni.com
2
3
1 Max queue size—Sets the maximum number of elements that the queue can hold.
2 Double-precision Numeric constant—Wired to the element data type input, specifies the type of data you want the queue to contain.
3 Obtain Queue—Creates the queue and defines the data type.
1 Enqueue Element—Adds each data element the Generate Sine VI generates in the Producer Loop to the back of the queue.
Dequeuing Data from the Producer Loop inside the Queue Consumer Loop
Figure 2-5. Dequeuing Data inside the Consumer Loop
2
1
1 Dequeue Element—Removes an element from the front of the queue and sends the data element to the Queue Loop waveform chart.
2 Get Queue Status—Indicates how many elements remain in the queue. In order to process these data elements, you must execute the Queue Consumer
Loop faster than the Producer Loop, or continue to process after the Producer Loop stops.
Lesson 2
Figure 2-6. Waiting for the Queue to Empty
|
ni.com
2 5
4
3
1 While Loop—Waits for the queue to empty before stopping the VI. Refer to this While Loop as the Queue Wait Loop.
2 Get Queue Status—Returns information about the current state of the queue, such as the number of data elements currently in the queue.
3 Equal To 0?—Wired to the stop condition of the Queue Wait Loop, checks if the queue is empty.
4 Release Queue—Releases and clears references to the queue.
5 Simple Error Handler—Reports any error at the end of execution.
Local Variable Consumer Loop
The Producer Loop also writes the generated sine wave data to a local variable while the Local Variable Consumer Loop periodically reads out the sine wave
data from the same local variable.
Test
Local Variable Consumer Loop
1. Switch to the front panel of the Queues vs Local Variables VI.
3. Select different speeds for the Local Variable Consumer Loop and observe the Local Variable Consumer Loop chart and the results generated on the
Missing Samples indicator or Duplicated Samples indicator.
Ensure that the Loop Speed selected is Same as Producer Loop and observe the Producer Loop chart and the Local Variable Consumer Loop chart.
A race condition may occur resulting in missed points or duplicated data.
Select 2x as Producer from the pull-down menu of the Loop Speed control and observe the Local Variable Consumer Loop chart. A race condition
occurs because data is consumed faster than it is produced, allowing the local variable to read the same value multiple times.
| 2-11
Select 1/2 as Producer from the pull-down menu of the Loop Speed control and observe the Local Variable Consumer Loop chart. A race condition
2-12
Lesson 2
occurs because data is produced faster than it is consumed. The data changes before the local variable has a chance to read it.
|
Select the remaining options available from the pull-down menu of the Loop Speed control and observe the data retrieval.
ni.com
Data transfer between two non-synchronized parallel loops using local variables causes a race condition. This occurs when the Producer Loop is writing
a value to a local variable while the Local Variable Consumer Loop is periodically reading out the value from the same local variable. Because the parallel
loops are not synchronized, the value can be written before it has actually been read or vice versa resulting in data starvation or data overflow.
2. Select the loop time speed of the Queue Consumer Loop and observe the Queue Consumer Loop waveform chart and the results generated on the
Samples in Queue indicator.
Ensure that the Loop Speed selected is Same as Producer and observe the value of the Samples in Queue indicator. The value should remain zero.
Hence with queues, you will not lose data when the producer and consumer loops are executing at the same rate.
Select 2x as Producer from the pull-down menu of the Loop Speed control and observe the value of the Samples in Queue indicator. The value
should remain zero, because the Dequeue Element function in the Queues Consumer Loop controls the maximum speed of the loop. If the queue is
empty, the Dequeue Element function waits for a data element to enter the queue, essentially pausing the loop.
Select 1/2 as Producer from the pull-down menu of the Loop Speed control and observe the value of the Samples in Queue indicator. The data
points accumulate in the queue. You need to process the accumulated elements in the queue before reaching the maximum size of the queue to
avoid data loss.
Select the remaining options available from the pull-down menu of the Loop Speed control and observe the synchronization of data transfer between
the producer loop and the consumer loop using queues.
When the Producer Loop and Queue Consumer Loop run at the same speed, the number of elements in the queue remains unchanged. When the Queue
Consumer Loop runs slower, the queue quickly backs up and the Producer Loop must wait for the Queue Consumer Loop to remove the elements. When
the Queue Consumer Loop runs faster, the queue quickly empties and the consumer loop must wait for the Producer loop to insert elements. Hence
queues synchronize the data transfer between the two independent parallel loops and thus avoid loss or duplication of data.
Lesson 3
|
Goal
ni.com
Implementation
1. Open the Producer Consumer project located in the <Exercises>\LabVIEW Core 2\Producer Consumer - Event directory, and then open Main.vi,
shown in Figure 3-1, from the project.
Notice that State to Execute says High Priority and the Processed Value indicator says 1000.
Click the Highlight Execution button on the block diagram and then run the VI and watch what happens when you click the Normal Priority button.
Notice that the Wait (ms) in the Default state of the Consumer loop is set to 1000. This is what causes the processing of one message per second.
Notice that the VI stops even though the backlog has not been processed.
The Enqueue Element at Opposite End function caused this to occur. If the Stop should occur after all messages in the backlog are processed, then
this function would be replaced with a regular Enqueue Element function.
Right-click the error output tunnel of the Case Structure and select Create»Constant.
In the new error cluster constant, set the value of the Status Boolean to True.
| 3-9
Run the VI again and click Normal Priority.
3-10
Lesson 3
Notice that the VI does not behave properly anymore. This is because an error in the Consumer loop has caused the Consumer loop to shut down.
|
Because the Consumer loop was doing the bulk of the work, the VI does not behave correctly. The Producer loop is still running.
ni.com
This VI does not include any error handling. You modify a version of this VI in another exercise to enable error handling so the VI shuts down if an error occurs.
Lesson 3
|
Goal
ni.com
To create a gating application, using a functional global variables design pattern, which restricts user access to certain features based on different user
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.
Design
The following table describes the different actions you need to handle so you can implement user access control. In this exercise, you create a custom
control to handle these items.
Action Description
Read User Access Level File Read information about authorized users and their access levels from a specified file and stores this access information in
memory.
Set Current User Specify the name of the current user. Store the access level for that user in application memory.
Get User Access Level Retrieve the access level of the current user from memory so that the application can determine if a user has access to a
certain feature.
Implementation
1. Open the User Level FGV.lvproj project from <Exercises>\LabVIEW Core 2\FGVs.
2. Open the User Level FGV folder in the Project Explorer window and then open User Access Level FGV.vi. The User Access Level FGV VI already contains
several items on the front panel, an icon, and connector pane.
3. Create a type-defined enum control and modify the front panel as shown in Figure 3-2.
1 Enum (Silver)—Place an Enum (Silver) control on the front panel. Right-click the enum control and select Make Type Def.
4. Right-click the Use Level Cmd enum control and select Open Type Def from the shortcut menu.
Lesson 3
Figure 3-3. Editing the User Access Level Cmd Enum
|
ni.com
6. Save the enum as User Level Cmd.ctl in <Exercises>\LabVIEW Core 2\FGVs\User Level FGV and close the custom control editor window.
7. From the User Access Level FGV VI front panel, assign a terminal from the top-level of the User Access Level FGV VI connector pane to the User Level
Cmd control as shown in Figure 3-4.
Figure 3-4. Assign the User Level Cmd Control to a Connector Pane Terminal
1 Connector pane terminal—Click the terminal indicated by the arrow, then click the User Level Cmd control to assign the control to the connector pane
terminal.
Right-click the connector pane terminal and select This Connection Is»Required. By making this terminal required, an application must provide a value
to the User Level Cmd input when you use the User Access Level VI in another VI.
8. Create the framework for the functional global variable design by completing the block diagram as shown in Figure 3-5.
5 5
1 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.
2 Case selector—Wire User Level Cmd to the case selector.
3 Case structure—Right-click the Case structure and select Add Case for Every Value from the shortcut menu and then select “Read User Access Level
File”, Default.
4 Error In/Error Out—Wire Error In to Error Out through the default case.
5 Wire Error In/Error Out through all cases—Right-click the output tunnel and select Linked Input Tunnel»Create & Wire Unwired Cases. When the cursor
changes to a wiring tool, click on the left-side input tunnel. Small white triangles inside the input and output tunnels indicate the link.
Tip Use the Add Case for Every Value option when you know that each case diagram is significantly different. If cases contain similar
Lesson 3
Figure 3-6. Configuring the Read User Access Level File Case
|
ni.com
3 4 5 5 3
1 The path to User Access Levels.txt is relative to where you save the User Access Level FGV VI. In this case, the text file is in a parallel directory.
2 Read From Spreadsheet File VI—Click the polymorphic VI selector and select String. Wire the all rows output through a tunnel on the Case Structure
to the While Loop.
3 Shift register—Right-click the tunnel and select Replace with Shift Register. Click the left side of the While Loop to complete the shift register.
4 Label—Right-click the wire and select Visible Items»Label to show the label, then type the name User Names & Levels.
5 Right-click the output tunnel and select Linked Input Tunnel»Create & Wire Unwired Cases, then click the corresponding input tunnel.
10. Complete the Set Current User case as shown in Figure 3-7.
4 4 3
2 1
1 Index Array function—Wire the User Names & Levels wire to an Index Array function.
2 User Levels Column and Names Column constants—Create constants for the index (col) input of the Index Array function.
3 Shift register—Change the tunnel to shift register.
4 Right-click the output tunnel and select Linked Input Tunnel»Create & Wire Unwired Cases then click the corresponding input tunnel.
Lesson 3
Figure 3-8. Get User Access Level Case
|
ni.com
2. Double-click User Access Level FGV Unit Test.vi in the Project Explorer window to open the VI. This VI takes a user name you input, sets the permissions
of the VI to the user's access level, and tests whether the proper access level is set.
Note The User Access Level FGV Unit Test VI is broken until you complete step 3 because of the required input you set in step 7 of the
implementation.
3. Complete the “Set Current User”: Value Change event as shown in Figure 3-10.
Figure 3-10. Completing the “Set Current User”: Value Change Event
1 1
1 User Access Level FGV VI—This is the VI you modified in this exercise. It has already been placed on the block diagram.
2 User Level Cmd Constants—Right-click the User Level Cmd input and select Create»Constant.
| 3-19
4. Complete the “Test Access Level”: Value Change event case as shown in Figure 3-11.
3-20
Lesson 3
Figure 3-11. Completing the “Test Access Level”: Value Change Event
|
ni.com
John Operator
Paul Admin
George Admin
Ringo Operator
Scenario
You need to test error handling in a Producer/Consumer design pattern VI.
Design
Add buttons to inject simulated errors in the producer loop and the consumer loop. Use Error Ring constants to produce simulated errors. Update the producer
loop to handle an error case.
Implementation
1. Open the Producer Consumer project located in the <Exercises>\LabVIEW Core 2\Producer Consumer - Error directory, and then open the
Main.vi from the project.
This VI is similar to the one you used in Exercise 3-1. The Producer Error and Consumer Error buttons are provided on the front panel, as shown in
Figure 3-12. You modify the block diagram to enable the buttons and test error handling in this VI.
Figure 3-12. Producer Consumer Main VI Front Panel with Error Buttons
Lesson 3
Figure 3-13. Producer Loop “Producer Error”: Value Change Event
|
ni.com
1 “Producer Error”: Value Change Event—Right-click the Event Structure and select Add Event Case.
2 Producer Error—Drag the terminal into the new Event Case.
3 Error Ring Constant—When an error occurs, the VI stops running and the error message you select here is displayed in a dialog box. Refer to Figure 3-14
to configure the Error Ring Constant.
3. Click the down arrow in the Error Ring constant and configure the Error Ring to display the message 15: LabVIEW: Resource not found as shown
in Figure 3-14.
Lesson 3
Figure 3-15. Consumer Loop Custom Error Code
|
ni.com
Test
1. Run Main.vi.
Lesson 3
|
Goal
ni.com
You can modify the producer/consumer template to handle those three tasks as well as errors and UI events from the producer/consumer template itself.
Design
After copying the template, you update the producer loop to generate waveform data and you update the consumer loop to display a histogram and take a
snapshot of the histogram when the user specifies.
Implementation
1. Move and rename the Producer Consumer project and files.
Open the Producer Consumer.lvproj located in the <Exercises>\LabVIEW Core 2\Producer Consumer - Template directory.
Select File»Save As and set the save as options as shown in Figure 3-17, and then click the Continue button.
3. Open Histogram.lvproj and rename the project VIs in LabVIEW so that LabVIEW can update all links and instances of the VIs.
4. Add the Shared folder to the project as an auto-populating folder. The Shared folder contains the Generate Data VI and the Running Histogram VI that
you use later.
5. Open the block diagram of the Histogram Main VI.
3-36
Lesson 3
6. Update the Consumer Message type definition, shown in Figure 3-18 to handle waveform data.
|
ni.com
Figure 3-18. Consumer Message Type Definition Terminal on Histogram Main VI Block Diagram
1 Consumer Message type definition—Right-click the Consumer Message type definition located to the left of the producer loop on the Histogram Main
VI block diagram and select Open Type Def.
a. Modify the Consumer Message type definition as shown in Figure 3-19.
1 2
1 Array—Add an array to the type definition so it can handle waveform data. Rename the Array Signal.
2 Numeric Indicator—Add a numeric indicator to the array.
3 Right-click the cluster border and select Reorder Controls In Cluster and arrange them so that the Signal control is directly below the Numeric Data
control.
Lesson 3
Figure 3-20. Viewing a Type Definition as an Icon
|
ni.com
1 Right-click the Consumer Message type definition and select AutoSizing»Arrange Vertically from the shortcut menu.
2 Right-click the Consumer Message type definition and select View Cluster as Icon to save space on the block diagram.
8. Send signal data through the Consumer Message type definition. Complete the Timeout event in the producer loop as shown in Figure 3-21.
6
2
3
1 Consumer Message type definition—Copy the Consumer Message type definition and paste it inside the Timeout event case.
2 Bundle By Name function—Wire the Consumer Message typedef to the input cluster input.
Expand the node to display two elements.
Select Consumer State and Signal.
3 Generate Data VI—Drag the Generate Data VI from the Shared folder in the Project Explorer window into the Timeout event case.
4 Wire the Y output of the Generate Data VI to the Signal input of the Bundle By Name function.
5 Create a control for the signal input of the Generate Data VI.
Lesson 3
Figure 3-22. Updating the Consumer Loop Display Case
|
ni.com
10 7 8 1 3 6 9 7
2 4
1 Open to the Default case of the Case structure and rename the case to “Display”, Default.
2 Unbundle By Name function—Change the Numeric Data element to Signal and remove the Boolean Data wire and element.
3 Running Histogram VI—Drag the Running Histogram VI from the Shared folder in the Project Explorer window.
4 Numeric control—Create a control for the bins input and label the control Bins.
5 XY Graph (Silver)—On the front panel, place an XY Graph (Silver) and rename it Histogram.
6 Bundle function—Wire the histogram and x axis outputs from the Running Histogram VI to the Bundle function.
7 Replace the right Histogram tunnel with a shift register and complete the shift register.
8 Wire the left shift register to the Case structure.
9 Right-click the Histogram output tunnel and select Linked Input tunnel»Create & Wire Unwired Cases and then click the Histogram input tunnel on the
left.
10 Right-click the left shift register and create a constant.
10. Create a Snapshot event in the producer loop by changing the “High Priority Message”: Value Change event, as shown in Figure 3-23.
Figure 3-23. Updating the Producer Loop “Snapshot”: Value Change Event
3 1 2
1 Change the event name—Change the label of the High Priority button to Snapshot. Changing the name of the button changes the event name.
2 Bundle By Name function—Delete the values wired to the Boolean Data and Numeric Data inputs of the Bundle By Name function and hide the terminals.
3 Change the value of the Consumer State string constant to Snapshot.
4 Double-click the Snapshot control to locate the button on the front panel. Change the Boolean text displayed on the button to Snapshot.
Lesson 3
Figure 3-24. Updating the Consumer Loop Snapshot Event
|
ni.com
1 2 4
1 Duplicate the Initialize case—Right-click the case structure and select Duplicate Case. Rename the duplicate case Snapshot.
2 Unbundle function—After you wire the input, the Unbundle function contains two 1D arrays.
3 Build Array function—Wire both 1D Array outputs to the Build Array function.
4 Write to Spreadsheet File VI—Wire the appended array output of the Build Array function to the 2D data input.
12. Delete the Normal Priority Message event from the Event structure in the Producer Loop. LabVIEW deletes the corresponding button from the front panel.
Test
1. Run the VI.
2. To create the look of a histogram in the chart, click the plot legend and select a horizontal bar plot type from the bottom row. You may also want to
remove the line interpolation by clicking the plot legend and selecting Interpolation from the shortcut menu.
3. Notice how changing the Signal and Bins values changes the look of the histogram.
4. Click the Snapshot button. A file dialog box displays so you can save the histogram file.
Lesson 3
6. Open the saved text file and review the contents to see the bins and values of the histogram.
|
ni.com
Lesson 4
|
Goal
ni.com
Use Property Nodes to change the properties of front panel objects programmatically.
Design
You build this VI in four stages, including a challenge.
Notice that while the VI runs, the controls are still enabled.You can change the values on the controls while the VI runs.
Lesson 4
Figure 4-2. Temperature Limit—Disable Controls Block Diagram
|
ni.com
2 3
1 Delta t (ms) Property Node—Right-click the Delta t (ms) control and select Create»Property Node»Disabled. Right click the property node and select
Change All to Write.
2 High Limit Property Node—In the Timeout Event Case, right-click the High Limit control and select Create»Property Node»Disabled.
Place the Property Node outside the While Loop, so you can move it into the “Start”: Value Change event case.
Right-click the property node and select Change All to Write.
Move the High Limit property node into the “Start”: Value Change event case.
3 Temperature Property Node—In the Timeout Event Case, right-click the Temperature indicator and select Create»Property Node»X Scale»Offset and
Multiplier»Multiplier.
Place the Property Node outside the While Loop, so you can move it into the “Start”: Value Change event case.
Right-click the property node and select Change All to Write.
Move the Temperature property node into the “Start”: Value Change event case.
4 To Double Precision Float—Converts the I32 input from the Delta t (ms) control to a double precision number.
5 Right-click the Delta t (ms) property node and select Create»Constant and set it to Disabled and Grayed Out.
Test
1. Run the VI and click the Start Acquisition button. The Delta t (ms) and High Limit controls are disabled and grayed out.
3. Run the VI a second time, click the Start Acquisition button and notice that the controls are still disabled.
1. Modify the block diagram as shown in Figure 4-3 to enable the controls each time you run the VI.
1 Create copies of the Delta t (ms) and High Limit property nodes and drag them to the left of the While Loop.
2 Create a constant to enable the controls.
Test
1. Run the VI and notice that the controls are enabled again before you click the Start Acquisition button.
2. Set different values for the controls and 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.
| 4-9
Part 3—Clear Chart
4-10
Lesson 4
You want to clear the chart each time you run the VI.
|
1. Modify the block diagram as shown in Figure 4-4 to clear old data from the chart each time you run the VI.
ni.com
1 Temperature Property Node—Create a copy of the Temperature Property node and drag it to the left of the While Loop.
Click the new property node and select History Data.
2 Right-click the History input and select Create»Constant. This creates an empty array of clusters to initialize the temperature chart to 0 when the VI
starts running.
Test
1. Run the VI, click the Start Acquisition button and let the VI run for a few seconds, then click the Stop button.
2. Run the VI a second time. Notice that the chart clears before you click the Start Acquisition button and new data is written to it.
Lesson 4
|
Goal
ni.com
Modify the Temperature Limit VI to have the following appearance and behaviors when the VI is running:
• Hide the tool bar
• Hide the menu bar
• Hide the scroll bars
• Move to the center of the screen
• Write data to an Excel file
Design—Properties
Use the following properties and methods on the VI class:
• ShowMenuBar—When this property is false, the menu bar of the VI is not displayed.
• Tool Bar:Visible—When this property is false, the tool bar of the VI is not displayed.
Tip Use the Context Help window to view descriptions of each property and method.
After you implement the changes to the VI, when you run the Temperature Limit VI it should move to the center of the screen and look similar to Figure 4-7.
Lesson 4
Part 1—Set Appearance Properties
|
1. Open the Temperature Limit VI from the Temperature Limit project located in the <Exercises>\LabVIEW Core 2\Temp Limit - Methods directory.
ni.com
2 1 3 4
Test
1. Run the VI.
2. Verify that the scroll bars, tool bar, and menu bar are not displayed, and that the front panel window is centered on the screen while the VI runs.
1. Modify the block diagram as shown in Figure 4-9 to export the data displayed on the Temperature chart to Excel.
1 Temperature Invoke Node—Right-click the Temperature indicator and select Create»Invoke Node»Export Data to Excel.
Lesson 4
1. Run the VI.
|
2. Click Stop. The Export Data to Excel method creates a temporary Excel file with the data from the Waveform chart. View the data in the Excel file.
ni.com
Scenario
Create subVIs for the Temperature Limit VI that allow you to handle some of the functionality that you enabled in previous exercises.
Implementation
1. Open the Temperature Limit VI from the Temperature Limit Project located in the <Exercises>\LabVIEW Core 2\Temp Limit - SubVIs directory.
Lesson 4
Temperature Limit VI more modular and scalable.
|
1 2
1 Set Scroll Bar State SubVI—Hides the scroll bars when the VI runs.
2 Set Dialog Properties SubVI—Hides the tool bar and menu bar when the VI runs.
3 Set Enable State on Multiple Controls VI—Sets all the controls in the input array to the Enable state value.
On the Temperature Limit block diagram, highlight the code shown in Figure 4-12 and select Edit»Create SubVI.
Double-click the subVI icon on the block diagram to open and modify the front panel of the subVI you just created as shown in Figure 4-13.
1 Pane Ref Out Indicator—Create a copy of the Pane Ref In control. Right-click the copy and select Change to Indicator and change the label.
2 Assign the Pane Ref Out indicator to the top right terminal of the connector pane. Connections for the other controls and indicators should already be
created.
5. Create a meaningful icon for the subVI and save it as Set Scroll Bar State.vi in the <Exercises>\LabVIEW Core 2\Temp Limit - SubVI
directory.
| 4-21
6. Modify the block diagram of the Set Scroll Bar State subVI as shown in Figure 4-14.
4-22
Lesson 4
Figure 4-14. Set Scroll Bar State SubVI Block Diagram
|
ni.com
On the Temperature Limit VI, highlight the code shown in Figure 4-15 and select Edit»Create SubVI.
1 VI Ref Out Indicator—Create a copy of the VI Ref In Control. Right-click the copy and select Change to Indicator and change the label.
created.
11. Create a meaningful icon for the subVI and save it as Set Dialog Properties.vi in the <Exercises>\LabVIEW Core 2\Temp Limit - SubVI
directory.
| 4-23
12. Modify the block diagram of the Set Dialog Properties subVI as shown in Figure 4-17.
4-24
Lesson 4
Figure 4-17. Set Dialog Properties SubVI Block Diagram
|
ni.com
1 Not function—Invert the logic for the Enable Dialog Properties button when wired to the property node to show the menu bar and tool bar
13. Wire the reference and error wires through the Error case.
The Set Enable State on Multiple Controls VI is provided for you in the Temperature Limit project.
Drag two copies of the VI from the Project Explorer window onto the Temperature Limit block diagram and complete the block diagram as shown
in Figure 4-18.
1 VI Server References—Create references for the Delta t (ms) control, the High Limit control, and the Start button control.
Right-click each of the controls and select Create»Reference.
The High Limit control is in the Timeout event case.
2 Build Array—Expand the node to accept three inputs.
3 Set Enable State on Multiple Controls VI—This subVI disables the specified controls when the user clicks on the Start button.
Test
2. Save and close all open VIs and the Temperature Limit project.
Lesson 6
|
This exercise consists of five VIs that you can evaluate for ways to improve. Look over each option and choose one or two to complete during the time
ni.com
allotted in class. The options are listed from easiest to hardest in terms of refactoring.
Improving an Existing VI
Select from the following options to practice refactoring LabVIEW code:
• SubVIs to For Loops
• Array Manipulation
• Polling to Events
• Format Into String
• String Formatting
Description
In the course of the development of a LabVIEW application, there are times when VIs or sections of VIs end up being written “badly”.
Scenario
Your customer is a research facility that is doing experiments on superconducting material. The researchers must perform experiments at very low
temperatures. The materials are tested in a chamber that contains four temperature sensors spread throughout the chamber. The sensors return temperatures
in °C. Due to the low temperatures involved, the temperatures in °C are less readable than K. For this reason the customer’s application already includes a
VI that converts the temperatures from °C to K.
The customer has recently decided to monitor more than four temperatures. He is worried that every time he increases the number of temperatures he will
have to update the VI that does the conversion. In this exercise you will refactor the conversion VI to make it more scalable. You also will make the VI more
readable and maintainable.
Note The Kelvin scale defines Absolute Zero as the lowest temperature possible. No temperature below Absolute Zero is allowed. Absolute
Zero is approximately equal to -273 °C. You should build your refactored application to generate errors if the user tries to convert invalid
temperatures, for example, temperatures less than -273 °C.
Implementation
Open the Convert Temperatures VI located in the <Exercises>\LabVIEW Core 2\Refactoring\Use subVIs_ForLoop and refactor it.
Hints
• Find repeated code and replace it with subVIs.
• Find code that works on a limited number of elements of an array and scale it to work on an unlimited number of elements.
• Clean up the block diagram of the VI to make it readable.
• Organize subVIs and related files in a project.
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.
Array Manipulation
Goal
Refactor a VI that uses an outdated technique for conditionally separating an array into multiple arrays.
Description
Each release of LabVIEW introduces new features that improve coding efficiencies. Therefore, you might refactor code you inherited from someone who
developed the code in an earlier version of LabVIEW.
Scenario
You inherit an old LabVIEW application which uses outdated programming techniques.
Implementation
Open Separate Array Values.vi from the Array Manipulation project located in the <Exercises>\LabVIEW Core 2\Refactoring\Array
Manipulation directory and refactor it.
Hints
Test
Test your refactored code to ensure that it works as the original application did. Notice that the input array contains a mix of positive and negative values.
After running, the Positive Array contains positive values while the Negative Array contains negative values.
| 6-9
Polling to Events
6-10
Lesson 6
Goal
|
To take an existing VI that uses outdated techniques and refactor it to be more readable, scalable, and maintainable.
ni.com
Improving an Existing VI
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, scalability, and maintainability.
Scenario
You inherit an old LabVIEW application which performs the following functions:
• Acquire a waveform as a Time Series.
• Calculate the FFT of the waveform (that is, generate the Spectrum).
• 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.
You are asked to add a feature to calculate the Standard Deviation of the Time Series. You notice that the block diagram of the VI is built in such a way
that adding more features makes the block diagram larger and more difficult to read.
Implementation
Open the Waveform Analysis (Polling) VI located in the <Exercises>\LabVIEW Core 2\
Refactoring\Polling to Events directory and refactor it.
Hints
• Use Events instead of Polling.
• Use Shift Registers instead of Local Variables.
• Use a Project to organize the files.
Test
Test your refactored code to ensure that it works as the original application did.
Format Into String
Goal
Refactor a VI that uses the Format Into String function to make the VI more scalable.
Description
The Format Into String function is very versatile; it converts multiple pieces of data into a string according to a format string. However, if new parameters
are introduced, both the Format Into String function and the format string must be modified.
You can add parameters without changing the VI if all the parameters are of the same data type.
Scenario
You inherit an old LabVIEW application which is difficult to scale and maintain. You notice that it uses individual controls to input information into a Format
Into String function.
Implementation
Open Format Gas Params.vi from the Format Gas Parameters project located in the <Exercises>\LabVIEW Core 2\Refactoring\Format Into
String directory and refactor it.
Assume you need to add a new DBL parameter (for example, Explosiveness).
Also notice that the format string needs to have \r\nExplosiveness:\s%f added.
Hints
• Arrays of parameter values are easily expandable to include future values.
• Some string functions can handle arrays.
Test
Test your refactored code to ensure that it works as the original application did.
| 6-11
String Formatting
6-12
Lesson 6
Goal
|
Refactor a VI that uses the Format Into String function to make it more scalable.
ni.com
Improving an Existing VI
Description
The Format Into String function is very versatile; it converts multiple pieces of data into a string according to a format string. However, if new parameters
are introduced, both the Format Into String function and the format string must be modified.
Scenario
You inherited some code that creates a file header and includes a series of name-value pairs for your test data. Because the file is expected to be loaded
into Excel, each name and value is separated by a tab and terminated with an End of Line character. In addition to time and date information, the file header
also includes information contained in a cluster. The cluster element names and values are used in the name-value pairs.
Your manager wants to re-order the name-value pairs so that Date and Time appear first. In the future, you may want to expand the number of elements in
the File Header Data cluster from 3 elements to 10 elements. You must update the code to change the order and prepare for future scalability of the cluster
elements.
Implementation
Open the Generate File Header VI in the Format File Header project located in the <Exercises>\LabVIEW Core 2\Refactoring\String Formatting
directory and refactor it.
Hints
• Create a subVI which formats each name-value pair. Separate the name and value using a Tab constant and terminate each pair with an End of Line
constant.
• Process the list of name-value pairs. The challenge is to create two parallel arrays, one for names and one for values.
• If all cluster elements are of the same data type, you can convert a cluster to an array using the Cluster to Array function. You can then use a For Loop
to process each cluster element.
• Use a control property node to get a list of control references to all the cluster elements. You can then get access to the Label names of the cluster
elements. Use that to build an array of names.
Test
Test your refactored code to ensure that it works as the original application did.
Scenario
Review the Building Applications Checklist to assist you in the build process before creating a stand-alone application or installer.
Stand-alone applications in LabVIEW have the Window Appearance set to Top-level application to enable the front panel to open when the VI runs.
A VI that runs as a stand-alone executable remains in memory when the application finishes running. Therefore, it is necessary to call the Quit LabVIEW
function to close the application when the application finishes executing. Placing the Quit LabVIEW function on the block diagram can make editing the
application more difficult in the future because LabVIEW exits each time the application finishes.
Design
• Modify the VI Properties to prepare to build a stand-alone application.
• Modify the application to call the Quit LabVIEW function when the code is executed in the run-time system.
• Modify the application to specify a log path relative to the stand-alone executable.
Implementation
Before you build an application, you first prepare the code so that it executes reliably when compiled into an application.
Lesson 7
1. Open the Histogram Main VI.
|
ni.com
If you have hardware connected, open Histogram.lvproj in the <Exercises>\LabVIEW Core 2\Deployment\HW directory.
If you do not have hardware connected, open Histogram.lvproj in the <Exercises>\LabVIEW Core 2\Deployment\No HW directory.
In the Project Explorer window, double-click Histogram Main.vi to open the VI.
4. Enter a name, such as Histogram Application, in the Window Title text box.
5. Select Top-level application window to give the front panel a professional appearance when the VI opens as an executable.
6. Click the Customize button to view the various window settings that LabVIEW configures for top-level application windows.
7. Click OK to close the Customize Window Appearance dialog box and click OK to close the VI Properties dialog box.
Figure 7-1. Adding the Quit LabVIEW Function to the Block Diagram
1 Conditional Disable Structure—Right-click the border of the structure and select Add Subdiagram After... In the Configure Condition dialog, set the
value of Symbol(s) to Run_Time_Engine. Set Value(s) to True
2 Quit LabVIEW Function—Place this function in the “RUN_TIME_ENGINE==True” subdiagram. You can leave the Default subdiagram empty.
2. In the Project Explorer window, select File»Save All to save all the VIs.
Open the Create Data File VI in the Initialize case of the consumer loop. The Application Directory VI creates a path relative to the stand-alone application
when you call the VI from a stand-alone application. Otherwise, the Application Directory VI returns the path to the folder containing the project file.
Test
1. Run the Histogram Main VI to ensure that it is working.
Note If you have hardware installed and receive an error, check the configuration of the DAQ Assistant Express VI.
Lesson 7
|
Goal
ni.com
Create a build specification, build a stand-alone application (EXE) in LabVIEW, and debug the application running on the local computer.
Design
Use the Application (EXE) Build Specifications to create a stand-alone application for the histogram application.
Implementation
Review the Building Applications Checklist
1. Select Help»LabVIEW Help to open the LabVIEW Help.
2. Right-click Build Specifications in the Project Explorer window and select New»Application (EXE) from the shortcut menu.
3. (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.
4. Modify the filename of the target and destination directory for the application in the Information category.
Tip You do not need to create the directory. LabVIEW creates any directories that you specify.
5. Specify the top-level VI for the application.
Click the right arrow next to the Startup VIs listbox to add the selected VI to the Startup VIs listbox.
Click OK.
8. In the Project Explorer window, right-click the My Application build specification and select Build from the shortcut menu.
3. Run HistogramData.exe.
4. 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.
2. Run HistogramData.exe.
Lesson 7
Click the Refresh button if HistogramData.exe does not appear in the list.
|
ni.com
8. Stop the application by clicking the Stop button in the debugging window.
Lesson 7
|
Goal
ni.com
Create an installer build specification and build the installer. As a challenge, remotely debug the application created by the installer.
Design
Use an Installer Build Specification to create an installer for the Application (.exe) Build Specification you created in Exercise 7-2.
Implementation
Review the Building Applications Checklist
1. Open the LabVIEW Help by selecting Help»LabVIEW Help.
Click the right arrow next to the Project Files View tree to place the histogram executable and all executable support files under Program Files»
Histogram in the Destination View tree, as shown in Figure 7-2.
4. Add the NI LabVIEW Run-Time Engine to the installer by modifying the Additional Installers category.
Click OK.
Note Some additional installers you might select in the Additional Installers category, such as DAQmx, can require you to have the product
DVD (such as the NI Device Driver DVD) or a downloaded installation package (such as the NI-DAQmx Run-Time Engine) before you can include
the product installer in your application installer. To download an installation package, go to ni.com/info and enter the code downloads.
5. In the Project Explorer window, right-click the My Installer build specification and select Build from the shortcut menu.
Lesson 7
1. Run the setup.exe file in the <Exercises>\LabVIEW Core 2\Deployment\Installer\Volume directory.
|
2. Follow the instructions on-screen to install the application. By default, the executable is created inside the <Program Files>\Histogram directory.
ni.com
Note You must run the application as an administrator because the executable creates a file in the <Program Files> folder. If you do not run
the program as an administrator, Error 8 occurs.
5. Click Yes in the dialog box asking for permission to make changes to the computer.
Challenge
If you have internet access during class, try to debug the executable on a remote computer.
2. Decide whether to debug a classmate’s application or install your application on your classmate’s computer.
3. If you decide to debug your own application on a remote computer you must distinguish your application from the applications already on your
classmate’s computer.
In the installer build specification, rename your application with a unique name.
Transfer your installer to the remote computer using a USB flash drive or the network.
4. To use LabVIEW on your computer to debug a running application on a remote computer, you must determine the IP address of the remote computer,
also known as the Destination computer.
Note Consider your computer to be the Development computer and your classmate’s computer to be the Destination computer.
Enter cmd in the search box and press the <Enter> key.
Type ipconfig at the prompt in the Command window and press the <Enter> key.
8. Enter the IP address of the Destination computer in the Machine name or IP address text box.
9. Select the executable from the Application or shared library drop-down menu.
Click the Refresh button if the executable you want does not appear in the list.
12. Stop the application by clicking the Stop button in the debugging window.