LabVIEW Basics Vol1
LabVIEW Basics Vol1
1
TM
Lesson 4 Implementing a VI
A. B. C. D. E. F. G. H. I. Front Panel Design LabVIEW Data Types Documenting Code While Loops For Loops Timing a VI Iterative Data Transfer Plotting Data Case Structures
Lesson 1
Setting Up Hardware
A. DAQ Hardware
A data acquisition (DAQ) system uses a data acquisition device to pass a conditioned electrical signal to a computer for software analysis and data logging. You can choose a data acquisition device that uses a PCI bus, a PCI Express bus, a PXI bus, or the computer USB or IEEE 1394 port. This section explains the hardware used in a data acquisition system and how to configure the devices. A typical DAQ system has three basic types of hardwarea terminal block, a cable, and a DAQ device, as shown in Figure 1-1.
2 3
NATIONAL INSTRUMENTS
NATIONAL INSTRUMENTS
5 1
1 2 3
4 5
After you have converted a physical phenomenon into a measurable signal with or without signal conditioning, you need to acquire that signal. To acquire a signal, you need a terminal block, a cable, a DAQ device, and a computer. This hardware combination can transform a standard computer into a measurement and automation system.
Lesson 1
Setting Up Hardware
Lesson 1
Setting Up Hardware
A B 68-pin Device (Diff Mode) Lab/1200 Series (NRSE Mode) 50-pin MIO Device (Diff Mode) 24 Pulses/rev Digital Trigger Digital Port 0 3 2 1 0 Counters Frequency Frequency Range Adjust 13kHz-1MHz 1kHz-100kHz Lo Hi 100Hz-10kHz Analog Analog Function Out In Generator Temp Sensor Noise Off On Temp Sensor Mic Ch 6
DAQ
Signal Accessory Ch 0 1 1 2
V*100 = C Ch 0
The DAQ Signal Accessory is a customized terminal block designed for learning purposes. It has three different cable connectors to accommodate many different DAQ devices and spring terminals to connect signals. You can access three analog input channels, one of which is connected to the temperature sensor, and two analog output channels. The DAQ Signal Accessory includes a function generator with a switch to select the frequency range of the signal, and a frequency knob. The function generator can produce a sine wave or a square wave. A connection to ground is located between the sine wave and square wave terminal. A digital trigger button produces a TTL pulse for triggering analog input or output. When you press the trigger button, the signal goes from +5 V to 0 V and returns to +5 V when you release the button. Four LEDs connect to the first four digital lines on the DAQ device. The LEDs use reverse logic, so when the digital line is high, the LED is off and vice versa.
6
Lesson 1
Setting Up Hardware
The DAQ Signal Accessory has a quadrature encoder that produces two pulse trains when you turn the encoder knob. Terminals are provided for the input and output signals of two counters on the DAQ device. The DAQ Signal Accessory also has a relay, a thermocouple input, and a microphone jack.
Analog Input
Analog input is the process of measuring an analog signal and transferring the measurement to a computer for analysis, display or storage. An analog signal is a signal that varies continuously. Analog input is most commonly used to measure voltage or current. You can use many types of devices to perform analog input, such as multifunction DAQ (MIO) devices, high-speed digitizers, digital multimeters (DMMs) and Dynamic Signal Acquisition (DSA) devices. Acquiring an analog signal with a computer requires a process known as analog-to-digital conversion, which takes an electrical signal and translates it into digital data so that a computer can process it. Analog-to-digital converters (ADCs) are circuit components that convert a voltage level into a series of ones and zeroes. ADCs sample the analog signal on each rising or falling edge of a sample clock. In each cycle, the ADC takes a snapshot of the analog signal, so that the signal can be measured and converted into a digital value. A sample clock controls the rate at which samples of the input signal are taken. Because the incoming, or unknown signal is a real world signal with infinite precision, the ADC approximates the signal with fixed precision. After the
7
Lesson 1
Setting Up Hardware
ADC obtains this approximation, the approximation can be converted to a series of digital values. Some conversion methods do not require this step, because the conversion generates a digital value directly as the ADC reaches the approximation.
Analog Output
Analog output is the process of generating electrical signals from your computer. Analog output is generated by performing digital-to-analog (D/A) conversions. The available analog output types for a task are voltage and current. To perform a voltage or current task, a compatible device must be installed that can generate that form of signal. Digital-to-analog conversion is the opposite of analog-to-digital conversion. In digital-to-analog conversion, the computer generates the data. The data might have been acquired earlier using analog input or may have been generated by software on the computer. A digital-to-analog converter (DAC) accepts this data and uses it to vary the voltage on an output pin over time. The DAC generates an analog signal that the DAC can send to other devices or circuits. A DAC has an update clock that tells the DAC when to generate a new value. The function of the update clock is similar to the function of the sample clock for an ADC. At each cycle the clock, the DAC converts a digital value to an analog voltage and creates an output as a voltage on a pin. When used with a high speed clock, the DAC can create a signal that appears to vary constantly and smoothly.
Digital I/O
Digital signals are electrical signals that transfer digital data over a wire. These signals typically have only two stateson and off, also known as high and low, or 1 and 0. When sending a digital signal across a wire, the sender applies a voltage to the wire and the receiver uses the voltage level to determine the value being sent. The voltage ranges for each digital value depend on the voltage level standard being used. Digital signals have many uses; the simplest application of a digital signal is controlling or measuring digital or finite state devices such as switches and LEDs. Digital signals also can transfer data; you can use them to program devices or communicate between devices. In addition, you can use digital signals as clocks or triggers to control or synchronize other measurements. You can use the digital lines in a DAQ device to acquire a digital value. This acquisition is based on software timing. On some devices, you can configure the lines individually to either measure or generate digital samples. Each line corresponds to a channel in the task.
8
Lesson 1
Setting Up Hardware
You can use the digital port(s) in a DAQ device to acquire a digital value from a collection of digital lines. This acquisition is based on software timing. You can configure the ports individually to either measure or generate digital samples. Each port corresponds to a channel in the task.
Counters
A counter is a digital timing device. You typically use counters for event counting, frequency measurement, period measurement, position measurement, and pulse generation. When you configure a counter for simple event counting, the counter increments when an active edge is received on the source. In order for the counter to increment on an active edge, the counter must be armed or started. A counter has a fixed number it can count to as determined by the resolution of the counter. For example, a 24-bit counter can count to: 2(Counter Resolution) 1 = 224 1 = 16,777,215 When a 24-bit counter reaches the value of 16,777, 215, it has reached the terminal count. The next active edge forces the counter to roll over and start at 0.
Using NI-DAQ
NI-DAQ 7.x contains two NI-DAQ driversTraditional NI-DAQ (Legacy) and NI-DAQmxeach with its own application programming interface (API), hardware configuration, and software configuration. NI-DAQ 8.0 and later come with only NI-DAQmx, the replacement for Traditional NI-DAQ (Legacy). Traditional NI-DAQ (Legacy) is an upgrade to NI-DAQ 6.9.x, the earlier version of NI-DAQ. Traditional NI-DAQ (Legacy) has the same VIs and functions and works the same way as NI-DAQ 6.9.x. You can use Traditional NI-DAQ (Legacy) on the same computer as NI-DAQmx, which you cannot do with NI-DAQ 6.9.x. However, you cannot use Traditional NI-DAQ (Legacy) on Windows Vista.
9
Lesson 1
Setting Up Hardware
NI-DAQmx is the latest NI-DAQ driver with new VIs, functions, and development tools for controlling measurement devices. The advantages of NI-DAQmx over previous versions of NI-DAQ include the DAQ Assistant for configuring channels and measurement tasks for a device; increased performance, including faster single-point analog I/O and multithreading; and a simpler API for creating DAQ applications using fewer functions and VIs than earlier versions of NI-DAQ.
Note (Windows) LabVIEW supports NI-DAQmx and the DAQ Assistant. (Mac OS) LabVIEW supports NI-DAQmx Base but not the DAQ Assistant. (Linux) LabVIEW supports NI-DAQmx but not the DAQ Assistant.
Traditional NI-DAQ (Legacy) and NI-DAQmx support different sets of devices. Refer to Data Acquisition (DAQ) Hardware on the National Instruments Web site for the list of supported devices.
Windows
The Windows Configuration Manager keeps track of all the hardware installed in the computer, including National Instruments DAQ devices. If you have a Plug & Play (PnP) device, such as an E Series MIO device, the Windows Configuration Manager automatically detects and configures the device. If you have a non-PnP device, or legacy device, you must configure the device manually using the Add New Hardware option in the Windows Control Panel. You can verify the Windows Configuration by accessing the Device Manager. You can see Data Acquisition Devices, which lists all DAQ devices installed in the computer. Double-click a DAQ device to display a dialog box with tabbed pages. The General tab displays overall information regarding the device. The Driver tab specifies the driver version and location for the DAQ device. The Details tab contains additional information about hardware configuration. The Resources tab specifies the system resources to the device such as interrupt levels, DMA, and base address for software-configurable devices.
10
Lesson 1
Setting Up Hardware
1: AT-MIO-64E-3
The device parameters that you can set using the configuration utility depend on the device. MAX saves the logical device number and the configuration parameters in the Windows Registry. The plug and play capability of Windows automatically detects and configures switchless DAQ devices, such as the NI PCI-6024E, when you install a device in the computer.
Scales
You can configure custom scales for your measurements. This is very useful when working with sensors. It allows you to bring a scaled value into your application without having to work directly with the raw values. For example, in this course you use a temperature sensor that represents temperature with a voltage. The conversion equation for the temperature is: Voltage x 100 = Celsius. After a scale is set, you can use it in your application program, providing the temperature value, rather than the voltage.
11
Lesson 1
Setting Up Hardware
C. Instrument Control
When you use a PC to automate a test system, you are not limited to the type of instrument you can control. You can mix and match instruments from various categories. The most common categories of instrument interfaces are GPIB, serial, and modular instruments. Additional types of instruments include image acquisition, motion control, USB, Ethernet, parallel port, NI-CAN, and other devices. When you use PCs to control instruments, you need to understand properties of the instrument, such as the communication protocols to use. Refer to the instrument documentation for information about the properties of an instrument.
D. GPIB
The ANSI/IEEE Standard 488.1-1987, also known as General Purpose Interface Bus (GPIB), describes a standard interface for communication between instruments and controllers from various vendors. GPIB, or General Purpose Interface Bus, instruments offer test and manufacturing engineers the widest selection of vendors and instruments for general-purpose to specialized vertical market test applications. GPIB instruments are often used as stand-alone benchtop instruments where measurements are taken by hand. You can automate these measurements by using a PC to control the GPIB instruments. IEEE 488.1 contains information about electrical, mechanical, and functional specifications. The ANSI/IEEE Standard 488.2-1992 extends IEEE 488.1 by defining a bus communication protocol, a common set of data codes and formats, and a generic set of common device commands.
12
Lesson 1
Setting Up Hardware
GPIB is a digital, 8-bit parallel communication interface with data transfer rates of 1 Mbyte/s and higher, using a three-wire handshake. The bus supports one system controller, usually a computer, and up to 14 additional instruments. The GPIB protocol categorizes devices as controllers, talkers, or listeners to determine which device has active control of the bus. Each device has a unique GPIB primary address between 0 and 30. The Controller defines the communication links, responds to devices that request service, sends GPIB commands, and passes/receives control of the bus. Controllers instruct Talkers to talk and to place data on the GPIB. You can address only one device at a time to talk. The Controller addresses the Listener to listen and to read data from the GPIB. You can address several devices to listen.
13
Lesson 1
Setting Up Hardware
1 3
76.6F
RS-232 Instrument
RS-232 Cable
Serial Port
You must specify four parameters for serial communication: the baud rate of the transmission, the number of data bits that encode a character, the sense of the optional parity bit, and the number of stop bits. A character frame packages each transmitted character as a single start bit followed by the data bits. Baud rate is a measure of how fast data moves between instruments that use serial communication. Data bits are transmitted upside down and backwards, which means that inverted logic is used and the order of transmission is from least significant bit (LSB) to most significant bit (MSB). To interpret the data bits in a character frame, you must read from right to left and read 1 for negative voltage and 0 for positive voltage. An optional parity bit follows the data bits in the character frame. The parity bit, if present, also follows inverted logic. This bit is included as a means of error checking. You specify ahead of time for the parity of the transmission to be even or odd. If you choose for the parity to be odd, the parity bit is set in such a way so the number of 1s add up to make an odd number among the data bits and the parity bit.
14
Lesson 1
Setting Up Hardware
The last part of a character frame consists of 1, 1.5, or 2 stop bits that are always represented by a negative voltage. If no further characters are transmitted, the line stays in the negative (MARK) condition. The transmission of the next character frame, if any, begins with a start bit of positive (SPACE) voltage. The following figure shows a typical character frame encoding the letter m.
Idle
Start Bit
Data Bits
Parity Bit
Stop Bits
Idle
Space Mark
Bit Time
Character Frame
RS-232 uses only two voltage states, called MARK and SPACE. In such a two-state coding scheme, the baud rate is identical to the maximum number of bits of information, including control bits, that are transmitted per second. MARK is a negative voltage, and SPACE is positive. The previous illustration shows how the idealized signal looks on an oscilloscope. The following is the truth table for RS-232: Signal > +3 V = 0 Signal < 3 V = 1 The output signal level usually swings between +12 V and 12 V. The dead area between +3 V and 3 V is designed to absorb line noise. A start bit signals the beginning of each character frame. It is a transition from negative (MARK) to positive (SPACE) voltage. Its duration in seconds is the reciprocal of the baud rate. If the instrument is transmitting at 9,600 baud, the duration of the start bit and each subsequent bit is about 0.104 ms. The entire character frame of eleven bits would be transmitted in about 1.146 ms. Interpreting the data bits for the transmission yields 1101101 (binary) or 6D (hex). An ASCII conversion table shows that this is the letter m. This transmission uses odd parity. There are five ones among the data bits, already an odd number, so the parity bit is set to 0.
15
Lesson 1
Setting Up Hardware
Lesson 1
Setting Up Hardware
Lesson 1
Setting Up Hardware
Configure the objects listed in MAX by right-clicking each item and selecting an option from the shortcut menu. You learn to use MAX to configure and communicate with a GPIB instrument in an exercise.
G. Course Project
Throughout this course, the course project illustrates concepts, both as hands-on exercises and as a case study. The project meets the following requirements: 1. Acquires a temperature every half a second 2. Analyzes each temperature to determine if the temperature is too high or too low 3. Alerts the user if there is a danger of heat stroke or freeze 4. Displays the data to the user 5. Logs the data if a warning occurs 6. If the user does not stop the program, the entire process repeats The course project has the following inputs and outputs.
Inputs
Current Temperature (T) High Temperature Limit (X) Low Temperature Limit (Y) Stop
Outputs
Warning Levels: Heatstroke Warning, No Warning, Freeze Warning Current Temperature Display Data Log File
One state transition diagram, shown in Figure 1-7, is chosen so that all students may follow the same instruction set. This state transition diagram is chosen because it successfully solves the problem and it has parts that can be effectively used to demonstrate course concepts. However, it may not be the best solution to the problem.
18
Lesson 1
Setting Up Hardware
Initialize
Acquistion
Analysis
Datalog
Time Elapsed = FALSE and Stop = FALSE Time Check Warning = FALSE
Stop = TRUE
Figure 1-8 shows an example of an alternate state transition diagram. This state transition diagram also solves the problem very effectively. One of the major differences between these two diagrams is how they can be expanded for future functionality. In the state transition diagram in Figure 1-7, you can modify the diagram to include warning states for other physical phenomena, such as wind, pressure, and humidity. In the state transition diagram in Figure 1-8, you can add other layers of temperature warnings. The possible future changes you expect to your program affect which diagram you choose.
19
Lesson 1
Setting Up Hardware
Initialize
Heatstroke Warning
Freeze Warning
No Warning
Stop = FALSE
Stop
Stop = TRUE
20
Lesson 1
Setting Up Hardware
Self-Review: Quiz
1. You can use the Measurement & Automation Explorer (MAX) to examine, configure, and test your DAQ device and GPIB instruments. a. True b. False
2. Which of the following are benefits of instrument control? a. Automate processes b. Save time c. One platform for multiple tasks d. Limited to only one type of instrument
21
22
Lesson 1
Setting Up Hardware
2. Which of the following are benefits of instrument control? a. Automate processes b. Save time c. One platform for multiple tasks d. Limited to only one type of instrument
23
Lesson 1
Setting Up Hardware
Notes
24
Navigating LabVIEW
This lesson introduces how to navigate the LabVIEW environment. This includes using the menus, toolbars, palettes, tools, help, and common dialog boxes of LabVIEW. You also learn how to run a VI and gain a general understanding of a front panel and block diagram. At the end of this lesson, you create a simple VI that acquires, analyzes, and presents data.
Topics
A. Virtual Instruments (VIs) B. Parts of a VI C. Starting a VI D. Project Explorer E. Front Panel F. Block Diagram G. Searching for Controls, VIs and Functions H. Selecting a Tool I. Dataflow J. Building a Simple VI
25
Lesson 2
Navigating LabVIEW
B. Parts of a VI
LabVIEW VIs contain three main componentsthe front panel window, the block diagram, and the icon/connector pane.
26
Lesson 2
Navigating LabVIEW
Lesson 2
Navigating LabVIEW
C. Starting a VI
When you launch LabVIEW, the Getting Started window appears. Use this window to create new VIs and projects, select among the most recently opened LabVIEW files, find examples, and search the LabVIEW Help. You also can access information and resources to help you learn about LabVIEW, such as specific manuals, help topics, and resources at ni.com/manuals. The Getting Started window closes when you open an existing file or create a new file. You can display the window by selecting ViewGetting Started Window.
You can configure LabVIEW to open a new, blank VI on launch instead of displaying the window. Select ToolsOptions, select Environment from the Category list, and place a checkmark in the Skip Getting Started window on launch checkbox.
28
Lesson 2
Navigating LabVIEW
Note
The items in the Getting Started window vary depending on which version of LabVIEW and which toolkits you install.
Lesson 2
Navigating LabVIEW
Opening an Existing VI
Select Browse in the Open list in the Getting Started window to navigate to and open an existing VI.
Tip
The VIs you edit in this course are located in the <Exercises>\LabVIEW 1 directory. As the VI loads, a status dialog box similar to the following example might appear.
The Loading section lists the subVIs of the VI as they load into memory and shows the number of subVIs loaded into memory so far. You can cancel the load at any time by clicking the Stop button. If LabVIEW cannot immediately locate a subVI, it begins searching through all directories specified by the VI search path. You can edit the VI search path by selecting ToolsOptions and selecting Paths from the Category list. You can have LabVIEW ignore a subVI by clicking the Ignore Item button, or you can click the Browse button to search for the missing subVI.
30
Lesson 2
Navigating LabVIEW
Saving a VI
To save a new VI, select FileSave. If you already saved your VI, select FileSave As to access the Save As dialog box. From the Save As dialog box, you can create a copy of the VI, or delete the original VI and replace it with the new one.
Refer to the Save As Dialog Box topic of the LabVIEW Help for detailed information about each option in the Save As dialog box.
31
Lesson 2
Navigating LabVIEW
D. Project Explorer
Use projects to group together LabVIEW files and non-LabVIEW files, create build specifications, and deploy or download files to targets. When you save a project, LabVIEW creates a project file (.lvproj), which includes references to files in the project, configuration information, build information, deployment information, and so on. You must use a project to build applications and shared libraries. You also must use a project to work with a real-time (RT), field-programmable gate array (FPGA), or personal digital assistant (PDA) target. Refer to the specific module documentation for more information about using projects with the LabVIEW Real-Time, FPGA, and PDA modules.
Tip
Lesson 2
Navigating LabVIEW
When you add another target to the project, LabVIEW creates an additional item in the Project Explorer window to represent the target. Each target also includes Dependencies and Build Specifications sections. You can add files under each target.
Project-Related Toolbars
Use the Standard, Project, Build, and Source Control toolbar buttons to perform operations in a LabVIEW project. The toolbars are available at the top of the Project Explorer window, as shown in Figure 2-7. You might need to expand the Project Explorer window to view all of the toolbars.
1 2 3 4
5 6 7 8
The Source Control toolbar is only available if you have source control configured in LabVIEW. You can show or hide toolbars by selecting ViewToolbars and selecting the toolbars you want to show or hide. You can also right-click an open area on the toolbar and select the toolbars you want to show or hide.
33
Lesson 2
Navigating LabVIEW
Note
After you add a virtual folder on disk to a project, LabVIEW does not automatically update the folder in the project if you make changes to the folder on disk. Right-click the target and select NewVI from the shortcut menu to add a new, blank VI. You also can select FileNew VI or ProjectAdd To ProjectNew VI to add a new, blank VI. Select the VI icon in the upper right corner of a front panel or block diagram window and drag the icon to the target. Select an item or folder from the file system on your computer and drag it to the target.
34
Lesson 2
Navigating LabVIEW
Note
Removing an item from a project does not delete the item on disk.
Lesson 2
Navigating LabVIEW
Saving a Project
You can save a LabVIEW project in the following ways: Select FileSave Project. Select ProjectSave Project. Right-click the project and select Save from the shortcut menu. Click the Save Project button on the Project toolbar.
You must save new, unsaved files in a project before you can save the project. When you save a project, LabVIEW does not save dependencies as part of the project file. Make a backup copy of a project when you prepare to make major revisions to the project.
Note
36
Lesson 2
Navigating LabVIEW
E. Front Panel
When you open a new or existing VI, the front panel window of the VI appears. The front panel window is the user interface for the VI. Figure 2-8 shows an example of a front panel window.
1 3 2
Toolbar
Controls Palette
Lesson 2
Navigating LabVIEW
Every control or indicator has a data type associated with it. For example, the Delay(sec) horizontal slide is a numeric data type. The most commonly used data types are numeric, Boolean value and string. You learn about other data types in Lesson 4, Implementing a VI.
1 2
Numeric Indicator
To enter or change values in a numeric control, click the increment and decrement buttons with the Operating tool or double-click the number with either the Labeling tool or the Operating tool, enter a new number, and press the <Enter> key.
38
Lesson 2
Navigating LabVIEW
Controls Palette
The Controls palette contains the controls and indicators you use to create the front panel. You access the Controls palette from the front panel window by selecting ViewControls Palette. The Controls palette is broken into various categories; you can expose some or all of these categories to suit your needs. Figure 2-12 shows a Controls palette with all of the categories exposed and the Modern category expanded. During this course, you work exclusively in the Modern category.
Lesson 2
Navigating LabVIEW
To view or hide categories (subpalettes), select the View button on the palette, and select or deselect in the Always Visible Categories option.
Shortcut Menus
All LabVIEW objects have associated shortcut menus, also known as context menus, pop-up menus, and right-click menus. As you create a VI, use the shortcut menu items to change the appearance or behavior of front panel and block diagram objects. To access the shortcut menu, right-click the object. Figure 2-13 shows a shortcut menu for a meter.
40
Lesson 2
Navigating LabVIEW
You can select multiple objects on the front panel or the block diagram and edit any properties the objects share. To select multiple objects, use the Positioning tool to drag a selection rectangle around all of the objects you want to edit or hold down the <Shift> key while clicking each object. Right-click an object from the selection and select Properties from the shortcut menu to display the Properties dialog box. The Properties dialog box only displays tabs and properties that the objects you select share. Select similar objects to display more tabs and properties. If you select objects that do not share any common properties, the Properties dialog box does not display any tabs or properties.
41
Lesson 2
Navigating LabVIEW
Click the Run button to run a VI. LabVIEW compiles the VI, if necessary. You can run a VI if the Run button appears as a solid white arrow, shown at left. The solid white arrow also indicates you can use the VI as a subVI if you create a connector pane for the VI. While the VI runs, the Run button appears as shown at left if the VI is a top-level VI, meaning it has no callers and therefore is not a subVI. If the VI that is running is a subVI, the Run button appears as shown at left. The Run button appears broken when the VI you are creating or editing contains errors. If the Run button still appears broken after you finish wiring the block diagram, the VI is broken and cannot run. Click this button to display the Error list window, which lists all errors and warnings. Click the Run Continuously button to run the VI until you abort or pause execution. You also can click the button again to disable continuous running. While the VI runs, the Abort Execution button appears. Click this button to stop the VI immediately if there is no other way to stop the VI. If more than one running top-level VI uses the VI, the button is dimmed. The Abort Execution button stops the VI immediately, before the VI finishes the current iteration. Aborting a VI that uses external resources, such as external hardware, might leave the resources in an unknown state by not resetting or releasing them properly. Design VIs with a stop button to avoid this problem.
Caution
Click the Pause button to pause a running VI. When you click the Pause button, LabVIEW highlights on the block diagram the location where you paused execution, and the Pause button appears red. Click the Pause button again to continue running the VI. Select the Text Settings pull-down menu to change the font settings for the selected portions of the VI, including size, style, and color. Select the Align Objects pull-down menu to align objects along axes, including vertical, top edge, left, and so on.
42
Lesson 2
Navigating LabVIEW
Select the Distribute Objects pull-down menu to space objects evenly, including gaps, compression, and so on. Select the Resize Objects pull-down menu to resize multiple front panel objects to the same size. Select the Reorder pull-down menu when you have objects that overlap each other and you want to define which one is in front or back of another. Select one of the objects with the Positioning tool and then select from Move Forward, Move Backward, Move To Front, and Move To Back. Select the Show Context Help Window button to toggle the display of the Context Help window. Enter Text appears to remind you that a new value is available to replace an old value. The Enter Text button disappears when you click it, press the <Enter> key, or click the front panel or block diagram workspace. The <Enter> key on the numeric keypad ends a text entry, while the main <Enter> key adds a new line. To modify this behavior, select ToolsOptions, select the Environment from the Category list, and place a checkmark in the End text entry with Enter key option.
Tip
43
Lesson 2
Navigating LabVIEW
F. Block Diagram
Block diagram objects include terminals, subVIs, functions, constants, structures, and wires, which transfer data among other block diagram objects.
Indicator Terminals
Wires
Nodes
Control Terminals
Terminals
Objects on the front panel window appear as terminals on the block diagram. Terminals are entry and exit ports that exchange information between the front panel and block diagram.Terminals are analogous to parameters and constants in text-based programming languages. Types of terminals include control or indicator terminals and node terminals. Control and indicator terminals belong to front panel controls and indicators. Data you enter into the front panel controls (a and b in the previous front panel) enter the block diagram through the control terminals. The data then enter the Add and Subtract functions. When the Add and Subtract functions complete their calculations, they produce new data values. The data values flow to the indicator terminals, where they update the front panel indicators (a+b and ab in the previous front panel).
44
Lesson 2
Navigating LabVIEW
The terminals in Figure 2-15 belong to four front panel controls and indicators. Because terminals represent the inputs and outputs of your VI, subVIs and functions also have terminals shown at left. For example, the connector panes of the Add and Subtract functions have three node terminals. To display the terminals of the function on the block diagram, right-click the function node and select Visible ItemsTerminals from the shortcut menu.
In this algorithm, Base and Height are inputs and Area is an output, as shown in Figure 2-16.
The user will not change or access the constant .5, so it will not appear on the front panel unless included as documentation of the algorithm.
45
Lesson 2
Navigating LabVIEW
Figure 2-17 shows a possible implementation of this algorithm on a LabVIEW block diagram. This block diagram has four different terminals created by two controls, one constant, and one indicator.
Controls
Indicator
Constant
Figure 2-17. Area of a Triangle Block Diagram with Icon Terminal View
Notice that the Base (cm) and Height (cm) block diagram terminals have a different appearance from the Area (cm2) terminal. There are two distinguishing characteristics between a control and an indicator on the block diagram. The first is an arrow on the terminal that indicates the direction of data flow. The controls have arrows showing the data leaving the terminal, whereas the indicator has an arrow showing the data entering the terminal. The second distinguishing characteristic is the border around the terminal. Controls have a thick border and indicators have a thin border. You can view terminals with or without icon view. Figure 2-18 shows the same block diagram without using the icon view of the terminals; however, the same distinguishing characteristics between controls and indicators exist.
Figure 2-18. Area of a Triangle Block Diagram without Icon Terminal View
46
Lesson 2
Navigating LabVIEW
Functions
Functions are the fundamental operating elements of LabVIEW. Functions do not have front panel windows or block diagram windows but do have connector panes. Double-clicking a function only selects the function. A function has a pale yellow background on its icon.
SubVIs
SubVIs are VIs that you create to use inside of another VI or that you access on the Functions palette. Any VI has the potential to be used as a subVI. When you double-click a subVI on the block diagram, its front panel window appears. The front panel includes controls and indicators. The block diagram includes wires, icons, functions, possibly subVIs, and other LabVIEW objects. The upper right corner of the front panel window and block diagram window displays the icon for the VI. This is the icon that appears when you place the VI on a block diagram as a subVI. SubVIs also can be Express VIs. Express VIs are nodes that require minimal wiring because you configure them with dialog boxes. Use Express VIs for common measurement tasks. You can save the configuration of an Express VI as a subVI. Refer to the Express VIs topic of the LabVIEW Help for more information about creating a subVI from an Express VI configuration. LabVIEW uses colored icons to distinguish between Express VIs and other VIs on the block diagram. Icons for Express VIs appear on the block diagram as icons surrounded by a blue field whereas subVI icons have a yellow field.
47
Lesson 2
Navigating LabVIEW
Lesson 2
Navigating LabVIEW
If you display a subVI or Express VI as an expandable node, you cannot display the terminals for that node and you cannot enable database access for that node.
Note
Wires
You transfer data among block diagram objects through wires. In Figure 2-15, wires connect the control and indicator terminals to the Add and Subtract function. Each wire has a single data source, but you can wire it to many VIs and functions that read the data. Wires are different colors, styles, and thicknesses, depending on their data types. A broken wire appears as a dashed black line with a red X in the middle, as shown at left. Broken wires occur for a variety of reasons, such as when you try to wire two objects with incompatible data types. Table 2-1 shows the most common wire types.
Table 2-1. Common Wire Types
Scalar
1D Array
2D Array
Boolean String
In LabVIEW, you use wires to connect multiple terminals together to pass data in a VI. You must connect the wires to inputs and outputs that are compatible with the data that is transferred with the wire. For example, you cannot wire an array output to a numeric input. In addition the direction of the wires must be correct. You must connect the wires to only one input and at least one output. For example, you cannot wire two indicators together. The components that determine wiring compatibility include the data type of the control and/or the indicator and the data type of the terminal.
Data Types
Data types indicate what objects, inputs, and outputs you can wire together. For example, if a switch has a green border, you can wire a switch to any input with a green label on an Express VI. If a knob has an orange border, you can wire a knob to any input with an orange label. However, you cannot wire an orange knob to an input with a green label. Notice the wires are the same color as the terminal.
49
Lesson 2
Navigating LabVIEW
Functions Palette
The Functions palette contains the VIs, functions and constants you use to create the block diagram. You access the Functions palette from the block diagram by selecting ViewFunctions Palette. The Functions palette is broken into various categories; you can show and hide categories to suit your needs. Figure 2-20 shows a Functions palette with all of the categories exposed and the Programming category expanded. During this course, you work mostly in the Programming category, but you also use other categories, or subpalettes.
50
Lesson 2
Navigating LabVIEW
To view or hide categories, click the View button on the palette, and select or deselect the Change Visible Categories option.
Click the Highlight Execution button to display an animation of the block diagram execution when you run the VI. Notice the flow of data through the block diagram. Click the button again to disable execution highlighting. Click the Retain Wire Values button to save the wire values at each point in the flow of execution so that when you place a probe on the wire you can immediately retain the most recent value of the data that passed through the wire. You must successfully run the VI at least once before you can retain the wire values.
51
Lesson 2
Navigating LabVIEW
Click the Step Into button to open a node and pause. When you click the Step Into button again, it executes the first action and pauses at the next action of the subVI or structure. You also can press the <Ctrl> and down arrow keys. Single-stepping through a VI steps through the VI node by node. Each node blinks to denote when it is ready to execute. Click the Step Over button to execute a node and pause at the next node. You also can press the <Ctrl> and right arrow keys. By stepping over the node, you execute the node without single-stepping through the node. Click the Step Out button to finish executing the current node and pause. When the VI finishes executing, the Step Out button is dimmed. You also can press the <Ctrl> and up arrow keys. By stepping out of a node, you complete single-stepping through the node and navigate to the next node. Click the Clean Up Diagram button to automatically reroute all existing wires and rearrange objects on the block diagram to generate a cleaner layout. To configure the clean up options, select ToolsOptions to display the Options dialog box and select Block Diagram: Cleanup from the Category list. The Warning button appears if a VI includes a warning and you placed a checkmark in the Show Warnings checkbox in the Error List window. A warning indicates there is a potential problem with the block diagram, but it does not stop the VI from running.
52
Lesson 2
Navigating LabVIEW
Lesson 2
Navigating LabVIEW
Double-click the search result to highlight its location on the palette. If the object is one you need to use frequently, you can add it to your Favorites category. Right-click the object on the palette and select Add Item to Favorites, as shown in Figure 2-22.
54
Lesson 2
Navigating LabVIEW
H. Selecting a Tool
You can create, modify and debug VIs using the tools provided by LabVIEW. A tool is a special operating mode of the mouse cursor. The operating mode of the cursor corresponds to the icon of the tool selected. LabVIEW chooses which tool to select based on the current location of the mouse.
You can manually choose the tool you need by selecting it on the Tools palette. Select ViewTools Palette to display the Tools palette.
55
Lesson 2
Navigating LabVIEW
Operating Tool
When the mouse cursor changes to the icon shown at left, the Operating tool is in operation. Use the Operating tool to change the values of a control. For example, in Figure 2-24 the Operating tool moves the pointer on the Horizontal Pointer Slide. When the mouse hovers over the pointer, the cursor automatically accesses the Operating tool.
The Operating tool is mostly used on the front panel window, but you also can use the Operating tool on the block diagram window to change the value of a Boolean constant.
56
Lesson 2
Navigating LabVIEW
Positioning Tool
When the mouse cursor changes to the icon shown at left, the Positioning tool is in operation. Use the Positioning tool to select or resize objects. For example, in Figure 2-25 the Positioning tool selects the Number of Measurements numeric control. After selecting an object, you can move, copy, or delete the object. When the mouse hovers over the edge of an object, the cursor automatically accesses the Positioning tool.
57
Lesson 2
Navigating LabVIEW
If the mouse hovers over a resizing node of an object, the cursor mode changes to show that you can resize the object, as shown in Figure 2-26. Notice that the cursor is hovering over a corner of the XY Graph at a resizing node, and the cursor mode changes to a double-sided arrow.
You can use the Positioning tool on both the front panel window and the block diagram.
58
Lesson 2
Navigating LabVIEW
Labeling Tool
When the mouse cursor changes to the icon shown at left, the Labeling tool is in operation. Use the Labeling tool to enter text in a control, to edit text, and to create free labels. For example, in Figure 2-27 the Labeling tool enters text in the Number of Measurements numeric control. When the mouse hovers over the interior of the control, the cursor automatically accesses the Labeling tool. Click once to place a cursor inside the control. Then double-click to select the current text.
When you are not in a specific area of a front panel window or block diagram window that accesses a certain mouse mode, the cursor appears as cross-hairs. If automatic tool selection is enabled, you can double-click any open space to access the Labeling tool and create a free label.
59
Lesson 2
Navigating LabVIEW
Wiring Tool
When the mouse cursor changes to the icon shown at left, the Wiring tool is in operation. Use the Wiring tool to wire objects together on the block diagram. For example, in Figure 2-28 the Wiring tool wires the Number of Measurements terminal to the count terminal of the For Loop. When the mouse hovers over the exit or entry point of a terminal or over a wire, the cursor automatically accesses the Wiring tool.
The Wiring tool works mainly with the block diagram window and when you create a connector pane on the front panel window.
60
Lesson 2
Navigating LabVIEW
The top item in the Tools palette is the Automatic Tool Selection button. When this is selected, LabVIEW automatically chooses a tool based on the location of your cursor. You can turn off automatic tool selection by deselecting the item, or by selecting another item in the palette. There are some additional tools on the palette, as described below: Use the Object Shortcut Menu tool to access an object shortcut menu with the left mouse button. Use the Scrolling tool to scroll through windows without using scrollbars. Use the Breakpoint tool to set breakpoints on VIs, functions, nodes, wires, and structures to pause execution at that location. Use the Probe tool to create probes on wires on the block diagram. Use the Probe tool to check intermediate values in a VI that produces questionable or unexpected results. Use the Color Copy tool to copy colors for pasting with the Coloring tool. Use the Coloring tool to color an object. The Coloring tool also displays the current foreground and background color settings.
61
Lesson 2
Navigating LabVIEW
I. Dataflow
LabVIEW follows a dataflow model for running VIs. A block diagram node executes when it receives all required inputs. When a node executes, it produces output data and passes the data to the next node in the dataflow path. The movement of data through the nodes determines the execution order of the VIs and functions on the block diagram. Visual Basic, C++, JAVA, and most other text-based programming languages follow a control flow model of program execution. In control flow, the sequential order of program elements determines the execution order of a program. For a dataflow programming example, consider a block diagram that adds two numbers and then subtracts 50.00 from the result of the addition, as shown in Figure 2-30. In this case, the block diagram executes from left to right, not because the objects are placed in that order, but because the Subtract function cannot execute until the Add function finishes executing and passes the data to the Subtract function. Remember that a node executes only when data are available at all of its input terminals and supplies data to the output terminals only when the node finishes execution.
62
Lesson 2
Navigating LabVIEW
In Figure 2-31, consider which code segment would execute firstthe Add, Random Number, or Divide function. You cannot know because inputs to the Add and Divide functions are available at the same time, and the Random Number function has no inputs. In a situation where one code segment must execute before another, and no data dependency exists between the functions, use other programming methods, such as error clusters, to force the order of execution. Refer to Lesson 5, Relating Data, for more information about error clusters.
63
Lesson 2
Navigating LabVIEW
J. Building a Simple VI
Most LabVIEW VIs have three main tasksacquiring some sort of data, analyzing the acquired data, and presenting the result. When each of these parts are simple, you can complete the entire VI using very few objects on the block diagram. Express VIs are designed specifically for completing common, frequently used operations. In this section, you learn about some Express VIs that acquire, analyze, and present data. Then you learn to create a simple VI that uses these three tasks, as shown in Figure 2-32.
Figure 2-32. Acquire, Analyze, and Present Example Front Panel Window and Block Diagram Window
64
Lesson 2
Navigating LabVIEW
On the Functions palette, the Express VIs are grouped together in the Express category. Express VIs use the dynamic data type to pass data between Express VIs.
Acquire
Express VIs used for the Acquire task include the following: DAQ Assistant, Instrument I/O Assistant, Simulate Signal, and Read from Measurement File.
DAQ Assistant
The DAQ Assistant acquires data through a data acquisition device.You must use this Express VI frequently throughout this course. Until you learn more about data acquisition, you only use one channel of the data acquisition device, CH0. This channel is connected to a temperature sensor on the DAQ Signal Accessory. You can touch the temperature sensor to change the temperature the sensor reads.
Simulate Signal
The Simulate Signal Express VI generates simulated data such as a sine wave.
Analyze
Express VIs used for the Analyze task include the followingAmplitude and Level Measurements, Statistics, Tone Measurements, and so on.
65
Lesson 2
Navigating LabVIEW
Statistics
The Statistics Express VI calculates statistical data from a waveform. This includes mean, sum, standard deviation, and extreme values.
Spectral Measurements
The Spectral Measurements Express VI performs spectral measurement on a waveform, such as magnitude and power spectral density.
Tone Measurements
The Tone Measurements Express VI searches for a single tone with the highest frequency or highest amplitude. It also finds the frequency and amplitude of a single tone.
Filter
The Filter Express VI processes a signal through filters and windows. Filters used include the following: Highpass, Lowpass, Bandpass, Bandstop, and Smoothing. Windows used include Butterworth, Chebyshev, Inverse Chebyshev, Elliptical, and Bessel.
Present
Present results by using Express VIs that perform a function, such as the Write to Measurement File Express VI, or indicators that present data on the front panel window. The most commonly used indicators for this task include the Waveform Chart, the Waveform Graph, and the XY Graph. Common Express VIs include the Write to Measurement File Express VI, the Build Text Express VI, the DAQ Assistant, and the Instrument I/O Assistant. In this case, the DAQ Assistant and the Instrument I/O Assistant provide output data from the computer to the DAQ device or an external instrument.
Build Text
The Build Text Express VI creates text, usually for displaying on the front panel window or exporting to a file or instrument. Refer to Lesson 6, Managing Resources, for more information on creating strings.
66
Lesson 2
Navigating LabVIEW
Running a VI
After you configure the Express VIs and wire them together, you can run the VI. When you finish creating your VI, click the Run button on the toolbar to execute the VI. While the VI is running, the Run button icon changes to the figure shown at left. After the execution completes, the Run button icon changes back to its original state, and the front panel indicators contain data.
67
68
Lesson 2
Navigating LabVIEW
Self-Review: Quiz
Refer to Figure 2-33 to answer the following quiz questions.
1. Which function executes first: Add or Subtract? a. Add b. Subtract c. Unknown 2. Which function executes first: Sine or Divide? a. Sine b. Divide c. Unknown 3. Which function executes first: Random Number, Divide or Add? a. Random Number b. Divide c. Add d. Unknown 4. Which function executes last: Random Number, Subtract or Add? a. Random Number b. Subtract c. Add d. Unknown 5. What are the three parts of a VI? a. Front panel window b. Block diagram window c. Project d. Icon/connector pane 69
70
Lesson 2
Navigating LabVIEW
1. Which function executes first: Add or Subtract? a. Add b. Subtract c. Unknown 2. Which function executes first: Sine or Divide? a. Sine b. Divide c. Unknown 3. Which function executes first? a. Random Number b. Divide c. Add d. Unknown 4. Which function executes last: Random, Subtract or Add? a. Random Number b. Subtract c. Add d. Unknown 5. What are the three parts of a VI? a. Front panel window b. Block diagram window c. Project d. Icon/connector pane
71
Lesson 2
Navigating LabVIEW
Notes
72
To run a VI, you must wire all the subVIs, functions, and structures with the correct data types for the terminals. Sometimes a VI produces data or runs in a way you do not expect. You can use LabVIEW to configure how a VI runs and to identify problems with block diagram organization or with the data passing through the block diagram.
Topics
A. LabVIEW Help Utilities B. Correcting Broken VIs C. Debugging Techniques D. Undefined or Unexpected Data E. Error Checking and Error Handling
73
Lesson 3
Click the Show Optional Terminals and Full Path button located on the lower left corner of the Context Help window to display the optional terminals of a connector pane and to display the full path to a VI. Optional terminals are shown by wire stubs, informing you that other connections exist. The detailed mode displays all terminals, as shown in Figure 3-2.
74
Lesson 3
Click the Lock Context Help button to lock the current contents of the Context Help window. When the contents are locked, moving the cursor over another object does not change the contents of the window. To unlock the window, click the button again. You also can access this option from the Help menu. If a corresponding LabVIEW Help topic exists for an object the Context Help window describes, a blue Detailed help link appears in the Context Help window. Also, the More Help button is enabled. Click the link or the button to display the LabVIEW Help for more information about the object.
LabVIEW Help
You can access the LabVIEW Help by clicking the More Help button in the Context Help window, selecting HelpSearch the LabVIEW Help, or clicking the blue Detailed Help link in the Context Help window. You also can right-click an object and select Help from the shortcut menu. The LabVIEW Help contains detailed descriptions of most palettes, menus, tools, VIs, and functions. The LabVIEW Help also includes step-by-step instructions for using LabVIEW features. The LabVIEW Help includes links to the following resources: LabVIEW Documentation Resources, which describes online and print documents to help new and experienced users and includes PDF versions of all LabVIEW manuals. Technical support resources on the National Instruments Web site, such as the NI Developer Zone, the KnowledgeBase, and the Product Manuals Library.
75
Lesson 3
NI Example Finder
Use the NI Example Finder to browse or search examples installed on your computer or on the NI Developer Zone at ni.com/zone. These examples demonstrate how to use LabVIEW to perform a wide variety of test, measurement, control, and design tasks. Select HelpFind Examples or click the Find Examples link in the Examples section of the Getting Started window to launch the NI Example Finder. Examples can show you how to use specific VIs or functions. You can right-click a VI or function on the block diagram or on a pinned palette and select Examples from the shortcut menu to display a help topic with links to examples for that VI or function. You can modify an example VI to fit an application, or you can copy and paste from one or more examples into a VI that you create.
76
Lesson 3
Lesson 3
C. Debugging Techniques
If a VI is not broken, but you get unexpected data, you can use the following techniques to identify and correct problems with the VI or the block diagram data flow: Wire the error in and error out parameters at the bottom of most built-in VIs and functions. These parameters detect errors encountered in each node on the block diagram and indicate if and where an error occurred. You also can use these parameters in the VIs you build. To eliminate all VI warnings, select ViewError List and place a checkmark in the Show Warnings checkbox to see all warnings for the VI. Determine the causes and correct them in the VI. Use the Positioning tool to triple-click a wire to highlight its entire path and to ensure that the wires connect to the proper terminals. Use the Context Help window to check the default values for each function and subVI on the block diagram. VIs and functions pass default values if recommended or optional inputs are unwired. For example, a Boolean input might be set to TRUE if unwired. Use the Find dialog box to search for subVIs, text, and other objects to correct throughout the VI. Select ViewVI Hierarchy to find unwired subVIs. Unlike unwired functions, unwired VIs do not always generate errors unless you configure an input to be required. If you mistakenly place an unwired subVI on the block diagram, it executes when the block diagram does. Consequently, the VI might perform extra actions. Use execution highlighting to watch the data move through the block diagram.
78
Lesson 3
Single-step through the VI to view each action of the VI on the block diagram. Use the Probe tool to observe intermediate data values and to check the error output of VIs and functions, especially those performing I/O. Click the Retain Wire Values button on the block diagram toolbar to retain wire values for use with probes. This feature allows you to easily check values of data that last passed through any wire. Use breakpoints to pause execution, so you can single-step or insert probes. Suspend the execution of a subVI to edit values of controls and indicators, to control the number of times it runs, or to go back to the beginning of the execution of the subVI. Determine if the data that one function or subVI passes is undefined. This often happens with numbers. For example, at one point in the VI an operation could have divided a number by zero, thus returning Inf (infinity), whereas subsequent functions or subVIs were expecting numbers. If the VI runs more slowly than expected, confirm that you turned off execution highlighting in subVIs. Also, close subVI front panels and block diagrams when you are not using them because open windows can affect execution speed. Check the representation of controls and indicators to see if you are receiving overflow because you converted a floating-point number to an integer or an integer to a smaller integer. For example, you might wire a 16-bit integer to a function that only accepts 8-bit integers. This causes the function to convert the 16-bit integer to an 8-bit representation, potentially causing a loss of data. Determine if any For Loops inadvertently execute zero iterations and produce empty arrays. Verify you initialized shift registers properly unless you intend them to save data from one execution of the loop to another. Check the cluster element order at the source and destination points. LabVIEW detects data type and cluster size mismatches at edit time, but it does not detect mismatches of elements of the same type. Check the node execution order. Check that the VI does not contain hidden subVIs. You inadvertently might have hidden a subVI by placing one directly on top of another node or by decreasing the size of a structure without keeping the subVI in view.
79
Lesson 3
Check the inventory of subVIs the VI uses against the results of ViewBrowse RelationshipsThis VIs SubVIs and ViewBrowse RelationshipsUnopened SubVIs to determine if any extra subVIs exist. Also open the VI Hierarchy window to see the subVIs for a VI. To help avoid incorrect results caused by hidden VIs, specify that inputs to VIs are required.
Execution Highlighting
View an animation of the execution of the block diagram by clicking the Highlight Execution button. Execution highlighting shows the movement of data on the block diagram from one node to another using bubbles that move along the wires. Use execution highlighting in conjunction with single-stepping to see how data values move from node to node through a VI.
(MathScript RT Module) In MathScript Nodes, execution highlighting shows
the progression from one line of script to another using a blue arrow that blinks next to the line that is executing currently.
Note
Single-Stepping
Single-step through a VI to view each action of the VI on the block diagram as the VI runs. The single-stepping buttons, shown as follows, affect execution only in a VI or subVI in single-step mode.
80
Lesson 3
Enter single-step mode by clicking the Step Into or Step Over button on the block diagram toolbar. Move the cursor over the Step Into, Step Over, or Step Out button to view a tip strip that describes the next step if you click that button. You can single-step through subVIs or run them normally. When you single-step through a VI, nodes blink to indicate they are ready to execute. If you single-step through a VI with execution highlighting on, an execution glyph appears on the icons of the subVIs that are currently running.
Probe Tools
Use the Probe tool to check intermediate values on a wire as a VI runs. Use the Probe tool if you have a complicated block diagram with a series of operations, any one of which might return incorrect data. Use the Probe tool with execution highlighting, single-stepping, and breakpoints to determine if and where data is incorrect. If data is available, the probe immediately updates and displays the data in the Probe Watch Window during execution highlighting, single-stepping, or when you pause at a breakpoint. When execution pauses at a node because of single-stepping or a breakpoint, you also can probe the wire that just executed to see the value that flowed through that wire.
Types of Probes
You can check intermediate values on a wire when a VI runs by using a generic probe, by using an indicator on the Controls palette to view the data, by using a supplied probe, by using a customized supplied probe, or by creating a new probe.
Note (MathScript RT Module) You can view the data in a script in a MathScript Node as
a VI runs by using a LabVIEW MathScript probe. Generic Use the generic probe to view the data that passes through a wire. Right-click a wire and select Custom ProbeGeneric Probe from the shortcut menu to use the generic probe. The generic probe displays the data. You cannot configure the generic probe to respond to the data. LabVIEW displays the generic probe when you right-click a wire and select Probe, unless you already specified a custom or supplied probe for the data type.
81
Lesson 3
You can debug a custom probe similar to a VI. However, a probe cannot probe its own block diagram, nor the block diagram of any of its subVIs. When debugging probes, use the generic probe. Using Indicators to View Data You also can use an indicator to view the data that passes through a wire. For example, if you view numeric data, you can use a chart within the probe to view the data. Right-click a wire, select Custom ProbeControls from the shortcut menu, and select the indicator you want to use. You also can click the Select a Control icon on the Controls palette and select any custom control or type definition saved on the computer or in a shared directory on a server. LabVIEW treats type definitions as custom controls when you use them to view probed data. If the data type of the indicator you select does not match the data type of the wire you right-clicked, LabVIEW does not place the indicator on the wire. Supplied Supplied probes are VIs that display comprehensive information about the data that passes through a wire. For example, the VI Refnum Probe returns information about the VI name, the VI path, and the hex value of the reference. You also can use a supplied probe to respond based on the data that flows through the wire. For example, use an Error probe on an error cluster to receive the status, code, source, and description of the error and specify if you want to set a conditional breakpoint if an error or warning occurs. The supplied probes appear at the top of the Custom Probe shortcut menu. Right-click a wire and select Custom Probe from the shortcut menu to select a supplied probe. Only probes that match the data type of the wire you right-click appear on the shortcut menu. Refer to the Using Supplied Probes VI in the labview\examples\ general\probes.llb for an example of using supplied probes. Custom Use the Create New Probe dialog box to create a probe based on an existing probe or to create a new probe. Right-click a wire and select Custom ProbeNew from the shortcut menu to display the Create New Probe dialog box. Create a probe when you want to have more control over how LabVIEW probes the data that flows through a wire. When you create a new probe, the data type of the probe matches the data type of the wire you right-clicked. If you want to edit the probe you created, you must open it from the directory where you saved it.
82
Lesson 3
After you select a probe from the Custom Probe shortcut menu, navigate to it using the Select a Control palette option, or create a new probe using the Create New Probe dialog box, that probe becomes the default probe for that data type, and LabVIEW loads that probe when you right-click a wire and select Probe from the shortcut menu. LabVIEW only loads probes that exactly match the data type of the wire you right-click. That is, a double precision floating-point numeric probe cannot probe a 32-bit unsigned integer wire even though LabVIEW can convert the data. If you want a custom probe to be the default probe for a particular data type, save the probe in the user.lib\_probes\default directory. Do not save probes in the vi.lib\_probes directory because LabVIEW overwrites those files when you upgrade or reinstall.
Note
Breakpoints
Use the Breakpoint tool to place a breakpoint on a VI, node, or wire and pause execution at that location. When you set a breakpoint on a wire, execution pauses after data passes through the wire and the Pause button appears red. Place a breakpoint on the block diagram to pause execution after all nodes on the block diagram execute. The block diagram border appears red and blinks to reflect the placement of a breakpoint. When a VI pauses at a breakpoint, LabVIEW brings the block diagram to the front and uses a marquee to highlight the node, wire, or line of script that contains the breakpoint. When you move the cursor over an existing breakpoint, the black area of the Breakpoint tool cursor appears white. When you reach a breakpoint during execution, the VI pauses and the Pause button appears red. You can take the following actions: Single-step through execution using the single-stepping buttons. Probe wires to check intermediate values. Change the values of front panel controls. Click the Pause button to continue running to the next breakpoint or until the VI finishes running.
83
Lesson 3
Suspending Execution
Suspend execution of a subVI to edit values of controls and indicators, to control the number of times the subVI runs before returning to the caller, or to go back to the beginning of the execution of the subVI. You can cause all calls to a subVI to start with execution suspended, or you can suspend a specific call to a subVI. To suspend all calls to a subVI, open the subVI and select Operate Suspend when Called. The subVI automatically suspends when another VI calls it. If you select this menu item when single-stepping, the subVI does not suspend immediately. The subVI suspends when it is called. To suspend a specific subVI call, right-click the subVI node on the block diagram and select SubVI Node Setup from the shortcut menu. Place a checkmark in the Suspend when called checkbox to suspend execution only at that instance of the subVI. The VI Hierarchy window, which you display by selecting ViewVI Hierarchy, indicates whether a VI is paused or suspended. An arrow glyph indicates a VI that is running regularly or single-stepping. A pause glyph indicates a paused or suspended VI. A green pause glyph, or a hollow glyph in black and white, indicates a VI that pauses when called. A red pause glyph, or a solid glyph in black and white, indicates a VI that is currently paused. An exclamation point glyph indicates that the subVI is suspended. A VI can be suspended and paused at the same time.
84
Lesson 3
LabVIEW does not check for overflow or underflow conditions on integer values. Overflow and underflow for floating-point numbers is in accordance with IEEE 754, Standard for Binary Floating-Point Arithmetic. Floating-point operations propagate NaN and Inf reliably. When you explicitly or implicitly convert NaN or Inf to integers or Boolean values, the values become meaningless. For example, dividing 1 by zero produces Inf. Converting Inf to a 16-bit integer produces the value 32,767, which appears to be a normal value. Before you convert data to integer data types, use the Probe tool to check intermediate floating-point values for validity. Check for NaN by wiring the Comparison function, Not A Number/Path/Refnum?, to the value you suspect is invalid. Do not rely on special values such as NaN, Inf, or empty arrays to determine if a VI produces undefined data. Instead, confirm that the VI produces defined data by making the VI report an error if it encounters a situation that is likely to produce undefined data. For example, if you create a VI that uses an incoming array to auto-index a For Loop, determine what you want the VI to do when the input array is empty. Either produce an output error code, substitute defined data for the value that the loop creates, or use a Case structure that does not execute the For Loop if the array is empty.
85
Lesson 3
86
Lesson 3
Use the LabVIEW error handling VIs, functions, and parameters to manage errors. For example, if LabVIEW encounters an error, you can display the error message in a dialog box. Or you can fix the error programmatically then erase the error by wiring the error out output of the subVI or function to the error in input of the Clear Errors VI. Use error handling in conjunction with the debugging tools to find and manage errors. National Instruments strongly recommends using error handling.
Error Clusters
Use the error cluster controls and indicators to create error inputs and outputs in subVIs. The error in and error out clusters include the following components of information: status is a Boolean value that reports TRUE if an error occurred. code is a 32-bit signed integer that identifies the error numerically. A nonzero error code coupled with a status of FALSE signals a warning rather than a error. source is a string that identifies where the error occurred.
Error handling in LabVIEW follows the dataflow model. Just as data values flow through a VI, so can error information. Wire the error information from the beginning of the VI to the end. Include an error handler VI at the end of the VI to determine if the VI ran without errors. Use the error in and error out clusters in each VI you use or build to pass the error information through the VI. As the VI runs, LabVIEW tests for errors at each execution node. If LabVIEW does not find any errors, the node executes normally. If LabVIEW detects an error, the node passes the error to the next node without executing that part of the code. The next node does the same thing, and so on. At the end of the execution flow, LabVIEW reports the error.
Explain Error
When an error occurs, right-click within the cluster border and select Explain Error from the shortcut menu to open the Explain Error dialog box. The Explain Error dialog box contains information about the error. The shortcut menu includes an Explain Warning option if the VI contains warnings but no errors. You also can access the Explain Error dialog box from the HelpExplain Error menu.
87
88
Lesson 3
2. Which of the following are the contents of the error cluster? a. Status: Boolean b. Error: String c. Code: 32-bit integer d. Source: String
89
90
Lesson 3
2. Which of the following are the contents of the error cluster? a. Status: Boolean b. Error: String c. Code: 32-bit integer d. Source: String
91
Lesson 3
Notes
92
Implementing a VI
This lesson teaches you how to implement code in LabVIEW. These skills include designing a user interface, choosing a data type, documenting your code, using looping structures such as While Loops and For Loops, adding software timing to your code, displaying your data as a plot, and making decisions in your code using a Case structure.
Topics
A. Front Panel Design B. LabVIEW Data Types C. Documenting Code D. While Loops E. For Loops F. Timing a VI G. Iterative Data Transfer H. Plotting Data I. Case Structures
93
Lesson 4
Implementing a VI
You can display the outputs of the problem with indicators, such as graphs, charts, or LEDs, or log the outputs to a file. You also can output data to a device using signal generation. Lessons about data acquisition, signal generation, and file logging appear later in this course.
94
Lesson 4
Implementing a VI
Block Diagram
You also can hide and view items on controls and indicators. For example, in Figure 4-2, you can see both the caption and the label. However, you only need to see the caption. To hide the label, right-click the control and select Visible ItemsLabel as shown in Figure 4-2.
1 2
Lesson 4
Implementing a VI
Using Color
Proper use of color can improve the appearance and functionality of your user interface. Using too many colors, however, can result in color clashes that cause the user interface to look too busy and distracting. LabVIEW provides a color picker that can aid in selecting appropriate colors. Select the Coloring tool and right-click an object or workspace to display the color picker. The top of the color picker contains a grayscale spectrum and a box you can use to create transparent objects. The second spectrum contains muted colors that are well suited to backgrounds and front panel objects. The third spectrum contains colors that are well suited for highlights. Moving your cursor vertically from the background colors to the highlight colors helps you select appropriate highlight colors for a specific background color. The following tips are helpful for color matching: Use the default LabVIEW colors. LabVIEW also substitutes colors similarly to how it substitutes fonts. If one of the colors of the VI is unavailable, LabVIEW replaces it with the closest match.You also can use system colors to adapt the appearance of a front panel window to the system colors of any computer that runs the VI. Start with a gray scheme. Select one or two shades of gray and choose highlight colors that contrast well against the background. Add highlight colors sparinglyon plots, abort buttons, and perhaps the slider thumbsfor important settings. Small objects need brighter colors and more contrast than larger objects. Use differences in contrast more often that differences in color. Color-blind users find it difficult to discern objects when differences are in color rather than contrast. Use spacing to group objects instead of grouping by matching colors. Good places to learn about color are stand-alone hardware instrument panels, maps, and magazines. Choose objects from the System category of the Controls palette if you want your front panel controls to use the system colors.
Lesson 4
Implementing a VI
Use the following guidelines to design the front panel to serve as a user interface: Do not place objects too closely together. Leave some blank space between objects to make the front panel easier to read. Blank space also prevents users from accidentally clicking the wrong control or button. Do not place objects on top of other objects. Even partially covering a control or indicator with a label or other object slows down screen updates and can make the control or indicator flicker. Use dividing lines between menu sections, as shown in Figure 4-3, to help you find the items quickly and strengthen the relationship between the items in the sections.
Good Menu
Bad Menu
Lesson 4
Implementing a VI
a VI that uses the Arial font on a computer that does not have the Arial font, LabVIEW substitutes a similar, installed font. Using too many font styles can make your front panel window look busy and disorganized. Instead, use two or three different sizes of the same font. Serifs help people to recognize whole words from a distance. If you are using more than one size of a font, make sure the sizes are noticeably different. If not, it may look like a mistake. Similarly, if you use two different fonts, make sure they are distinct. Design your user interface with larger fonts and more contrast for industrial operator stations. Glare from lighting or the need to read information from a distance can make normal fonts difficult to read. Also, remember that touch screens generally require larger fonts and more spacing between selection items.
Note
If fonts do not exist on a target machine, substituted fonts can cause the user interface to appear skewed.
System Controls
A common user interface technique is to display dialog boxes at appropriate times to interact with the user. You can make a VI behave like a dialog box by selecting FileVI Properties, selecting the Window Appearance category, and selecting the Dialog option. Use the system controls and indicators located on the System palette in dialog boxes you create. The system controls change appearance depending on which platform you run the VI. When you run the VI on a different platform, the system controls adapt their color and appearance to match the standard dialog box controls for that platform. System controls typically ignore all colors except transparent. If you are integrating a graph or non-system control into the front panel windows, match them by hiding some borders or selecting colors similar to the system colors.
98
Lesson 4
Implementing a VI
Tab Controls
Physical instruments usually have good user interfaces. Borrow heavily from their design principles, but use smaller or more efficient controls, such as ring controls or tab controls, where appropriate. Use tab controls to overlap front panel controls and indicators in a smaller area. To add additional pages to a tab control, right-click a tab and select Add Page Before or Add Page After from the shortcut menu. Relabel the tabs with the Labeling tool, and place front panel objects on the appropriate pages. The terminals for these objects are available on the block diagram, as are terminals for any other front panel object (except Decorations). You can wire the enumerated control terminal of the tab control to the selector of a Case structure to produce cleaner block diagrams. With this method you associate each page of the tab control with a subdiagram in the Case structure. You place the control and indicator terminals from each page of the tab controlas well as the block diagram nodes and wires associated with those terminalsinto the subdiagrams of the Case structure.
Decorations
Use the decorations located on the Decorations palette to group or separate objects with boxes, lines, or arrows.
Menus
Use custom menus to present front panel functionality in an orderly way and in a relatively small space. Using small amounts of space leaves room on the front panel for critical controls and indicators, items for beginners, items needed for productivity, and items that do not fit well into menus. You also can create keyboard shortcuts for menu items. To create a run-time shortcut menu for front panel objects, right-click the front panel object and select AdvancedRun-Time Shortcut MenuEdit. To create a custom run-time menu for your VI, select EditRun-Time Menu.
Lesson 4
Implementing a VI
Terminals
The block diagram terminals visually communicate to the user some information about the data type they represent. For example, in Figure 4-4, Height (cm) is a double-precision, floating-point numeric. This is indicated by the color of the terminal, orange, and by the text shown on the terminal, DBL.
100
Lesson 4
Implementing a VI
When you wire two or more numeric inputs of different representations to a function, the function usually returns the data in the larger, or wider, representation. The functions coerce the smaller representations to the widest representation before execution and LabVIEW places a coercion dot on the terminal where the conversion takes place. The numeric data type includes the following subcategories of representationfloating-point numbers, signed integers, unsigned integers, and complex numbers.
101
Lesson 4
Implementing a VI
Floating-Point Numbers
Floating-point numbers represent fractional numbers. In LabVIEW, floating-point numbers are represented with the color orange. Single-precision (SGL)Single-precision, floating-point numbers have 32-bit IEEE single-precision format. Use single-precision, floating-point numbers to save memory and avoid overflowing the range of the numbers. Double-precision (DBL)Double-precision, floating-point numbers have 64-bit IEEE double-precision format. Double-precision is the default format for numeric objects. For most situations, use double-precision, floating-point numbers. Extended-precision (EXT)In memory, the size and precision of extended-precision numbers vary depending on the platform. In Windows, they have 80-bit IEEE extended-precision format.
To represent a rational number using the fixed-point data type, the denominator of the rational number must be a power of 2, because the binary number system is a base-2 number system. Use the fixed-point data type when you do not need the dynamic functionality of floating-point representation or when you want to work with a target that does not support floating-point arithmetic, such as an FPGA target. Specify the encoding, word length, and integer word length of a fixed-point number when you want the number to conform to a certain bit size. EncodingThe binary encoding of the fixed-point number. You can select signed or unsigned. If you select signed, the sign bit is always the first bit in the bit string that represents the data. Word lengthThe total number of bits in the bit string that LabVIEW uses to represent all possible values of the fixed-point data. LabVIEW accepts a maximum word length of 64 bits. Certain targets might limit data to smaller word lengths. If you open a VI on a target and the VI contains fixed-point 102
Lesson 4
Implementing a VI
data with larger word lengths than the target can accept, the VI contains broken wires. Refer to the documentation for a target to determine the maximum word length the target accepts. Integer word lengthThe number of integer bits in the bit string that LabVIEW uses to represent all possible values of the fixed-point data, or, given an initial position to the left or right of the most significant bit, the number of bits to shift the binary point to reach the most significant bit. The integer word length can be larger than the word length, and can be positive or negative.
Integers
Integers represent whole numbers. Signed integers can be positive or negative. Use the unsigned integer data types when you know the integer is always positive. In LabVIEW, integers are represented with the color blue. When LabVIEW converts floating-point numbers to integers, the VI rounds to the nearest even integer. For example, LabVIEW rounds 2.5 to 2 and rounds 3.5 to 4. Byte (I8)Byte integer numbers have 8 bits of storage and a range of 128 to 127. Word (I16)Word integer numbers have 16 bits of storage and a range of 32,768 to 32,767. Long (I32)Long integer numbers have 32 bits of storage and a range of 2,147,483,648 to 2,147,483,647. In most cases, it is best to use a 32-bit integer. Quad (I64)Quad integer numbers have 64 bits of storage and a range of 1e19 to 1e19. Byte (U8)Byte unsigned integer numbers have 8 bits of storage and a range of 0 to 255. Word (U16)Word unsigned integer numbers have 16 bits of storage and a range of 0 to 65,535. Long (U32)Long unsigned integer numbers have 32 bits of storage and a range of 0 to 4,294,967,295. Quad (U64)Quad unsigned integer numbers have 64 bits of storage and a range of 0 to 2e19.
103
Lesson 4
Implementing a VI
Complex Numbers
Complex numbers are represented by two values linked together in memoryone representing the real part and one representing the imaginary part. In LabVIEW, because complex numbers are a type of floating-point number, complex numbers are also represented with the color orange. Complex Single (CSG)Complex single-precision, floating-point numbers consist of real and imaginary values in 32-bit IEEE single-precision format. Complex Double (CDB)Complex double-precision, floating-point numbers consist of real and imaginary values in 64-bit IEEE double-precision format. Complex Extended (CXT)Complex extended-precision, floating-point numbers consist of real and imaginary values in IEEE extended-precision format. In memory, the size and precision of extended-precision numbers vary depending on the platform. In Windows, they have 80-bit IEEE extended-precision format.
Boolean Values
LabVIEW stores Boolean data as 8-bit values. If the 8-bit value is zero, the Boolean value is FALSE. Any nonzero value represents TRUE. In LabVIEW, the color green represents Boolean data. Boolean values also have a mechanical action associated with them. The two major actions are latch and switch. You can select from the following button behaviors: Switch when pressedChanges the control value each time you click it with the Operating tool. The frequency with which the VI reads the control does not affect this behavior. Switch when releasedChanges the control value only after you release the mouse button during a mouse click within the graphical boundary of the control. The frequency with which the VI reads the control does not affect this behavior. Switch until releasedChanges the control value when you click it and retains the new value until you release the mouse button. At this time, the control reverts to its default value, similar to the operation of a door buzzer. The frequency with which the VI reads the control does not affect this behavior. You cannot select this behavior for a radio buttons control.
104
Lesson 4
Implementing a VI
Latch when pressedChanges the control value when you click it and retains the new value until the VI reads it once. At this point, the control reverts to its default value even if you keep pressing the mouse button. This behavior is similar to a circuit breaker and is useful for stopping a While Loop or for getting the VI to perform an action only once each time you set the control. You cannot select this behavior for a radio buttons control. Latch when releasedChanges the control value only after you release the mouse button within the graphical boundary of the control. When the VI reads it once, the control reverts to its default value. This behavior works in the same manner as dialog box buttons and system buttons. You cannot select this behavior for a radio buttons control. Latch until releasedChanges the control value when you click it and retains the value until the VI reads it once or you release the mouse button, depending on which one occurs last. You cannot select this behavior for a radio buttons control.
To learn more about mechanical action, experiment with the Mechanical Action of Booleans VI in the NI Example Finder.
105
Lesson 4
Implementing a VI
Strings
A string is a sequence of displayable or non-displayable ASCII characters. Strings provide a platform-independent format for information and data. Some of the more common applications of strings include the following: Creating simple text messages. Controlling instruments by sending text commands to the instrument and returning data values in the form of either ASCII or binary strings which you then convert to numeric values. Storing numeric data to disk. To store numeric data in an ASCII file, you must first convert numeric data to strings before writing the data to a disk file. Instructing or prompting the user with dialog boxes.
On the front panel, strings appear as tables, text entry boxes, and labels. LabVIEW includes built-in VIs and functions you can use to manipulate strings, including formatting strings, parsing strings, and other editing. Refer to the ASCII Codes topic for more information about ASCII codes and conversion functions. In LabVIEW, strings are represented with the color pink. Right-click a string control or indicator on the front panel to select from the display types shown in the following table. The table also shows an example message in each display type. Display Type Normal Display Description Displays printable characters using the font of the control. Non-displayable characters generally appear as boxes. Displays backslash codes for all non-displayable characters. Displays an asterisk (*) for each character including spaces. Displays the ASCII value of each character in hex instead of the character itself. Message
There are four display types. \ is a backslash.
\ Codes Display
There\sare\sfour\sdisplay\ stypes.\n\\\sis\sa\ sbackslash. ************************** ******************* 5468 666F 6179 5C20 6B73 6572 7572 2074 6973 6C61 6520 2064 7970 2061 7368 6172 6973 6573 2062 2E 6520 706C 2E0A 6163
106
Lesson 4
Implementing a VI
LabVIEW stores strings as a pointer to a structure that contains a 4-byte length value followed by a 1D array of byte integers (8-bit characters).
Enums
An enum (enumerated control, constant or indicator) is a combination of data types. An enum represents a pair of values, a string and a numeric, where the enum can be one of a list of values. For example, if you created an enum type called Month, the possible value pairs for a Month variable are January-0, February-1, and so on through December-11. Figure 4-7 shows an example of these data pairs in the Properties dialog box for an enumerated control.
107
Lesson 4
Implementing a VI
Enums are useful because it is easier to manipulate numbers on the block diagram than strings. Figure 4-8 shows the Month enumerated control, the selection of a data pair in the enumerated control, and the corresponding block diagram terminal.
Selecting an Item
Dynamic
The dynamic data type stores the information generated or acquired by an Express VI. The dynamic data type appears as a dark blue terminal, shown at left. Most Express VIs accept and/or return the dynamic data type. You can wire the dynamic data type to any indicator or input that accepts numeric, waveform, or Boolean data. Wire the dynamic data type to an indicator that can best present the data. Indicators include graphs, charts, or numeric indicators. Most other VIs and functions in LabVIEW do not accept the dynamic data type. To use a built-in VI or function to analyze or process the data the dynamic data type includes, you must convert the dynamic data type. Use the Convert from Dynamic Data Express VI to convert the dynamic data type to numeric, Boolean, waveform, and array data types for use with other VIs and functions. When you place the Convert from Dynamic Data Express VI on the block diagram, the Configure Convert from Dynamic Data dialog box appears. The Configure Convert from Dynamic Data dialog box displays options that let you specify how you want to format the data that the Convert from Dynamic Data Express VI returns.
108
Lesson 4
Implementing a VI
When you wire a dynamic data type to an array indicator, LabVIEW automatically adds the Convert from Dynamic Data Express VI to the block diagram. Double-click the Convert from Dynamic Data Express VI to open the Configure Convert from Dynamic Data dialog box to control how the data appears in the array.
C. Documenting Code
Professional developers who maintain and modify VIs know the value of good documentation. Document the block diagram well to ease future modification of the code. In addition, document the front panel window well to explain the purpose of the VI and the front panel objects. Use tip strips, descriptions, VI Properties, and good design to document front panel windows.
VI Properties
Use the Documentation component of the VI Properties dialog box to create VI descriptions and to link from VIs to HTML files or to compiled help files. To display VI Properties right-click the VI icon on the front panel or block diagram and select VI Properties from the shortcut menu or select FileVI Properties. Then select Documentation from the Categories drop-down menu. You cannot access this dialog box while a VI runs. This page includes the following components: VI descriptionContains the text that appears in the Context Help window if you move the cursor over the VI icon. Use <B> and </B> tags around any text in the description you want to format as bold. You also can use the VI Description property to edit the VI description programmatically. Help tagContains the HTML filename or index keyword of the topic you want to link to in a compiled help file. You also can use the Help:Document Tag property to set the help tag programmatically.
109
Lesson 4
Implementing a VI
Help pathContains the path to the HTML file or to the compiled help file you want to link to from the Context Help window. If this field is empty, the Detailed help link does not appear in the Context Help window, and the Detailed help button is dimmed. BrowseDisplays a file dialog box to use to navigate to an HTML file or to a compiled help file to use as the Help path.
Graphical Programming
While the graphical nature of LabVIEW aids in self-documentation of block diagrams, extra comments are helpful when modifying your VIs in the future. There are two types of block diagram commentscomments that describe the function or operation of algorithms and comments that explain the purpose of data that passes through wires. Both types of comments are shown in the following block diagram. You can insert standard labels with the Labeling tool, or by inserting a free label from the Functions ProgrammingStructuresDecorations subpalette. By default, free labels have a yellow background color.
Use the following guidelines for commenting your VIs: Use comments on the block diagram to explain what the code is doing. While LabVIEW code can be self-documenting because it is graphical, use free labels to describe how the block diagram functions.
110
Lesson 4
Implementing a VI
Do not show labels on function and subVI calls because they tend to be large and unwieldy. A developer looking at the block diagram can find the name of a function or subVI by using the Context Help window. Use small free labels with white backgrounds to label long wires to identify their use. Labeling wires is useful for wires coming from shift registers and for long wires that span the entire block diagram.Refer to the Case Structures section of this lesson for more information about shift registers. Label structures to specify the main functionality of the structure. Label constants to specify the nature of the constant. Use free labels to document algorithms that you use on the block diagrams. If you use an algorithm from a book or other reference, provide the reference information.
D. While Loops
Similar to a Do Loop or a Repeat-Until Loop in text-based programming languages, a While Loop, shown in Figure 4-10, executes a subdiagram until a condition occurs. The following illustration shows a While Loop in LabVIEW, a flowchart equivalent of the While Loop functionality, and a pseudo code example of the functionality of the While Loop.
Code No Code Condition met? Yes End 1 2 3 Repeat (code); Until Condition met; End;
Flowchart
Pseudo Code
The While Loop is located on the Structures palette. Select the While Loop from the palette then use the cursor to drag a selection rectangle around the section of the block diagram you want to repeat. When you release the mouse button, a While Loop boundary encloses the section you selected.
111
Lesson 4
Implementing a VI
Add block diagram objects to the While Loop by dragging and dropping them inside the While Loop.
Tip
The While Loop always executes at least once. The While Loop executes the subdiagram until the conditional terminal, an input terminal, receives a specific Boolean value. The conditional terminal in a While Loop behaves the same as in a For Loop with a conditional terminal. However, because the For Loop also includes a set iteration count, it does not run infinitely if the condition never occurs. The While Loop does not include a set iteration count and runs infinitely if the condition never occurs. If a conditional terminal is Stop if True, you place the terminal of a Boolean control outside a While Loop, and the control is FALSE when the loop starts, you cause an infinite loop, as shown in the following example. You also cause an infinite loop if the conditional terminal is Continue if True and the control outside the loop is set to TRUE.
Changing the value of the control does not stop the infinite loop because the value is only read once, before the loop starts. To stop an infinite loop, you must abort the VI by clicking the Abort Execution button on the toolbar. You also can perform basic error handling using the conditional terminal of a While Loop. When you wire an error cluster to the conditional terminal, only the True or False value of the status parameter of the error cluster passes to the terminal. Also, the Stop if True and Continue if True shortcut menu items change to Stop if Error and Continue while Error. The iteration terminal is an output terminal that contains the number of completed iterations. The iteration count for the While Loop always starts at zero. 112
Lesson 4
Implementing a VI
In the following block diagram, the While Loop executes until the Random Number function output is greater than or equal to 10.00 and the Enable control is True. The And function returns True only if both inputs are True. Otherwise, it returns False. In the following example, there is an increased probability of an infinite loop. Generally, the desired behavior is to have one condition met to stop the loop, rather than requiring both conditions to be met.
Structure Tunnels
Tunnels feed data into and out of structures. The tunnel appears as a solid block on the border of the While Loop. The block is the color of the data type wired to the tunnel. Data pass out of a loop after the loop terminates. When a tunnel passes data into a loop, the loop executes only after data arrive at the tunnel. In the following block diagram, the iteration terminal is connected to a tunnel. The value in the tunnel does not get passed to the Iterations indicator until the While Loop finishes executing.
Only the last value of the iteration terminal displays in the Iterations indicator.
113
Lesson 4
Implementing a VI
114
Lesson 4
Implementing a VI
E. For Loops
A For Loop, shown as follows, executes a subdiagram a set number of times.Figure 4-14 shows a For Loop in LabVIEW, a flowchart equivalent of the For Loop functionality, and a pseudo code example of the functionality of the For Loop.
N=100
i=0 i=i+1 Code i=N? Yes End; End 1 2 3 No Code N=100; i=0; Until i=N: Repeat (code; i=i+1);
Flowchart
Pseudo Code
The For Loop is located on the Structures palette. You also can place a While Loop on the block diagram, right-click the border of the While Loop, and select Replace with For Loop from the shortcut menu to change a While Loop to a For Loop. The count terminal is an input terminal whose value indicates how many times to repeat the subdiagram. The iteration terminal is an output terminal that contains the number of completed iterations. The iteration count for the For Loop always starts at zero. The For Loop differs from the While Loop in that the For Loop executes a set number of times. A While Loop stops executing the subdiagram only if the value at the conditional terminal exists.
115
Lesson 4
Implementing a VI
The For Loop in Figure 4-15 generates a random number every second for 100 seconds and displays the random numbers in a numeric indicator.
116
Lesson 4
Implementing a VI
To add a conditional terminal to a For Loop, right-click on the For Loop border and select Conditional Terminal from the shortcut menu. Then wire the conditional terminal and the count terminal.
Numeric Conversion
LabVIEW can represent numeric data types as signed or unsigned integers, floating-point numeric values, or complex numeric values, as discussed in the LabVIEW Data Types section of this lesson. Normally, when you wire different representation types to the inputs of a function, the function returns an output in the larger or wider format. If you use a signed integer with an unsigned integer, it will coerce to the unsigned integer. If you use an unsigned integer with a floating point, it will coerce to the floating point. If you use a floating point number with a complex number, it will coerce to the complex number. If you use two numbers of the same type with different bit widths, LabVIEW will coerce to the larger of the two bit widths. If the number of bits is the same, LabVIEW chooses unsigned over signed integers. For example, if you wire a DBL and an I32 to a Multiply function, the result is a DBL, as shown in Figure 4-18. LabVIEW coerces the 32-bit signed integer because it uses fewer bits than the double-precision, floating-point numeric value. The lower input of the Multiply function shows a red dot, called a coercion dot, that indicates LabVIEW coerced the data.
117
Lesson 4
Implementing a VI
Coercion Dot
However, the For Loop count terminal works in the opposite manner. If you wire a double-precision, floating-point numeric value to the 32-bit count terminal, LabVIEW coerces the larger numeric value to a 32-bit signed integer. Although the conversion is contrary to normal conversion standards, it is necessary, because a For Loop can only execute an integer number of times.
Coercion Dot
For better performance, avoid coercion by using matching data types or programmatically converting to matching data types, as shown in Figure 4-20.
Lesson 4
Implementing a VI
F. Timing a VI
When a loop finishes executing an iteration, it immediately begins executing the next iteration, unless it reaches a stop condition. Most often, you need to control the iteration frequency or timing. For example, if you are acquiring data, and you want to acquire the data once every 10 seconds, you need a way to time the loop iterations so they occur once every 10 seconds. Even if you do not need the execution to occur at a certain frequency, you need to provide the processor with time to complete other tasks, such as responding to the user interface. This section introduces some methods for timing your loops.
Wait Functions
Place a wait function inside a loop to allow a VI to sleep for a set amount of time. This allows your processor to address other tasks during the wait time. Wait functions use the millisecond clock of the operating system. The Wait Until Next ms Multiple function monitors a millisecond counter and waits until the millisecond counter reaches a multiple of the amount you specify. Use this function to synchronize activities. Place this function in a loop to control the loop execution rate. For this function to be effective, your code execution time must be less than the time specified for this function. The execution rate for the first iteration of the loop is indeterminate. The Wait (ms) function waits until the millisecond counter counts to an amount equal to the input you specify. This function guarantees that the loop execution rate is at least the amount of the input you specify.
Note
The Time Delay Express VI behaves similarly to the Wait (ms) function with the addition of built-in error clusters. Refer to Lesson 3, Troubleshooting and Debugging VIs, for more information about error clusters.
Elapsed Time
In some cases, it is useful to determine how much time elapses after some point in your VI. The Elapsed Time Express VI indicates the amount of time that elapses after the specified start time. This Express VI keeps track of time while the VI continues to execute. This Express VI does not provide the processor with time to complete other tasks. You will use the Elapsed Time Express VI in the Weather Station course project.
119
Lesson 4
Implementing a VI
Shift registers are similar to static variables in text-based programming languages. Use shift registers when you want to pass values from previous iterations through the loop to the next iteration. A shift register appears as a pair of terminals directly opposite each other on the vertical sides of the loop border. The terminal on the right side of the loop contains an up arrow and stores data on the completion of an iteration. LabVIEW transfers the data connected to the right side of the register to the next iteration. After the loop executes, the terminal on the right side of the loop returns the last value stored in the shift register. Create a shift register by right-clicking the left or right border of a loop and selecting Add Shift Register from the shortcut menu. A shift register transfers any data type and automatically changes to the data type of the first object wired to the shift register. The data you wire to the terminals of each shift register must be the same type. You can add more than one shift register to a loop. If you have multiple operations that use previous iteration values within your loop, use multiple shift registers to store the data values from those different processes in the structure, as shown in the following figure.
120
Lesson 4
Implementing a VI
In Figure 4-22, the For Loop executes five times, incrementing the value the shift register carries by one each time. After five iterations of the For Loop, the shift register passes the final value, 5, to the indicator and the VI quits. Each time you run the VI, the shift register begins with a value of 0. If you do not initialize the shift register, the loop uses the value written to the shift register when the loop last executed or, if the loop has never executed, the default value for the data type.
121
Lesson 4
Implementing a VI
Use an uninitialized shift register to preserve state information between subsequent executions of a VI. Figure 4-23 shows an uninitialized shift register.
In Figure 4-23, the For Loop executes five times, incrementing the value the shift register carries by one each time. The first time you run the VI, the shift register begins with a value of 0, which is the default value for a 32-bit integer. After five iterations of the For Loop, the shift register passes the final value, 5, to the indicator, and the VI quits. The next time you run the VI, the shift register begins with a value of 5, which was the last value from the previous execution. After five iterations of the For Loop, the shift register passes the final value, 10, to the indicator. If you run the VI again, the shift register begins with a value of 10, and so on. Uninitialized shift registers retain the value of the previous iteration until you close the VI.
122
Lesson 4
Implementing a VI
If you add another element to the left terminal in the previous block diagram, values from the last two iterations carry over to the next iteration, with the most recent iteration value stored in the top shift register. The bottom terminal stores the data passed to it from the previous iteration.
123
Lesson 4
Implementing a VI
H. Plotting Data
You already used charts and graphs to plot simple data. This section explains more about using and customizing charts and graphs.
Waveform Charts
The waveform chart is a special type of numeric indicator that displays one or more plots of data typically acquired at a constant rate.Waveform charts can display single or multiple plots. Figure 4-25 shows the elements of a multiplot waveform chart. Two plots are displayed: Raw Data and Running Avg.
3 5
1 2
Label Y-scale
3 4
5 6
Configure how the chart updates to display new data. Right-click the chart and select AdvancedUpdate Mode from the shortcut menu to set the chart update mode. The chart uses the following modes to display data: Strip ChartShows running data continuously scrolling from left to right across the chart with old data on the left and new data on the right. A strip chart is similar to a paper tape strip chart recorder. Strip Chart is the default update mode.
124
Lesson 4
Implementing a VI
Scope ChartShows one item of data, such as a pulse or wave, scrolling partway across the chart from left to right. For each new value, the chart plots the value to the right of the last value. When the plot reaches the right border of the plotting area, LabVIEW erases the plot and begins plotting again from the left border. The retracing display of a scope chart is similar to an oscilloscope. Sweep ChartWorks similarly to a scope chart except it shows the old data on the right and the new data on the left separated by a vertical line. LabVIEW does not erase the plot in a sweep chart when the plot reaches the right border of the plotting area. A sweep chart is similar to an EKG display.
Figure 4-26 shows an example of each chart update mode. The scope chart and sweep chart have retracing displays similar to an oscilloscope. Because retracing a plot requires less overhead, the scope chart and the sweep chart display plots significantly faster than the strip chart.
Wiring Charts
You can wire a scalar output directly to a waveform chart. The waveform chart terminal shown in Figure 4-27 matches the input data type.
Waveform charts can display multiple plots together using the Bundle function located on the Cluster, Class & Variant palette. In Figure 4-28, the Bundle function bundles the outputs of the three VIs to plot on the waveform chart.
125
Lesson 4
Implementing a VI
The waveform chart terminal changes to match the output of the Bundle function. To add more plots, use the Positioning tool to resize the Bundle function. Refer to Lesson 5, Relating Data, for more information about the Bundle function.
Waveform Graphs
VIs with a graph usually collect the data in an array and then plot the data to the graph. Figure 4-29 shows the elements of a graph.
11
2 3 4 5
10 6 9
7 8
1 2 3
4 5 6
7 8 9
10 Y-Scale 11 Label
The graphs located on the Graph Indicators palette include the waveform graph and XY graph. The waveform graph plots only single-valued functions, as in y = f(x), with points evenly distributed along the x-axis, such as acquired time-varying waveforms. XY graphs display any set of points, evenly sampled or not. 126
Lesson 4
Implementing a VI
Resize the plot legend to display multiple plots. Use multiple plots to save space on the front panel and to make comparisons between plots. XY and waveform graphs automatically adapt to multiple plots.
Lesson 4
Implementing a VI
Use a plot array instead of a 2D array if the number of elements in each plot is different. For example, when you sample data from several channels using different time amounts from each channel, use this data structure instead of a 2D array because each row of a 2D array must have the same number of elements. The number of elements in the interior arrays of an array of clusters can vary. Refer to the (Y) Multi Plot 2 graph in the Waveform Graph VI in the labview\examples\general\graphs\gengraph.llb for an example of a graph that accepts this data type. The waveform graph accepts a cluster of an initial x value, a delta x value, and an array that contains clusters. Each cluster contains a 1D array that contains the y data. You use the Bundle function to bundle the arrays into clusters and you use the Build Array function to build the resulting clusters into an array. You also can use the Build Cluster Array function, which creates arrays of clusters that contain the inputs you specify. Refer to the (Xo = 10, dX = 2, Y) Multi Plot 3 graph in the Waveform Graph VI in the labview\examples\general\graphs\gengraph.llb for an example of a graph that accepts this data type. The waveform graph accepts an array of clusters of an x value, a delta x value, and an array of y data. This is the most general of the multiple-plot waveform graph data types because you can indicate a unique starting point and increment for the x-scale of each plot. Refer to the (Xo = 10, dX = 2, Y) Multi Plot 1 graph in the Waveform Graph VI in the labview\examples\ general\graphs\gengraph.llb for an example of a graph that accepts this data type. The waveform graph also accepts the dynamic data type, which is for use with Express VIs. In addition to the data associated with a signal, the dynamic data type includes attributes that provide information about the signal, such as the name of the signal or the date and time the data was acquired. Attributes specify how the signal appears on the waveform graph. When the dynamic data type includes multiple channels, the graph displays a plot for each channel and automatically formats the plot legend and x-scale time stamp.
128
Lesson 4
Implementing a VI
Multiplot XY Graphs
The XY graph accepts three data types for displaying multiple plots. The XY graph accepts an array of plots, where a plot is a cluster that contains an x array and a y array. Refer to the (X and Y arrays) Multi Plot graph in the XY Graph VI in the labview\examples\general\graphs\ gengraph.llb for an example of a graph that accepts this data type. The XY graph also accepts an array of clusters of plots, where a plot is an array of points. A point is a cluster that contains an x value and a y value. Refer to the (Array of Pts) Multi Plot graph in the XY Graph VI in the labview\examples\general\graphs\gengraph.llb for an example of a graph that accepts this data type. The XY graph also accepts an array of clusters of plots, where a plot is an array of complex data, in which the real part is plotted on the x-axis and the imaginary part is plotted on the y-axis.
129
Lesson 4
Implementing a VI
I. Case Structures
A Case structure has two or more subdiagrams, or cases. Only one subdiagram is visible at a time, and the structure executes only one case at a time. An input value determines which subdiagram executes. The Case structure is similar to switch statements or if...then...else statements in text-based programming languages. The case selector label at the top of the Case structure contains the name of the selector value that corresponds to the case in the center and decrement and increment arrows on each side. Click the decrement and increment arrows to scroll through the available cases. You also can click the down arrow next to the case name and select a case from the pull-down menu. Wire an input value, or selector, to the selector terminal to determine which case executes. You must wire an integer, Boolean value, string, or enumerated type value to the selector terminal. You can position the selector terminal anywhere on the left border of the Case structure. If the data type of the selector terminal is Boolean, the structure has a True case and a False case. If the selector terminal is an integer, string, or enumerated type value, the structure can have any number of cases. By default, string values you wire to the selector terminal are case sensitive. To allow case-insensitive matches, wire a string value to the selector terminal, right-click the border of the Case structure, and select Case Insensitive Match from the shortcut menu.
Note
If you do not specify a default case for the Case structure to handle out-of-range values, you must explicitly list every possible input value. For example, if the selector is an integer and you specify cases for 1, 2, and 3, you must specify a default case to execute if the input value is 4 or any other unspecified integer value.
Note
You cannot specify a default case if you wire a Boolean control to the selector. If you right-click the case selector label, Make This The Default Case does not appear in the shortcut menu. Make the Boolean control TRUE or FALSE to determine which case to execute. To convert a Case structure to a Stacked Sequence structure, right-click the Case Sequence structure and select Replace with Stacked Sequence from the shortcut menu.
130
Lesson 4
Implementing a VI
Right-click the Case structure border to add, duplicate, remove, or rearrange cases, and to select a default case.
Selecting a Case
Figure 4-31 shows a VI that uses a Case structure to execute different code dependent on whether a user selects C or F for temperature units. The top block diagram shows the True case in the foreground. In the middle block diagram, the False case is selected. To select a case, enter the value in the case selector identifier or use the Labeling tool to edit the values. After you select another case, that case displays on the block diagram, as shown in the bottom block diagram of Figure 4-31.
If you enter a selector value that is not the same type as the object wired to the selector terminal, the value appears red. This indicates that the VI will not run until you delete or edit the value. Also, because of the possible round-off error inherent in floating-point arithmetic, you cannot use floating-point numbers as case selector values. If you wire a floating-point value to the case, LabVIEW rounds the value to the nearest integer. If you type a floating-point value in the case selector label, the value appears red to indicate that you must delete or edit the value before the structure can execute.
131
Lesson 4
Implementing a VI
Default Value
empty ()
Examples
In the following examples, the numeric values pass through tunnels to the Case structure and are either added or subtracted, depending on the value wired to the selector terminal.
132
Lesson 4
Implementing a VI
If the Boolean control wired to the selector terminal is True, the VI adds the numeric values. Otherwise, the VI subtracts the numeric values.
Integer is a text ring control located on the Text Controls palette that associates numeric values with text items. If the Integer wired to the selector terminal is 0 (add), the VI adds the numeric values. If the value is 1 (subtract), the VI subtracts the numeric values. If Integer is any other value than 0 (add) or 1 (subtract), the VI adds the numeric values, because that is the default case.
133
Lesson 4
Implementing a VI
If String is add, the VI adds the numeric values. If String is subtract, the VI subtracts the numeric values.
An enumerated type control gives users a list of items from which to select. The data type of an enumerated type control includes information about the numeric values and string labels in the control. The case selector displays the string label for each item in the enumerated type control when you select Add Case For Every Value from the Case structure shortcut menu. The Case structure executes the appropriate case subdiagram based on the current item in the enumerated type control. In the previous block diagram, if Enum is add, the VI adds the numeric values. If Enum is subtract, the VI subtracts the numeric 134 values.
Lesson 4
Implementing a VI
When you wire an error cluster to the selector terminal of a Case structure, the case selector label displays two casesError and No Errorand the border of the Case structure changes colorred for Error and green for No Error. If an error occurs, the Case structure executes the Error subdiagram. When you wire an error cluster to the selection terminal, the Case structure recognizes only the status Boolean element of the cluster.
135
136
Lesson 4
Implementing a VI
Self-Review: Quiz
1. Which identifies the control or indicator on the block diagram? a. Caption b. Location c. Label d. Value
2. Which structure must run at least one time? a. While Loop b. For Loop
3. Which is only available on the block diagram? a. Control b. Constant c. Indicator d. Connector pane
4. Which mechanical action causes a Boolean control in the False state to change to True when you click it and stay True until you release it and LabVIEW has read the value? a. Switch until released b. Switch when released c. Latch until released d. Latch when released
137
138
Lesson 4
Implementing a VI
2. Which structure must run at least one time? a. While Loop b. For Loop
3. Which is only available on the block diagram? a. Control b. Constant c. Indicator d. Connector pane
4. Which mechanical action causes a Boolean control in the False state to change to True when you click it and stay True until you release it and LabVIEW has read the value? a. Switch until released b. Switch when released c. Latch until released d. Latch when released
139
Lesson 4
Implementing a VI
Notes
140
Relating Data
Sometimes it is beneficial to group data related to one another. Use arrays and clusters to group related data in LabVIEW. Arrays combine data of the same data type into one data structure, and clusters combine data of multiple data types into one data structure. Use type definitions to define custom arrays and clusters. This lesson explains arrays, clusters, and type definitions, and applications where using these can be beneficial.
Topics
A. Arrays B. Clusters C. Type Definitions
141
Lesson 5
Relating Data
A. Arrays
An array consists of elements and dimensions. Elements are the data that make up the array. A dimension is the length, height, or depth of an array. An array can have one or more dimensions and as many as (231) 1 elements per dimension, memory permitting. You can build arrays of numeric, Boolean, path, string, waveform, and cluster data types. Consider using arrays when you work with a collection of similar data and when you perform repetitive computations. Arrays are ideal for storing data you collect from waveforms or data generated in loops, where each iteration of a loop produces one element of the array. Array indexes in LabVIEW are zero-based. The index of the first element in the array, regardless of its dimension, is zero.
Note
Restrictions
You cannot create arrays of arrays. However, you can use a multidimensional array or create an array of clusters where each cluster contains one or more arrays. Also, you cannot create an array of subpanel controls, tab controls, .NET controls, ActiveX controls, charts, or multiplot XY graphs. Refer to the clusters section of this lesson for more information about clusters. An example of a simple array is a text array that lists the nine planets of our solar system. LabVIEW represents this as a 1D array of strings with nine elements. Array elements are ordered. An array uses an index so you can readily access any particular element. The index is zero-based, which means it is in the range 0 to n 1, where n is the number of elements in the array. For example, n = 12 for the twelve months of the year, so the index ranges from 0 to 11. March is the third month, so it has an index of 2.
142
Lesson 5
Relating Data
Figure 5-1 shows an example of an array of numerics. The first element shown in the array (3.00) is at index 1, and the second element (1.00) is at index 2. The element at index 0 is not shown in this image, because element 1 is selected in the index display. The element selected in the index display always refers to the element shown in the upper left corner of the element display.
Index Display
Element Display
If you attempt to drag an invalid control or indicator into the array shell, you are unable to place the control or indicator in the array shell. You must insert an object in the array shell before you use the array on the block diagram. Otherwise, the array terminal appears black with an empty bracket and has no data type associated with it.
143
Lesson 5
Relating Data
Two-Dimensional Arrays
The previous examples use 1D arrays. A 2D array stores elements in a grid. It requires a column index and a row index to locate an element, both of which are zero-based. Figure 5-3 shows an 8 column by 8 row 2D array, which contains 8 8 = 64 elements.
To add a multidimensional array to the front panel, right-click the index display and select Add Dimension from the shortcut menu. You also can resize the index display until you have as many dimensions as you want.
Initializing Arrays
You can initialize an array or leave it unitialized. When an array is initialized, you defined the number of elements in each dimension and the contents of each element. An uninitialized array contains a fixed number of dimensions but no elements. Figure 5-4 shows an uninitialized 2D array control. Notice that the elements are all dimmed. This indicates that the array is uninitialized.
144
Lesson 5
Relating Data
In Figure 5-5, six elements are initialized. In a 2D array, after you initialize an element in a row, the remaining elements in that row are initialized and populated with the default value for the data type. For example, in Figure 5-5, if you enter 4 into the element in the first column, third row, the elements in the second and third column in the third row are automatically populated with a 0.
Array Inputs
If you enable auto-indexing on an array wired to a For Loop input terminal, LabVIEW sets the count terminal to the array size so you do not need to wire the count terminal. Because you can use For Loops to process arrays one element at a time, LabVIEW enables auto-indexing by default for every array you wire to a For Loop. You can disable auto-indexing if you do not need to process arrays one element at a time. In Figure 5-6, the For Loop executes a number of times equal to the number of elements in the array. Normally, if the count terminal of the For Loop is not wired, the run arrow is broken. However, in this case the run arrow is not broken.
145
Lesson 5
Relating Data
If you enable auto-indexing for more than one tunnel or if you wire the count terminal, the actual number of iterations becomes the smaller of the choices. For example, if two auto-indexed arrays enter the loop, with 10 and 20 elements respectively, and you wire a value of 15 to the count terminal, the loop still only executes 10 times, indexing all elements of the first array but only the first 10 elements of the second array.
Array Outputs
When you auto-index an array output tunnel, the output array receives a new element from every iteration of the loop. Therefore, auto-indexed output arrays are always equal in size to the number of iterations. The wire from the output tunnel to the array indicator becomes thicker as it changes to an array at the loop border, and the output tunnel contains square brackets representing an array, as shown Figure 5-7.
146
Lesson 5
Relating Data
Right-click the tunnel at the loop border and select Enable Indexing or Disable Indexing from the shortcut menu to enable or disable auto-indexing. Auto-indexing for While Loops is disabled by default. For example, disable auto-indexing if you need only the last value passed out of the tunnel.
B. Clusters
Clusters group data elements of mixed types. An example of a cluster is the LabVIEW error cluster, which combines a Boolean value, a numeric value, and a string. A cluster is similar to a record or a struct in text-based programming languages. Bundling several data elements into clusters eliminates wire clutter on the block diagram and reduces the number of connector pane terminals that subVIs need. The connector pane has, at most, 28 terminals. If your front panel contains more than 28 controls and indicators that you want to pass to another VI, group some of them into a cluster and assign the cluster to a terminal on the connector pane. Most clusters on the block diagram have a pink wire pattern and data type terminal. Error clusters have a dark yellow wire pattern and data type terminal. Clusters of numeric values, sometimes referred to as points, have a brown wire pattern and data type terminal. You can wire brown numeric clusters to Numeric functions, such as Add or Square Root, to perform the same operation simultaneously on all elements of the cluster.
147
Lesson 5
Relating Data
148
Lesson 5
Relating Data
Figure 5-10 is an example of a cluster containing three controls: a string, a Boolean switch, and a numeric. A cluster is either a control or an indicator; it cannot contain a mixture of controls and indicators.
Cluster Order
Cluster elements have a logical order unrelated to their position in the shell. The first object you place in the cluster is element 0, the second is element 1, and so on. If you delete an element, the order adjusts automatically. The cluster order determines the order in which the elements appear as terminals on the Bundle and Unbundle functions on the block diagram. You can view and modify the cluster order by right-clicking the cluster border and selecting Reorder Controls In Cluster from the shortcut menu.
149
Lesson 5
Relating Data
1 3
1 2
3 4
New Order
The white box on each element shows its current place in the cluster order. The black box shows the new place in the order for an element. To set the order of a cluster element, enter the new order number in the Click to set to text box and click the element. The cluster order of the element changes, and the cluster order of other elements adjusts. Save the changes by clicking the Confirm button on the toolbar. Revert to the original order by clicking the Cancel button.
Use the Bundle function to assemble a cluster, use the Bundle function and Bundle by Name function to modify a cluster, and use the Unbundle function and the Unbundle by Name function to disassemble clusters. You also can place the Bundle, Bundle by Name, Unbundle, and Unbundle by Name functions on the block diagram by right-clicking a cluster terminal on the block diagram and selecting Cluster, Class & Variant Palette from the shortcut menu. The Bundle and Unbundle functions automatically
150
Lesson 5
Relating Data
contain the correct number of terminals. The Bundle by Name and Unbundle by Name functions appear with the first element in the cluster. Use the Positioning tool to resize the Bundle by Name and Unbundle by Name functions to show the other elements of the cluster.
Assembling Clusters
Use the Bundle function to assemble a cluster from individual elements or to change the values of individual elements in an existing cluster without having to specify new values for all elements. Use the Positioning tool to resize the function or right-click an element input and select Add Input from the shortcut menu.
Modifying a Cluster
If you wire the cluster input, you can wire only the elements you want to change. For example, the Input Cluster shown in Figure 5-13 contains three controls.
If you know the cluster order, you can use the Bundle function to change the Command value by wiring the elements shown in Figure 5-13. You can also use the Bundle by Name function to replace or access labeled elements of an existing cluster. The Bundle by Name function works like the Bundle function, but instead of referencing cluster elements by their cluster order, it references them by their owned labels. You can access only elements with owned labels. The number of inputs does not need to match the number of elements in output cluster.
151
Lesson 5
Relating Data
Use the Operating tool to click an input terminal and select an element from the pull-down menu. You also can right-click the input and select the element from the Select Item shortcut menu. In Figure 5-14, you can use the Bundle by Name function to update the values of Command and Function with the values of New Command and New Function.
Use the Bundle by Name function for data structures that might change during development. If you add a new element to the cluster or modify its order, you do not need to rewire the Bundle by Name function because the names are still valid.
Disassembling Clusters
Use the Unbundle function to split a cluster into its individual elements. Use the Unbundle by Name function to return the cluster elements whose names you specify. The number of output terminals does not depend on the number of elements in the input cluster. Use the Operating tool to click an output terminal and select an element from the pull-down menu. You also can right-click the output terminal and select the element from the Select Item shortcut menu. For example, if you use the Unbundle function with the cluster in Figure 5-15, it has four output terminals that correspond to the four controls in the cluster. You must know the cluster order so you can associate the correct Boolean terminal of the unbundled cluster with the corresponding switch in the cluster. In this example, the elements are ordered from top to bottom starting with element 0. If you use the Unbundle by Name function, you can have an arbitrary number of output terminals and access individual elements by name in any order.
152
Lesson 5
Relating Data
Error Clusters
LabVIEW contains a custom cluster called the error cluster. LabVIEW uses error clusters to pass error information. An error cluster contains the following elements: statusBoolean value that reports TRUE if an error occurred. code32-bit signed integer that identifies the error numerically. sourceString that identifies where the error occurred.
For more information about using error clusters, refer to Lesson 3, Troubleshooting and Debugging VIs, of this manual and the Handling Errors topic of the LabVIEW Help.
153
Lesson 5
Relating Data
C. Type Definitions
You can use type definitions to define custom arrays and clusters.
Custom Controls
Use custom controls and indicators to extend the available set of front panel objects. You can create custom user interface components for an application that vary cosmetically from built-in LabVIEW controls and indicators. You can save a custom control or indicator you created in a directory or LLB and use the custom control or indicator on other front panels. You also can create an icon for the custom control or indicator and add it to the Controls palette. Refer to the caveats and recommendations before you begin creating custom controls and indicators. Refer to the Creating Custom Controls, Indicators, and Type Definitions topic of the LabVIEW Help for more information about creating and using custom controls and type definitions. Use the Control Editor window to customize controls and indicators. For example, you can change the size, color, and relative position of the elements of a control or indicator and import images into the control or indicator. You can display the Control Editor window in the following ways: Right-click a front panel control or indicator and select Advanced Customize from the shortcut menu. Use the Positioning tool to select a front panel control or indicator and select EditCustomize Control. Use the New dialog box.
The Control Editor appears with the selected front panel object in its window. The Control Editor has two modes, edit mode and customize mode. The Control Editor window toolbar indicates whether you are in edit mode or in customize mode. The Control Editor window opens in edit mode. Click the Change to Edit Mode button to change to edit mode. Click the Change to Customize Mode button to change to customize mode. You also can switch between modes by selecting OperateChange to Customize Mode or OperateChange to Edit Mode. Use edit mode to change the size or color of a control or indicator and to select options from its shortcut menu, just as you do in edit mode on a front panel.
154
Lesson 5
Relating Data
Use customize mode to make extensive changes to controls or indicators by changing the individual parts of a control or indicator.
Edit Mode
In the edit mode, you can right-click the control and manipulate its settings as you would in the LabVIEW programming environment.
1 2 3 4
5 6 7
Customize Mode
In the customize mode, you can move the individual components of the control around with respect to each other. For a listing of what you can manipulate in customize mode, select WindowShow Parts Window.
1 2 3 4
5 6 7
One way to customize a control is to change its type definition status. You can save a control as a control, a type definition, or a strict type definition, depending on the selection visible in the Type Def. Status ring. The control option is the same as a control you would select from the Controls palette. You can modify it in any way you need to, and each copy you make and change retains its individual properties.
Lesson 5
Relating Data
Type Definitions
Use type definitions and strict type definitions to link all the instances of a custom control or indicator to a saved custom control or indicator file. You can make changes to all instances of the custom control or indicator by editing only the saved custom control or indicator file, which is useful if you use the same custom control or indicator in several VIs. When you place a custom control or indicator in a VI, no connection exists between the custom control or indicator you saved and the instance of the custom control or indicator in the VI. Each instance of a custom control or indicator is a separate, independent copy. Therefore, changes you make to a custom control or indicator file do not affect VIs already using that custom control or indicator. If you want to link instances of a custom control or indicator to the custom control or indicator file, save the custom control or indicator as a type definition or strict type definition. All instances of a type definition or a strict type definition link to the original file from which you created them. When you save a custom control or indicator as a type definition or strict type definition, any data type changes you make to the type definition or strict type definition affect all instances of the type definition or strict type definition in all the VIs that use it. Also, cosmetic changes you make to a strict type definition affect all instances of the strict type definition on the front panel. Type definitions identify the correct data type for each instance of a custom control or indicator. When the data type of a type definition changes, all instances of the type definition automatically update. In other words, the data type of the instances of the type definition change in each VI where the type definition is used. However, because type definitions identify only the data type, only the values that are part of the data type update. For example, on numeric controls, the data range is not part of the data type. Therefore, type definitions for numeric controls do not define the data range for the instances of the type definitions. Also, because the item names in ring controls do not define the data type, changes to ring control item names in a type definition do not change the item names in instances of the type definition. However, if you change the item names in the type definition for an enumerated type control, the instances update because the item names are part of the data type. An instance of a type definition can have its own unique caption, label, description, tip strip, default value, size, color, or style of control or indicator, such as a knob instead of a slide.
156
Lesson 5
Relating Data
If you change the data type in a type definition, LabVIEW converts the old default value in instances of the type definition to the new data type, if possible. LabVIEW cannot preserve the instance default value if the data type changes to an incompatible type, such as replacing a numeric control or indicator with a string control or indicator. When the data type of a type definition changes to a data type incompatible with the previous type definition, LabVIEW sets the default value of instances to the default value you specify in the .ctl file. If you do not specify a default value, LabVIEW uses the default value for the data type. For example, if you change a type definition from a numeric to a string type, LabVIEW replaces any default values associated with the old numeric data type with empty strings.
157
158
Lesson 5
Relating Data
Self-Review: Quiz
1. You can create an array of arrays. a. True b. False 2. You have two input arrays wired to a For Loop. Auto-indexing is enabled on both tunnels. One array has 10 elements, the second array has five elements. A value of 7 is wired to the Count terminal, as shown in Figure 5-16. What is the value of the Iterations indicator after running this VI?
3. You customize a control, select Control from the Control Type pull-down menu, and save the control as a .ctl file. You then use an instance of the custom control on your front panel window. If you open the .ctl file and modify the control, does the control on the front panel window change? a. Yes b. No 4. You are inputting data that represents a circle. The circle data includes three double precision numerics: x position, y position and radius. In the future, you might need to expand all instances of the circle data to include the color of the circle, represented as an integer. How should you represent the circle on your front panel window? a. Three separate controls for the two positions and the radius. b. A cluster containing all of the data. c. A custom control containing a cluster. d. A type definition containing a cluster. e. An array with three elements.
159
160
Lesson 5
Relating Data
Value of Iterations = 4 LabVIEW does not exceed the array size. This helps to protect against programming error. LabVIEW mathematical functions work the same wayif you wire a 10 element array to the x input of the Add function, and a 5 element array to the y input of the Add function, the output is a 5 element array. Although the for loop runs 5 times, the iterations are zero based, therefore the value of the Iterations indicators is 4. 3. You customize a control, select Control from the Control Type pull-down menu, and save the control as a .ctl file. You then use an instance of the custom control on your front panel window. If you open the .ctl file and modify the control, does the control on the front panel window change? a. Yes b. No
161
Lesson 5
Relating Data
4. You are inputting data that represents a circle. The circle data includes three double precision numerics: x position, y position and radius. In the future, you might need to expand all instances of the circle data to include the color of the circle, represented as an integer. How should you represent the circle on your front panel window? a. Three separate controls for the two positions and the radius. b. A cluster containing all of the data. c. A custom control containing a cluster. d. A type definition containing a cluster. e. An array with three elements.
162
Lesson 5
Relating Data
Notes
163
Lesson 5
Relating Data
Notes
164
Managing Resources
You have learned how to acquire data and how to display it, but storage of your data is usually a very important part of any project. You have also learned how to set up your hardware and configure it in the Measurement & Automation Explorer. In this lesson, you learn about storing data, programming a basic DAQ application using the DAQmx API, and controlling stand-alone instruments with the VISA API and instrument drivers in LabVIEW.
Topics
A. Understanding File I/O B. Understanding High-Level File I/O C. Understanding Low-Level File I/O D. DAQ Programming E. Instrument Control Programming F. Using Instrument Drivers
165
Lesson 6
Managing Resources
1 2
3 4
File Formats
LabVIEW can use or create the following file formats: Binary, ASCII, LVM, and TDMS. BinaryBinary files are the underlying file format of all other file formats. ASCIIAn ASCII file is a specific type of binary file that is a standard used by most programs. It consists of a series of ASCII codes. ASCII files are also called text files. LVMThe LabVIEW measurement data file (.lvm) is a tab-delimited text file you can open with a spreadsheet application or a text-editing application. The .lvm file includes information about the data, such as the date and time the data was generated. This file format is a specific type of ASCII file created for LabVIEW. TDMSThis file format is a specific type of binary file created for National Instruments products. It actually consists of two separate filesa binary file that contains data and stores properties about the data, and a binary index file that provides consolidated information on all the attributes and pointers in the binary file.
166
Lesson 6
Managing Resources
In this course, you learn about creating text (ASCII) files. Use text files when you want to access the file from another application, if disk space and file I/O speed are not crucial, if you do not need to perform random access read or writes, and if numeric precision is not important. You used an LVM file in Lesson 2, Navigating LabVIEW. To learn more about binary and TDMS files, refer to the LabVIEW Help.
167
Lesson 6
Managing Resources
Tip
Avoid placing the high-level VIs in loops, because the VIs perform open and close operations each time they run.
168
Lesson 6
Managing Resources
169
Lesson 6
Managing Resources
170
Lesson 6
Managing Resources
D. DAQ Programming
You already have an understanding of transducers, signals, DAQ device configuration, and MAX. Now you can begin learning to use LabVIEW to develop a data acquisition application. NI-DAQmx supports software packages other than LabVIEW, but this course describes only LabVIEW development of DAQ applications.
171
Lesson 6
Managing Resources
Constants
DAQmx Task Name ConstantLists all tasks you create and save using the DAQ Assistant. Right-click the constant and select I/O Name Filtering from the shortcut menu to limit the tasks the constant displays and to limit what you can enter in the constant. DAQmx Global Channel ConstantLists all global channels you create and save by using the DAQ Assistant. Click and select Browse to select multiple channels. Right-click the constant and select I/O Name Filtering from the shortcut menu to limit the channels the constant displays and to limit what you can enter in the constant.
VIs
DAQmx Create Virtual Channel VICreates a virtual channel or set of virtual channels and adds them to a task. The instances of this polymorphic VI correspond to the I/O type of the channel, such as analog input, digital output, or counter output; the measurement or generation to perform, such as temperature measurement, voltage generation, or event counting; and in some cases, the sensor to use, such as a thermocouple or RTD for temperature measurements. This function sets the same settings that you configure in MAX when creating a virtual channel. Use this function if the operator of your program might periodically change the physical channel connection, but not other important settings, such as terminal configuration mode or the custom scale applied. Use the physical channel pull-down menu to specify the device number of the DAQ device and the actual physical channel your signal is connected to. DAQmx Read VIReads samples from the task or channels you specify. The instances of this polymorphic VI specify what format of samples to return, whether to read a single sample or multiple samples at once, and whether to read from one or multiple channels. You can select an instance by right clicking on the DAQmx Read VI and choose Select Type to include additional configuration options for read operations.
172
Lesson 6
Managing Resources
DAQmx Write VIWrites samples to task or channels you specify. The instances of this polymorphic VI specify the format of the samples to write, whether to write one or multiple samples, and whether to write to one or multiple channels. You can select an instance by right clicking on the DAQmx Write VI and choose Select Type to include additional configuration options for write operations DAQmx Wait Until Done VIWaits for the measurement or generation to complete. Use this VI to ensure that the specified operation is complete before you stop the task. DAQmx Timing VI Configures number of samples to acquire or generate and creates a buffer when needed. The instances of this polymorphic VI correspond to the type of timing to use on the task. DAQmx Trigger VIConfigures triggering for the task. The instances of this polymorphic VI correspond to the trigger and trigger type to configure. DAQmx Start Task VITransitions the task to the running state to begin the measurement or generation. Using this VI is required for some applications and is optional for others. DAQmx Stop Task VIStops the task and returns it to the state the task was in before you used the DAQmx Start Task VI or used the DAQmx Write VI with the autostart input set to TRUE. DAQmx Clear Task VIClears the task. Before clearing, this VI stops the task, if necessary, and releases any resources reserved by the task. You cannot use a task after you clear it unless you recreate the task.
173
Lesson 6
Managing Resources
The instrument descriptor is similar to a telephone number, the resource is similar to the person with whom you want to speak, and the session is similar to the telephone line. Each call uses its own line, and crossing these lines results in an error. Table 6-1 shows the proper syntax for the instrument descriptor.
174
Lesson 6
Managing Resources
Interface Asynchronous serial GPIB VXI instrument through embedded or MXIbus controller GPIB-VXI controller
Syntax
ASRL[device][::INSTR] GPIB[device]::primary address[::secondary address][::INSTR] VXI[device]::VXI logical address[::INSTR] GPIB-VXI[device][::GPIB-VXI primary address]::VXI logical address[::INSTR]
You can use an alias you assign in MAX instead of the instrument descriptor. The most commonly used VISA communication functions are the VISA Write and VISA Read functions. Most instruments require you to send information in the form of a command or query before you can read information back from the instrument. Therefore, the VISA Write function is usually followed by a VISA Read function. The VISA Write and VISA Read functions work with any type of instrument communication and are the same whether you are doing GPIB or serial communication. However, because serial communication requires you to configure extra parameters, you must start the serial port communication with the VISA Configure Serial Port VI.
175
Lesson 6
Managing Resources
You also can use the VIs and functions located on the Serial palette for parallel port communication. You specify the VISA resource name as being one of the LPT ports. For example, you can use MAX to determine that LPT1 has a VISA resource name of ASRL10::INSTR.
Lesson 6
Managing Resources
This is an example program that is available in the NI Example Finder when you install the LabVIEW Plug and Play instrument driver for the Agilent 34401 DMM. Many programmable instruments have a large number of functions and modes. With this complexity, it is necessary to provide a consistent design model that aids both instrument driver developers as well as end users who develop instrument control applications. The LabVIEW Plug and Play instrument driver model contains both external structure and internal structure guidelines. The external structure shows how the instrument driver interfaces with the user and to other software components in the system. The internal structure shows the internal organization of the instrument driver software module.
177
Lesson 6
Managing Resources
For the external structure of the instrument driver, the user interacts with the instrument driver using an API or an interactive interface. Usually, the interactive interface is used for testing or for end-users. The API is accessed through LabVIEW. The instrument driver communicates with the instrument using VISA. Internally, the VIs in an instrument driver are organized into six categories. These categories are summarized in the following table. Category Initialize Description The Initialize VI establishes communication with the instrument and is the first instrument driver VI called. Configure VIs are software routines that configure the instrument to perform specific operations. After calling these VIs, the instrument is ready to take measurements or stimulate a system. Action/Status VIs command the instrument to carry out an action (for example, arming a trigger) or obtain the current status of the instrument or pending operations. The data VIs transfer data to or from the instrument. Utility VIs perform a variety of auxiliary operations, such as reset and self-test. The close VI terminates the software connection to the instrument. This is the last instrument driver VI called.
Configure
Action/Status
178
Lesson 6
Managing Resources
Self-Review: Quiz
1. Your continuously running test program logs to a single file the results of all tests that occur in one hour as they are calculated. If you are concerned about the execution speed of your program, should you use low-level or high-level File I/O VIs? a. Low-level file I/O VIs b. High-level file I/O VIs
2. If you want to view data in a text editor like Notepad, what file format should you use to save the data? a. ASCII b. TDMS
3. Which of the following conveys the basic DAQmx programming flow? a. Create TaskConfigure TaskAcquire/Generate DataStart Task b. Acquire/Generate DataStart TaskClear Task c. Start TaskCreate TaskConfigure TaskAcquire/Generate Data Clear Task d. Create TaskConfigure TaskStart TaskAcquire/Generate Data Clear Task
179
180
Lesson 6
Managing Resources
2. If you want to view data in a text editor like Notepad, what file format should you use to save the data? a. ASCII b. TDMS
3. Which of the following conveys the basic DAQmx programming flow? a. Create TaskConfigure TaskAcquire/Generate DataStart Task b. Acquire/Generate DataStart TaskClear Task c. Start TaskCreate TaskConfigure TaskAcquire/Generate Data Clear Task d. Create TaskConfigure TaskStart TaskAcquire/Generate DataClear Task
181
Lesson 6
Managing Resources
Notes
182
This lesson describes how to develop modular applications. The power of LabVIEW lies in the hierarchical nature of the VI. After you create a VI, you can use it on the block diagram of another VI. There is no limit on the number of layers in the hierarchy. Using modular programming helps you manage changes and debug the block diagram quickly.
Topics
A. Understanding Modularity B. Building the Icon and Connector Pane C. Using SubVIs
183
Lesson 7
A. Understanding Modularity
Modularity defines the degree to which a program is composed of discrete modules such that a change to one module has minimal impact on other modules. Modules in LabVIEW are called subVIs. A VI within another VI is called a subVI. A subVI corresponds to a subroutine in text-based programming languages. When you double-click a subVI, a front panel and block diagram appear, rather than a dialog box in which you can configure options. The front panel includes controls and indicators. The block diagram includes wires, front panel icons, functions, possibly subVIs, and other LabVIEW objects that also might look familiar. The upper right corner of the front panel window and block diagram window displays the icon for the VI. This icon is the same as the icon that appears when you place the VI on the block diagram. As you create VIs, you might find that you perform a certain operation frequently. Consider using subVIs or loops to perform that operation repetitively. For example, the following block diagram contains two identical operations.
184
Lesson 7
The example calls the Temperature VI as a subVI twice on its block diagram and functions the same as the previous block diagram. You also can reuse the subVI in other VIs. The following pseudo-code and block diagrams demonstrate the analogy between subVIs and subroutines. Function Code
function average (in1, in2, out) { out = (in1 + in2)/2.0; }
185
Lesson 7
Customizing the icon is recommended, but optional. Using the default LabVIEW icon does not affect functionality. You also need to build a connector pane to use the VI as a subVI. The connector pane is a set of terminals that correspond to the controls and indicators of that VI, similar to the parameter list of a function call in text-based programming languages. The connector pane defines the inputs and outputs you can wire to the VI so you can use it as a subVI. A connector pane receives data at its input terminals and passes the data to the block diagram code through the front panel controls and receives the results at its output terminals from the front panel indicators.
Creating an Icon
Icons are graphical representations of VIs. Every VI displays an icon in the upper right corner of the front panel and block diagram windows. The default VI icon contains a number that indicates how many new VIs, up to nine VIs, you have opened since launching LabVIEW. To disable this numbering, select ToolsOptionsFront Panel and remove the checkmark from the Use numbers in icons of new VIs (1 through 9) checkbox. An icon can contain text or images. If you use a VI as a subVI, the icon identifies the subVI on the block diagram of the VI. If you add the VI to a palette, the VI icon also appears on the Functions palette. Use the Icon Editor dialog box to edit a VI icon. Double-click the icon in the upper right corner of the front panel or block diagram window to display the Icon Editor dialog box.
186
Lesson 7
Create an icon to represent a VI or custom control graphically. Use the Icon Editor dialog box to create or edit icons. You can use banners to identify related VIs. National Instruments recommends creating and saving a banner as a template. You then can use this template for a related VI icon and modify the body of the VI icon to provide information about the specific VI.
187
Lesson 7
4. On the Glyphs page, drag and drop glyphs onto the Preview area. Press the <F> key or the <R> key to flip a glyph horizontally or rotate a glyph clockwise, respectively, as you move the glyph. You also can double-click a glyph to place the glyph in the top-left corner of the icon. You can browse glyphs by category or by keyword. 5. Use the Move tool to move any glyph. Each glyph is on a separate layer and therefore moves separately. Notice that the rest of the icon becomes dimmed when you select a glyph so you can identify which selection you are moving. 6. Use the editing tools on the right side of the Icon Editor dialog box to edit the icon further if necessary. The Icon Editor dialog box creates a new user layer for each non-consecutive use of the editing tools. Select LayersCreate New Layer to create a new user layer during consecutive uses of the editing tools. You cannot modify the icon template or icon text with the editing tools on the right side of the Icon Editor dialog box. Use the Templates page and the Icon Text page to modify the icon template and icon text, respectively.
Note
7. (Optional) Select LayersShow Layers Page to display the Layers page. Use this page to configure the name, opacity, visibility, and order of the layers of the icon. 8. Click the OK button to save the icon information with the VI and close the Icon Editor dialog box. You also can drag a graphic from anywhere in the file system and drop it in the upper right corner of the front panel window to use the graphic as a VI icon. You can drag and drop .png, .bmp, or .jpg files. If you modify an icon by dragging and dropping a graphic from the file system, LabVIEW creates a user layer called VI Icon for the graphic and deletes any other existing icon information from the Icon Editor dialog box.
Note
Lesson 7
Each rectangle on the connector pane represents a terminal. Use the rectangles to assign inputs and outputs. The default connector pane pattern is 4 2 2 4. If you anticipate changes to the VI that would require a new input or output, keep the default connector pane pattern to leave extra terminals unassigned. The front panel in Figure 7-3 has four controls and one indicator, so LabVIEW displays four input terminals and one output terminal on the connector pane.
189
Lesson 7
Figure 7-4 shows an example of the standard layout used for terminal patterns. The top inputs and outputs are commonly used for passing references and the bottom inputs and outputs are used for error handling.
Avoid using connector panes with more than 16 terminals. Although connector pane patterns with more terminals might seem useful, they are very difficult to wire. If you need to pass more data, use clusters.
Although you use the Wiring tool to assign terminals on the connector pane to front panel controls and indicators, no wires are drawn between the connector pane and these controls and indicators.
190
Lesson 7
C. Using SubVIs
To place a subVI on the block diagram, click the Select a VI button on the Functions palette. Navigate to the VI you want to use as a subVI and double-click to place it on the block diagram. You also can place an open VI on the block diagram of another open VI. Use the Positioning tool to click the icon in the upper right corner of the front panel or block diagram of the VI you want to use as a subVI and drag the icon to the block diagram of the other VI.
You can select Dynamic Dispatch Input (Required) or Dynamic Dispatch Output (Recommended) for dynamic dispatch member VIs.
191
Lesson 7
For terminal inputs, required means that the block diagram on which you placed the subVI will be broken if you do not wire the required inputs. Required is not available for terminal outputs. For terminal inputs and outputs, recommended or optional means that the block diagram on which you placed the subVI can execute if you do not wire the recommended or optional terminals. If you do not wire the terminals, the VI does not generate any warnings. Inputs and outputs of VIs in vi.lib are already marked as Required, Recommended, or Optional. LabVIEW sets inputs and outputs of VIs you create to Recommended by default. Set a terminal setting to required only if the VI must have the input or output to run properly.
192
Lesson 7
The Error case, as shown in Figure 7-6, typically passes the error from the error in cluster control to the error out cluster indicator and contains any code necessary to handle the error.
Avoid using the Simple Error Handler VI and General Error Handler VI inside subVIs. If necessary, use these VIs in the calling VI, as shown in Figure 7-7.
193
Lesson 7
The new subVI uses a default pattern for the connector pane and a default icon. Double-click the subVI to edit the connector pane and icon, and to save the subVI.
Note
Do not select more than 28 objects to create a subVI because 28 is the maximum number of connections on a connector pane. If your front panel contains more than 28 controls and indicators that you want to use programmatically, group some of them into a cluster and assign the cluster to a terminal on the connector pane.
194
Lesson 7
Self-Review: Quiz
1. On a subVI, which setting causes an error if the terminal is not wired? a. Required b. Recommended c. Optional
195
196
Lesson 7
2. You must create an icon to use a VI as a subVI. a. True b. False You do not need to create a custom icon to use a VI as a subVI, but it is highly recommended to increase the readability of your code.
197
Lesson 7
Notes
198
The first step in developing a LabVIEW project is to explore the architectures that exist within LabVIEW. Architectures are essential for creating a successful software design. The most common architectures are usually grouped into design patterns. As a design pattern gains acceptance, it becomes easier to recognize when a design pattern has been used. This recognition helps you and other developers read and modify VIs that are based on design patterns. There are many design patterns for LabVIEW VIs. Most applications use at least one design pattern. In this course, you explore the State Machine design pattern.
Topics
A. Using Sequential Programming B. Using State Programming C. State Machines D. Using Parallelism
199
Lesson 8
200
Lesson 8
In LabVIEW, you can complete sequential tasks by placing each task in a separate subVI, and wiring the subVIs in the order you want them to execute using the error cluster wires. However, in this example, only two of the tasks have a error cluster. Using the error clusters, you can force the execution order of the two DAQ Assistants, but not the One Button Dialog functions, as shown in Figure 8-2.
You can use a Sequence structure to force the order of operations of block diagram objects. A Sequence structure contains one or more subdiagrams, or frames, that execute in sequential order; a frame cannot begin execution until everything in the previous frame has completed execution. Figure 8-3 shows an example of this VI using a Sequence structure to force execution order.
201
Lesson 8
To take advantage of the inherent parallelism in LabVIEW, avoid overusing Sequence structures. Sequence structures guarantee the order of execution, but prohibit parallel operations. Another negative to using Sequence structures is that you cannot stop the execution part way through the sequence. A good way to use Sequence structures for this example is shown in Figure 8-4.
Figure 8-4. Tasks Sequenced with Sequence Structures and an Error Cluster
The best way to write this VI, however, is to enclose the One Button Dialog functions in a Case structure, and wire the error cluster to the case selector. Use Sequence structures sparingly because they do not enforce error checking and will continue to go through a sequence even after errors are detected. Rely on data flow rather than sequence structures to control the order of execution.
Figure 8-5. Tasks Sequenced with an Error Cluster and Case Structures
202
Lesson 8
Although your program may not have any of the above requirements, there is always the possibility that the program must be modified in the future. For this reason, a state programming architecture is a good choice, even if a sequential programming structure would be sufficient.
C. State Machines
The state machine design pattern is a common and very useful design pattern for LabVIEW. You can use the state machine design pattern to implement any algorithm that can be explicitly described by a state diagram or flowchart. A state machine usually implements a moderately complex decision-making algorithm, such as a diagnostic routine or a process monitor. A state machine, which is more precisely defined as a finite state machine, consists of a set of states and a transition function that maps to the next state. Finite state machines have many variations. The two most common finite state machines are the Mealy machine and the Moore machine. A Mealy machine performs an action for each transition. A Moore machine performs a specific action for each state in the state transition diagram. The state machine design pattern template in LabVIEW implements any algorithm described by a Moore machine.
Lesson 8
State machines are commonly used to create user interfaces. In a user interface, different user actions send the user interface into different processing segments. Each processing segment acts as a state in the state machine. Each segment can lead to another segment for further processing or wait for another user action. In a user interface application, the state machine constantly monitors the user for the next action to take. Process testing is another common application of the state machine design pattern. For a process test, a state represents each segment of the process. Depending on the result of each states test, a different state might be called. This can happen continually, resulting in an in-depth analysis of the process you are testing. The advantage of using a state machine is that after you have created a state transition diagram, you can create LabVIEW VIs easily.
Figure 8-6 shows the basic structure of a state machine implemented in LabVIEW for a temperature data acquisition system.
While Loop
Shift Register
Case Structure
Lesson 8
The flow of the state transition diagram is implemented by the While Loop. The individual states are represented by cases in the Case structure. A shift register on the While Loop keeps track of the current state and communicates the current state to the Case structure input.
Default Transition
For the default transition, no code is needed to determine the next state, because there is only one possible state that occurs next. Figure 8-7 shows a design pattern that uses a default transition implemented for a temperature data acquisition system.
Lesson 8
This method works well if you know that the individual state always transitions between two states. However, this method limits the scalability of the application. If you need to modify the state to transition among more than two states, this solution would not work and would require a major modification of the transition code.
Lesson 8
One advantage to using a Case structure is that the code is self-documenting. Because each case in the Case structure corresponds to an item in the enum, it is easy to read and understand the code. A Case structure also is scalable. As the application grows, you can add more transitions to a particular state by adding more cases to the Case structure for that state. A disadvantage to using a Case structure is that not all the code is visible at once. Because of the nature of the Case structure, it is not possible to see at a glance the complete functionality of the transition code. Transition ArrayIf you need more of the code to be visible than a Case structure allows, you can create a transition array for all the transitions that can take place. Figure 8-10 shows the transition array implemented for a temperature data acquisition system.
In this example, the decision making code provides the index that describes the next state. For example, if the code should progress to the Error Handler state next, the decision making code outputs the number 1 to the index input of the Index Array function. This design pattern makes the transition code scalable and easy to read. One disadvantage of this pattern is that you must use caution when developing the transition code because the array is zero-indexed.
207
Lesson 8
Initialize
Acquistion
Analysis
Datalog
Time Elapsed = FALSE and Stop = FALSE Time Check Warning = FALSE
Stop = TRUE
208
Lesson 8
Figures 8-12 through 8-15 illustrate the states of the state machine that implements the state transition diagram detailed in Figure 8-11. If you have installed the exercises and solutions, the project is located in the <Exercises>\LabVIEW 1\Course Project directory, and you can further explore this state machine.
209
Lesson 8
210
Lesson 8
D. Using Parallelism
Often, you need to program multiple tasks so that they execute at the same time. In LabVIEW tasks can run in parallel if they do not have a data dependency between them, and if they are not using the same shared resource. An example of a shared resource is a file, or an instrument.
211
212
Lesson 8
Self-Review: Quiz
1. When using a Sequence structure, you can stop the execution part way through a sequence. a. True b. False
2. Which of the following are benefits of using a state machine instead of a sequential structure? a. You can change the order of the sequence b. You can repeat individual items in the sequence c. You can set conditions to determine when an item in the sequence should execute d. You can stop the program at any point in the sequence
213
214
Lesson 8
2. Which of the following are benefits of using a state machine instead of a sequential structure? a. You can change the order of the sequence b. You can repeat individual items in the sequence c. You can set conditions to determine when an item in the sequence should execute d. You can stop the program at any point in the sequence
215
Lesson 8
Notes
216
Using Variables
In this lesson, you learn to use variables to transfer data among multiple loops and VIs. You also learn about the programming issues involved when using variables and how to overcome these challenges.
Topics
A. Parallelism B. Variables C. Functional Global Variables D. Race Conditions
217
Lesson 9
Using Variables
A. Parallelism
In this course, parallelism refers to executing multiple tasks at the same time. Consider the example of creating and displaying two sine waves at a different frequencies. Using parallelism, you place one sine wave in a loop, and the second sine wave in a different loop. A challenge in programming parallel tasks is passing data among multiple loops without creating a data dependency. For example, if you pass the data using a wire, the loops are no longer parallel. In the multiple sine wave example, you may want to share a single stop mechanism between the loops, as shown in Figure 9-1.
Examine what happens when you try to share data among parallel loops with a wire using those different methods.
218
Lesson 9
Using Variables
Method 1 (Incorrect)
Place the Loop Control terminal outside of both loops and wire it to each conditional terminal, as shown in Figure 9-2. The Loop control is a data input to both loops, therefore the Loop Control terminal is read only once, before either While Loop begins executing. If False is passed to the loops, the While Loops run indefinitely. Turning off the switch does not stop the VI because the switch is not read during the iteration of either loop.
Method 2 (Incorrect)
Move the Loop Control terminal inside Loop 1 so that it is read in each iteration of Loop 1, as shown in the following block diagram. Although Loop 1 terminates properly, Loop 2 does not execute until it receives all its data inputs. Loop 1 does not pass data out of the loop until the loop stops, so Loop 2 must wait for the final value of the Loop Control, available only after Loop 1 finishes. Therefore, the loops do not execute in parallel. Also, Loop 2 executes for only one iteration because its conditional terminal receives a True value from the Loop Control switch in Loop 1.
219
Lesson 9
Using Variables
Method 3 (Solution)
If you could read the value of the loop control from a file, you would no longer have a dataflow dependency between the loops, as each loop can independently access the file. However, reading and writing to files can be time consuming, at least in processor time. Another way to accomplish this task is to find the location where the loop control data is stored in memory and read that memory location directly. The rest of this lesson will provide information on methods for solving this problem.
B. Variables
In LabVIEW, the flow of data rather than the sequential order of commands determines the execution order of block diagram elements. Therefore, you can create block diagrams that have simultaneous operations. For example, you can run two For Loops simultaneously and display the results on the front panel, as shown in the following block diagram.
However, if you use wires to pass data between parallel block diagrams, they no longer operate in parallel. Parallel block diagrams can be two parallel loops on the same block diagram without any data flow dependency, or two separate VIs that are called at the same time.
220
Lesson 9
Using Variables
The block diagram in Figure 9-4 does not run the two loops in parallel because of the wire between the two subVIs.
The wire creates a data dependency, because the second loop does not start until the first loop finishes and passes the data through its tunnel. To make the two loops run concurrently, remove the wire. To pass data between the subVIs, use another technique, such as a variable. In LabVIEW, variables are block diagram elements that allow you to access or store data in another location. The actual location of the data varies depending on the type of the variable. Local variables store data in front panel controls and indicators. Global variables and single-process shared variables store data in special repositories that you can access from multiple VIs. Functional global variables store data in While Loop shift registers. Regardless of where the variable stores data, all variables allow you to circumvent normal data flow by passing data from one place to another without connecting the two places with a wire. For this reason, variables are useful in parallel architectures, but also have certain drawbacks, such as race conditions.
221
Lesson 9
Using Variables
222
Lesson 9
Using Variables
With a local variable, you can write to or read from a control or indicator on the front panel. Writing to a local variable is similar to passing data to any other terminal. However, with a local variable you can write to it even if it is a control or read from it even if it is an indicator. In effect, with a local variable, you can access a front panel object as both an input and an output. For example, if the user interface requires users to log in, you can clear the Login and Password prompts each time a new user logs in. Use a local variable to read from the Login and Password string controls when a user logs in and to write empty strings to these controls when the user logs out.
223
Lesson 9
Using Variables
Lesson 9
Using Variables
LabVIEW uses owned labels to identify global variables, so label the front panel controls and indicators with descriptive owned labels. You can create several single global VIs, each with one front panel object, or if you want to group similar variables together, you can create one global VI with multiple front panel objects. You can create several single global variables, each with one front panel object, or you can create one global variable with multiple front panel objects. A global variable with multiple objects is more efficient because you can group related variables together. The block diagram of a VI can include several global variable nodes that are associated with controls and indicators on the front panel of a global variable. These global variable nodes are either copies of the first global variable node that you placed on the block diagram of the global VI, or they are the global variable nodes of global VIs that you placed on the current VI. You place global VIs on other VIs the same way you place subVIs on other VIs. Each time you place a new global variable node on a block diagram, LabVIEW creates a new VI associated only with that global variable node and copies of it. Figure 9-6 shows a global variable front panel window with a numeric, a string, and a cluster containing a numeric and a Boolean control. The toolbar does not show the Run, Stop, or related buttons as a normal front panel window.
After you finish placing objects on the global VI front panel, save it and return to the block diagram of the original VI. You must then select the object in the global VI that you want to access. Click the global variable node and select a front panel object from the shortcut menu. The shortcut
225
Lesson 9
Using Variables
menu lists all the front panel objects in the global VI that have owned labels. You also can right-click the global variable node and select a front panel object from the Select Item shortcut menu. You also can use the Operating tool or Labeling tool to click the global variable node and select the front panel object from the shortcut menu. If you want to use this global variable in other VIs, select the Select a VI option on the Functions palette. By default, the global variable is associated with the first front panel object with an owned label that you placed in the global VI. Right-click the global variable node you placed on the block diagram and select a front panel object from the Select Item shortcut menu to associate the global variable with the data from another front panel object.
Under Variable Type, select Single Process. Give the variable a name and a data type. After you create the shared variable, it automatically appears in a new library in your project file. Save the library. You can add additional shared variables to this library as needed. You can drag and drop the variable from the listing in the Project Explorer window directly to the block diagram. Use the short-cut menu to switch between writing or reading. Use the error clusters on the variable to impose data flow.
226
Lesson 9
Using Variables
227
Lesson 9
Using Variables
The example shown in Figure 9-9 accomplishes the same task, but more efficiently and using a better design. Notice that this example is much easier to read and understand than the previous example, mostly by reducing variable use. By placing the indicators in the While Loop outside the Case structure, the indicators can update after every state without using a variable. This example is less difficult to modify for further functionality, such as adding left turn signals, than the previous example.
Initializing Variables
To initialize a local or global variable, verify that the variable contains known data values before the VI runs. Otherwise, the variables might contain data that causes the VI to behave incorrectly. If the variable relies on a computation result for the initial value, make sure LabVIEW writes the value to the variable before it attempts to access the variable for any other action. Wiring the write action in parallel with the rest of the VI can cause a race condition. To make sure it executes first, you can isolate the code that writes the initial value for the variable to the first frame of a sequence structure or to a subVI and wire the subVI to execute first in the data flow of the block diagram. If you do not initialize the variable before the VI reads the variable for the first time, the variable contains the default value of the associated front panel object.
228
Lesson 9
Using Variables
Figure 9-10 shows a common mistake when using variables. A shared variable synchronizes the stop conditions for two loops. This example operates the first time it runs, because the default value of a Boolean is False. However, each time this VI runs, the Stop control writes a True value to the variable. Therefore, the second and subsequent times that this VI runs, the lower loop stops after only a single iteration unless the first loop updates the variable quickly enough.
Figure 9-11 shows the VI with code added to initialize the shared variable. Initialize the variable before the loops begin to insure that the second loop does not immediately stop.
229
Lesson 9
Using Variables
A functional global variable usually has an action input parameter that specifies which task the VI performs. The VI uses an uninitialized shift register in a While Loop to hold the result of the operation.
230
Lesson 9
Using Variables
Figure 9-13 shows a simple functional global variable with set and get functionality.
Figure 9-13. Functional Global Variable with Set and Get Functionality
In this example, data passes into the VI and the shift register stores the data if you configure the enumerated data type to Set. Data is retrieved from the shift register if the enumerated data type is configured to Get. Although you can use functional global variables to implement simple global variables, as shown in the previous example, they are especially useful when implementing more complex data structures, such as a stack or a queue buffer. You also can use functional global variables to protect access to global resources, such as files, instruments, and data acquisition devices, that you cannot represent with a global variable.
Note
A functional global variable is a subVI that is not reentrant. This means that when the subVI is called from multiple locations, the same copy of the subVI is used. Therefore, only one call to the subVI can occur at a time.
231
Lesson 9
Using Variables
Using Functional Global Variables for Timing One powerful application of functional global variables is to perform timing in your VI. Many VIs that perform measurement and automation require some form of timing. Often an instrument or hardware device needs time to initialize, and you must build explicit timing into your VI to take into account the physical time required to initialize a system. You can create a functional global variable that measures the elapsed time between each time the VI is called, as shown in Figure 9-14.
The Elapsed Time case gets the current date and time in seconds and subtracts it from the time that is stored in the shift register. The Reset Time case initializes the functional global variable with a known time value. The Elapsed Time Express VI implements the same functionality as this functional global variable. The benefit of using the functional global variable is that you can customize the implementation easily, such as adding a pause option.
232
Lesson 9
Using Variables
D. Race Conditions
A race condition occurs when the timing of events or the scheduling of tasks unintentionally affects an output or data value. Race conditions are a common problem for programs that execute multiple tasks in parallel and share data between them. Consider the following example in Figure 9-15 and Figure 9-16.
The two loops both increment a shared variable during each iteration. If you run this VI, the expected result after clicking the Stop button is that the Total Count is equal to the sum of Count 1 and Count 2. If you run the VI for a short period of time, you generally see the expected result. However, if you run the VI for a longer period of time, the Total Count is less than the sum of Count 1 and Count 2, because this VI contains a race condition.
233
Lesson 9
Using Variables
On a single processor computer, actions in a multi-tasking program like this example actually happen sequentially, but LabVIEW and the operating system rapidly switch tasks so that the tasks effectively execute at the same time. The race condition in this example occurs when the switch from one task to the other occurs at a certain time. Notice that both of the loops perform the following operations: Read the shared variable. Increment the value read. Write the incremented value to the shared variable.
Now consider what happens if the loop operations happen to be scheduled in the following order: 1. Loop 1 reads the shared variable. 2. Loop 2 reads the shared variable. 3. Loop 1 increments the value it read. 4. Loop 2 increments the value it read. 5. Loop 1 writes the incremented value to the shared variable. 6. Loop 2 writes the incremented value to the shared variable. In this example, both loops write the same value to the variable, and the increment of the first loop is effectively overwritten by Loop 2. This generates a race condition, which can cause serious problems if you intend the program to calculate an exact count. In this particular example, there are few instructions between when the shared variable is read and when it is written. Therefore, the VI is less likely to switch between the loops at the wrong time. This explains why this VI runs accurately for short periods and only loses a few counts for longer periods. Race conditions are difficult to identify and debug, because the outcome depends upon the order in which the operating system executes scheduled tasks and the timing of external events. The way tasks interact with each other and the operating system, as well as the arbitrary timing of external events, make this order essentially random. Often, code with a race condition can return the same result thousands of times in testing, but still can return a different result, which can appear when the code is in use. The best way to avoid race conditions is by using the following techniques: Controlling and limiting shared resources. Identifying and protecting critical sections within your code. Specifying execution order.
234
Lesson 9
Using Variables
235
Lesson 9
Using Variables
Figure 9-17. Using Functional Global Variables to Protect the Critical Section in Loop 1
236
Lesson 9
Using Variables
Figure 9-18. Using Functional Global Variables to Protect the Critical Section in Loop 2
Semaphores
Semaphores are synchronization mechanisms specifically designed to protect resources and critical sections of code. You can prevent critical sections of code from interrupting each other by enclosing each between an Acquire Semaphore and Release Semaphore VI. By default, a semaphore only allows one task to acquire it at a time. Therefore, after one of the tasks enters a critical section, the other tasks cannot enter their critical sections until the first task completes. When done properly, this eliminates the possibility of a race condition.
237
Lesson 9
Using Variables
You can use semaphores to protect the critical sections of the VIs, as shown in Figure 9-15 and Figure 9-16. A named semaphore allows you to share the semaphore between VIs. You must open the semaphore in each VI, then acquire it just before the critical section and release it after the critical section. Figure 9-20 and Figure 9-21 show a solution to the race condition using semaphores.
238
Lesson 9
Using Variables
The code in this example has four possible outcomes, depending on the order in which the operations execute.
239
Lesson 9
Using Variables
240
Lesson 9
Using Variables
Self-Review: Quiz
1. You should use variables frequently in your VIs. a. True b. False
2. Which of the following cannot transfer data? a. Semaphores b. Functional global variables c. Local variables d. Single process shared variables
3. Which of the following must be used within a project? a. Local variable b. Global variable c. Functional global variable d. Single-process shared variable
4. Which of the following cannot be used to pass data between multiple VIs? a. Local variable b. Global variable c. Functional global variable d. Single-process shared variable
241
242
Lesson 9
Using Variables
2. Which of the following cannot transfer data? a. Semaphores b. Functional global variables c. Local variables d. Single process shared variables
3. Which of the following must be used within a project? a. Local variable b. Global variable c. Functional global variable d. Single-process shared variable
4. Which of the following cannot be used to pass data between multiple VIs? a. Local variable b. Global variable c. Functional global variable d. Single-process shared variable
243
Lesson 9
Using Variables
Notes
244
Users generally start their work by acquiring data into an application or program, because their tasks typically require interaction with physical processes. In order to extract valuable information from that data, make decisions on the process, and obtain results, the data needs to be manipulated and analyzed. As an engineering-focused tool, LabVIEW makes hundreds of analysis functions available for researchers, scientists, and engineers, as well as students and professors. They can build these functions right into their applications to make intelligent measurements and obtain results faster.
Topics
A. Choosing the Correct Method for Analysis B. Analysis Categories
245
Appendix A
246
Appendix A
LabVIEW offers analysis and mathematical routines that natively work together with data acquisition functions and display capabilities, so that they can be easily built into any application. In addition, LabVIEW offers analysis routines for point-by-point execution; these routines are designed specifically to meet the needs of inline analysis in real-time applications. Users should consider certain aspects when deciding whether point-by-point routines are appropriate. Offline applications dont typically have the demand for results to be obtained in real-time fashion in order to make decisions on the process. Offline analysis applications require only that sufficient computational resources are available. The main intent of such applications is to identify cause and effect of variables affecting a process by correlating multiple data sets. These applications generally require importing data from custom binary or ASCII files and commercial databases such as Oracle, Access, and other SQL/ODBC-enabled databases. Once the data is imported into LabVIEW, users perform several or hundreds of available analysis routines, manipulate the data, and arrange it in a specific format for reporting purposes. LabVIEW provides functions to access any type of file format and database, seamlessly connect to powerful reporting tools such as NI DIAdem and the Report Generation Toolkit for Microsoft Office, and execute the latest data-sharing technologies such as XML, Web-enabled data presentation, and ActiveX.
Appendix A
In order to simplify the process of analyzing measurements, LabVIEW programmers create applications that provide dialogs and interfaces that others can use so that depending on their input, specific analysis routines are performed on any given data set. By building this type of application, users build a certain degree of interactivity into their applications. For this to be efficient, the programmer must have extensive knowledge about the information and the types of analysis in which the user is interested. With LabVIEW, you can easily perform significant data reduction and formatting before storing it to disk, so that when the stored data is retrieved for further analysis, it is easier to handle. LabVIEW also provides numerous functions for generating reports based on the results and information obtained from the acquired data.
B. Analysis Categories
LabVIEW offers hundreds of built-in analysis functions that cover different areas and methods of extracting information from acquired data. You can use these functions as is, or modify, customize, and extend them to suit a particular need. These functions are categorized in the following groups: Measurement, Signal Processing, Mathematics, Image Processing, Control, Simulation, and Application Areas. Measurement Amplitude and Level Frequency (Spectral) Analysis Noise and Distortion Pulse and Transition Signal and Waveform Generation
Time Domain Analysis Tone Measurements Signal Processing Digital Filters Convolution and Correlation Frequency Domain Joint Time-Frequency Analysis (Signal Processing Toolset) Sampling/Resampling Signal Generation Super-Resolution Spectral Analysis (Signal Processing Toolset) Transforms Time Domain
248
Appendix A
Wavelet and Filter Bank Design (Signal Processing Toolset) Windowing Mathematics Basic Math Curve Fitting and Data Modeling Differential Equations Interpolation and Extrapolation Linear Algebra Nonlinear Systems Optimization Root Finding Special Functions Statistics and Random Processes Image Processing Blob Analysis and Morphology Color Pattern Matching Filters High-Level Machine Vision Tools High-Speed Grayscale Pattern Matching Image Analysis Image and Pixel Manipulation Image Processing Optical Character Recognition Region-of-Interest Tools Control PID and Fuzzy Control Simulation Simulation Interface (Simulation Interface Toolkit)
Application Areas Machine Condition Monitoring (Order Analysis Toolset) Machine Vision (IMAQ, Vision Builder) Motion Control Sound and Vibration (Sound and Vibration Analysis Toolset) For a complete list of LabVIEW analysis functions refer to ni.com/ analysis.
249
Appendix A
Notes
250
Measurement Fundamentals
This appendix explains concepts that are critical to acquiring and generating signals effectively. These concepts focus on understanding the parts of your measurement system that exist outside the computer. You will learn about transducers, signal sources, signal conditioning, grounding of your measurement system, and ways to increase the quality of your measurement acquisition. This appendix provides basic understanding of these concepts.
Topics
A. Using Computer-Based Measurement Systems B. Understanding Measurement Concepts C. Increasing Measurement Quality
251
Appendix B
Measurement Fundamentals
252
Appendix B
Measurement Fundamentals
+ V
+ HV
+ mV
Signal Conditioning
Signal Conditioning
SC-2
345
MAINFR
SCX I
AME
Stand-alone Instrument
ON
STAND BY
6 7 8
253
Appendix B
Measurement Fundamentals
Signal Acquisition
Signal acquisition is the process of converting physical phenomena into data the computer can use. A measurement starts with using a transducer to convert a physical phenomenon into an electrical signal. Transducers can generate electrical signals to measure such things as temperature, force, sound, or light. Table B-1 lists some common transducers.
Table B-1. Phenomena and Transducers
Phenomena Temperature
Transducer Thermocouples Resistance temperature detectors (RTDs) Thermistors Integrated circuit sensors Vacuum tube photosensors Photoconductive cells Microphones Strain gages Piezoelectric transducers Load cells Potentiometers Linear voltage differential transformers (LVDT) Optical encoders Head meters Rotameters Ultrasonic flowmeters pH electrodes
pH
254
Appendix B
Measurement Fundamentals
Signal Sources
Analog input acquisitions use grounded and floating signal sources.
Vs
Ground
The grounds of two independently grounded signal sources generally are not at the same potential. The difference in ground potential between two instruments connected to the same building ground system is typically 10 mV to 200 mV. The difference can be higher if power distribution circuits are not properly connected. This causes a phenomenon known as a ground loop.
Note
Vs
Ground
Appendix B
Measurement Fundamentals
Signal Conditioning
Signal conditioning is the process of measuring and manipulating signals to improve accuracy, isolation, filtering, and so on. Many stand-alone instruments and DAQ devices have built-in signal conditioning. Signal conditioning also can be applied externally by designing a circuit to condition the signal or by using devices specifically made for signal conditioning. National Instruments has SCXI devices and other devices that are designed for this purpose. Throughout this section, different DAQ and SCXI devices illustrate signal conditioning topics. To measure signals from transducers, you must convert them into a form a measurement device can accept. For example, the output voltage of most thermocouples is very small and susceptible to noise. Therefore, you might need to amplify the thermocouple output before you digitize it. This amplification is a form of signal conditioning. Common types of signal conditioning include amplification, linearization, transducer excitation, and isolation. Figure B-4 shows some common types of transducers and signals and the signal conditioning each requires.
Transducers/Signals Thermocouples
Signal Conditioning Amplification, Linearization, and Cold-Junction Compensation Current Excitation, Four-Wire and Three-Wire Configuration, Linearization Voltage Excitation, Bridge Configuration, and Linearization Isolation Amplifiers (Optical Isolation) Electromechanical Relays or Solid-State Relays
RTDs
Strain Gages
Common Mode or High Voltages Loads Requiring AC Switching or Large Current Flow Signals with High Frequency Noise
DAQ Device
Lowpass Filters
256
Appendix B
Measurement Fundamentals
Amplification
Amplification is the most common type of signal conditioning. Amplifying electrical signals improves accuracy in the resulting digitized signal and reduces the effects of noise. Amplify signals as close to the signal source as possible. Amplifying a signal near the device also amplifies any noise that attached to the signal. Amplifying near the signal source results in the largest signal-to-noise ratio (SNR). For the highest possible accuracy, amplify the signal so the maximum voltage range equals the maximum input range of the analog-to-digital converter (ADC).
Noise Instrumentation Amplifier
+ Low-Level Signal
DAQ Device
If you amplify the signal at the DAQ device while digitizing and measuring the signal, noise might have entered the lead wire, which decreases SNR. However, if you amplify the signal close to the signal source with a SCXI module, noise has a less destructive effect on the signal, and the digitized representation is a better reflection of the original low-level signal. Refer to the National Instruments Web site at ni.com/info and enter the info code exd2hc for more information about analog signals.
Linearization
Many transducers, such as thermocouples, have a nonlinear response to changes in the physical phenomena you measure. LabVIEW can linearize the voltage levels from transducers so you can scale the voltages to the measured phenomena. LabVIEW provides scaling functions to convert voltages from strain gages, RTDs, thermocouples, and thermistors.
Transducer Excitation
Signal conditioning systems can generate excitation, which some transducers require for operation. Strain gages and RTDs require external voltage and currents, respectively, to excite their circuitry into measuring physical phenomena. This type of excitation is similar to a radio that needs power to receive and decode audio signals.
257
Appendix B
Measurement Fundamentals
Isolation
Another common way to use signal conditioning is to isolate the transducer signals from the computer for safety purposes. When the signal you monitor contains large voltage spikes that could damage the computer or harm the operator, do not connect the signal directly to a DAQ device without some type of isolation.
Caution
You also can use isolation to ensure that differences in ground potentials do not affect measurements from the DAQ device. When you do not reference the DAQ device and the signal to the same ground potential, a ground loop can occur. Ground loops can cause an inaccurate representation of the measured signal. If the potential difference between the signal ground and the DAQ device ground is large, damage can occur to the measuring system. Isolating the signal eliminates the ground loop and ensures that the signals are accurately measured.
Measurement Systems
You configure a measurement system based on the hardware you use and the measurement you acquire.
258
Appendix B
Measurement Fundamentals
CH7+
+
MUX
Instrumentation Amplifier +
Vm
CH7
AIGND
259
Appendix B
Measurement Fundamentals
Instrumentation Amplifier +
CH15
Vm
AIGND
DAQ devices often use a non-referenced single-ended (NRSE) measurement technique, or pseudodifferential measurement, which is a variant of the referenced single-ended measurement technique. Figure B-8 shows a NRSE system.
MUX CH0+ CH1+ CH2+
Instrumentation Amplifier +
CH15+
Vm
AISENSE
AIGND
In a NRSE measurement system, all measurements are still made with respect to a single-node analog input sense (AISENSE on E Series devices), but the potential at this node can vary with respect to the measurement system ground (AIGND). A single-channel NRSE measurement system is the same as a single-channel 260 differential measurement system.
Appendix B
Measurement Fundamentals
Input
Examples Ungrounded Thermocouples Signal Conditioning with Isolated Outputs Battery Devices
ACH(+)
+ V 1 Differential (DIFF)
ACH(+)
ACH()
+ V 1
ACH()
R AIGND AIGND
ACH
+ V 1
ACH
AIGND
+ V 1
+ Vg
AIGND
AISENSE
+ V 1
AISENSE
AIGND
AIGND
261
Appendix B
Measurement Fundamentals
Resolution
Resolution is the smallest amount of input signal change that a device or sensor can detect. The number of bits used to represent an analog signal determines the resolution of the ADC. You can compare the resolution on a measurement device to the marks on a ruler. The more marks you have, the more precise your measurements. Similarly, the higher the resolution, the higher the number of divisions into which your system can break down the ADC range, and therefore, the smaller the detectable change. A 3-bit ADC divides the range into 23 or 8 divisions. A binary or digital code between 000 and 111 represents each division. The ADC translates each measurement of the analog signal to one of the digital divisions. The following figure shows a sine wave digital image as obtained by a 3-bit ADC. Clearly, the digital signal does not represent the original signal adequately, because the converter has too few digital divisions to represent the varying voltages of the analog signal. By increasing the resolution to 16 bits, however, the number of divisions of the ADC increases from 8 to 65,536 (216). The ADC now can obtain an extremely accurate representation of the analog signal.
262
Appendix B
Measurement Fundamentals
16-bit
Amplitude (V)
3-bit
50
100 Time ( s)
150
200
Device Range
Device range refers to the minimum and maximum analog signal levels that the ADC can digitize. Many measurement devices can select from several ranges (typically 0 to 10 V or 10 to 10 V), by changing from unipolar mode to bipolar mode or by selecting from multiple gains, allowing the ADC to take full advantage of its resolution to digitize the signal. Unipolar and Bipolar Modes Unipolar mode means that a device only supports a range of 0 V to +X V. Bipolar mode means that a device supports a range of X V to +X V. Some devices support only one mode or the other, while other devices can change from unipolar mode to bipolar mode. Devices that can change from unipolar to bipolar mode are able to select the mode that best fits the signal to measure. Chart 1 in Figure B-11 illustrates unipolar mode for a 3-bit ADC. The ADC has eight digital divisions in the range from 0 to 10 V. In bipolar mode, the range is 10.00 to 10.00 V, as shown in chart 2. The same ADC now separates a 20 V range into eight divisions. The smallest detectable difference in voltage increases from 1.25 to 2.50 V, and you now have a much less accurate representation of the signal. The device selects the best mode available based on the input limits you specify when you create a virtual channel.
Caution
263
Appendix B
Measurement Fundamentals
Amplitude (V)
50
100
150
200
Amplitude (V)
110
50
100
150
200
Range = 0 to 10 V
Range = 10 to 10 V
Amplification
Amplification or attenuation of a signal can occur before the signal is digitized to improve the representation of the signal. By amplifying or attenuating a signal, you can effectively decrease the input range of an ADC and thus allow the ADC to use as many of the available digital divisions as possible to represent the signal. For example, Figure B-12 shows the effects of applying amplification to a signal that fluctuates between 0 and 5 V using a 3-bit ADC and a range of 0 to 10 V. With no amplification, or gain = 1, the ADC uses only four of the eight divisions in the conversion. By amplifying the signal by two before digitizing, the ADC uses all eight digital divisions, and the digital representation is much more accurate. Effectively, the device has an allowable input range of 0 to 5 V because any signal above 5 V, when amplified by a factor of two, makes the input to the ADC greater than 10 V.
10.00 8.75 Amplitude (V) 7.5 6.25 5.00 3.75 2.50 1.25 0.00 Time (s) Gain = 1 Gain = 2
111 110 101 100 011 010 001 000 Gain = 2 Gain = 1
Appendix B
Measurement Fundamentals
The range, resolution, and amplification available on a DAQ device determine the smallest detectable change in the input voltage. This change in voltage represents one least significant bit (LSB) of the digital value and is also called the code width.
Code Width
Code width is the smallest change in a signal that a system can detect. Calculate code width using the following formula: 1 C = D ---------R (2 ) where C is code width, D is device input range, and R is bits of resolution Device input range is a combination of the gain applied to the signal and the input range of the ADC. For example, if the ADC input range is 10 to +10 V peak to peak and the gain is 2, the device input range is 5 to +5 V peak to peak, or 10 V. The smaller the code width, the more accurately a device can represent the signal. The formula confirms what you have already learned in the discussion on resolution, range, and gain: Larger resolution = smaller code width = more accurate representation of the signal Larger amplification = smaller code width = more accurate representation of the signal Larger range = larger code width = less accurate representation of the signal
Determining the code width is important in selecting a DAQ device. For example, a 12-bit DAQ device with a 0 to 10 V input range and an amplification of one detects a 2.4 mV change, while the same device with a 10 to 10 V input range would detect a change of 4.9 mV. 1 1 - = 2.4 mV C = D ---------= 10 ----------R 12 (2 ) (2 ) 1 1 C = D ---------= 20 ----------= 4.9 mV R 12 (2 ) (2 )
265
Appendix B
Measurement Fundamentals
266
Appendix B
Measurement Fundamentals
A
Sampled at
B
Sampled at 2
C
Sampled at 4/3
Decreasing Noise
To reduce noise take the following precautions: Use shielded cables or a twisted pair of cables. Minimize wire length to minimize noise the lead wires pick up. Keep signal wires away from AC power cables and monitors to reduce 50 or 60 Hz noise. Increase the signal-to-noise ratio (SNR) by amplifying the signal close to the signal source. Acquire data at a higher frequency than necessary, then average the data to reduce the impact of the noise, as noise tends to average to zero.
267
268
Appendix B
Measurement Fundamentals
Self-Review: Quiz
1. Calculate the code width for signal acquired using a 16 bit DAQ device with a device input range of 5 V.
2. You are acquiring a triangle wave with a frequency of 1100 Hz. Which sampling frequency should you use for best shape recovery of the signal? a. 1 kHz b. 10 kHz c. 100 kHz d. 1000 kHz
3. You are acquiring a triangle wave with a frequency of 1100 Hz. You can sample the signal at the following rates. Which is the minimum sampling frequency you should use to reliably acquire the frequency of the signal? a. 1 kHz b. 10 kHz c. 100 kHz d. 1000 kHz
269
270
Appendix B
Measurement Fundamentals
2. You are acquiring a triangle wave with a frequency of 1100 Hz. Which sampling frequency should you use for best shape recovery of the signal? a. 1 kHz b. 10 kHz c. 100 kHz d. 1000 kHz
3. You are acquiring a triangle wave with a frequency of 1100 Hz. You can sample the signal at the following rates. Which is the minimum sampling frequency you should use to reliably acquire the frequency of the signal? a. 1 kHz b. 10 kHz c. 100 kHz d. 1000 kHz
271