Telemark University College Department of Electrical Engineering, Information Technology and Cybernetics LabVIEW Programming Hans-Petter Halvorsen 10-May, 2010 Faculty of Technology, Postboks 203, Kjølnes ring 56, N-3901 Porsgrunn, Norway. Tel: +47 35 57 50 00 Fax: +47 35 57 54 01 Telemark University College Department of Electrical Engineering, Information Technology and Cybernetics INTRODUCTION TO LABVIEW HANS-PETTER HALVORSEN, 2010.01.29 Faculty of Technology, Postboks 203, Kjølnes ring 56, N-3901 Porsgrunn, Norway. Tel: +47 35 57 50 00 Fax: +47 35 57 54 01 PREFACE This document explains the basic concepts of LabVIEW. You need to install the LabVIEW Professional Development System. For more information about LabVIEW, visit my Blog: http://home.hit.no/~hansha/ INSTALLATION REQUIREMENTS NI LabVIEW Name Required LabVIEW Professional Development System Yes NI LabVIEW Core Components Name Required LabVIEW Control Design and Simulation Module LabVIEW MathScript RT Module NI Vision Development Module Vision Builder for Automated Inspection LabVIEW Digital Filter Design Toolkit LabVIEW Modulation Toolkit LabVIEW System Identification Toolkit LabVIEW Desktop Execution Trace Toolkit LabVIEW Report Generation for Microsoft Office Toolkit LabVIEW Database Connectivity Toolkit LabVIEW Internet Toolkit NI LabVIEW SignalExpress LabVIEW Basics 1 and 2 Computer Based Training Extended Development Suite Components Name Required LabWindows/CVI Full Development System LabWindows/CVI Real-Time Module LabWindows/CVI PID Control Toolkit LabWindows/CVI Signal Processing Toolkit LabWindows/CVI Spectral Measurements Toolkit and Run-time Engine LabWindows/CVI SQL Toolkit Measurement Studio Enterprise Edition iii DIAdem Professional Control and Embedded Systems Option Components Name Required LabVIEW FPGA Module LabVIEW Real-Time Module LabVIEW Statechart Module LabVIEW Mobile Module LabVIEW Datalogging and Supervisory Control Module LabVIEW PID and Fuzzy Logic Toolkit NI Real-Time Execution Trace Toolkit LabVIEW Simulation Interface Toolkit NI Motion Assistant NI-DAQ Base Signal processing and Communications Option Components Name Required LabVIEW FPGA Module LabVIEW Sound and Vibration Measurement Suite LabVIEW Spectral Measurement Toolkit LabVIEW Advanced Signal Processing Toolkit LabVIEW Adaptive Filter Toolkit NI Device Drivers Name FieldPoint NI-DAQmx NI LabVIEW SignalExpress NI Instrument I/O Assistant NI-IMAQ NI Measurement & Automation Explorer Required NI PXI NI-VISA TABLE OF CONTENTS Preface .................................................................................................................................................................... 2 Installation Requirements ....................................................................................................................................... iii Table of Contents .................................................................................................................................................... vi 1 2 Introduction ................................................................................................................................................... 1 1.1 Dataflow programming.......................................................................................................................... 1 1.2 Graphical programming ......................................................................................................................... 1 1.3 Benefits .................................................................................................................................................. 2 Start using LabVIEW ...................................................................................................................................... 4 2.1 The LabVIEW Environment .................................................................................................................... 4 2.2 Front Panel ............................................................................................................................................ 5 2.3 Block Diagram ........................................................................................................................................ 7 2.4 Controls Palette ..................................................................................................................................... 9 2.4.1 Numeric Sub Palette ................................................................................................................... 10 2.4.2 Boolean Sub Palette .................................................................................................................... 11 2.4.3 String & Path Sub Palette ............................................................................................................ 11 2.5 Function Palette .................................................................................................................................. 12 2.6 Tools Palette ........................................................................................................................................ 13 2.7 Wiring .................................................................................................................................................. 15 2.8 Toolbar................................................................................................................................................. 15 2.9 Execution ............................................................................................................................................. 16 2.10 The Objects short-cut menu ................................................................................................................ 17 2.11 Dataflow Programming........................................................................................................................ 17 2.12 Help...................................................................................................................................................... 18 Exercises ........................................................................................................................................................... 19 3 Sub VIs ......................................................................................................................................................... 23 3.1 Create New Sub VI from Scratch ......................................................................................................... 24 vi vii Table of Contents 3.1.1 Input and Output SubVI Connectors ........................................................................................... 25 3.1.2 Icon Editor ................................................................................................................................... 27 3.2 Create Sub VI from existing code......................................................................................................... 28 3.3 Using Sub Vis ....................................................................................................................................... 29 Exercises ........................................................................................................................................................... 29 4 Customize LabVIEW ..................................................................................................................................... 32 Exercises ........................................................................................................................................................... 33 5 Loops and Structures ................................................................................................................................... 34 5.1 Loops ................................................................................................................................................... 34 5.1.1 For Loop ...................................................................................................................................... 35 5.1.2 While Loop .................................................................................................................................. 36 5.2 Structures ............................................................................................................................................ 37 5.2.1 Case Structure ............................................................................................................................. 37 5.2.2 Sequence Structure ..................................................................................................................... 38 5.2.3 Event Structure ........................................................................................................................... 39 Exercises ........................................................................................................................................................... 41 6 Troubleshooting and Debugging ................................................................................................................. 44 6.1 How to find errors ............................................................................................................................... 44 6.2 Highlight Execution .............................................................................................................................. 44 6.3 Probes .................................................................................................................................................. 44 6.4 Breakpoints .......................................................................................................................................... 45 6.5 Step into/over/out debugging ............................................................................................................. 46 Exercises ........................................................................................................................................................... 46 7 Working with Data ....................................................................................................................................... 48 7.1 Arrays ................................................................................................................................................... 48 7.1.1 Auto-Indexing ............................................................................................................................. 48 7.1.2 Array Functions ........................................................................................................................... 48 7.2 Cluster .................................................................................................................................................. 51 Tutorial: An Introduction to LabVIEW viii Table of Contents 7.2.1 Cluster Order............................................................................................................................... 51 7.2.2 Cluster Elements ......................................................................................................................... 52 Exercises ........................................................................................................................................................... 53 8 Working with Strings ................................................................................................................................... 55 Exercises ........................................................................................................................................................... 57 9 Error Handling.............................................................................................................................................. 59 9.1 finding Error ......................................................................................................................................... 59 9.2 Error Wiring ......................................................................................................................................... 59 9.3 Error handling in SubVIs ...................................................................................................................... 60 9.4 Error Handling...................................................................................................................................... 61 Exercises ........................................................................................................................................................... 61 10 Working with Projects ................................................................................................................................. 62 10.1 Project Explorer ................................................................................................................................... 62 10.2 Deployment ......................................................................................................................................... 63 Exercises ........................................................................................................................................................... 65 11 Design Techniques ....................................................................................................................................... 66 11.1 Force Program Flow ............................................................................................................................. 66 11.2 Shift Register........................................................................................................................................ 67 11.3 State Programming Architecture ......................................................................................................... 67 11.4 Multiple Loops/Parallell programming ................................................................................................ 70 11.5 Templates ............................................................................................................................................ 71 Exercises ........................................................................................................................................................... 73 12 User Interface .............................................................................................................................................. 75 12.1 VI Properties ........................................................................................................................................ 76 Exercises ........................................................................................................................................................... 79 13 Plotting Data ................................................................................................................................................ 80 13.1 Customizing ......................................................................................................................................... 81 Exercises ........................................................................................................................................................... 83 Tutorial: An Introduction to LabVIEW ix Table of Contents 14 Tips & Tricks ................................................................................................................................................. 85 14.1 10 functions you need to know about ................................................................................................. 85 14.2 The 10 most useful Short-cuts ............................................................................................................. 89 15 Additional Exercises ..................................................................................................................................... 91 16 Whats Next? ................................................................................................................................................ 96 16.1 My Blog ................................................................................................................................................ 96 16.2 Training ................................................................................................................................................ 96 16.3 Additional Resources ........................................................................................................................... 96 16.4 Examples .............................................................................................................................................. 96 16.5 Documentation .................................................................................................................................... 97 16.6 LabVIEW Wiki....................................................................................................................................... 97 16.7 LabVIEW on YouTube .......................................................................................................................... 98 Quick Reference .................................................................................................................................................... 99 Tutorial: An Introduction to LabVIEW 1 INTRODUCTION LabVIEW (short for Laboratory Virtual Instrumentation Engineering Workbench) is a platform and development environment for a visual programming language from National Instruments. The graphical language is named "G". Originally released for the Apple Macintosh in 1986, LabVIEW is commonly used for data acquisition, instrument control, and industrial automation on a variety of platforms including Microsoft Windows, various flavors of UNIX, Linux, and Mac OS X. The latest version of LabVIEW is version LabVIEW 2009, released in August 2009. Visit National Instruments at www.ni.com. The code files have the extension “.vi”, which is an abbreviation for “Virtual Instrument”. LabVIEW offers lots of additional Add-Ons and Toolkits. This paper is part of a series with LabVIEW papers: Introduction to LabVIEW Data Acquisition in LabVIEW Control and Simulation in LabVIEW LabVIEW MathScript Linear Algebra in LabVIEW Datalogging and Supervisory Control in LabVIEW Wireless Data Acquisition in LabVIEW Intermediate Topics in LabVIEW Advanced Topics in LabVIEW Each paper may be used independently of each other. 1.1 DATAFLOW PROGRAMMING The programming language used in LabVIEW, also referred to as G, is a dataflow programming language. Execution is determined by the structure of a graphical block diagram (the LV-source code) on which the programmer connects different function-nodes by drawing wires. These wires propagate variables and any node can execute as soon as all its input data become available. Since this might be the case for multiple nodes simultaneously, G is inherently capable of parallel execution. Multi-processing and multi-threading hardware is automatically exploited by the built-in scheduler, which multiplexes multiple OS threads over the nodes ready for execution. 1.2 GRAPHICAL PROGRAMMING LabVIEW ties the creation of user interfaces (called front panels) into the development cycle. LabVIEW programs/subroutines are called virtual instruments (VIs). Each VI has three components: a block diagram, a front panel, and a connector panel. The last is used to represent the VI in the block diagrams of other, calling VIs. Controls and indicators on the front panel allow an operator to input data into or extract data from a running virtual instrument. However, the front panel can also serve as a programmatic interface. Thus a virtual instrument can either be run as a program, with the front panel serving as a user interface, or, when dropped as a node onto the block diagram, the front panel defines the inputs and outputs for the given node through the connector pane. This implies each VI can be easily tested before being embedded as a subroutine into a larger program. 1 2 Introduction The graphical approach also allows non-programmers to build programs simply by dragging and dropping virtual representations of lab equipment with which they are already familiar. The LabVIEW programming environment, with the included examples and the documentation, makes it simple to create small applications. This is a benefit on one side, but there is also a certain danger of underestimating the expertise needed for good quality "G" programming. For complex algorithms or large-scale code, it is important that the programmer possess an extensive knowledge of the special LabVIEW syntax and the topology of its memory management. The most advanced LabVIEW development systems offer the possibility of building stand-alone applications. Furthermore, it is possible to create distributed applications, which communicate by a client/server scheme, and are therefore easier to implement due to the inherently parallel nature of G-code. 1.3 BENEFITS One benefit of LabVIEW over other development environments is the extensive support for accessing instrumentation hardware. Drivers and abstraction layers for many different types of instruments and buses are included or are available for inclusion. These present themselves as graphical nodes. The abstraction layers offer standard software interfaces to communicate with hardware devices. The provided driver interfaces save program development time. The sales pitch of National Instruments is, therefore, that even people with limited coding experience can write programs and deploy test solutions in a reduced time frame when compared to more conventional or competing systems. A new hardware driver topology (DAQmxBase), which consists mainly of G-coded components with only a few register calls through NI Measurement Hardware DDK (Driver Development Kit) functions, provides platform independent hardware access to numerous data acquisition and instrumentation devices. The DAQmxBase driver is available for LabVIEW on Windows, Mac OS X and Linux platforms. This document introducing the following themes: Start using LabVIEW o The LabVIEW Environment o Front Panel and Block Diagram o Palettes: Control Palette, Functions Palette, Tools Palette o Data Types o Property Nodes Sub VIs Loops and Structures Troubleshooting and Debugging Working with Data o Arrays Array Functions o Cluster Working with Strings Error Handling Working with Projects using Project Explorer Design Techniques o Shift Register o State Machine o Multiple Loops Tutorial: An Introduction to LabVIEW 3 Introduction User Interface Plotting Data Deployment: Building Executable Applications (.exe) Introduction to Add Ons and Toolkits o Briefly explanations… o More detail about Control and Simulation Toolkit in later chapter Introduction to DAQ - Data Acquisition o MAX – Measurement and Automation Explorer o NI-DAQmx Quick Reference with Keyboard Short-cuts For more information about LabVIEW, visit my Blog: http://home.hit.no/~hansha/ Tutorial: An Introduction to LabVIEW 2 START USING LABVIEW This chapter explains the basic concepts in LabVIEW. The topics are as follows: The LabVIEW Environment Front Panel and Block Diagram Palettes: Control Palette, Functions Palette, Tools Palette Data Types Property Nodes 2.1 THE LABVIEW ENVIRONMENT LabVIEW programs are called Virtual Instruments, or VIs, because their appearance and operation imitate physical instruments, such as oscilloscopes and multimeters. LabVIEW contains a comprehensive set of tools for acquiring analyzing, displaying, and storing data, as well as tools to help you troubleshoot your code. When opening LabVIEW, you first come to the “Getting Started” window. 4 5 Start using LabVIEW In order to create a new VI, select “Blank VI” or in order to create a new LabVIEW project, select “Empty project”. When you open a blank VI, an untitled front panel window appears. This window displays the front panel and is one of the two LabVIEW windows you use to build a VI. The other window contains the block diagram. The sections below describe the front panel and the block diagram. 2.2 FRONT PANEL When you have created a new VI or selected an existing VI, the Front Panel and the Block Diagram for that specific VI will appear. In LabVIEW, you build a user interface, or front panel, with controls and indicators. Controls are knobs, push buttons, dials, and other input devices. Indicators are graphs, LEDs, and other displays. You build the front panel with controls and indicators, which are the interactive input and output terminals of the VI, respectively. Controls are knobs, push buttons, dials, and other input devices. Indicators are graphs, LEDs, and other displays. Controls simulate instrument input devices and supply data to the block diagram of the VI. Indicators simulate instrument output devices and display data the block diagram acquires or generates. E.g., a “Numeric” can either be a “Numeric Control” or a “Numeric Indicator”, as seen below. Tutorial: An Introduction to LabVIEW 6 Start using LabVIEW I you select a “Numeric Control”, it can easy be changed to an “Numeric Indicator” by right click on the object an select “Change to Indicator” Or opposite, I you select a “Numeric Indicator”, it can easy be changed to an “Numeric Control” by right click on the object an select “Change to Control” Tutorial: An Introduction to LabVIEW 7 Start using LabVIEW The difference between a “Numeric Control” and a “Numeric Indicator” is that for a “Numeric Control” you may enter a value, while the “Numeric Indicator” is read-only, i.e., you may only read the value, not change it. The appearance is also slightly different, the “Numeric Control” has an increment and an decrement button in front, while the “Numeric Indicator” has a darker background color in order to indicate that its read-only. 2.3 BLOCK DIAGRAM After you build the user interface, you add code using VIs and structures to control the front panel objects. The block diagram contains this code. In some ways, the block diagram resembles a flowchart. After you build the front panel, you add code using graphical representations of functions to control the front panel objects. The block diagram contains this graphical source code. Front panel objects appear as terminals, Tutorial: An Introduction to LabVIEW 8 Start using LabVIEW on the block diagram. Block diagram objects include terminals, subVIs, functions, constants, structures, and wires, which transfer data among other block diagram objects. The Figure below shows a front panel and its corresponding block diagram with front panel and block diagram components. The different components are as follows: 1. 2. 3. 4. 5. 6. 7. 8. Toolbar Owned Label Numeric Control Free Label Numeric Control Terminal Knob Terminal Numeric Constant Multiply Function Tutorial: An Introduction to LabVIEW 9 Start using LabVIEW 9. Icon 10. Knob Control 11. Plot Legend 12. XY Graph 13. Wire Data Path 14. XY Graph Terminal 15. Bundle Function 16. SubVI 17. For Loop Structure 2.4 CONTROLS PALETTE The Controls and Functions palettes contain sub palettes of objects you can use to create a VI. When you click a sub palette icon, the entire palette changes to the sub palette you selected. To use an object on the palettes, click the object and place it on the front panel or block diagram. The Controls palette is available only on the front panel. The Controls palette contains the controls and indicators you use to build the front panel. The most used Sub Palettes are the Numeric Sub Palette, the Boolean Sub Palette and the String & Path Sub Palette. You may change the appearance and the contents of the Controls palette: Tutorial: An Introduction to LabVIEW 10 Start using LabVIEW You may Pin the palette, so it is always visible, just click the little pin button palette: in the upper left corner of the If you want to change the content and appearance of the palette, click the “View” button. Here you may change the way the palette should look. If you click “Change Visible Categories…” you may change which Categories you want to have visible. 2.4.1 NUMERIC SUB PALETTE “Numerical Control” and “Numerical Indicator” are the most used objects in the numeric sub palette. Tutorial: An Introduction to LabVIEW 11 Start using LabVIEW 2.4.2 BOOLEAN SUB PALETTE This palette has lots of different buttons you may use. OK, Cancel and Stop buttons are useful. 2.4.3 STRING & PATH SUB PALETTE Tutorial: An Introduction to LabVIEW 12 Start using LabVIEW In the String and Path palette we have String Controls, Combo Box, etc. 2.5 FUNCTION PALETTE The Functions palette is available only on the block diagram. The Functions palette contains the VIs and functions you use to build the block diagram. Tutorial: An Introduction to LabVIEW 13 2.6 Start using LabVIEW TOOLS PALETTE You can create, modify, and debug VIs using the tools located on the floating Tools palette. The Tools palette is available on both the front panel and the block diagram. A tool is a special operating mode of the mouse cursor. The cursor corresponds to the icon of the tool selected in the Tools palette. Use the tools to operate and modify front panel and block diagram objects. Tutorial: An Introduction to LabVIEW 14 Start using LabVIEW The Tools palette is available from the View menu: If you make sure “Automatic wiring” is disabled (I recommend you do so!) you may use the Tab key on your keyboard in order to switch between the most common tools. The most used tools are: Use the Operating tool, shown at left, to change the values of a control or select the text within a control. The Operating tool changes to the icon shown at left when it moves over a text control, such as a numeric or string control. Use the Positioning tool, shown at left, to select, move, or resize objects. The Positioning tool changes to resizing handles when it moves over the edge of a resizable object. Use the Labeling tool, shown at left, to edit text and create free labels. The Labeling tool changes to the following icon when you create free labels. Use the Wiring tool, shown at left, to wire objects together on the block diagram. Tutorial: An Introduction to LabVIEW 15 2.7 Start using LabVIEW WIRING In order to create the logical flow between the object on the Block Diagram, you need to use the Wiring tool in order to connect the different objects together. Use the Wiring tool to wire objects together on the block diagram. Available Keyboard Shortcuts when dealing with Wiring: Ctrl-B is very useful. This short-cut removes all broken wires on the Block Diagram. 2.8 TOOLBAR Below we see the LabVIEW Toolbar: The behaviors of the different buttons are as follows: 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. The solid white arrow, shown above, also indicates you can use the VI as a subVI if you create a connector pane for the VI. Tutorial: An Introduction to LabVIEW 16 Start using LabVIEW 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, shown at left, when the VI you are creating or editing contains errors. If the Run button still appears broken after you nish 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, shown at left, 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, shown at left, 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. Note: Avoid using the Abort Execution button to stop a VI. Either let the VI complete its data ow or design a method to stop the VI programmatically. By doing so, the VI is at a known state. For example, place a button on the front panel that stops the VI when you click it. Click the Pause button, shown at left, 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 button again to continue running the VI. 2.9 EXECUTION In addition to the Toolbar buttons above the following Keyboard Shortcuts are available when dealing with Execution: Tutorial: An Introduction to LabVIEW 17 Start using LabVIEW 2.10 THE OBJECTS SHORT-CUT MENU The most often-used menu is the object shortcut menu. All LabVIEW objects and empty space on the front panel and block diagram have associated shortcut menus. Use the shortcut menu items to change the look or behavior of front panel and block diagram objects. To access the shortcut menu, right-click the object, front panel, or block diagram. The Numeric control has the following short-cut/right-click menu: The short-cut menu will be different for the different controls or objects. 2.11 DATAFLOW PROGRAMMING LabVIEW follows a dataflow model for running VIs. A block diagram node executes when all its inputs are available. When a node completes execution, it supplies data to its output terminals and passes the output data to the next node in the dataflow path. Visual Basic, C++/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. Example: Dataflow Programming Tutorial: An Introduction to LabVIEW 18 Start using LabVIEW The Example shows a block diagram that adds two numbers and then subtracts 50.00 from the result of the addition. 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 it supplies data to its output terminals only when it finishes execution. Example: Dataflow Programming In this example, consider which code segment would execute first-the 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. 2.12 HELP The Context Help window (Ctrl +H) displays basic information about LabVIEW objects when you move the cursor over each object. The Context Help window is visible by default. To toggle display of the Context Help window, select Help-Show Context Help, press the Ctrl-H keys, or click the Show Context Help Window button on the toolbar. When you move the cursor over front panel and block diagram objects, the Context Help window displays the icon for subVIs, functions, constants, controls, and indicators, with wires attached to each terminal. When you move the cursor over dialog box options, the Context Help window displays descriptions of those options. In the window, required connections are bold, recommended connections are plain text, and optional connections are dimmed or do not appear. The Figure below shows an example of the Context Help window. Tutorial: An Introduction to LabVIEW 19 Start using LabVIEW EXERCISES Exercise: Create your first LabVIEW application (VI) Create a simple LabVIEW application (VI) with a Front Panel with some Controls and Indicators. Create the logic by connecting the Terminals on the Block Diagram The Front Panel could look something like this: The Block Diagram could look something like this: Tutorial: An Introduction to LabVIEW 20 Start using LabVIEW Start the program with the Run button. Exercise: Create a simple Calculator Create a simple calculator that Add and Subtract 2 numbers like this: Start the program with the Run button. Exercise: Write Data to File Create a VI that writes data to a Text File. Use Vis or functions from the File I/O palette Tutorial: An Introduction to LabVIEW 21 Start using LabVIEW The program could look something like this: Tutorial: An Introduction to LabVIEW 22 Start using LabVIEW Exercise: Read Data from File Create another VI that read the text file you created in the previous VI. Tutorial: An Introduction to LabVIEW 3 SUB VIS This chapter explains the basic concepts of creating and using Sub VIs in LabVIEW. Topics: Create New Sub VI from Scratch Create Sub VI from existing code Using Sub VIs When you place a VI on the block diagram, LabVIEW considers the VI to be a subVI. When you double-click a subVI, its 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. The upper right corner of the front panel and block diagram displays. Below we see an example of a bad Block Diagram. This example does not make use of the SubVI functionality in LabVIEW at all! This makes the Block diagram hard to read and understand. The size of the diagram is also too large! The Block Diagram should always fit into the screen. Both the Front Panel and the Block Diagram should fit into a screen resolution of 1024x768. 23 24 Sub VIs With use of SubVIs, the example above could turn into, e.g.: As you can see, much of the code in the Main VI have been replaced and put into SubVIs. The program is now more readable. Another approach is to use a so-called State Machine principle (more about this in chapter 11 - Design Techniques ). Available Keyboard Shortcuts when dealing with Sub Vis: 3.1 CREATE NEW SUB VI FROM SCRATCH Tutorial: An Introduction to LabVIEW 25 Sub VIs Select “Blank VI” in the “Getting Started” window when opening LabVIEW, or when LabVIEW is already opened select File → New V” or use the short-cut Ctrl+N. 3.1.1 INPUT AND OUTPUT SUBVI CONNECTORS Most SubVIs will have input and output “connectors”. This is similar with functions or methods in other programming language that have input arguments and an output/result. In order to create connectors, Right-click on the icon in the upper right corner of the VI and select “Show Connector”. You may select different Patterns, i.e., how many input and output connectors you need. Tutorial: An Introduction to LabVIEW 26 Sub VIs Make sure you select a Pattern with enough connectors even if you don’t need all the connectors at the moment. I recommend that you standardize on the pattern in the Figure above. Select the Wire tool and click on the wanted connector, then click on the Control or Indicator on the Front Panel you want to connect to this connector. You should always follow these connector rules: Upper left connector: “Reference” In Upper right connector: “Reference” Out Lower left connector: Error In Cluster Lower right connector: Error Out Cluster Example: SubVI Connectors See example below about these connector rules: Tutorial: An Introduction to LabVIEW 27 Sub VIs Most common VIs that exits follow these rules, see example below. If you follow these connector rules it’s much easier to create a clean and neat code like this: By doing this it’s also clear how the Data flows in the program. It should always flow from left to right. 3.1.2 ICON EDITOR You should also create a suitable icon for your SubVI. In order to open the Icon Editor, double-click on the icon in the upper right corner of your VI. Tutorial: An Introduction to LabVIEW 28 Sub VIs Below we see a block diagram with SubVIs icon appearance created with the Icon Editor. 3.2 CREATE SUB VI FROM EXISTING CODE If you find out that you code is getting messy, you could consider put some code into a SubVI. The procedure is as follows: 1. 2. 3. 4. 5. Select the part of your code you want to turn into a SubVI From the Edit menu, select “Create SubVI” LabVIEW will automatically create a SubVI for the selected code. Clean up automatically created wires, etc. Create a suitable icon for your SubVI Tutorial: An Introduction to LabVIEW 29 Sub VIs Although this is quite easy to do this, I do not recommend that you use this functionality to much. This is because you should create and use SubVIs from the first moment you start creating your application and not afterwards when you find out that you have been creating a messy code. So you should structure and design your code with the use of SubVIs from the beginning! 3.3 USING SUB VIS Below we see an example of how to use SubVIs in a program (Top VI or SubVIs): You may open a SubVI from the File menu, select a SubVI from the Functions palette or use drag and drop in different ways, e.g., you may drag a VI from the File Explorer in Windows directly into an existing VI you have already opened in LabVIEW EXERCISES Exercise: Convert C to F VI Create a SubVI that convert a Temperature in Celsius to a Temperature in Fahrenheit Tutorial: An Introduction to LabVIEW 30 Sub VIs 1. 2. 3. 4. Create the SubVI Create the Front Panel and the Block Diagram as shown above Create necessary Connectors Create a suitable icon, e.g.: 5. 6. 7. Use the SubVI in another VI Run the program to see if it works Expand the program so you can select if you want to convert from Celsius to Fahrenheit or from Fahrenheit to Celsius Exercise: Convert existing code into a SubVI Convert a part of your application into a SubVI by using the Create SubVI function in LabVIEW. Tutorial: An Introduction to LabVIEW 31 Sub VIs Tutorial: An Introduction to LabVIEW 4 CUSTOMIZE LABVIEW LabVIEW has lots of possibilities for customizing the appearance and the use of the LabVIEW environment. Select “Options…” from the Tools menu. The default settings is not necessary the best, here are some recommendations for setting up the LabVIEW environment. Category: Block Diagram 32 33 Customize LabVIEW Disable “Enable auto wiring” option. This prevents LabVIEW from automatically connecting adjacent blocks. Although it seems useful to have auto wiring enables, it is my experience that the auto wiring is a little annoying since it tends to draw wires between blocks when you do not want any wire. Disable “Place front panel elements as icons” option. This causes LabVIEW to use small terminal icons on the block diagram. If you, instead, activate this option, the terminal icons are larger, with a mimic of the element as it appears at the front panel. Category: Controls/Functions Palettes In the Format list: select “Category (Icons and Text)” Category: Alignment Grid Turn off “Show Front Panel Grid” and “Show Block Diagram Grid” EXERCISES Exercise: Customize LabVIEW Try the different settings explained in this chapter. Turn them on and off and watch the different. Tutorial: An Introduction to LabVIEW 5 LOOPS AND STRUCTURES This chapter explains the basic concepts of Loops and Structures in LabVIEW. The topics are as follows: For Loop While Loop Case Structure Sequence Structure Event Structure The different Loops and Structures available is located in the “Structures” sub palette in the Functions palette on the Block Diagram. 5.1 LOOPS The most important loops are: For Loop While Loop These loops will be explained in detail below. 34 35 Loops and Structures 5.1.1 FOR LOOP A For Loop executes a sub diagram a set number of times. The Figure below shows an empty For Loop in LabVIEW. A For loop executes its sub diagram n times, where n is the value wired to the count ( iteration ( ) terminal. The ) terminal provides the current loop iteration count, which ranges from 0 to n-1. After you create a For Loop, you can use shift registers to pass values from one iteration to the next. If you wire an array to a For Loop, you can read and process every element in that array by enabling auto-indexing. You also can enable auto-indexing by configuring a For Loop to return an array of every value generated by the loop. You can add a conditional terminal to configure a For Loop to stop when a Boolean condition or an error occurs. A For Loop with a conditional terminal executes until the condition occurs or until all iterations complete, whichever happens first. To add a conditional terminal to a For Loop, right-click the For Loop border and select Conditional Terminal from the shortcut menu. You must wire the conditional terminal and either wire the count terminal or auto-index an input array for the loop to execute and for the VI to run. To convert a For Loop to a While Loop, right-click the For Loop and select Replace with While Loop from the shortcut menu. Example: For Loop The following example uses a For Loop in order to create an array with 10 elements and fill it with random numbers. Tutorial: An Introduction to LabVIEW 36 Loops and Structures 5.1.2 WHILE LOOP A While loop repeats the sub diagram inside it until the conditional terminal, an input terminal, receives a particular Boolean value. The Boolean value depends on the continuation behavior of the While Loop. Right-click the conditional terminal and select Stop if True or Continue if True from the shortcut menu. You also can wire an error cluster to the conditional terminal, right-click the terminal, and select Stop on Error or Continue while Error from the shortcut menu. The While Loop always executes at least once. Below we see an empty While loop: After you create a While Loop, you can use shift registers to pass values from one iteration to the next. If you wire an array to a While Loop, you can read and process every element in that array by enabling auto-indexing. In order to convert a While Loop into a For Loop, right-click the While Loop and select “Replace with For Loop” from the shortcut menu. To convert a While Loop into a Timed Loop, right-click the While Loop and select “Replace with Timed Loop” from the shortcut menu. Example: While Loop This example run until either the user clicks the stop button or number of iterations is greater than 10. Tutorial: An Introduction to LabVIEW 37 5.2 Loops and Structures STRUCTURES 5.2.1 CASE STRUCTURE The Case Structure has one or more sub diagrams, or cases, exactly one of which executes when the structure executes. The value wired to the selector terminal determines which case to execute and can be Boolean, string, integer, or enumerated type. You may right-click the structure border to add or delete cases. Use the Labeling tool to enter value(s) in the case selector label and configure the value(s) handled by each case. Below we see an empty Case structure: Below we see an example of a Case structure with 2 cases, a “True” case and a “False” case. Depending of the Boolean input value, the Numeric1 and Numeric2 is either Added or Subtracted. Tutorial: An Introduction to LabVIEW 38 Loops and Structures 5.2.2 SEQUENCE STRUCTURE A Sequence structure Consists of one or more sub diagrams, or frames, that execute sequentially. Right-click the structure border to add and delete frames or to create sequence locals to pass data between frames. Use the Stacked Sequence structure to ensure a sub diagram executes before or after another sub diagram. Below we see an empty Sequence structure. Tutorial: An Introduction to LabVIEW 39 Loops and Structures Below we see an example where we use “Sequence Local”, i.e., we pass a value from one sequence to the next Note! 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. 5.2.3 EVENT STRUCTURE An Event structure has one or more sub diagrams, or event cases, exactly one of which executes when the structure executes. The Event structure waits until an event happens, then executes the appropriate case to handle that event. Right-click the structure border to add new event cases and configure which events to handle. Wire a value to the Timeout terminal at the top left of the Event structure to specify the number of milliseconds the Event structure should wait for an event to occur. The default is –1, indicating never to time out. Below we see an example: Tutorial: An Introduction to LabVIEW 40 Loops and Structures Right-click on the border in order to Add/Edit Event Cases, see the dialog box below. Tutorial: An Introduction to LabVIEW 41 Loops and Structures EXERCISES Exercise: For Loop Create a VI with a For Loop. Create the logic to find out if a number in an array is greater than 10. See Front Panel below: Tutorial: An Introduction to LabVIEW 42 Loops and Structures Exercise: While Loop Create a VI with a While Loop. Create the logic to find out which (the first) index in the array that have a number greater than 30. See Front Panel below: Exercise: Case Structure Create a VI with a Case Structure. Use a Case structure inside a For Loop to write the text “The Number is greater than 10” if value is greater than 10. See Front Panel below: Tutorial: An Introduction to LabVIEW 43 Loops and Structures Exercise: Sequence Structure Create a VI with a Sequence Structure. See Front Panel below: Exercise: Event Structure Create a VI with an Event Structure. See Front Panel below: Tutorial: An Introduction to LabVIEW 6 TROUBLESHOOTING AND DEBUGGING This chapter explains the basic concepts of troubleshooting and debugging in LabVIEW. Topics: How to find errors Highlight Execution Probes Breakpoints Step into/over/out debugging 6.1 HOW TO FIND ERRORS If a VI does not run, it is a broken, or “nonexecutable”, VI. The Run button often appears broken, shown at left, when you create or edit a VI. If it is still broken when you finish wiring the block diagram, the VI is broken and will not run. Generally, this means that a required input is not wired, or a wire is broken. Click the broken Run button to display the Error list window, which lists all the errors. Double-click an error description to display the relevant block diagram or front panel and highlight the object that contains the error. 6.2 HIGHLIGHT EXECUTION View an animation of the execution of the block diagram by clicking the Highlight Execution button. Execution highlighting shows the flow of data on the block diagram from one node to another using bubbles that move along the wires. Note! Execution highlighting greatly reduces the speed at which the VI runs. 6.3 PROBES Use the Probe tool to check intermediate values on a wire as a VI runs. 44 45 Troubleshooting and Debugging 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. You also can create a custom probe to specify which indicator you use to view the probed data. For example, if you are viewing numeric data, you can choose to see that data in a chart within the probe. To create a custom probe, right-click a wire and select Custom Probe-New from the shortcut menu. 6.4 BREAKPOINTS Use the Breakpoint tool to place a breakpoint on a VI, node, or wire on the block diagram and pause execution at that location. When you set a breakpoint on a wire, execution pauses after data pass through the wire. Place a breakpoint on the block diagram workspace to pause execution after all nodes on the block diagram execute. When a VI pauses at a breakpoint, LabVIEW brings the block diagram to the front and uses a marquee to highlight the node or wire that contains the breakpoint. LabVIEW highlights breakpoints with red borders for nodes and block diagrams and red bullets for wires. When you move the cursor over an existing breakpoint, the black area of the Breakpoint tool cursor appears white. Use the Breakpoint tool to click an existing breakpoint to remove it. You may also right-click on the wire in order to set a breakpoint or open the Breakpoint Manager. Tutorial: An Introduction to LabVIEW 46 Troubleshooting and Debugging Breakpoint Manager is a tool for enable, disable and delete breakpoints. 6.5 STEP INTO/OVER/OUT DEBUGGING Available Keyboard Shortcuts when Debugging: EXERCISES Tutorial: An Introduction to LabVIEW 47 Troubleshooting and Debugging Exercise: Highlight Execution Enable “Highlight Execution” in one of your programs, and see how it works. Exercise: Probes Set Several Probes around in your application and watch how it works. Use the Probe watch Window and check out the functionality this tool offers. Also check out the “Custom Probe” and the “Find Probe” functionality. Exercise: Breakpoints Set some Breakpoint around in your code and check out how it works. Use the Breakpoint Manager tool. Example: Exercise: Step into/over/out debugging Use the Step into/over/out functionality together with your Breakpoints and learn how you can use them and see what the difference between them is. Tutorial: An Introduction to LabVIEW 7 WORKING WITH DATA This chapter explains the basic concepts of creating and using Sub Vis in LabVIEW. Topics: Arrays Array Functions Cluster 7.1 ARRAYS Arrays are very powerful to use in LabVIEW. In all your applications you would probably use both One-Dimensional Arrays and Two-Dimensional Arrays. 7.1.1 AUTO-INDEXING LabVIEW uses a powerful mechanism called “Auto-indexing”. For Example you may use a For loop to create Array data like this: Or you may use an Array like this in order to automatically specify number of iterations: 7.1.2 ARRAY FUNCTIONS LabVIEW has lots of built-in functions for manipulating arrays. 48 49 Working with Data The most useful Array functions are: Array Size Index Array Delete from Array Search 1D Array Initialize Array Build Array Array Subset Array Constant All these functions are basic (but very useful) array functions you will probably be using in all your applications and VIs. Tutorial: An Introduction to LabVIEW 50 Working with Data Example: Array functions In this example we see how we can use these Array functions and what they do. The resulting Front Panel is as follows: Tutorial: An Introduction to LabVIEW 51 7.2 Working with Data CLUSTER Clusters group data elements of mixed types, such as a bundle of wires, as in a telephone cable, where each wire in the cable represents a different element of the cluster. 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 a 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. Like an array, a cluster is either a control or an indicator. A cluster cannot contain a mixture of controls and indicators. Although cluster and array elements are both ordered, you must unbundle all cluster elements at once rather than index one element at a time. You also can use the “Unbundle By Name” function to access specific cluster elements. Example of a Cluster in LabVIEW: 7.2.1 CLUSTER ORDER You may sort the different elements in the cluster by right-click on the cluster border and select “Reorder Controls in Cluster…” Tutorial: An Introduction to LabVIEW 52 Working with Data 7.2.2 CLUSTER ELEMENTS In order to manipulate and work with cluster LabVIEW offers lots of functions, such as the “Bundle” and “Unbundle” functions. In order to write to a cluster from the code, you may use the “Bundle” function or the “Bundle By Name” function. See example below: Example: Clusters Tutorial: An Introduction to LabVIEW 53 Working with Data In order to get access to the different elements in the cluster, you need to “Unbundle” by using the “Unbundle” function or the “Unbundle By Name”. See example below: EXERCISES Exercise: Arrays Create some simple VIs where you use these array functions to manipulate array data: Array Size Index Array Delete from Array Search 1D Array Initialize Array Build Array Array Subset Exercise: Arrays Create a SubVI that find the “peaks” in the input array regarding to an input peak level. Tutorial: An Introduction to LabVIEW 54 Working with Data Exercise: Clusters Create a Cluster and get the different values from the controls in the Cluster. See Front Panel below: Tutorial: An Introduction to LabVIEW 8 WORKING WITH STRINGS Working and manipulating with strings is an important part in LabVIEW development. On the Front panel we have the following String controls and indicators available from the Control palette: On the Block Diagram we have the following String functions available from the Functions palette: Some of the most important String functions are: Concatenate Strings 55 56 Working with Strings This function concatenates several strings into on string: Search and Replace String Use this when you want to replace or remove a certain text in a string. Match Pattern Tutorial: An Introduction to LabVIEW 57 Working with Strings This is the most useful function when it comes to string manipulation. Format Into String Example: EXERCISES Here are some exercises using some of the String functions that is available in LabVIEW. Exercise: SubVI: Remove leading zeros in string.vi Create a SubVI which removes leading zeros in a string. Create a Test VI that uses the SubVI. Tutorial: An Introduction to LabVIEW 58 Working with Strings Exercise: SubVI: Remove space from end of string.vi Create a SubVI which removes all spaces from the end of the string. Create a Test VI that uses the SubVI. Exercise: SubVI: Add 2 String.vi Create a SubVI which adds 2 strings into one. Create a Test VI that uses the SubVI. Tutorial: An Introduction to LabVIEW 9 ERROR HANDLING This chapter explains the basic concepts of handle errors in your code. Topics: Finding Errors Error Wiring Error Handling 9.1 FINDING ERROR If a VI does not run, it is a broken, or “nonexecutable”, VI. The Run button often appears broken, shown at left, when you create or edit a VI. If it is still broken when you finish wiring the block diagram, the VI is broken and will not run. Generally, this means that a required input is not wired, or a wire is broken. Click the broken Run button to display the Error list window, which lists all the errors. Double-click an error description to display the relevant block diagram or front panel and highlight the object that contains the error. 9.2 ERROR WIRING Error handling is important in all programming languages. LabVIEW has powerful mechanism for handling errors and error wiring. You should always wire the Error cluster between all SubVIs, nodes, etc. that support this, see example below. The Error cluster is located in the Controls palette here: 59 60 Error Handling The Error Cluster: The Error cluster contains of the following parts: Status – True/False. False: No Error, True: Error Code – Error Code Source – Textual Error message 9.3 ERROR HANDLING IN SUBVIS When creating SubVIs you should always create an Error In and an Error Out. In the SubVI code you should also use a Case structure and wire the Error in cluster to the Case Selector as shown below. Tutorial: An Introduction to LabVIEW 61 9.4 Error Handling ERROR HANDLING LabVIEW has several useful SubVIs, etc for Error Handling: These are: In general you should always show the error to the user. See LabVIEW Help for more details of how to use these SubVIs. EXERCISES Exercise: Error Handling Check out the different Error Vis in LabVIEW. Use them in some of your previous Vis. Tutorial: An Introduction to LabVIEW 10 WORKING WITH PROJECTS This chapter explains the basic concepts of the project Explorer in LabVIEW. Topics: Project Explorer Building .exe (executable) applications Deployment: Create an Installer 10.1 PROJECT EXPLORER It is not necessary to use the Project Explorer when developing your LabVIEW code, but it is an easy way to structure your code, especially for larger projects. The project Explorer is necessary when you want to deploy your code into, e.g., an executable (.exe) application, build a setup, etc. The Project Explorer is also very useful when you integrate a source control tool, such as Team Foundation Server, Visual Source Safe, etc. Then you may easily check files in and out of the source code system. In order to create a new Project in LabVIEW, simply select “Empty Project” from the Getting Started window when you open LabVIEW. 62 63 Working with Projects 10.2 DEPLOYMENT When your application is finished, you may want to distribute or deploy your application and share it with others. The Project Explorer gives you several choices when it comes to distribute and deploy your application. Some of the options are: Create an executable application (.exe) – this means that the target doesn’t need to have LabVIEW installed on their computer. All the target need is LabVIEW Run-Rime, which is a small installation package. You may create your own installer, so all the target need is to run a setup.exe in order to use your application Other possibilities is to create a Web Service or a Shared Library (DLL) of your application All these options are available from the Project Explorer, just right-click on your “Build Specifications” node. Tutorial: An Introduction to LabVIEW 64 Working with Projects We will go through how we create an executable application. Click Build Specifications→New→Application (EXE). In the Properties window fill in your name of the application. Make sure you select a Startup VI. Tutorial: An Introduction to LabVIEW 65 Working with Projects There are lots of properties and setting you may use in order to create your application, go through all the Categories in the Properties window. When you have finished all the steps, just select “Build” in order to create your application. When you make changes in your application, it is easy to rebuild your application: EXERCISES Exercise: Project Explorer Create a new Project and put on of your existing application into the project Exercise: Deployment Create an executable application Tutorial: An Introduction to LabVIEW 11 DESIGN TECHNIQUES This chapter explains some useful techniques to use when creating your application. Topics: Force the Program Flow using an Error cluster Shift Register State Machine Multiple Loops Templates 11.1 FORCE PROGRAM FLOW As mentioned earlier, LabVIEW follows a dataflow model for running VIs. A block diagram node executes when all its inputs are available. When a node completes execution, it supplies data to its output terminals and passes the output data to the next node in the dataflow path. In the example below we cannot be sure that the DAQmx Write.vi executes before the DAQmx Stop Task.vi executes. LabVIEW will in this case randomly execute one of these first. If the Stop VI happens to execute first then the Write VI will failed because task has been stopped. In the example below we wire the Error cluster through all the VIs, and there will be no doubt that the Write VI will execute before the Stop VI. This approach will also take care of the error handling in your program, which is very important in real-world applications. 66 67 Design Techniques 11.2 SHIFT REGISTER Use shift registers on For Loops and While Loops to transfer values from one loop iteration to the next. Shift registers are similar to static variables in text-based programming languages. A shift register appears as a pair of terminals, directly opposite each other on the vertical sides of the loop border. The right terminal 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. 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. To initialize a shift register, wire any value from outside the loop to the left terminal. If you do not initialize the shift register, the loop uses the value written to the shift register when the loop last executed or the default value for the data type if the loop has never executed. Use a loop with an uninitialized shift register to run a VI repeatedly so that each time the VI runs, the initial output of the shift register is the last value from the previous execution. Use an uninitialized shift register to preserve state information between subsequent executions of a VI. After the loop executes, the last value stored in the shift register remains at the right terminal. If you wire the right terminal outside the loop, the wire transfers the last value stored in the shift register. You can add more than one shift register to a loop. If you have multiple operations within a loop, use multiple shift registers to store the data values from those different processes in the structure. 11.3 STATE PROGRAMMING ARCHITECTURE Creating VIs using the State Machine approach is very useful when creating (large) applications. In general, a state machine is a model of behavior composed of a finite number of states, transitions between those states, and actions. It is similar to a "flow graph" where we can inspect the way in which the logic runs when certain conditions are met. Tutorial: An Introduction to LabVIEW 68 Design Techniques Sometimes, you may want to change the order of the sequence, repeat one item in the sequence more often than the other items, stop a sequence immediately, or have items in the sequence that may execute only when certain conditions are met. Although your program may not have any such requirements, there is always the possibility that the program must be modified in the future. Therefore, a state programming architecture is a good choice, even if a sequential programming structure is sufficient. The following list describes more complex programming requirements that justify the use of a state programming architecture for an application. You need to change the order of the sequence You must repeat an item in the sequence more often than other items You want some items in the sequence to execute only when certain conditions are met The State Machine approach in LabVIEW uses a Case structure inside a While loop to handle the different states in the program, and the transitions between them. The Shift Register is used to save data from and between the different states. Tutorial: An Introduction to LabVIEW 69 Design Techniques Below we see examples of a state machine principle implemented in LabVIEW. Simple State Machine principle State Machine with multiple transitions depending on the State: More advanced State Machine using Shift Registers: Tutorial: An Introduction to LabVIEW 70 Design Techniques 11.4 MULTIPLE LOOPS/PARALLELL PROGRAMMING 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. Using multiple While loops is sometimes useful in applications that need to handle User interactions in parallel with, e.g., DAQ operations, etc. Below we see an example of how this structure could look like. The upper loop could handle interaction with the user, while the lower loop could handle DAQ operations, such as reading and writing to some I/O equipments. Tutorial: An Introduction to LabVIEW 71 Design Techniques In order to pass data between the loops, you may e.g. use local variables. The loop may have different time cycles. The I/O may require faster cycles than the User interaction loop. 11.5 TEMPLATES You should create your own templates for such VI you use a lot. It is easy to create your own templates for scratch, just create a VI as you normally do and then save it as a template with the ending “.vit”. You may also convert a VI you already made just by changing the extension to “.vit”. You should copy your templates to the LabVIEW template folder which is default located in “C:\Program Files\National Instruments\LabVIEW X.X\Templates\”. Tutorial: An Introduction to LabVIEW 72 Design Techniques The Templates will then be available from the Getting Started Window or File→New… in LabVIEW. I may case I have created a sub folder called “My Templates” where I place all my templates. Tutorial: An Introduction to LabVIEW 73 Design Techniques EXERCISES Here are some exercises about shift-registers, State Machines and parallel programming. Exercise: Shift-register Create a VI (see example below) where you have the following states: Initialize Write Read Close In the VI you will use a shift-register as a temporary storage. In the Write state you Write Data to the storage (shift-register) while you in the Read state will read the Data from the Storage. See Example below: Tutorial: An Introduction to LabVIEW 74 Design Techniques Write a Test program that test the SubVI, e.g., This example shows how you can use a shift-register as a temporary storage, which is very useful in many situations. Exercise: State Machine Use the State Machine principle on one of your previous exercises. Exercise: Parallel Programming Create a VI that consists of 2 parallel loops. Use local variables and other mechanisms in order to share data between the 2 loops. Exercise: Templates Strip some of yours previous Vis and save them as reusable Templates. Tutorial: An Introduction to LabVIEW 12 USER INTERFACE This chapter explains the basic concepts of creating user-friendly Graphical User Interfaces (GUI) in LabVIEW. Topics: Decorations Tab Control Splitter Sub Panel Etc. Below we see a Front Panel (GUI) with a “poor” design. The information (Controls and Indicators) on the Front Panel is not structured. You should group elements that naturally belong together and use different colors with care. When creating Graphical User Interfaces (GUI) you should use the controls from the System palette and not from the Modern or Classic palettes. Modern Controls may be used in Sub Vis with no visible User Interface (for the user). The appearance of the controls in the System palette is standard MS Windows look and feeling and this look is familiar for most users. These controls also change appearance due to changes in the appearance in the operation system. 75 76 User Interface 12.1 VI PROPERTIES In order to make the appearance of the Window that hosts your application, you should always make some changes in the “VI Properties”. You find the “VI Properties” by right-click on the icon in the upper right corner of your VI. Tutorial: An Introduction to LabVIEW 77 User Interface The first thing you should change is the “Window title”. Here you may type appropriate name of your application or SubVI. The next you should do is to the “Customize” button in order to customize the Window appearance. Below we see an application with a simple and neat User Interface and with a Customized Windows appearance. Tutorial: An Introduction to LabVIEW 78 User Interface Below we see a professional application created in LabVIEW that implement common GUI objects such as a Toolbar, a Tree view and a List view. Tutorial: An Introduction to LabVIEW 79 User Interface EXERCISES Exercise: User Interface Create a Dialog Box where you use some of the Controls from the System palette. Make the necessary settings in VI Properties in order to hide menus, buttons, create a Title, etc. Create a Test VI from where you open this Dialog Box, enter some data in the Dialog Box, and then retrieve these data in the calling VI. Example: Tutorial: An Introduction to LabVIEW 13 PLOTTING DATA This chapter explains the basic concepts when plotting data in LabVIEW. LabVIEW offers powerful functionality for plotting data. In the Graph palette we have lots of useful controls for plotting and visualization of data. The most useful are: Waveform Chart Waveform Graph XY Graph Example: This simple example creates a graph with some random values. 80 81 Plotting Data The example below show the basic difference between a “Chart” and a “Graph”. You use the “Graph” if you want to plot a set of data, e.g., an array with data, plot data from a file, etc. Use the “Chart” if you want to plot one data point at a time, e.g., inside a loop, etc. 13.1 CUSTOMIZING The different Chart components in LabVIEW offer a great deal of customizing. Tutorial: An Introduction to LabVIEW 82 Plotting Data You may click on the “Plot Legend” in order to set colors, different line styles, etc. If you right-click on the Graph/Chart, you may set properties such as auto-scaling, etc. If you select Properties, you get the following dialog: Tutorial: An Introduction to LabVIEW 83 Plotting Data You may also select which items that should be visible or not. The “Graph Palette” lets you zoom in and out on the Graph, etc. EXERCISES Exercise: Graph Tutorial: An Introduction to LabVIEW 84 Plotting Data Create a VI that reads data from a file and plot the data in a Graph component. Exercise: Chart Create a VI where you use Data Binding in order to retrieve data from an OPC demo. Data Binding is set in the Properties → Data Binding tab: Exercise: Customizing Customize the Graph and the Chart in the examples above in order to set colors, line thickness, etc. Tutorial: An Introduction to LabVIEW 14 TIPS & TRICKS This chapter give you some useful Tips & Tricks 14.1 10 FUNCTIONS YOU NEED TO KNOW ABOUT These are the 10 most useful functions in LabVIEW, so you could already now learn how to use them and where to find them! Build Array This example using the Build Array function inside a For loop in order build an array with 10 elements. Index Array It is always useful to find a specific value in an array: 85 86 Tips & Tricks The Index Array is extendible, so you can drag it out to find more than one elements: Array Size Find the size of an arbitrary array: Select Depending on the input data, go to the Alarm case or the Write Data case. Tutorial: An Introduction to LabVIEW 87 Tips & Tricks Concatenate Strings This function concatenate several strings into on string: Search and Replace String Use this when you want to replace or remove a certain text in a string. Tutorial: An Introduction to LabVIEW 88 Tips & Tricks Match Pattern This is the most useful function when it comes to string manipulation. Format Into String Example: Tutorial: An Introduction to LabVIEW 89 Tips & Tricks Fract/Exp String to Number This function converts a string into a number: Example: Number To Fractional String Example: 14.2 THE 10 MOST USEFUL SHORT-CUTS These are the 10 most useful short-cuts in LabVIEW, so you could already now learn how to use them! Short-Cut Description Ctrl + B Deletes all broken wires in a VI Ctrl + . Stops the Running VI Ctrl + E Toggle between the Front Panel and Block Diagram Tab Cycles through the most common Tools (Automatic Tool Selection should be Tutorial: An Introduction to LabVIEW 90 Tips & Tricks disabled!) Ctrl + Mouse wheel Scrolls through subdiagrams in Case, Event or Sequence structures Ctrl + H Displays the Context Help window Ctrl + Mouse Double-click on a SubVI Opens the Block Diagram directly Ctrl + Arrows (→←←↓ ) Move faster. You first have to select a SubVI, a Function, Object, etc Ctrl + W Close the SubVI Double-click on a wire Selects the hole wire Tutorial: An Introduction to LabVIEW 15 ADDITIONAL EXERCISES This chapter lists lots of additional exercises you could try out in order to improve your LabVIEW skills. Exercise: vCard Reader Create an application that reads information from a vCard. vCard is a file format standard for electronic business cards. vCards are often attached to e-mail messages, but can be exchanged in other ways, such as on the World Wide Web. They can contain name and address information, phone numbers, URLs, logos, photographs, and even audio clips. Example: BEGIN:VCARD VERSION:2.1 N:Gump;Forrest FN:Forrest Gump ORG:Bubba Gump Shrimp Co. TITLE:Shrimp Man TEL;WORK;VOICE:(111) 555-1212 TEL;HOME;VOICE:(404) 555-1212 ADR;WORK:;;100 Waters Edge;Baytown;LA;30314;United States of America LABEL;WORK;ENCODING=QUOTED-PRINTABLE:100 Waters Edge=0D=0ABaytown, LA 30314=0D=0AUSA ADR;HOME:;;42 Plantation St.;Baytown;LA;30314;United States of America LABEL;HOME;ENCODING=QUOTED-PRINTABLE:42 Plantation St.=0D=0ABaytown, LA 30314=0D=0AUSA EMAIL;PREF;INTERNET:forrestgump@example.com REV:20080424T195243Z END:VCARD For more information about the vCard format, see http://en.wikipedia.org/wiki/VCard. The application should look something like this: When the user click Open, then a dialog box like this should appear: 91 92 Additional Exercises Requirements: Use the Project Explorer Use the State Machine principle Use the Event Structure Use System Controls Set the appropriate settings in the VI Properties. Create a executable application (vCard.exe) Exercise: vCard Write & Read Extend the application in the previous example. You should now be able to both write and read vCard files. The application could look something like this: Tutorial: An Introduction to LabVIEW 93 Additional Exercises When the user clicks New, the dialog box in the previous exercise appears. The user may enter a new vCard. If the user clicks Edit, a dialog box with the selected contact should appear. Exercise: Read/Write from .ini files Read/Write from .ini files. Use the Configuration File VIs: Exercise: ActiveX Create a simple Web Browser using ActiveX and the Internet Explorer ActiveX control (Microsoft Web Browser) Use the ActiveX Container from the Containers control palette: Tutorial: An Introduction to LabVIEW 94 Additional Exercises Use the ActiveX function palette: The application could look something like this: Tutorial: An Introduction to LabVIEW 95 Additional Exercises Exercise: Themes In e.g., ASP.NET we have something called Themes. Themes are used to change the appearance of your whole application regarding to color, font, pictures, etc. LabVIEW do not offer such a functionality , but try to create your own Theme Configurator, so you can change the appearance of your VI instantly. Here is an example of how Windows XP handles different Themes: Create a similar Theme Configurator so you may easily change the appearance of your Vis. Tutorial: An Introduction to LabVIEW 16 WHATS NEXT? 16.1 MY BLOG For more information about LabVIEW, visit my Blog: http://home.hit.no/~hansha/ 16.2 TRAINING This Training is a part of a series with other Training Kits I have made, such as: Introduction to LabVIEW Data Acquisition in LabVIEW Control and Simulation in LabVIEW LabVIEW MathScript Linear Algebra in LabVIEW Datalogging and Supervisory Control in LabVIEW Wireless Data Acquisition in LabVIEW Intermediate Topics in LabVIEW Advanced Topics in LabVIEW These Training Kits are available for download from my blog: http://home.hit.no/~hansha 16.3 ADDITIONAL RESOURCES www.ni.com 16.4 EXAMPLES In the NI example Finder (Help→Find Examples…) you find lots of useful examples that you can play with or use as a start when creating your own applications. 96 97 Whats Next? 16.5 DOCUMENTATION As part of the LabVIEW installation there comes a lots of useful documentation. 16.6 LABVIEW WIKI LabVIEW Wiki is the free LabVIEW information resource that anyone can edit. http://labviewwiki.org/Home Tutorial: An Introduction to LabVIEW 98 Whats Next? 16.7 LABVIEW ON YOUTUBE There are lots of LabVIEW videos available at YouTube: http://www.youtube.com/results?search_query=labview&search=Search Tutorial: An Introduction to LabVIEW QUICK REFERENCE 99 Quick Reference Tutorial: An Introduction to LabVIEW Telemark University College Faculty of Technology Kjølnes Ring 56 N-3914 Porsgrunn, Norway www.hit.no Hans-Petter Halvorsen, M.Sc. Telemark University College Department of Electrical Engineering, Information Technology and Cybernetics Phone: +47 3557 5158 E-mail: hans.p.halvorsen@hit.no Blog: http://home.hit.no/~hansha/ Room: B-237a Telemark University College Department of Electrical Engineering, Information Technology and Cybernetics LABVIEW MATHSCRIPT HANS-PETTER HALVORSEN, 2010.03.09 Faculty of Technology, Postboks 203, Kjølnes ring 56, N-3901 Porsgrunn, Norway. Tel: +47 35 57 50 00 Fax: +47 35 57 54 01 PREFACE This document explains the basic concepts of using LabVIEW MathScript. For more information about LabVIEW, visit my Blog: http://home.hit.no/~hansha/ What is LabVIEW? LabVIEW (short for Laboratory Virtual Instrumentation Engineering Workbench) is a platform and development environment for a visual programming language from National Instruments. The graphical language is named "G". What is MATLAB? MATLAB is a tool for technical computing, computation and visualization in an integrated environment. MATLAB is an abbreviation for MATrix LABoratory, so it is well suited for matrix manipulation and problem solving related to Linear Algebra. MATLAB offers lots of additional Toolboxes for different areas such as Control Design, Image Processing, Digital Signal Processing, etc. What is MathScript? MathScript is a high-level, text- based programming language. MathScript includes more than 800 built-in functions and the syntax is similar to MATLAB. You may also create custom-made m-file like you do in MATLAB. MathScript is an add-on module to LabVIEW but you don’t need to know LabVIEW programming in order to use MathScript. If you want to integrate MathScript functions (built-in or custom-made m-files) as part of a LabVIEW application and combine graphical and textual programming, you can work with the MathScript Node. In addition to the MathScript built-in functions, different add-on modules and toolkits installs additional functions. The LabVIEW Control Design and Simulation Module and LabVIEW Digital Filter Design Toolkit install lots of additional functions. You can more information about MathScript here: http://www.ni.com/labview/mathscript.htm How do you start using MathScript? You need to install LabVIEW and the LabVIEW MathScript RT Module. When necessary software is installed, start MathScript by open LabVIEW: i ii Preface In the Getting Started window, select Tools -> MathScript Window...: Tutorial: LabVIEW MathScript INSTALLATION REQUIREMENTS NI LabVIEW Name Required LabVIEW Professional Development System Yes NI LabVIEW Core Components Name Required LabVIEW Control Design and Simulation Module LabVIEW MathScript RT Module Yes NI Vision Development Module Vision Builder for Automated Inspection LabVIEW Digital Filter Design Toolkit LabVIEW Modulation Toolkit LabVIEW System Identification Toolkit LabVIEW Desktop Execution Trace Toolkit LabVIEW Report Generation for Microsoft Office Toolkit LabVIEW Database Connectivity Toolkit LabVIEW Internet Toolkit NI LabVIEW SignalExpress LabVIEW Basics 1 and 2 Computer Based Training Extended Development Suite Components Name Required LabWindows/CVI Full Development System LabWindows/CVI Real-Time Module LabWindows/CVI PID Control Toolkit LabWindows/CVI Signal Processing Toolkit LabWindows/CVI Spectral Measurements Toolkit and Run-time Engine LabWindows/CVI SQL Toolkit Measurement Studio Enterprise Edition iii DIAdem Professional Control and Embedded Systems Option Components Name Required LabVIEW FPGA Module LabVIEW Real-Time Module LabVIEW Statechart Module LabVIEW Mobile Module LabVIEW Datalogging and Supervisory Control Module LabVIEW PID and Fuzzy Logic Toolkit NI Real-Time Execution Trace Toolkit LabVIEW Simulation Interface Toolkit NI Motion Assistant NI-DAQ Base Signal processing and Communications Option Components Name Required LabVIEW FPGA Module LabVIEW Sound and Vibration Measurement Suite LabVIEW Spectral Measurement Toolkit LabVIEW Advanced Signal Processing Toolkit LabVIEW Adaptive Filter Toolkit NI Device Drivers Name FieldPoint NI-DAQmx NI LabVIEW SignalExpress NI Instrument I/O Assistant NI-IMAQ NI Measurement & Automation Explorer Required NI PXI NI-VISA TABLE OF CONTENTS Preface ......................................................................................................................................................................i Installation Requirements ....................................................................................................................................... iii Table of Contents .................................................................................................................................................... vi 1 Introduction to LabVIEW ............................................................................................................................... 1 1.1 Dataflow programming.......................................................................................................................... 1 1.2 Graphical programming ......................................................................................................................... 1 1.3 Benefits .................................................................................................................................................. 2 1.4 LabVIEW MathScript RT Module ........................................................................................................... 2 2 LabVIEW MathScript RT Module ................................................................................................................... 3 3 LabVIEW MathScript ...................................................................................................................................... 4 3.1 Help........................................................................................................................................................ 6 3.2 Examples ................................................................................................................................................ 6 3.3 Useful commands .................................................................................................................................. 8 3.4 Flow Control .......................................................................................................................................... 9 3.4.1 If-else Statement ........................................................................................................................... 9 3.4.2 Switch and Case Statement .......................................................................................................... 9 3.4.3 For loop ....................................................................................................................................... 10 3.4.4 While loop ................................................................................................................................... 10 3.5 4 Plotting ................................................................................................................................................ 11 Linear Algebra Examples.............................................................................................................................. 13 4.1 Vectors ................................................................................................................................................. 13 4.2 Matrices ............................................................................................................................................... 14 4.2.1 Transpose .................................................................................................................................... 14 4.2.2 Diagonal ...................................................................................................................................... 14 4.2.3 Triangular .................................................................................................................................... 15 4.2.4 Matrix Multiplication .................................................................................................................. 15 vi vii 5 Table of Contents 4.2.5 Matrix Addition ........................................................................................................................... 16 4.2.6 Determinant ................................................................................................................................ 17 4.2.7 Inverse Matrices ......................................................................................................................... 18 4.3 Eigenvalues .......................................................................................................................................... 19 4.4 Solving Linear Equations ...................................................................................................................... 19 4.5 LU factorization ................................................................................................................................... 20 4.6 The Singular Value Decomposition (SVD) ............................................................................................ 22 4.7 Commands ........................................................................................................................................... 22 Control Design and Simulation .................................................................................................................... 24 5.1 State-space models and Transfer functions ........................................................................................ 24 5.1.1 PID ............................................................................................................................................... 25 5.1.2 State-space model ...................................................................................................................... 26 5.1.3 Transfer function ........................................................................................................................ 27 5.1.4 First Order Systems ..................................................................................................................... 27 5.1.5 Second Order Systems ................................................................................................................ 28 5.1.6 Padé-approximation ................................................................................................................... 30 5.2 Frequency Response Analysis .............................................................................................................. 31 5.2.1 Bode Diagram ............................................................................................................................. 31 Time Response ................................................................................................................................................. 35 6 MathScript Node ......................................................................................................................................... 37 6.1 Transferring MathScript Nodes between Computers ......................................................................... 38 6.2 Examples .............................................................................................................................................. 39 6.3 Exercises .............................................................................................................................................. 42 7 MATLAB Script ............................................................................................................................................. 43 8 Whats Next? ................................................................................................................................................ 44 8.1 My Blog ................................................................................................................................................ 44 8.2 Training ................................................................................................................................................ 44 8.3 MathScript Functions .......................................................................................................................... 44 Tutorial: LabVIEW MathScript viii Table of Contents Quick Reference .................................................................................................................................................... 46 Tutorial: LabVIEW MathScript 1 INTRODUCTION TO LABVIEW LabVIEW (short for Laboratory Virtual Instrumentation Engineering Workbench) is a platform and development environment for a visual programming language from National Instruments. The graphical language is named "G". Originally released for the Apple Macintosh in 1986, LabVIEW is commonly used for data acquisition, instrument control, and industrial automation on a variety of platforms including Microsoft Windows, various flavors of UNIX, Linux, and Mac OS X. The latest version of LabVIEW is version LabVIEW 2009, released in August 2009. Visit National Instruments at www.ni.com. The code files have the extension “.vi”, which is an abbreviation for “Virtual Instrument”. LabVIEW offers lots of additional Add-Ons and Toolkits. This paper is part of a series with LabVIEW papers: Introduction to LabVIEW Data Acquisition in LabVIEW Control and Simulation in LabVIEW Linear Algebra in LabVIEW Database Communication in LabVIEW Datalogging and Supervisory Control in LabVIEW Intermediate Topics in LabVIEW Advanced Topics in LabVIEW Etc. Each paper may be used independently of each other. 1.1 DATAFLOW PROGRAMMING The programming language used in LabVIEW, also referred to as G, is a dataflow programming language. Execution is determined by the structure of a graphical block diagram (the LV-source code) on which the programmer connects different function-nodes by drawing wires. These wires propagate variables and any node can execute as soon as all its input data become available. Since this might be the case for multiple nodes simultaneously, G is inherently capable of parallel execution. Multi-processing and multi-threading hardware is automatically exploited by the built-in scheduler, which multiplexes multiple OS threads over the nodes ready for execution. 1.2 GRAPHICAL PROGRAMMING LabVIEW ties the creation of user interfaces (called front panels) into the development cycle. LabVIEW programs/subroutines are called virtual instruments (VIs). Each VI has three components: a block diagram, a front panel, and a connector panel. The last is used to represent the VI in the block diagrams of other, calling VIs. Controls and indicators on the front panel allow an operator to input data into or extract data from a running virtual instrument. However, the front panel can also serve as a programmatic interface. Thus a virtual instrument can either be run as a program, with the front panel serving as a user interface, or, when dropped as a node onto the block diagram, the front panel defines the inputs and outputs for the given node through the connector pane. This implies each VI can be easily tested before being embedded as a subroutine into a larger program. 1 2 Introduction to LabVIEW The graphical approach also allows non-programmers to build programs simply by dragging and dropping virtual representations of lab equipment with which they are already familiar. The LabVIEW programming environment, with the included examples and the documentation, makes it simple to create small applications. This is a benefit on one side, but there is also a certain danger of underestimating the expertise needed for good quality "G" programming. For complex algorithms or large-scale code, it is important that the programmer possess an extensive knowledge of the special LabVIEW syntax and the topology of its memory management. The most advanced LabVIEW development systems offer the possibility of building stand-alone applications. Furthermore, it is possible to create distributed applications, which communicate by a client/server scheme, and are therefore easier to implement due to the inherently parallel nature of G-code. 1.3 BENEFITS One benefit of LabVIEW over other development environments is the extensive support for accessing instrumentation hardware. Drivers and abstraction layers for many different types of instruments and buses are included or are available for inclusion. These present themselves as graphical nodes. The abstraction layers offer standard software interfaces to communicate with hardware devices. The provided driver interfaces save program development time. The sales pitch of National Instruments is, therefore, that even people with limited coding experience can write programs and deploy test solutions in a reduced time frame when compared to more conventional or competing systems. A new hardware driver topology (DAQmxBase), which consists mainly of G-coded components with only a few register calls through NI Measurement Hardware DDK (Driver Development Kit) functions, provides platform independent hardware access to numerous data acquisition and instrumentation devices. The DAQmxBase driver is available for LabVIEW on Windows, Mac OS X and Linux platforms. For more information about LabVIEW, visit my Blog: http://home.hit.no/~hansha/ 1.4 LABVIEW MATHSCRIPT RT MODULE The LabVIEW MathScript RT Module is an add-on module to LabVIEW. With LabVIEW MathScript RT Module you can: Deploy your custom .m files to NI real-time hardware Reuse many of your scripts created with The MathWorks, Inc. MATLAB® software and others Develop your .m files with an interactive command-line interface Embed your scripts into your LabVIEW applications using the MathScript Node Tutorial: LabVIEW MathScript 2 LABVIEW MATHSCRIPT RT MODULE You can work with LabVIEW MathScript through either of two interfaces: the “LabVIEW MathScript Interactive Window” or the “MathScript Node”. You can work with LabVIEW MathScript RT Module through both interactive and programmatic interfaces. For an interactive interface in which you can load, save, design, and execute your .m file scripts, you can work with the “MathScript Interactive Window”. To deploy your .m file scripts as part of a LabVIEW application and combine graphical and textual programming, you can work with the “MathScript Node”. The LabVIEW MathScript RT Module complements traditional LabVIEW graphical programming for such tasks as algorithm development, signal processing, and analysis. The LabVIEW MathScript RT Module speeds up these and other tasks by giving users a single environment in which they can choose the most effective syntax, whether textual, graphical, or a combination of the two. In addition, you can exploit the best of LabVIEW and thousands of publicly available .m file scripts from the web, textbooks, or your own existing m-script applications. LabVIEW MathScript RT Module is able to process your files created using the current MathScript syntax and, for backwards compatibility, files created using legacy MathScript syntaxes. LabVIEW MathScript RT Module can also process certain of your files utilizing other text-based syntaxes, such as files you created using MATLAB software. Because the MathScript RT engine is used to process scripts contained in a MathScript Windows or MathScript Node, and because the MathScript RT engine does not support all syntaxes, not all existing text-based scripts are supported. LabVIEW MathScript RT Module supports most of the functionality available in MATLAB, the syntax is also similar. For more details, see http://zone.ni.com/devzone/cda/tut/p/id/3257 3 3 LABVIEW MATHSCRIPT Requires: MathScript RT Module How do you start using MathScript? You need to install LabVIEW and the LabVIEW MathScript RT Module. When necessary software is installed, start MathScript by open LabVIEW: In the Getting Started window, select Tools -> MathScript Window...: The “LabVIEW MathScript Window” is an interactive interface in which you can enter .m file script commands and see immediate results, variables and commands history. The window includes a command-line interface where you can enter commands one-by-one for quick calculations, script debugging or learning. Alternatively, you can enter and execute groups of commands through a script editor window. As you work, a variable display updates to show the graphical / textual results and a history window tracks your commands. The history view facilitates algorithm development by allowing you to use the clipboard to reuse your previously executed commands. 4 5 LabVIEW MathScript You can use the “LabVIEW MathScript Window” to enter commands one at time. You also can enter batch scripts in a simple text editor window, loaded from a text file, or imported from a separate text editor. The “LabVIEW MathScript Window” provides immediate feedback in a variety of forms, such as graphs and text. Example: Tutorial: LabVIEW MathScript 6 3.1 LabVIEW MathScript HELP You may also type help in your command window >>help Or more specific, e.g., >>help plot 3.2 EXAMPLES I advise you to test all the examples in this text in LabVIEW MathScript in order to get familiar with the program and its syntax. All examples in the text are outlined in a frame like this: >> … This is commands you should write in the Command Window. You type all your commands in the Command Window. I will use the symbol “>>” to illustrate that the commands should be written in the Command Window. Example: Matrices Defining the following matrix The syntax is as follows: >> A = [1 2;0 3] Or >> A = [1,2;0,3] If you, for an example, want to find the answer to >>a=4 >>b=3 >>a+b MathScript then responds: ans = 7 Tutorial: LabVIEW MathScript 7 LabVIEW MathScript MathScript provides a simple way to define simple arrays using the syntax: “init:increment:terminator”. For instance: >> array = 1:2:9 array = 1 3 5 7 9 The code defines a variable named array (or assigns a new value to an existing variable with the name array) which is an array consisting of the values 1, 3, 5, 7, and 9. That is, the array starts at 1 (the init value), increments with each step from the previous value by 2 (the increment value), and stops once it reaches (or to avoid exceeding) 9 (the terminator value). The increment value can actually be left out of this syntax (along with one of the colons), to use a default value of 1. >> ari = 1:5 ari = 1 2 3 4 5 The code assigns to the variable named ari an array with the values 1, 2, 3, 4, and 5, since the default value of 1 is used as the incrementer. Note that the indexing is one-based, which is the usual convention for matrices in mathematics. This is atypical for programming languages, whose arrays more often start with zero. Matrices can be defined by separating the elements of a row with blank space or comma and using a semicolon to terminate each row. The list of elements should be surrounded by square brackets: []. Parentheses: () are used to access elements and subarrays (they are also used to denote a function argument list). >> A = [16 3 2 13; 5 10 11 8; 9 6 7 12; 4 15 14 1] A = 16 3 2 13 5 10 11 9 6 8 7 12 4 15 14 1 >> A(2,3) ans = 11 Tutorial: LabVIEW MathScript 8 LabVIEW MathScript Sets of indices can be specified by expressions such as "2:4", which evaluates to [2, 3, 4]. For example, a submatrix taken from rows 2 through 4 and columns 3 through 4 can be written as: >> A(2:4,3:4) ans = 11 8 7 12 14 1 A square identity matrix of size n can be generated using the function eye, and matrices of any size with zeros or ones can be generated with the functions zeros and ones, respectively. >> eye(3) ans = 1 0 0 0 1 0 0 0 1 >> zeros(2,3) ans = 0 0 0 0 0 0 >> ones(2,3) ans = 1 1 1 1 1 1 3.3 USEFUL COMMANDS Here are some useful commands: Command Description eye(x), eye(x,y) Identity matrix of order x ones(x), ones(x,y) A matrix with only ones Tutorial: LabVIEW MathScript 9 LabVIEW MathScript zeros(x), zeros(x,y) A matrix with only zeros diag([x y z]) Diagonal matrix size(A) Dimension of matrix A A’ Inverse of matrix A 3.4 FLOW CONTROL This chapter explains the basic concepts of flow control in MathScript. The topics are as follows: If-else statement Switch and case statement For loop While loop 3.4.1 IF-ELSE STATEMENT The if statement evaluates a logical expression and executes a group of statements when the expression is true. The optional elseif and else keywords provide for the execution of alternate groups of statements. An end keyword, which matches the if, terminates the last group of statements. The groups of statements are delineated by the four keywords—no braces or brackets are involved. Example: If-Else Statement Test the following code: n=5 if n > 2 M = eye(n) elseif n < 2 M = zeros(n) else M = ones(n) end 3.4.2 SWITCH AND CASE STATEMENT The switch statement executes groups of statements based on the value of a variable or expression. The keywords case and otherwise delineate the groups. Only the first matching case is executed. There must always be an end to match the switch. Example: Switch and Case Statement Test the following code: Tutorial: LabVIEW MathScript 10 LabVIEW MathScript n=2 switch(n) case 1 M = eye(n) case 2 M = zeros(n) case 3 M = ones(n) end 3.4.3 FOR LOOP The for loop repeats a group of statements a fixed, predetermined number of times. A matching end delineates the statements. Example: For Loop Test the following code: m=5 for n = 1:m r(n) = rank(magic(n)); end r 3.4.4 WHILE LOOP The while loop repeats a group of statements an indefinite number of times under control of a logical condition. A matching end delineates the statements. Example: While Loop Test the following code: m=5; while m > 1 m = m - 1; zeros(m) end Tutorial: LabVIEW MathScript 11 3.5 LabVIEW MathScript PLOTTING This chapter explains the basic concepts of creating plots in MathScript. Topics: Basic Plot commands Example: Plotting Function plot can be used to produce a graph from two vectors x and y. The code: x = 0:pi/100:2*pi; y = sin(x); plot(x,y) produces the following figure of the sine function: Example: Plotting Three-dimensional graphics can be produced using the functions surf, plot3 or mesh. [X,Y] = meshgrid(-10:0.25:10,-10:0.25:10); f = sinc(sqrt((X/pi).^2+(Y/pi).^2)); mesh(X,Y,f); axis([-10 10 -10 10 -0.3 1]) Tutorial: LabVIEW MathScript 12 LabVIEW MathScript xlabel('{\bfx}') ylabel('{\bfy}') zlabel('{\bfsinc} ({\bfR})') hidden off This code produces the following 3D plot: Tutorial: LabVIEW MathScript 4 LINEAR ALGEBRA EXAMPLES Requires: MathScript RT Module Linear algebra is a branch of mathematics concerned with the study of matrices, vectors, vector spaces (also called linear spaces), linear maps (also called linear transformations), and systems of linear equations. MathScript are well suited for Linear Algebra. 4.1 VECTORS Given a vector x Example: Vectors Given the following vector >> x=[1; 2; 3] x = 1 2 3 The Transpose of vector x: >> x' ans = 1 2 3 The Length of vector x: Orthogonality: 13 14 4.2 Linear Algebra Examples MATRICES Given a matrix A: Example: Matrices Given the following matrix: >> A=[0 1;-2 -3] A = 0 1 -2 -3 4.2.1 TRANSPOSE The Transpose of matrix A: Example: Transpose Given the matrix: >> A' ans = 0 -2 1 -3 4.2.2 DIAGONAL The Diagonal elements of matrix A is the vector Example: Diagonal Tutorial: LabVIEW MathScript 15 Linear Algebra Examples Find the diagonal elements of matrix A: >> diag(A) ans = 0 -3 The Diagonal matrix Λ is given by: Given the Identity matrix I: Example: Identity Matrix Get the 3x3 Identity matrix: >> eye(3) ans = 1 0 0 0 1 0 0 0 1 4.2.3 TRIANGULAR Lower Triangular matrix L: Upper Triangular matrix U: 4.2.4 MATRIX MULTIPLICATION Given the matrices and , then Tutorial: LabVIEW MathScript 16 Linear Algebra Examples where Example: Matrix Multiplication Matrix multiplication: >> A=[0 1;-2 -3] A = 0 1 -2 -3 >> B=[1 0;3 -2] B = 1 0 3 -2 >> A*B ans = 3 -2 -11 6 Note! 4.2.5 MATRIX ADDITION Given the matrices and , then Example: Matrix Addition Matrix addition: >> A=[0 1;-2 -3] >> B=[1 0;3 -2] >> A+B Tutorial: LabVIEW MathScript 17 Linear Algebra Examples ans = 1 1 1 -5 4.2.6 DETERMINANT Given a matrix , then the Determinant is given: Given a 2x2 matrix Then Example: Determinant Find the determinant: A = 0 1 -2 -3 >> det(A) ans = 2 Notice that and Example: Determinant Determinants: >> det(A*B) ans = Tutorial: LabVIEW MathScript 18 Linear Algebra Examples -4 >> det(A)*det(B) ans = -4 >> det(A') ans = 2 >> det(A) ans = 2 4.2.7 INVERSE MATRICES The inverse of a quadratic matrix is defined by: if For a 2x2 matrix we have: The inverse is given by Example: Inverse Matrices Inverse matrix: A = 0 1 -2 -3 >> inv(A) ans = -1.5000 1.0000 -0.5000 0 Notice that: → Prove this in MathScript Tutorial: LabVIEW MathScript 19 Linear Algebra Examples 4.3 EIGENVALUES Given , then the Eigenvalues is defined as: Example: Eigenvalues Find the Eigenvalues: A = 0 1 -2 -3 >> eig(A) ans = -1 -2 4.4 SOLVING LINEAR EQUATIONS Given the linear equation with the solution: (Assuming that the inverse of A exists) Example: Solving Linear Equations Solving the following equation: The equations may be written where Tutorial: LabVIEW MathScript 20 Linear Algebra Examples The solution is: A = 1 2 3 4 >> b=[5;6] b = 5 6 >> x=inv(A)*b x = -4.0000 4.5000 In MathScript you could also write “x=A\b”, which should give the same answer. This syntax can also be used when the inverse of A don’t exists. Example: Solving Linear Equations Illegal operation: >> A=[1 2;3 4;7 8] >> x=inv(A)*b ??? Error using ==> inv Matrix must be square. >> x=A\b x = -3.5000 4.1786 4.5 LU FACTORIZATION LU factorization of is given by where L is a lower triangular matrix Tutorial: LabVIEW MathScript 21 Linear Algebra Examples U is a upper triangular matrix The MathScript syntax is [L,U]=lu(A) Example: LU Factorization Find L and U: >> A=[1 2;3 4] >> [L,U]=lu(A) L = 0.3333 1.0000 1.0000 0 3.0000 4.0000 0 0.6667 U = Or sometimes LU factorization of is given by where D is a diagonal matrix The MathScript syntax is [L,U,P]=lu(A) Example: LU Factorization Find L, U and P: >> A=[1 2;3 4] A = 1 2 3 4 >> [L,U,P]=lu(A) L = 1.0000 0 0.3333 1.0000 3.0000 4.0000 U = Tutorial: LabVIEW MathScript 22 Linear Algebra Examples 0 0.6667 P = 4.6 0 1 1 0 THE SINGULAR VALUE D ECOMPOSITION (SVD) The Singular value Decomposition (SVD) of the matrix is given by where U is a orthogonal matrix V is a orthogonal matrix S is a diagonal singular matrix Example: SVD Decomposition Find S, V and D: >> A=[1 2;3 4]; >> [U,S,V] = svd(A) U = -0.4046 -0.9145 -0.9145 0.4046 5.4650 0 0 0.3660 -0.5760 0.8174 -0.8174 -0.5760 S = V = 4.7 COMMANDS Tutorial: LabVIEW MathScript 23 Linear Algebra Examples Command [L,U]=lu(A) Description LU Factorization [L,U,P]=lu(A) [U,S,V] = svd(A) Singular Value Decomposition (SVD ) Tutorial: LabVIEW MathScript 5 CONTROL DESIGN AND SIMULATION Using LabVIEW MathScript for Control Design purposes you need to install the “Control Design and Simulation Module” in addition to the “MathScript RT Module” itself. Use the Control Design MathScript RT Module functions to design, analyze, and simulate linear controller models using a text-based language. The following is a list of Control Design MathScript RT Module classes of functions and commands that LabVIEW MathScript supports. Getting help about MathScript functions regarding the Control Design Toolkit (CDT), type “help cdt” in the Command Window in the MathScript environment. The following function classes exist: We will go through some of the classes and function in detail below: 5.1 STATE-SPACE MODELS AND TRANSFER FUNCTIONS MathScript offers lots of functions for defining and manipulate state-space models and transfer functions. Class: contruct Description: Use functions in the construct class to construct linear time-invariant system models and to convert between model forms. Below we see the different functions available in the construct class: 24 25 Control Design and Simulation Below we will give some examples of how to use the most import functions in this class. 5.1.1 PID Currently, the Proportional-Integral-Derivative (PID) algorithm is the most common control algorithm used in industry. In PID control, you must specify a process variable and a setpoint. The process variable is the system parameter you want to control, such as temperature, pressure, or flow rate, and the setpoint is the desired value for the parameter you are controlling. A PID controller determines a controller output value, such as the heater power or valve position. The controller applies the controller output value to the system, which in turn drives the process variable toward the setpoint value. Then the PID controller calculates the controller action, u(t): Where Controller gain Integral time Derivative time And is the error SP – Setpoint PV – Process Variable Tutorial: LabVIEW MathScript 26 Control Design and Simulation Function: pid Description: Constructs a proportional-integral-derivative (PID) controller model in either parallel, series, or academic form. Examples: Kc = 0.5; Ti = 0.25; SysOutTF = pid(Kc, Ti, 'academic'); 5.1.2 STATE-SPACE MODEL A state-space model is just a structured form or representation of the differential equations for a system. A linear State-space model: where x is the state vector and u is the input vector. A is called the system-matrix, and is square in all cases. Example: The differential equations: May be written on state-space form: Function: ss Description: This function constructs a continuous or discrete linear system model in state-space form. You also can use this function to convert transfer function and zero-pole-gain models to state-space form. Examples: % Creates a state-space model A = eye(2) B = [0; 1] C = B' SysOutSS = ss(A, B, C) Tutorial: LabVIEW MathScript 27 Control Design and Simulation % Converts a zero-pole-gain model to state-space form z = 1 p = [1, -1] k = 1 SysIn = zpk(z, p, k) SysOutSS = ss(SysIn) 5.1.3 TRANSFER FUNCTION The transfer function of a linear system is defined as the ratio of the Laplace transform of the output variable to the Laplace transform of the input variable. Function tf Description: This function creates a continuous or discrete linear system model in transfer function form. You also can use this function to convert zero-pole-gain and state-space models to transfer function form. Examples: >>s = tf('s') This specifies that you want to create the continuous transfer function s / 1. After you enter this command, you can use LabVIEW MathScript operands on this transfer function to define a zero-pole-gain or transfer function model. SysOutZPK = 4*(s + 2) / (s + 1) This example constructs a zero-pole-gain model with a gain of 4, a zero at -2, and a pole at -1. SysOutTF = (3*(s*s*s) + 2) / (4*(s*s*s*s) + 8) This example constructs the transfer function model 3s^3 + 2 / 4s^4 + 8. 5.1.4 FIRST ORDER SYSTEMS The following transfer function defines a first order system: Where Tutorial: LabVIEW MathScript 28 Control Design and Simulation is the gain is the Time constant Function sys_order1 Description: This function constructs the components of a first-order system model based on a gain, time constant, and delay that you specify. You can use this function to create either a state-space model or a transfer function model, depending on the output parameters you specify. Inputs: K Specifies the gain matrix. K is a real matrix. tau Specifies the time constant, in seconds, which is the time required for the model output to reach 63% of its final value. The default value is 0. delay Specifies the response delay of the model, in seconds. The default value is 0. Examples: K = 0.5; tau = 1.5; SysOutTF = sys_order1(K, tau); … 5.1.5 SECOND ORDER SYSTEMS A standard second order transfer function model may be written like this: Where is the gain (zetais the relative damping factor [rad/s] is the undamped resonance frequency. Function sys_order2 Description: This function constructs the components of a second-order system model based on a damping ratio and natural frequency you specify. You can use this function to create either a state-space model or a transfer function model, depending on the output parameters you specify. Tutorial: LabVIEW MathScript 29 Control Design and Simulation Example: Examples of how to use the sys_order2 function: dr = 0.5 wn = 20 [num, den] = sys_order2(wn, dr) SysTF = tf(num, den) [A, B, C, D] = sys_order2(wn, dr) SysSS = ss(A, B, C, D) Class: connect Description: Use members of the connect class to connect systems models together in various configurations. Below we see the different functions available in the connect class: Function series Description: This function connects two system models in series to produce a model SysSer with input and output connections you specify. The input models must be either continuous models or discrete models with identical sampling times. Example: Here is an example of how to use the series function. SysIn_1 = tf([1, 1], [1 -1, 3]) SysIn_2 = zpk([1], [1, -1], 1) SysSer = series(SysIn_1, SysIn_2) Class: convert Tutorial: LabVIEW MathScript 30 Control Design and Simulation Description: Use members of the convert class to convert a continuous system model to a discrete model, convert a discrete model to a continuous model, and resample a discrete model. You also can use members of this class to incorporate delays into a system model. Below we see the different functions available in the convert class: 5.1.6 PADÉ-APPROXIMATION The Transfer function of a time-delay is: In some situations it is necessary to substitute with an approximation, e.g., the Padé-approximation: Function: pade Description: This function incorporates time delays into a system model using the Pade approximation method, which converts all residuals. You must specify the delay using the set function. You also can use this function to calculate coefficients of numerator and denominator polynomial functions with a specified delay. Example: Examples of how to use the pade function: SysCon = zpk(1, 3.2, 6) SysCon = set(SysCon, 'inputdelay', 6, 'outputdelay', 1.1) SysDel = pade(SysCon, 2) delay = 1.2 order = 3 [num, den] = pade(delay, order) Tutorial: LabVIEW MathScript 31 5.2 Control Design and Simulation FREQUENCY RESPONSE ANALYSIS The frequency response of a system is a frequency dependent function which expresses how a sinusoidal signal of a given frequency on the system input is transferred through the system. Each frequency component is a sinusoidal signal having a certain amplitude and a certain frequency. The frequency response is an important tool for analysis and design of signal filters and for analysis and design of control systems. The frequency response can found experimentally or from a transfer function model. The frequency response of a system is defined as the steady-state response of the system to a sinusoidal input signal. When the system is in steady-state it differs from the input signal only in amplitude (A) and phase angle (ω). If we have the input signal: The steady-state output signal will be: A and is a function of the frequency ω so we may write For a transfer function We have: Where is the frequency response of the system, i.e., we may find the frequency response by setting in the transfer function. 5.2.1 BODE DIAGRAM Bode diagrams are useful in frequency response analysis. The Bode diagram consists of 2 diagrams, the Bode magnitude diagram, and the Bode phase diagram, . The -axis is in decibel (dB) Where the decibel value of x is calculated as: The -axis is in degrees (not radians) Tutorial: LabVIEW MathScript 32 Control Design and Simulation Function: bode Description: This function creates the Bode magnitude and Bode phase plots of a system model. You also can use this function to return the magnitude and phase values of a model at frequencies you specify. If you do not specify an output, this function creates a plot. Examples: We have the following transfer function We want to plot the Bode diagram for this transfer function: In MathScript we could write: num=[1]; den=[1,1]; H1=tf(num,den) bode(H1) Function: margin Description: Tutorial: LabVIEW MathScript 33 Control Design and Simulation This function calculates and/or plots the smallest gain and phase margins of a single-input single-output (SISO) system model. The gain margin indicates where the frequency response crosses at 0 decibels (“crossover frequency”, ). is also the bandwidth of the system The phase margin indicates where the frequency response crosses -180 degrees (“crossover frequency”, Examples: The following example illustrates the use of the margin function. num = [1] den = [1, 5, 6] H = tf(num, den) margin(H) Example: Given the following system: We want to plot the Bode diagram and find the crossover-frequencies for the system using MathScript. The code is as follows: H = tf([1, 1], [1, -1, 3]) bode(H) [gmf, gm, pmf, pm] = margins(H) margin(H) We use the following functions: tf, bode, margins and margin. gmf is the gain margin frequencies, in radians/second. A gain margin frequency indicates where the model phase crosses -180 degrees. gm Returns the gain margins of the system. pmf Returns the phase margin frequencies, in radians/second. A phase margin frequency indicates where the model magnitude crosses 0 decibels. Tutorial: LabVIEW MathScript ). 34 Control Design and Simulation pm Returns the phase margins of the system. We get the following results: Bode Plot: Cross-frequencies: We get the following values: Tutorial: LabVIEW MathScript 35 Control Design and Simulation gmf = 1 gm = 2 pmf = -70.379 2.2333e-010 pm = 1.4155 2 TIME RESPONSE Class: timeresp Description: Use members of the timeresp class to create generic linear simulations and time domain plots for step inputs, impulse inputs, and initial condition responses. Below we see the different functions available in the timeresp class: Function: step Description: This function creates a step response plot of the system model. You also can use this function to return the step response of the model outputs. If the model is in state-space form, you also can use this function to return the step response of the model states. This function assumes the initial model states are zero. If you do not specify an output, this function creates a plot. Example: Given the following system: We will plot the time response for the transfer function using the step function The result is as follows: Tutorial: LabVIEW MathScript 36 Control Design and Simulation The MathScript code: H = tf([1, 1], [1, -1, 3]) step(H) Tutorial: LabVIEW MathScript 6 MATHSCRIPT NODE The “MathScript Node” offers an intuitive means of combining graphical and textual code within LabVIEW. The figure below shows the “MathScript Node” on the block diagram, represented by the blue rectangle. Using “MathScript Nodes”, you can enter .m file script text directly or import it from a text file. You can define named inputs and outputs on the MathScript Node border to specify the data to transfer between the graphical LabVIEW environment and the textual MathScript code. You can associate .m file script variables with LabVIEW graphical programming, by wiring Node inputs and outputs. Then you can transfer data between .m file scripts with your graphical LabVIEW programming. The textual .m file scripts can now access features from traditional LabVIEW graphical programming. The MathScript Node is available from LabVIEW from the Functions Palette: Mathematics → Scripts & Formulas 37 38 MathScript Node If you click Ctrl+H you get help about the MathScript Node: Click “Detailed help” in order to get more information about the MathScript Node. Use the NI Example Finder in order to find examples: 6.1 TRANSFERRING MATHSCRIPT NODES BETWEEN COMPUTERS If a script in a MathScript Node calls a user-defined function, LabVIEW uses the default search path list to link the function call to the specified .m file. After you configure the default search path list and save the VI that contains the MathScript Node, you do not need to reconfigure the MathScript search path list when you open the VI on a different computer because LabVIEW looks for the .m file in the directory where the .m file was Tutorial: LabVIEW MathScript 39 MathScript Node located when you last saved the VI. However, you must maintain the same relative path between the VI and the .m file. 6.2 EXAMPLES Example: Using the MathScript Node Here is an example of how you use the MathScript Node. On the left border you connect input variables to the script, on the right border you have output variables. Right-click on the border and select “Add Input” or “Add Output”. Example: Calling a Windows DLL: Example: Using m-files in the MathScript Node: Use the LabVIEW MathScript to create a m-file script (or you may use MATLAB to create the same script): Tutorial: LabVIEW MathScript 40 MathScript Node Right-click on the border of the MathScript Node and select “Import”, and then select the m-file you want to import into the Node. Tutorial: LabVIEW MathScript 41 MathScript Node Right-click on the right border and select “Add Output”. Then right-click on the output variable and select “Create Indicator”. Block Diagram: The result is as follows (click the Run button): If you, e.g., add the following command in the MathScript Node: plot(x), the following window appears: Tutorial: LabVIEW MathScript 42 6.3 MathScript Node EXERCISES Use the MathScript Node and test the same examples you did in the previous chapter (Chapter 4 - “Linear Algebra Examples”) Tutorial: LabVIEW MathScript 7 MATLAB SCRIPT The MATLAB Script calls the MATLAB software to execute scripts. You must have a licensed copy of the MATLAB software version 6.5 or later installed on your computer to use MATLAB script nodes because the script nodes invoke the MATLAB software script server to execute scripts written in the MATLAB language syntax. Because LabVIEW uses ActiveX technology to implement MATLAB script nodes, they are available only on Windows. 43 8 WHATS NEXT? 8.1 MY BLOG For more information about LabVIEW, visit my Blog: http://home.hit.no/~hansha/ 8.2 TRAINING This Training is a part of a series with other Training Kits I have made, such as: Introduction to LabVIEW Data Acquisition in LabVIEW Control and Simulation in LabVIEW LabVIEW MathScript Linear Algebra in LabVIEW Datalogging and Supervisory Control in LabVIEW Wireless Data Acquisition in LabVIEW Intermediate Topics in LabVIEW Advanced Topics in LabVIEW These Training Kits are available for download from my blog: http://home.hit.no/~hansha 8.3 MATHSCRIPT FUNCTIONS In the Help system there is detailed information about all the MathScript functions available. In addition to the MathScript RT Module functions, different add-on modules and toolkits installs additional functions. The LabVIEW Control Design and Simulation Module and LabVIEW Digital Filter Design Toolkit install lots of additional functions. 44 45 MathScript Node Tutorial: LabVIEW MathScript QUICK REFERENCE 46 47 Quick Reference Tutorial: LabVIEW MathScript Telemark University College Faculty of Technology Kjølnes Ring 56 N-3914 Porsgrunn, Norway www.hit.no Hans-Petter Halvorsen, M.Sc. Telemark University College Department of Electrical Engineering, Information Technology and Cybernetics Phone: +47 3557 5158 E-mail: hans.p.halvorsen@hit.no Blog: http://home.hit.no/~hansha/ Room: B-237a Telemark University College Department of Electrical Engineering, Information Technology and Cybernetics DATA ACQUISITION IN LABVIEW HANS-PETTER HALVORSEN, 2010.02.09 Faculty of Technology, Postboks 203, Kjølnes ring 56, N-3901 Porsgrunn, Norway. Tel: +47 35 57 50 00 Fax: +47 35 57 54 01 PREFACE This tutorial explains the basic concepts of a Data Acquisition in LabVIEW. You should have some basic knowledge about LabVIEW, e.g., the “Introduction to LabVIEW” tutorial. This document is available for download at http://home.hit.no/~hansha/. For more information about LabVIEW, visit: http://home.hit.no/~hansha/?page=labview. INSTALLATION REQUIREMENTS NI LabVIEW Name Required LabVIEW Professional Development System Yes NI LabVIEW Core Components Name Required LabVIEW Control Design and Simulation Module LabVIEW MathScript RT Module NI Vision Development Module Vision Builder for Automated Inspection LabVIEW Digital Filter Design Toolkit LabVIEW Modulation Toolkit LabVIEW System Identification Toolkit LabVIEW Desktop Execution Trace Toolkit LabVIEW Report Generation for Microsoft Office Toolkit LabVIEW Database Connectivity Toolkit LabVIEW Internet Toolkit NI LabVIEW SignalExpress LabVIEW Basics 1 and 2 Computer Based Training Extended Development Suite Components Name Required LabWindows/CVI Full Development System LabWindows/CVI Real-Time Module LabWindows/CVI PID Control Toolkit LabWindows/CVI Signal Processing Toolkit LabWindows/CVI Spectral Measurements Toolkit and Run-time Engine LabWindows/CVI SQL Toolkit Measurement Studio Enterprise Edition 3 DIAdem Professional Control and Embedded Systems Option Components Name Required LabVIEW FPGA Module LabVIEW Real-Time Module LabVIEW Statechart Module LabVIEW Mobile Module LabVIEW Datalogging and Supervisory Control Module LabVIEW PID and Fuzzy Logic Toolkit NI Real-Time Execution Trace Toolkit LabVIEW Simulation Interface Toolkit NI Motion Assistant NI-DAQ Base Signal processing and Communications Option Components Name Required LabVIEW FPGA Module LabVIEW Sound and Vibration Measurement Suite LabVIEW Spectral Measurement Toolkit LabVIEW Advanced Signal Processing Toolkit LabVIEW Adaptive Filter Toolkit NI Device Drivers Name Required FieldPoint NI-DAQmx Yes NI LabVIEW SignalExpress NI Instrument I/O Assistant NI-IMAQ NI Measurement & Automation Explorer NI PXI Yes NI-VISA Yes TABLE OF CONTENTS Preface .................................................................................................................................................................... 2 Installation Requirements ....................................................................................................................................... 3 Table of Contents .................................................................................................................................................... vi 1 2 Introduction to LabVIEW ............................................................................................................................... 1 1.1 Dataflow programming.......................................................................................................................... 1 1.2 Graphical programming ......................................................................................................................... 1 1.3 Benefits .................................................................................................................................................. 2 Introduction to Data Acquisition ................................................................................................................... 3 2.1 Introduction to DAQ - Data Acquisition ................................................................................................. 3 2.1.1 Physical input/output signals ........................................................................................................ 4 2.1.2 DAQ device/hardware .................................................................................................................. 4 2.1.3 Driver software ............................................................................................................................. 5 2.1.4 Your software application (Application software) ........................................................................ 5 2.2 MAX – Measurement and Automation Explorer ................................................................................... 6 2.3 NI-DAQmx .............................................................................................................................................. 7 2.3.1 2.4 3 DAQ Assistant ............................................................................................................................... 7 NI USB-6008 ........................................................................................................................................... 8 Physical input/output signals ........................................................................................................................ 9 3.1 Transducers ........................................................................................................................................... 9 3.2 Signals .................................................................................................................................................. 10 3.2.1 3.3 Analog Signals ............................................................................................................................ 10 Digital Signals ....................................................................................................................................... 11 4 MAX ............................................................................................................................................................. 13 5 NI-DAQmx .................................................................................................................................................... 15 5.1.1 5.2 DAQ Assistant ............................................................................................................................. 16 Simulating a DAQ Device ..................................................................................................................... 16 vi vii Table of Contents 6 DAQ Devices ................................................................................................................................................ 18 7 6.1 Performing Analog-to-Digital Conversion ............................................................................................ 19 6.2 Performing Digital-to-Analog Conversion ............................................................................................ 19 6.3 Using Counters .................................................................................................................................... 19 6.4 Using Digital I/O ................................................................................................................................... 19 NI USB 6008 ................................................................................................................................................. 20 7.1 Connect NI USB-6008 to the PC ........................................................................................................... 20 7.1.1 8 Testing the USB-6008 in MAX ..................................................................................................... 20 7.2 Using NI USB-6008 in LabVIEW ............................................................................................................ 26 7.3 DAQ Assistant ...................................................................................................................................... 27 7.3.1 Analog Input................................................................................................................................ 27 7.3.2 Analog Output ............................................................................................................................. 34 Whats Next? ................................................................................................................................................ 37 8.1 My Blog ................................................................................................................................................ 37 8.2 Training ................................................................................................................................................ 37 8.3 Additional Resources ........................................................................................................................... 37 8.4 Examples .............................................................................................................................................. 37 8.5 Documentation .................................................................................................................................... 38 8.6 LabVIEW Wiki....................................................................................................................................... 38 8.7 lABview ON yOUtUBE .......................................................................................................................... 39 Quick Reference .................................................................................................................................................... 40 Tutorial: Data Acquisition in LabVIEW 1 INTRODUCTION TO LABVIEW LabVIEW (short for Laboratory Virtual Instrumentation Engineering Workbench) is a platform and development environment for a visual programming language from National Instruments. The graphical language is named "G". Originally released for the Apple Macintosh in 1986, LabVIEW is commonly used for data acquisition, instrument control, and industrial automation on a variety of platforms including Microsoft Windows, various flavors of UNIX, Linux, and Mac OS X. The latest version of LabVIEW is version LabVIEW 2009, released in August 2009. Visit National Instruments at www.ni.com. The code files have the extension “.vi”, which is a abbreviation for “Virtual Instrument”. LabVIEW offers lots of additional Add-Ons and Toolkits. This paper is part of a series with LabVIEW Tutorials: Introduction to LabVIEW Data Acquisition in LabVIEW Control and Simulation in LabVIEW LabVIEW MathScript Linear Algebra in LabVIEW Datalogging and Supervisory Control in LabVIEW Wireless Data Acquisition in LabVIEW Intermediate Topics in LabVIEW Advanced Topics in LabVIEW Etc. Each tutorial may be used independently of each other. 1.1 DATAFLOW PROGRAMMING The programming language used in LabVIEW, also referred to as G, is a dataflow programming language. Execution is determined by the structure of a graphical block diagram (the LV-source code) on which the programmer connects different function-nodes by drawing wires. These wires propagate variables and any node can execute as soon as all its input data become available. Since this might be the case for multiple nodes simultaneously, G is inherently capable of parallel execution. Multi-processing and multi-threading hardware is automatically exploited by the built-in scheduler, which multiplexes multiple OS threads over the nodes ready for execution. 1.2 GRAPHICAL PROGRAMMING LabVIEW ties the creation of user interfaces (called front panels) into the development cycle. LabVIEW programs/subroutines are called virtual instruments (VIs). Each VI has three components: a block diagram, a front panel, and a connector panel. The last is used to represent the VI in the block diagrams of other, calling VIs. Controls and indicators on the front panel allow an operator to input data into or extract data from a running virtual instrument. However, the front panel can also serve as a programmatic interface. Thus a virtual instrument can either be run as a program, with the front panel serving as a user interface, or, when dropped as a node onto the block diagram, the front panel defines the inputs and outputs for the given node through the connector pane. This implies each VI can be easily tested before being embedded as a subroutine into a larger program. 1 2 Introduction to LabVIEW The graphical approach also allows non-programmers to build programs simply by dragging and dropping virtual representations of lab equipment with which they are already familiar. The LabVIEW programming environment, with the included examples and the documentation, makes it simple to create small applications. This is a benefit on one side, but there is also a certain danger of underestimating the expertise needed for good quality "G" programming. For complex algorithms or large-scale code, it is important that the programmer possess an extensive knowledge of the special LabVIEW syntax and the topology of its memory management. The most advanced LabVIEW development systems offer the possibility of building stand-alone applications. Furthermore, it is possible to create distributed applications, which communicate by a client/server scheme, and are therefore easier to implement due to the inherently parallel nature of G-code. 1.3 BENEFITS One benefit of LabVIEW over other development environments is the extensive support for accessing instrumentation hardware. Drivers and abstraction layers for many different types of instruments and buses are included or are available for inclusion. These present themselves as graphical nodes. The abstraction layers offer standard software interfaces to communicate with hardware devices. The provided driver interfaces save program development time. The sales pitch of National Instruments is, therefore, that even people with limited coding experience can write programs and deploy test solutions in a reduced time frame when compared to more conventional or competing systems. A new hardware driver topology (DAQmxBase), which consists mainly of G-coded components with only a few register calls through NI Measurement Hardware DDK (Driver Development Kit) functions, provides platform independent hardware access to numerous data acquisition and instrumentation devices. The DAQmxBase driver is available for LabVIEW on Windows, Mac OS X and Linux platforms. Tutorial: Data Acquisition in LabVIEW 2 INTRODUCTION TO DATA ACQUISITION This chapter explains the basic concepts of using DAQ in LabVIEW. Topics: Introduction to DAQ - Data Acquisition MAX – Measurement and Automation Explorer NI-DAQmx LabVIEW is very powerful when it comes to creating DAQ applications. LabVIEW includes a set of VIs that let you configure, acquire data from, and send data to DAQ devices. Often, one device can perform a variety of functions, such as analog-to-digital (A/D) conversion, digital-to-analog (D/A) conversion, digital I/O, and counter/timer operations. Each device supports different DAQ and signal generation speeds. Also, each DAQ device is designed for specific hardware, platforms and operating systems. National Instruments, the inventor of LabVIEW, also make DAQ devices, so the integration with the DAQ devices from NI and the LabVIEW software is seamless and makes it easy to do I/O operations from the LabVIEW environment. 2.1 INTRODUCTION TO DAQ - DATA ACQUISITION The purpose of data acquisition is to measure an electrical or physical phenomenon such as voltage, current, temperature, pressure, or sound. PC-based data acquisition uses a combination of modular hardware, application software, and a computer to take measurements. While each data acquisition system is defined by its application requirements, every system shares a common goal of acquiring, analyzing, and presenting information. Data acquisition systems incorporate signals, sensors, actuators, signal conditioning, data acquisition devices, and application software. So summing up, Data Acquisition is the process of: Acquiring signals from real-world phenomena Digitizing the signals Analyzing, presenting and saving the data The DAQ system has the following parts involved, see Figure: 3 4 Introduction to Data Acquisition The parts are: Physical input/output signals DAQ device/hardware Driver software Your software application (Application software) For an Introduction to Data Acquisition, see this webcast: http://zone.ni.com/wv/app/doc/p/id/wv-169 2.1.1 PHYSICAL INPUT/OUTPUT SIGNALS A physical input/output signal is typically a voltage or current signal. 2.1.2 DAQ DEVICE/HARDWARE DAQ hardware acts as the interface between the computer and the outside world. It primarily functions as a device that digitizes incoming analog signals so that the computer can interpret them A DAQ device (Data Acquisition Hardware) usually has these functions: Analog input Analog output Digital I/O Counter/timers We have different DAQ devices, such as: “Desktop DAQ devices” where you need to plug a PCI DAQ board into your computer. The software is running on a computer. “Portable DAQ devices” for connection to the USB port, Wi-Fi connections, etc. The software is running on a computer “Distributed DAQ devices” where the software is developed on your computer and then later downloaded to the distributed DAQ device. Tutorial: Data Acquisition in LabVIEW 5 Introduction to Data Acquisition 2.1.3 DRIVER SOFTWARE Driver software is the layer of software for easily communicating with the hardware. It forms the middle layer between the application software and the hardware. Driver software also prevents a programmer from having to do register-level programming or complicated commands in order to access the hardware functions. Driver software from National Instruments: NI-DAQmx NI-DAQmx Base The DAQ Assistant, included with NI-DAQmx, is a graphical, interactive guide for configuring, testing, and acquiring measurement data. With a single click, you can even generate code based on your configuration, making it easier and faster to develop complex operations. Because DAQ Assistant is completely menu-driven, you will make fewer programming errors and drastically decrease the time from setting up your DAQ system to taking your first measurement. NI-DAQmx Base offers a subset of NI-DAQmx functionality on Windows and Linux, Mac OS X, Windows Mobile and Windows CE. 2.1.4 YOUR SOFTWARE APPLICATION (APPLICATION SOFTWARE) Application software adds analysis and presentation capabilities to the driver software. Your software application normally does such tasks as: Real-time monitoring Data analysis Data logging Control algorithms Human machine interface (HMI) Tutorial: Data Acquisition in LabVIEW 6 Introduction to Data Acquisition In order to create your DAQ application you need a programming development tool, such as LabVIEW. 2.2 MAX – MEASUREMENT AND AUTOMATION EXPLORER Measurement & Automation Explorer (MAX) provides access to your National Instruments devices and systems. With MAX, you can: Configure your National Instruments hardware and software Create and edit channels, tasks, interfaces, scales, and virtual instruments Execute system diagnostics View devices and instruments connected to your system Update your National Instruments software In addition to the standard tools, MAX can expose item-specific tools you can use to configure, diagnose, or test your system, depending on which NI products you install. As you navigate through MAX, the contents of the application menu and toolbar change to reflect these new tools. Tutorial: Data Acquisition in LabVIEW 7 2.3 Introduction to Data Acquisition NI-DAQMX The NI-DAQmx Driver software is the layer of software for easily communicating with the hardware. It forms the middle layer between the application software and the hardware. Driver software also prevents a programmer from having to do register-level programming or complicated commands in order to access the hardware functions. The DAQmx palette in LabVIEW: 2.3.1 DAQ ASSISTANT The DAQ Assistant, included with NI-DAQmx, is a graphical, interactive guide for configuring, testing, and acquiring measurement data. With a single click, you can even generate code based on your configuration, making it easier and faster to develop complex operations. Because DAQ Assistant is completely menu-driven, Tutorial: Data Acquisition in LabVIEW 8 Introduction to Data Acquisition you will make fewer programming errors and drastically decrease the time from setting up your DAQ system to taking your first measurement. 2.4 NI USB-6008 NI USB-6008 is a simple and low-cost multifunction I/O device from National Instruments. The device has the following specifications: 8 analog inputs (12-bit, 10 kS/s) 2 analog outputs (12-bit, 150 S/s) 12 digital I/O USB connection, No extra power-supply neeeded Compatible with LabVIEW, LabWindows/CVI, and Measurement Studio for Visual Studio .NET NI-DAQmx driver software The NI USB-6008 is well suited for education purposes due to its small size and easy USB connection. Tutorial: Data Acquisition in LabVIEW 3 PHYSICAL INPUT/OUTPUT SIGNALS Data acquisition involves gathering signals from measurement sources and digitizing the signal for storage, analysis, and presentation on a PC. Data acquisition (DAQ) systems come in many different PC technology forms for great flexibility when choosing your system. Scientists and engineers can choose from PCI, PXI, PCI Express, PXI Express, PCMCIA, USB, Wireless and Ethernet data acquisition for test, measurement, and automation applications. There are five components to be considered when building a basic DAQ system Transducers and sensors Signals Signal conditioning DAQ hardware Driver and application software In this chapter we focus on Transducers, sensors and Signals. 3.1 TRANSDUCERS Data acquisition begins with the physical phenomenon to be measured. This physical phenomenon could be he temperature of a room, the intensity of a light source, the pressure inside a chamber, the force applied to an object, or many other things. An effective DAQ system can measure all of these different phenomena. A transducer is a device that converts a physical phenomenon into a measurable electrical signal, such as voltage or current. The ability of a DAQ system to measure different phenomena depends on the transducers to convert the physical phenomena into signals measurable by the DAQ hardware. Transducers are synonymous with sensors in DAQ systems. There are specific transducers for many different applications, such as measuring temperature, pressure, or fluid flow. Below we see some common phenomena and the transducers used to measure them. Phenomenon Transducer Temperature Thermocouple, RTD, Thermistor Light Photo Sensor Sound Microphone Force and Pressure Strain Gage, Piezoelectric Transducer Position and Displacement Potentiometer, LVDT, Optical Encoder Acceleration Accelerometer pH pH Electrode Different transducers have different requirements for converting phenomena into a measurable signal. Some transducers may require excitation in the form of voltage or current. Other transducers may require additional components and even resistive networks to produce a signal. 9 10 Physical input/output signals Refer to ni.com/sensors for more information on transducers. 3.2 SIGNALS The appropriate transducers convert physical phenomena into measurable signals. However, different signals need to be measured in different ways. For this reason, it is important to understand the different types of signals and their corresponding attributes. Signals can be categorized into two groups: Analog Digital 3.2.1 ANALOG SIGNALS 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, and Dynamic Signal Acquisition (DSA) devices. An analog signal can be at any value with respect to time. A few examples of analog signals include voltage, temperature, pressure, sound, and load. The three primary characteristics of an analog signal is: Level Shape Frequency Tutorial: Data Acquisition in LabVIEW 11 Physical input/output signals Level Because analog signals can take on any value, the level gives vital information about the measured analog signal. The intensity of a light source, the temperature in a room, and the pressure inside a chamber are all examples that demonstrate the importance of the level of a signal. When measuring the level of a signal, the signal generally does not change quickly with respect to time. The accuracy of the measurement, however, is very important. A DAQ system that yields maximum accuracy should be chosen to aid in analog level measurements. Shape Some signals are named after their specific shape - sine, square, sawtooth, and triangle. The shape of an analog signal can be as important as the level, because by measuring the shape of an analog signal, you can further analyze the signal, including peak values, DC values, and slope. Signals where shape is of interest generally change rapidly with respect to time, but system accuracy is still important. The analysis of heartbeats, video signals, sounds, vibrations, and circuit responses are some applications involving shape measurements. Frequency All analog signals can be categorized by their frequency. Unlike the level or shape of the signal, frequency cannot be directly measured. The signal must be analyzed using software to determine the frequency information. This analysis is usually done using an algorithm known as the Fourier transform. When frequency is the most important piece of information, it is important to consider including both accuracy and acquisition speed. Although the acquisition speed for acquiring the frequency of a signal is less than the speed required for obtaining the shape of a signal, the signal must still be acquired fast enough that the pertinent information is not lost while the analog signal is being acquired. The condition that stipulates this speed is known as the Nyquist Sampling Theorem. Speech analysis, telecommunication, and earthquake analysis are some examples of common applications where the frequency of the signal must be known. 3.3 DIGITAL SIGNALS A digital signal cannot take on any value with respect to time. Instead, a digital signal has two possible levels: high and low. Digital signals generally conform to certain specifications that define characteristics of the signal. Digital signals are commonly referred to as transistor-to-transistor logic (TTL). TTL specifications indicate a Tutorial: Data Acquisition in LabVIEW 12 Physical input/output signals digital signal to be low when the level falls within 0 to 0.8 V, and the signal is high between 2 to 5 V. The useful information that can be measured from a digital signal includes the state and the rate. State Digital signals cannot take on any value with respect to time. The state of a digital signal is essentially the level of the signal - on or off, high or low. Monitoring the state of a switch - open or closed - is a common application showing the importance of knowing the state of a digital signal. Rate The rate of a digital signal defines how the digital signal changes state with respect to time. An example of measuring the rate of a digital signal includes determining how fast a motor shaft spins. Unlike frequency, the rate of a digital signal measures how often a portion of a signal occurs. A software algorithm is not required to determine the rate of a signal Tutorial: Data Acquisition in LabVIEW 4 MAX Measurement & Automation Explorer (MAX) provides access to your National Instruments devices and systems. With MAX, you can: Configure your National Instruments hardware and software Create and edit channels, tasks, interfaces, scales, and virtual instruments Execute system diagnostics View devices and instruments connected to your system Update your National Instruments software In addition to the standard tools, MAX can expose item-specific tools you can use to configure, diagnose, or test your system, depending on which NI products you install. As you navigate through MAX, the contents of the application menu and toolbar change to reflect these new tools. LabVIEW installs MAX to establish all devices and channel configuration parameters. MAX reads the information the Device Manager records in the Windows Registry and assigns a logical device number to each DAQ device. You use the device number to refer to the device in LabVIEW. You can access MAX by selecting Tools»Measurement & Automation Explorer in LabVIEW. This displays the primary MAX window. 13 14 MAX Before using a data acquisition board, you must confirm that the software can communicate with the board by configuring the devices. For Windows, the Windows Configuration Manager keeps track of all the hardware installed in the computer, including National Instruments DAQ devices. The Windows Configuration Manager automatically detects and configures Plug & Play (PnP) devices. Windows Configuration Manager If you have a 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 Control Panel. You can verify the Windows Configuration by accessing the Device Manager. Tutorial: Data Acquisition in LabVIEW 5 NI-DAQMX Driver software is the layer of software for easily communicating with the hardware. It forms the middle layer between the application software and the hardware. Driver software also prevents a programmer from having to do register-level programming or complicated commands in order to access the hardware functions. Driver software from National Instruments: NI-DAQmx NI-DAQmx Base The DAQ Assistant, included with NI-DAQmx, is a graphical, interactive guide for configuring, testing, and acquiring measurement data. With a single click, you can even generate code based on your configuration, making it easier and faster to develop complex operations. Because DAQ Assistant is completely menu-driven, you will make fewer programming errors and drastically decrease the time from setting up your DAQ system to taking your first measurement. NI-DAQmx Base offers a subset of NI-DAQmx functionality on Windows and Linux, Mac OS X, Windows Mobile and Windows CE. National Instruments DAQ boards have a driver engine that communicates between the board and the application software. There are two driver engines, NI-DAQmx and Traditional NI-DAQ. You can also use the DAQ Assistant, an Express VI that communicates with NI-DAQmx, in LabVIEW to communicate with the DAQ board. In addition, National Instruments provides Measurement & Automation Explorer (MAX) for configuring DAQ boards. The NI-DAQmx Driver software is the layer of software for easily communicating with the hardware. It forms the middle layer between the application software and the hardware. Driver software also prevents a programmer from having to do register-level programming or complicated commands in order to access the hardware functions. The DAQmx palette in LabVIEW: 15 16 NI-DAQmx 5.1.1 DAQ ASSISTANT The DAQ Assistant, included with NI-DAQmx, is a graphical, interactive guide for configuring, testing, and acquiring measurement data. With a single click, you can even generate code based on your configuration, making it easier and faster to develop complex operations. Because DAQ Assistant is completely menu-driven, you will make fewer programming errors and drastically decrease the time from setting up your DAQ system to taking your first measurement. Scales You can configure custom scales for your measurements using MAX. 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, you can 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. Using Task Timing When performing analog input, the task can be timed to: Acquire 1 Sample Acquire n Samples Acquire Continuosly Performing Task Triggering When a device controlled by NI-DAQmx does something, it performs an action. Two very common actions are producing a sample and starting a generation. Every NI-DAQmx action needs a stimulus or cause. When the stimulus occurs, the action is performed. Causes for actions are called triggers. A start trigger starts the generation. 5.2 SIMULATING A DAQ DEVICE You can create NI-DAQmx simulated devices in NI-DAQmx 7.4 or later. Using NI-DAQmx simulated devices: Tutorial: Data Acquisition in LabVIEW 17 NI-DAQmx You can try NI products in your application without the hardware. Later, when you acquire the hardware, you can import the NI-DAQmx simulated device configuration to the physical device using the MAX Portable Configuration Wizard. You can work on your applications on a portable system and upon returning to the original system, you can easily import your application work. Creating NI-DAQmx Simulated Devices To create an NI-DAQmx simulated device, right-click Devices and Interfaces and select Create New. The Create New dialog box prompts you to select a device to add. Select NI-DAQmx Simulated Device and click Finish. In the Choose Device dialog box, select the family of devices for the device you want to simulate. Select the device and click OK. If you select a PXI device, you are prompted to select a chassis number and PXI slot number. If you select an SCXI chassis, the SCXI configuration panels open. Tutorial: Data Acquisition in LabVIEW 6 DAQ DEVICES DAQ hardware acts as the interface between the computer and the outside world. It primarily functions as a device that digitizes incoming analog signals so that the computer can interpret them A DAQ device (Data Acquisition Hardware) usually has these functions: Analog input Analog output Digital I/O Counter/timers We have different DAQ devices, such as: “Desktop DAQ devices” where you need to plug a PCI DAQ board into your computer. The software is running on a computer. “Portable DAQ devices” for connection to the USB port, Wi-Fi connections, etc. The software is running on a computer “Distributed DAQ devices” where the software is developed on your computer and then later downloaded to the distributed DAQ device. Most DAQ devices have four standard elements: analog input, analog output, digital I/O, and counters. The DAQ device transfers the measured signals to a computer through different bus structures. For example, you can plug a DAQ device into the PCI bus or the USB port of a computer or the Personal Computer Memory Card International Association (PCMCIA) socket of a laptop. You also can use PXI/CompactPCI to create a portable, versatile, and rugged measurement system. 18 19 6.1 DAQ Devices PERFORMING ANALOG-TO-DIGITAL CONVERSION Analog-to-digital conversion is a process of acquiring and translating signals 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, measures and converts it into a digital value. The ADC obtains and approximates the signal with fixed precision and converts it into a series of digital values. 6.2 PERFORMING DIGITAL-TO-ANALOG CONVERSION Digital-to-analog conversion is the opposite of analog-to-digital conversion. In digital-to-analog conversion, the computer generates the data. 6.3 USING COUNTERS A counter is a digital timing device. You typically use counters for event counting, frequency measurement, period measurement, position measurement, and pulse generation. 6.4 USING DIGITAL I/O Digital signals are electrical signals that transfer digital data over a wire. These signals typically have only two states: on 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 users: Digital signals control or measure digital devices such as switches or LEDs Tutorial: Data Acquisition in LabVIEW 7 NI USB 6008 NI USB-6008 is a simple and low-cost multifunction I/O device from National Instruments. The device has the following specifications: 8 analog inputs (12-bit, 10 kS/s) 2 analog outputs (12-bit, 150 S/s) 12 digital I/O USB connection, No extra power-supply neeeded Compatible with LabVIEW, LabWindows/CVI, and Measurement Studio for Visual Studio .NET NI-DAQmx driver software The NI USB-6008 is well suited for education purposes due to its small size and easy USB connection. 7.1 CONNECT NI USB-6008 TO THE PC Configuring and testing: USB-6008 can be configured and tested using MAX (Measurement and Automation Explorer), which is installed with the NI-DAQmx Driver Software. The first time you connect the USB-6008 to the PC, the Windows Hardware Installer Wizard will open. The wizard searches the PC for the necessary driver software for the USB-6008. This driver software was installed along with the installation of the NI-DAQ software. When the wizard has finished the installation of the driver software, the USB-6008 is ready for use. 7.1.1 TESTING THE USB-6008 IN MAX Before you start to use the USB-6008 in an application, you should test the device in the Measurement and Automation Explorer (MAX). 20 21 NI USB 6008 In the MAX window, expand the “Devices and Interfaces” node and then “NI DAQmx Devices”. Right-click on the NI USB-6008 device and select “Self-Test”. Hopefully the self-test passes without errors. Then, you should test the individual channels of the USB-6008 to check that the input signals are detected correctly by the USB-6008, and that the output signals generated by the USB-6009 have correct values. This I/O can be tested in several ways, depending on which channels you actually want to test. Tutorial: Data Acquisition in LabVIEW 22 NI USB 6008 We will perform a simple loopback test: Here, let us test analog output channel 0 (AO0) and the analog input channel 0 (AI0) to see if they work correctly. We will perform a very simple test, which is sufficient if we are to check that both AO0 and AI0 work correctly. The test procedure, which is denoted loopback, is to connect the AI0 channel to the AO0 channel. Then we generate some legal voltage at AO0. If AI0 detects the same voltage, we know that both AO0 and AI0 work. (We may then repeat this procedure for other channels.) If for some reason AI0 detects some other voltage than the value we set for AO0, then there is an error in either the AI0 channel or in the the AO0 channel, and further investigations are necessary. To prepare for the loopback test, we wire together AI0 and AO0. To see the terminals of the USB-6000, select “Device Pinouts” from the right-click menu. The Figure shows the AI0 and AO0 channels wired together. Tutorial: Data Acquisition in LabVIEW 23 NI USB 6008 To actually perform the loopback test, right-click on the NI USB-6008 device in MAX, and then select “Test Panels..” in order to open the Test Panels. In the Test Panels window, select the Analog Output tab. Tutorial: Data Acquisition in LabVIEW 24 NI USB 6008 Figure 11: The Voltage Output dialog window in the Test Panels window In the Analog Output tab, select any voltage between 0V and 5V. Next, click the Analog Input tab in the Test Panels window. Tutorial: Data Acquisition in LabVIEW 25 NI USB 6008 The Analog Input tab should indicate the same (or almost the same) voltage as is set out on AO0. There may be a small difference between the values due to the limited resolution in the DA-converter (digital-to-analog) and in the AD-converter (analog-to-digital). Tutorial: Data Acquisition in LabVIEW 26 7.2 NI USB 6008 USING NI USB-6008 IN LABVIEW In order to use the NI USB-6008 in LabVIEW you need to use the DAQmx functions, see Figure below. DAQmx – Data Acquisition palette: Tutorial: Data Acquisition in LabVIEW 27 7.3 NI USB 6008 DAQ ASSISTANT The easiest ways is to use the DAQ Assistant. 7.3.1 ANALOG INPUT When you drag the DAQ Assistant icon on your Block Diagram, the following window appears: Tutorial: Data Acquisition in LabVIEW 28 NI USB 6008 In this window you need to select either “Acquire Signals” (i.e., Input Signals) or “Generate Signals” (i.e., Output Signals). Select Acquire Signals → Analog Input → Voltage. In the next window you select which Analog Input you want to use. Select ai0 (Analog Input channel 0) and click Finish. Tutorial: Data Acquisition in LabVIEW 29 NI USB 6008 The following window appears: Tutorial: Data Acquisition in LabVIEW 30 NI USB 6008 In the Timing Settings Select “1 Sample (On Demand)”. Tutorial: Data Acquisition in LabVIEW 31 NI USB 6008 The next step is to select the Signal Input Range. A common signal is 0-5V. You may also rename the name of the channel (right-click on the name): Tutorial: Data Acquisition in LabVIEW 32 NI USB 6008 You are now finished with the configuration. Click OK in the DAQ Assistant window The DAQ Assistant icon appears on the Block Diagram: Example: Tutorial: Data Acquisition in LabVIEW 33 NI USB 6008 Wire the data output to a numeric indicator like this (and hit the Run button): Then numeric indicator will show, e.g., the following value: Example: If you want a continuous acquisition, put a While loop around the DAQ Assistant like this: However you should not use the DAQ Assistant inside a loop because of the lack of performance. The following is therefore better: Tutorial: Data Acquisition in LabVIEW 34 NI USB 6008 In this example we have put the DAQ Assistant outside the While loop. Inside the loop we have used the DAQmx Read.vi in order to read the value from the ai0 channel. You should also use the “DAQmx Start Task.vi” and the “DAQmx Clear Task.vi”. 7.3.2 ANALOG OUTPUT Analog Output is similar. Tutorial: Data Acquisition in LabVIEW 35 NI USB 6008 Tutorial: Data Acquisition in LabVIEW 36 NI USB 6008 Example: Or inside a loop: Or better, put the DAQ Assistant outside the While loop: Tutorial: Data Acquisition in LabVIEW 8 WHATS NEXT? 8.1 MY BLOG For more information about LabVIEW, visit my Blog: http://home.hit.no/~hansha/ 8.2 TRAINING This Training is a part of a series with other Training Kits I have made, such as: Introduction to LabVIEW Data Acquisition in LabVIEW Control and Simulation in LabVIEW LabVIEW MathScript Linear Algebra in LabVIEW Datalogging and Supervisory Control in LabVIEW Wireless Data Acquisition in LabVIEW Intermediate Topics in LabVIEW Advanced Topics in LabVIEW These Training Kits are available for download from my blog: http://home.hit.no/~hansha 8.3 ADDITIONAL RESOURCES www.ni.com 8.4 EXAMPLES In the NI example Finder (Help→Find Examples…) you find lots of useful examples that you can play with or use as a start when creating your own applications. 37 38 8.5 Whats Next? DOCUMENTATION As part of the LabVIEW installation there comes a lots of useful documentation. 8.6 LABVIEW WIKI LabVIEW Wiki is the free LabVIEW information resource that anyone can edit. http://labviewwiki.org/Home Tutorial: Data Acquisition in LabVIEW 39 8.7 Whats Next? LABVIEW ON YOUTUBE There are lots of LabVIEW videos available at YouTube: http://www.youtube.com/results?search_query=labview&search=Search Tutorial: Data Acquisition in LabVIEW QUICK REFERENCE 40 41 Quick Reference Tutorial: Data Acquisition in LabVIEW Telemark University College Faculty of Technology Kjølnes Ring 56 N-3914 Porsgrunn, Norway www.hit.no Hans-Petter Halvorsen, M.Sc. Telemark University College Department of Electrical Engineering, Information Technology and Cybernetics Phone: +47 3557 5158 E-mail: hans.p.halvorsen@hit.no Blog: http://home.hit.no/~hansha/ Room: B-237a Telemark University College Department of Electrical Engineering, Information Technology and Cybernetics CONTROL AND SIMULATION IN LABVIEW HANS-PETTER HALVORSEN, 2010.02.09 Faculty of Technology, Postboks 203, Kjølnes ring 56, N-3901 Porsgrunn, Norway. Tel: +47 35 57 50 00 Fax: +47 35 57 54 01 PREFACE This document explains the basic concepts of using LabVIEW for Control and Simulation purposes. You should have some basic knowledge about LabVIEW, e.g., the training: “An Introduction to LabVIEW”. This document is available for download at http://home.hit.no/~hansha/. For more information about LabVIEW, visit my Blog: http://home.hit.no/~hansha/. INSTALLATION REQUIREMENTS NI LabVIEW Name Required LabVIEW Professional Development System Yes NI LabVIEW Core Components Name Required LabVIEW Control Design and Simulation Module Yes LabVIEW MathScript RT Module Yes NI Vision Development Module Vision Builder for Automated Inspection LabVIEW Digital Filter Design Toolkit LabVIEW Modulation Toolkit LabVIEW System Identification Toolkit Yes LabVIEW Desktop Execution Trace Toolkit LabVIEW Report Generation for Microsoft Office Toolkit LabVIEW Database Connectivity Toolkit LabVIEW Internet Toolkit NI LabVIEW SignalExpress LabVIEW Basics 1 and 2 Computer Based Training Extended Development Suite Components Name Required LabWindows/CVI Full Development System LabWindows/CVI Real-Time Module LabWindows/CVI PID Control Toolkit LabWindows/CVI Signal Processing Toolkit LabWindows/CVI Spectral Measurements Toolkit and Run-time Engine LabWindows/CVI SQL Toolkit Measurement Studio Enterprise Edition iii DIAdem Professional Control and Embedded Systems Option Components Name Required LabVIEW FPGA Module LabVIEW Real-Time Module LabVIEW Statechart Module LabVIEW Mobile Module LabVIEW Datalogging and Supervisory Control Module LabVIEW PID and Fuzzy Logic Toolkit Yes NI Real-Time Execution Trace Toolkit LabVIEW Simulation Interface Toolkit (Yes) NI Motion Assistant NI-DAQ Base Signal processing and Communications Option Components Name Required LabVIEW FPGA Module LabVIEW Sound and Vibration Measurement Suite LabVIEW Spectral Measurement Toolkit LabVIEW Advanced Signal Processing Toolkit LabVIEW Adaptive Filter Toolkit NI Device Drivers Name Required FieldPoint NI-DAQmx Yes NI LabVIEW SignalExpress NI Instrument I/O Assistant NI-IMAQ NI Measurement & Automation Explorer NI PXI Yes NI-VISA Yes TABLE OF CONTENTS Preface .................................................................................................................................................................... 2 Installation Requirements ....................................................................................................................................... iii Table of Contents .................................................................................................................................................... vi 1 Introduction to LabVIEW ............................................................................................................................... 1 1.1 Dataflow programming.......................................................................................................................... 1 1.2 Graphical programming ......................................................................................................................... 1 1.3 Benefits .................................................................................................................................................. 2 2 Introduction to Control and Simulation ........................................................................................................ 3 3 Introduction to Control and Simulation in LabVIEW ..................................................................................... 4 3.1 3.1.1 Simulation ..................................................................................................................................... 4 3.1.2 Control Design .............................................................................................................................. 5 3.2 4 LabVIEW Control Design and Simulation Module ................................................................................. 4 LabVIEW PID and Fuzzy Logic Toolkit .................................................................................................... 6 3.2.1 PID Control .................................................................................................................................... 6 3.2.2 Fuzzy Logic .................................................................................................................................... 6 3.3 LabVIEW System Identification Toolkit .................................................................................................. 6 3.4 LabVIEW Simulation Interface Toolkit ................................................................................................... 7 Simulation ...................................................................................................................................................... 8 4.1 Simulation in LabvIEW ........................................................................................................................... 8 4.2 Simulation Subsystem ......................................................................................................................... 12 4.3 Continuous Linear Systems .................................................................................................................. 13 Exercises ........................................................................................................................................................... 18 5 6 PID Control................................................................................................................................................... 29 5.1 PID Control in LabVIEW ....................................................................................................................... 30 5.2 Auto-tuning.......................................................................................................................................... 30 Control Design ............................................................................................................................................. 32 vi vii Table of Contents 6.1 7 System Identification ................................................................................................................................... 33 7.1 8 10 System Identification in LabVIEW ........................................................................................................ 33 Fuzzy Logic ................................................................................................................................................... 34 8.1 9 Control Design in LabVIEW .................................................................................................................. 32 Fuzzy Logic in LabVIEW ........................................................................................................................ 34 LabVIEW MathScript .................................................................................................................................... 35 9.1 Help...................................................................................................................................................... 36 9.2 Examples .............................................................................................................................................. 36 9.3 Useful commands ................................................................................................................................ 39 9.4 Plotting ................................................................................................................................................ 39 Whats next? ................................................................................................................................................. 41 10.1 My Blog ................................................................................................................................................ 41 10.2 Training ................................................................................................................................................ 41 10.3 Additional Resources ........................................................................................................................... 41 10.4 Examples .............................................................................................................................................. 41 10.5 Documentation .................................................................................................................................... 42 10.6 LabVIEW Wiki....................................................................................................................................... 42 10.7 lABview ON yOUtUBE .......................................................................................................................... 43 Quick Reference .................................................................................................................................................... 44 Tutorial: Control and Simulation in LabVIEW 1 INTRODUCTION TO LABVIEW LabVIEW (short for Laboratory Virtual Instrumentation Engineering Workbench) is a platform and development environment for a visual programming language from National Instruments. The graphical language is named "G". Originally released for the Apple Macintosh in 1986, LabVIEW is commonly used for data acquisition, instrument control, and industrial automation on a variety of platforms including Microsoft Windows, various flavors of UNIX, Linux, and Mac OS X. The latest version of LabVIEW is version LabVIEW 2009, released in August 2009. Visit National Instruments at www.ni.com. The code files have the extension “.vi”, which is a abbreviation for “Virtual Instrument”. LabVIEW offers lots of additional Add-Ons and Toolkits. This paper is part of a series with LabVIEW Tutorials: Introduction to LabVIEW Linear Algebra in LabVIEW Data Acquisition and Instrument Control in LabVIEW Control Design and Simulation in LabVIEW Signal Processing in LabVIEW Datalogging and Supervisory Control in LabVIEW System identification in LabVIEW Model based Control in LabVIEW Advanced Topics in LabVIEW Etc. Each tutorial may be used independently of each other. 1.1 DATAFLOW PROGRAMMING The programming language used in LabVIEW, also referred to as G, is a dataflow programming language. Execution is determined by the structure of a graphical block diagram (the LV-source code) on which the programmer connects different function-nodes by drawing wires. These wires propagate variables and any node can execute as soon as all its input data become available. Since this might be the case for multiple nodes simultaneously, G is inherently capable of parallel execution. Multi-processing and multi-threading hardware is automatically exploited by the built-in scheduler, which multiplexes multiple OS threads over the nodes ready for execution. 1.2 GRAPHICAL PROGRAMMING LabVIEW ties the creation of user interfaces (called front panels) into the development cycle. LabVIEW programs/subroutines are called virtual instruments (VIs). Each VI has three components: a block diagram, a front panel, and a connector panel. The last is used to represent the VI in the block diagrams of other, calling VIs. Controls and indicators on the front panel allow an operator to input data into or extract data from a running virtual instrument. However, the front panel can also serve as a programmatic interface. Thus a virtual instrument can either be run as a program, with the front panel serving as a user interface, or, when dropped as a node onto the block diagram, the front panel defines the inputs and outputs for the given node through the connector pane. This implies each VI can be easily tested before being embedded as a subroutine into a larger program. 1 2 Introduction to LabVIEW The graphical approach also allows non-programmers to build programs simply by dragging and dropping virtual representations of lab equipment with which they are already familiar. The LabVIEW programming environment, with the included examples and the documentation, makes it simple to create small applications. This is a benefit on one side, but there is also a certain danger of underestimating the expertise needed for good quality "G" programming. For complex algorithms or large-scale code, it is important that the programmer possess an extensive knowledge of the special LabVIEW syntax and the topology of its memory management. The most advanced LabVIEW development systems offer the possibility of building stand-alone applications. Furthermore, it is possible to create distributed applications, which communicate by a client/server scheme, and are therefore easier to implement due to the inherently parallel nature of G-code. 1.3 BENEFITS One benefit of LabVIEW over other development environments is the extensive support for accessing instrumentation hardware. Drivers and abstraction layers for many different types of instruments and buses are included or are available for inclusion. These present themselves as graphical nodes. The abstraction layers offer standard software interfaces to communicate with hardware devices. The provided driver interfaces save program development time. The sales pitch of National Instruments is, therefore, that even people with limited coding experience can write programs and deploy test solutions in a reduced time frame when compared to more conventional or competing systems. A new hardware driver topology (DAQmxBase), which consists mainly of G-coded components with only a few register calls through NI Measurement Hardware DDK (Driver Development Kit) functions, provides platform independent hardware access to numerous data acquisition and instrumentation devices. The DAQmxBase driver is available for LabVIEW on Windows, Mac OS X and Linux platforms. Tutorial: Control and Simulation in LabVIEW 2 INTRODUCTION TO CONTROL AND SIMULATION Control design is a process that involves developing mathematical models that describe a physical system, analyzing the models to learn about their dynamic characteristics, and creating a controller to achieve certain dynamic characteristics. Simulation is a process that involves using software to recreate and analyze the behavior of dynamic systems. You use the simulation process to lower product development costs by accelerating product development. You also use the simulation process to provide insight into the behavior of dynamic systems you cannot replicate conveniently in the laboratory. Below we see a closed-loop feedback control system: 3 3 INTRODUCTION TO CONTROL AND SIMULATION IN LABVIEW LabVIEW has several additional modules and Toolkits for Control and Simulation purposes, e.g., “LabVIEW Control Design and Simulation Module”, “LabVIEW PID and Fuzzy Logic Toolkit”, “LabVIEW System Identification Toolkit” and “LabVIEW Simulation Interface Toolkit”. LabVIEW MathScript is also useful for Control Design and Simulation. LabVIEW Control Design and Simulation Module LabVIEW PID and Fuzzy Logic Toolkit LabVIEW System Identification Toolkit LabVIEW Simulation Interface Toolkit This tutorial will focus on the main aspects in these modules and toolkits. All VIs related to these modules and toolkits are placed in the Control Design and Simulation Toolkit: 3.1 LABVIEW CONTROL DESIGN AND SIMULATION MODULE With LabVIEW Control Design and Simulation Module you can construct plant and control models using transfer function, state-space, or zero-pole-gain. Analyze system performance with tools such as step response, pole-zero maps, and Bode plots. Simulate linear, nonlinear, and discrete systems with a wide option of solvers. With the NI LabVIEW Control Design and Simulation Module, you can analyze open-loop model behavior, design closed-loop controllers, simulate online and offline systems, and conduct physical implementations. 3.1.1 SIMULATION The Simulation palette in LabVIEW: 4 5 Introduction to Control and Simulation in LabVIEW The main features in the Simulation palette are: Control and Simulation Loop - You must place all Simulation functions within a Control & Simulation Loop or in a simulation subsystem. Continuous Linear Systems Functions - Use the Continuous Linear Systems functions to represent continuous linear systems of differential equations on the simulation diagram. Signal Arithmetic Functions - Use the Signal Arithmetic functions to perform basic arithmetic operations on signals in a simulation system. 3.1.2 CONTROL DESIGN The Control Design palette in LabVIEW: Tutorial: Control and Simulation in LabVIEW 6 3.2 Introduction to Control and Simulation in LabVIEW LABVIEW PID AND FUZZY LOGIC TOOLKIT The NI LabVIEW PID and Fuzzy Logic Toolkit add control algorithms to LabVIEW. By combining the PID and fuzzy logic control functions in this toolkit with the math and logic functions in LabVIEW software, you can quickly develop programs for automated control. You may integrate these control tools with the power of data acquisition. 3.2.1 PID CONTROL The PID palette in LabVIEW: 3.2.2 FUZZY LOGIC The Fuzzy Logic palette in LabVIEW: 3.3 LABVIEW SYSTEM IDENTIFICATION TOOLKIT The “LabVIEW System Identification Toolkit” combines data acquisition tools with system identification algorithms for plant modeling. You can use the LabVIEW System Identification Toolkit to find empirical models from real plant stimulus-response information. The System Identification palette in LabVIEW: Tutorial: Control and Simulation in LabVIEW 7 3.4 Introduction to Control and Simulation in LabVIEW LABVIEW SIMULATION INTERFACE TOOLKIT The “LabVIEW Simulation Interface Toolkit” gives control system design and test engineers a link between the LabVIEW graphical development environment and Simulink software from The MathWorks. With the LabVIEW Simulation Interface Toolkit, you can easily build custom LabVIEW user interfaces to view and control your simulation model during run time. The “LabVIEW Simulation Interface Toolkit” will not be further investigated in this training. Tutorial: Control and Simulation in LabVIEW 4 SIMULATION Simulation is a process that involves using software to recreate and analyze the behavior of dynamic systems. You use the simulation process to lower product development costs by accelerating product development. You also use the simulation process to provide insight into the behavior of dynamic systems you cannot replicate conveniently in the laboratory. For example, simulating a jet engine saves time, labor, and money compared to building, testing, and rebuilding an actual jet engine. You can use the LabVIEW Control Design and Simulation Module to simulate a dynamic system or a component of a dynamic system. For example, you can simulate only the plant while using hardware for the controller, actuators, and sensors (Hardware-in-the-loop Simulation). A dynamic system model is a differential or difference equation that describes the behavior of the dynamic system. 4.1 SIMULATION IN LABVIEW Use the Simulation VIs and functions to create simulation applications in LabVIEW. In the Control Design & Simulation palette we have the Simulation Sub palette: Below we see the Simulation Sub palette: 8 9 Simulation Note! All the “Blocks” in the Simulation palette are not SubVIs, i.e., we cannot double-click on them and open the Block Diagram because they have none. All the Blocks in the Simulation palette must be used inside the Control and Simulation Loop (explained below). Control and Simulation Loop: In the “Simulation” Sub palette we have the “Control and Simulation Loop” which is very useful in simulations: You must place all Simulation functions within a Control & Simulation Loop or in a simulation subsystem. You also can place simulation subsystems within a Control & Simulation Loop or another simulation subsystem, or you can place simulation subsystems on a block diagram outside a Control & Simulation Loop or run the simulation subsystems as stand-alone VIs. Tutorial: Control and Simulation in LabVIEW 10 Simulation The Control & Simulation Loop has an Input Node (upper left corner) and an Output Node (upper right corner). Use the Input Node to configure simulation parameters programmatically. You also can configure these parameters interactively using the Configure Simulation Parameters dialog box. Access this dialog box by double-clicking the Input Node or by right-clicking the border and selecting Configure Simulation Parameters from the shortcut menu. Configuration: When you place these blocks on the diagram you may double-click or right-click and then select “Configuration…” Example: Configuration Dialog box For the “Transfer Function” (Simulation → Continuous Linear Systems) block we have the following Configuration window: All the different blocks have their own different Configuration window. In the Parameter source you may select between: Configuration Dialog Box Terminal If you select “Configuration Dialog Box” you enter the configuration in the Configuration window like we see above, while if you select “Terminal” that specific configuration is set from the Block Diagram like this: Tutorial: Control and Simulation in LabVIEW 11 Simulation Icon Style: When you place the block on the block diagram you may select how that should appear. Right-click on the block/icon and select “Icon Style”: Example: Icon Style For the “Transfer Function” (Simulation → Continuous Linear Systems) block we have the following different icon styles: Static: Dynamic: Text Only: Express: Tutorial: Control and Simulation in LabVIEW 12 Simulation We see for the Dynamic and Express styles that the appearance changes according to configuration parameters we set. I personally prefer the “static” icon style because it does not require lots of space on the diagram. 4.2 SIMULATION SUBSYSTEM You may create a Simulation Subsystem (File → New…): The Simulation Subsystem is very useful when dealing with larger simulation systems in order to create a more structured code. I recommend that you (always) use this feature. The Simulation Subsystem is almost equal to a normal LabVIEW Block Diagram but notice the background color is slightly darker. Note! In order to open the Simulation Subsystem, right-click and select “Open Subsystem”. The Simulation Subsystem may also be represented by different icons. If you select “dynamic” icon style, you will see a “miniature” version of the subsystem like this: Tutorial: Control and Simulation in LabVIEW 13 Simulation You may drag in the corner in order to increase or decrease the dynamic icon. If you select “static” icon style you see the icon you created with the Icon Editor. Like this: 4.3 CONTINUOUS LINEAR SYSTEMS In the “Continuous Linear Systems” Sub palette we want to create a simulation model: The most used blocks probably are Integrator, Transport Delay, State-Space and Transfer Function. When you place these blocks on the diagram you may double-click or right-click and then select “Configuration…” Tutorial: Control and Simulation in LabVIEW 14 Simulation Integrator - Integrates a continuous input signal using the ordinary differential equation (ODE) solver you specify for the simulation. The Configuration window for the Integrator block looks like this: Transport Delay - Delays the input signal by the amount of time you specify. The Configuration window for the Transport Delay block looks like this: Transfer Function - Implements a system model in transfer function form. You define the system model by specifying the Numerator and Denominator of the transfer function equation. The Configuration window for the Transfer Function block looks like this: Tutorial: Control and Simulation in LabVIEW 15 Simulation State-Space - Implements a system model in state-space form. You define the system model by specifying the input, output, state, and direct transmission matrices. The Configuration window for the State-Space block looks like this: Signal Arithmetic: The “Signal Arithmetic” Sub palette is also useful when creating a simulation model: Tutorial: Control and Simulation in LabVIEW 16 Simulation Example: Simulation Model Below we see an example of a simulation model created in LabVIEW. Example: Simulation Below we see an example of a simulation model using the Control and Simulation Loop. Tutorial: Control and Simulation in LabVIEW 17 Simulation Notice the following: Click on the border of the simulation loop and select “Configure Simulation Parameters…” The following window appears (Configure Simulation Parameters): In this window you set some Parameters regarding the simulation, some important are: Final Time (s) – set how long the simulation should last. For an infinite time set “Inf”. Tutorial: Control and Simulation in LabVIEW 18 Simulation Enable Synchronized Timing - Specifies that you want to synchronize the timing of the Control & Simulation Loop to a timing source. To enable synchronization, place a checkmark in this checkbox and then choose a timing source from the Source type list box. Click the Help button for more details. You may also set some of these Parameters in the Block Diagram: You may use the mouse to increase the numbers of Parameters and right-click and select “Select Input”. EXERCISES Exercise: Simulation of a spring-mass damper system In this exercise you will construct a simulation diagram that represents the behavior of a dynamic system. You will simulate a spring-mass damper system. where t is the simulation time, F(t) is an external force applied to the system, c is the damping constant of the spring, k is the stiffness of the spring, m is a mass, and x(t) is the position of the mass. is the first derivative of the position, which equals the velocity of the mass. is the second derivative of the position, which equals the acceleration of the mass. The following figure shows this dynamic system. The goal is to view the position x(t) of the mass m with respect to time t. You can calculate the position by integrating the velocity of the mass. You can calculate the velocity by integrating the acceleration of the mass. Tutorial: Control and Simulation in LabVIEW 19 Simulation If you know the force and mass, you can calculate this acceleration by using Newton's Second Law of Motion, given by the following equation: Force = Mass × Acceleration Therefore, Acceleration = Force / Mass Substituting terms from the differential equation above yields the following equation: You will construct a simulation diagram that iterates the following steps over a period of time. Creating the Simulation Diagram You create a simulation diagram by placing a Control & Simulation Loop on the LabVIEW block diagram. 1. 2. 3. 4. 5. 6. Launch LabVIEW and select File»New VI to create a new, blank VI. Select Window»Show Block Diagram to view the block diagram. You also can press the <Ctrl-E> keys to view the block diagram. If you are not already viewing the Functions palette, select View»Functions Palette to display this palette. Select Control Design & Simulation»Simulation to view the Simulation palette. Click the Control & Simulation Loop icon. Move the cursor over the block diagram. Click to place the top left corner of the loop, drag the cursor diagonally to establish the size of the loop, and click again to place the loop on the block diagram. The simulation diagram is the area enclosed by the Control & Simulation Loop. Notice the simulation diagram has a pale yellow background to distinguish it from the rest of the block diagram. You can resize the Control & Simulation Loop by dragging its borders. Configuring Simulation Parameters The Control & Simulation Loop contains the parameters that define how the simulation executes. Complete the following steps to view and configure these simulation parameters. 1. 2. 3. 4. 5. Double-click the Input Node, attached to the left side of the Control & Simulation Loop, to display the Configure Simulation Parameters dialog box. You also can right-click the loop border and select Configure Simulation Parameters from the shortcut menu. Ensure the value of the Final Time (s) numeric control is 10, which specifies that this tutorial simulates ten seconds of time. Click the ODE Solver pull-down menu to view the list of ODE solvers the Control Design and Simulation Module includes. If the term (variable) appears next to an ODE solver, that solver has a variable step size. The other ODE solvers have a fixed step size. Ensure a checkmark is beside the default ODE solver Runge-Kutta 23 (variable). Because this ODE solver is a variable step-size solver, you can specify the Minimum Step Size (s) and Maximum Step Size (s) this ODE solver can take. Enter 0.01 in the Maximum Step Size (s) numeric control to limit the size of the time step this ODE solver can take. Click the Timing Parameters tab to access parameters that control how often the simulation executes. Tutorial: Control and Simulation in LabVIEW 20 Simulation 6. 7. Ensure the Synchronize Loop to Timing Source checkbox does not contain a checkmark. This option specifies that the simulation executes without any timing restrictions. Use this option when you want the simulation to run as fast as possible. If you are running this simulation in real-time, you can place a checkmark in this checkbox and configure how often the simulation executes. Click the OK button to save changes and return to the simulation diagram. Building the Simulation The next step is to build the simulation by placing Simulation functions on the simulation diagram and wiring these functions together. Note that you can place most Simulation functions only on the simulation diagram, that is, you cannot place Simulation functions on a LabVIEW block diagram. Complete the following steps to build the simulation of this dynamic system. Placing Functions on the Simulation Diagram 1. 2. Open the Simulation palette. Select the Signal Arithmetic palette and place a Multiplication function on the simulation diagram. You will use this function to divide the force by the mass to calculate the acceleration. 3. Double-click the Multiplication function to display the Multiplication Configuration dialog box. You can double-click most Simulation functions to view and change the parameters of that function. 4. The function currently displays two × symbols on the left side of the dialog box. This setting specifies that both incoming signals are multiplied together. Click the bottom × symbol to change it to a ÷ symbol. This Multiplication function now divides the top signal by the bottom signal. 5. Click the OK button to save changes and return to the simulation diagram. 6. Right-click the Multiplication function and select Visible Items»Label from the shortcut menu. Double-click the Multiplication label and enter Calculate Acceleration as the new label. 7. Return to the Simulation palette and select the Continuous Linear Systems palette. 8. Place an Integrator function on the simulation diagram. You will use this function to calculate velocity by integrating acceleration. 9. Label this Integrator function Calculate Velocity. 10. Press the <Ctrl> key and click and drag the Integrator function to another location on the simulation diagram. This action creates a copy of the Integrator function, which you will use to calculate position by integrating velocity. Label this new Integrator function Calculate Position. 11. Select the Graph Utilities palette and place two SimTime Waveform functions on the simulation diagram. You will use these functions to view the results of the simulation over time. 12. Each SimTime Waveform function has an associated Waveform Chart. Label the first waveform chart Velocity and the second waveform chart Position. 13. Arrange the functions to look like the following simulation diagram. 14. Save this VI by selecting File»Save. Save this VI to a convenient location as “Spring-Mass Damper Example.vi”. The Block Diagram should now look like this: Tutorial: Control and Simulation in LabVIEW 21 Simulation Wiring the Simulation Functions Together The next step is wiring the functions together to represent the flow of data from one function to another. Note! Wires on the simulation diagram include arrows that show the direction of the dataflow, whereas wires on a LabVIEW block diagram do not show these arrows. Complete the following steps to wire these functions together. 1. 2. 3. 4. 5. 6. 7. 8. Right-click the Operand1 input of the Calculate Acceleration function and select Create»Control from the shortcut menu to add a numeric control to the front panel window. Label this control Force. Double-click this control on the simulation diagram. LabVIEW displays the front panel and highlights the Force control. Display the block diagram and create a control for the Operand2 input of the Calculate Acceleration function. Label this new control Mass. Wire the Result output of the Calculate Acceleration function to the input input of the Calculate Velocity function. Wire the output output of the Calculate Velocity function to the input input of the Calculate Position function. Right-click the wire you just created and select Create Wire Branch from the shortcut menu. Wire this branch to the Value input of the SimTime Waveform function that has the Velocity waveform chart. Wire the output output of the Calculate Position function to the Value input of the SimTime Waveform function that has the Position waveform chart. The Block Diagram should now look like this: Tutorial: Control and Simulation in LabVIEW 22 Simulation Running the Simulation You now can run this simulation to test that the data is flowing properly through the Simulation functions. Complete the following steps to run this simulation. 1. 2. 3. 4. 5. Select Window»Show Front Panel, or press <Ctrl-E>, to view the front panel of this simulation. The front panel displays the following objects: a control labeled Force, a control labeled Mass, a waveform chart labeled Velocity, and a waveform chart labeled Position. If necessary, rearrange these controls and indicators so that all objects are visible. Enter -9.8 in the Force numeric control. This value represents the force of gravity, 9.8 meters per second squared, acting on the dynamic system. Enter 1 in the Mass numeric control. This value represents a mass of one kilogram. Click the Run button, or press the <Ctrl-R> keys, to run the VI. The Front Panel should look like this: Tutorial: Control and Simulation in LabVIEW 23 Simulation In the Figure above notice that the force of gravity causes the mass position and velocity to constantly decrease. However, in the real world, a mass attached to a spring oscillates up and down. This simulated spring does not oscillate because the simulation diagram does not represent damping or stiffness. You must represent these factors to have a complete simulation of the dynamic system. Representing Damping and Stiffness Representing damping and stiffness involves feeding back the velocity and position, each multiplied by a different constant, to the input of the Calculate Acceleration function. Recall the following differential equation this VI simulates. In the previous equation, notice you multiply the damping constant c by the velocity of the mass . You multiply the stiffness constant k by the mass position x(t). You then subtract these quantities from the external force applied to the mass. Complete the following steps to represent damping and stiffness in this dynamic system model. 1. 2. View the simulation diagram. Select the Signal Arithmetic palette and place a Summation function on the simulation diagram. Move this function to the left of the Force and Mass controls. Tutorial: Control and Simulation in LabVIEW 24 Simulation 3. Double-click the Summation function to configure its operation. By default, the Summation function displays the following three input terminals: a Ø symbol, a + symbol, and a – symbol. This configuration subtracts one input signal from another. 4. Click the Ø symbol twice to change this terminal to the – symbol. This Summation function now subtracts the top and bottom input signals from the left input signal. 5. Click the OK button to save changes and return to the simulation diagram. 6. Select the Signal Arithmetic palette and place a Gain function on the simulation diagram. Move this function above the existing simulation diagram code but still within the Control & Simulation Loop. 7. The input of the Gain function is on the left side of the function, and the output is on the right side. You can reverse the direction of these terminals to indicate feedback better. Right-click the Gain function and select Reverse Terminals from the shortcut menu. The Gain function now points toward the left side of the simulation diagram. 8. Label this Gain function Damping. 9. Press the <Ctrl> key and drag the Gain function to create a separate copy. Move this copy below the existing simulation diagram code but still within the Control & Simulation Loop. Label this function Stiffness. 10. Right-click the wire connecting the Force control to the Calculate Acceleration function and select Delete Wire Branch from the shortcut menu. Move the Force control to the left of the Summation function, and wire this control to the Operand2 input of the Summation function. 11. Create wires 1–5 as indicated in the Figure below. The simulation diagram now fully represents the equation that defines the behavior of the dynamic system. 12. Press <Ctrl-S> to save the VI. The Block Diagram should now look like this: Configuring the Stiffness of the Spring Before you run the simulation again, you must configure the stiffness of the simulated spring. Complete the following steps to configure this Simulation function. Tutorial: Control and Simulation in LabVIEW 25 Simulation 1. 2. 3. 4. 5. 6. Double-click the Stiffness function to display the Gain Configuration dialog box. Enter 100 in the gain numeric control. This value represents a stiffness of 100 Newtons per meter. Click OK to return to the simulation diagram. Notice that the Stiffness function displays 100. Display the front panel and ensure the Force control is set to -9.8 and the Mass control is set to 1. Run the simulation. The Velocity and Position charts display the behavior of the mass as the spring oscillates. Notice the new behavior compared to the last time you ran the simulation. This time, the velocity and position do not constantly decrease. Both values oscillate, which is how a spring behaves in the real world. Change the value of the Mass control to 10 and run the simulation again. Notice the different behavior in the Velocity and Position charts. The 10 kg mass forces the spring to oscillate less frequently and within a smaller velocity/position range. The Front Panel should look like this: Configuring Simulation Functions Programmatically The previous section provided information about configuring Simulation functions using the configuration dialog box. Instead of using the configuration dialog box, you can improve the interactivity of a simulation by creating front panel controls that configure a Simulation function programmatically. Complete the following steps to configure the Stiffness function programmatically. 1. 2. If you are not already viewing the Context Help window, press <Ctrl-H> to display this window. Display the block diagram and move the cursor over the Stiffness function. Notice this function has only one input terminal. Tutorial: Control and Simulation in LabVIEW 26 Simulation 3. 4. 5. 6. 7. 8. Display the Gain Configuration dialog box of the Stiffness function. Select Terminal from the Parameter source pull-down menu. This action disables the gain numeric control. Click the OK button to save changes and return to the block diagram. Move the cursor over the Stiffness function. Notice the Context Help window displays the Gain function with the new gain input terminal. Create a control for this input, and label the control gain (k). View the front panel. Notice the new control gain (k). Enter a value of 100 for this control and run the simulation. Notice the behavior is exactly the same as when you used the configuration dialog box to configure the Stiffness function. Modularizing Simulation Diagram Code You can create simulation subsystems to divide simulation diagrams into components that are modular, reusable, and independently verifiable. Complete the following steps to create a simulation subsystem from this simulation diagram. 1. 2. 3. 4. View the simulation diagram. Select the Calculate Acceleration, Calculate Velocity, and Calculate Position functions by pressing the <Shift> key and clicking each function. Select Edit»Create Simulation Subsystem. LabVIEW replaces these three functions with a single function that represents the simulation subsystem, which is circled in the Figure below. The inputs and outputs of the simulation subsystem include the inputs and outputs of all the functions you selected. Also, notice the amount of blank space on the simulation diagram. Because you combined three functions into a subsystem, you can resize the Control & Simulation Loop and reposition the functions to make the simulation diagram easier to view. Press <Ctrl-S> to save the simulation diagram. LabVIEW prompts you to save the simulation subsystem you just created. Click the Yes button and save this simulation subsystem as “Newton.vi”. You now have a simulation subsystem that obtains the position of a mass by using Newton's Second Law of Motion. Note! You can resize the simulation subsystem to better display its simulation diagram. You also can double-click the simulation subsystem to display the configuration dialog box of that simulation subsystem. The simulation subsystem should look like this: Tutorial: Control and Simulation in LabVIEW 27 Simulation Editing the Simulation Subsystem Edit the simulation subsystem “Newton.vi” by right-clicking this subsystem and selecting Open Subsystem from the shortcut menu. View the simulation diagram. Notice this simulation subsystem does not contain a Control & Simulation Loop, but the entire background is pale yellow to indicate a simulation diagram. If you place this simulation subsystem in a Control & Simulation Loop, the simulation subsystem inherits all simulation parameters from the Control & Simulation Loop. If you run this subsystem as a stand-alone VI, you can configure the simulation parameters by selecting Operate»Configure Simulation Parameters. Any parameters you configure using this method do not take effect when the subsystem is within another Control & Simulation Loop. If you place this simulation subsystem on a block diagram outside a Control & Simulation Loop, you can configure the simulation parameters by double-clicking the simulation subsystem to display the configuration dialog box of that simulation subsystem. Configuring Simulation Parameters Programmatically Earlier in this exercise, you used the Configure Simulation Parameters dialog box to configure the parameters of “Spring-Mass Damper Example.vi”. You also can configure simulation parameters programmatically by using the Input Node of the Control & Simulation Loop. Complete the following steps to configure simulation parameters programmatically. 1. 2. 3. View the simulation diagram of “Spring-Mass Damper Example.vi”. Move the cursor over the Input Node to display resizing handles. Drag the bottom handle down to display all available Node inputs. You use these inputs to configure the simulation parameters without displaying the Configure Simulation Parameters dialog box. You also can right-click the Input Node and select Show All Inputs from the shortcut menu. Notice the gray boxes next to each input. These boxes display values you configure in the Configure Simulation Parameters dialog box. For example, the third gray box from the top displays 10.0000, which is the value of the Final Time numeric control that you configured. The fifth gray box from the top displays RK 23. This box specifies the current ODE solver, which you configured as Runge-Kutta 23 (variable). Move the cursor over the left edge of each Node input to display the label of that input. Tutorial: Control and Simulation in LabVIEW 28 Simulation 4. Right-click the input terminal of the ODE Solver input and select Create»Constant from the shortcut menu. A block diagram constant appears outside the Control & Simulation Loop. The value of this constant is Runge-Kutta 1 (Euler), which is different than what you configured in the Configure Simulation Parameters dialog box. However, the gray box disappears from the Input Node, indicating that the value of this parameter does not come from the Configure Simulation Parameters dialog box. Values that you programmatically configure override any settings you made in the Configure Simulation Parameters dialog box. The Input Node should now looks like the following figure: Summary This exercise introduced you to the following concepts: The simulation diagram reflects the dynamic system model you want to simulate. This dynamic system model is a differential or difference equation that represents a dynamic system. The Control & Simulation Loop contains the parameters that define the behavior of the simulation. The Control & Simulation Loop also defines the visual boundary of the simulation diagram. Double-click the Input Node of the Control & Simulation Loop to access configurable parameters. You also can expand the Input Node to access these parameters. The Simulation palette contains the VIs and functions you use to build a simulation. You can double-click most Simulation functions to display a dialog box that configures that function. You also can create input terminals for function inputs. You can create simulation subsystems to modularize, encapsulate, validate, and re-use portions of the simulation diagram. Tutorial: Control and Simulation in LabVIEW 5 PID CONTROL Currently, the Proportional-Integral-Derivative (PID) algorithm is the most common control algorithm used in industry. Often, people use PID to control processes that include heating and cooling systems, fluid level monitoring, flow control, and pressure control. In PID control, you must specify a process variable and a setpoint. The process variable is the system parameter you want to control, such as temperature, pressure, or flow rate, and the setpoint is the desired value for the parameter you are controlling. A PID controller determines a controller output value, such as the heater power or valve position. The controller applies the controller output value to the system, which in turn drives the process variable toward the setpoint value. The PID controller compares the setpoint (SP) to the process variable (PV) to obtain the error (e). Then the PID controller calculates the controller action, u(t), where Kc is controller gain. Ti is the integral time in minutes, also called the reset time, and Td is the derivative time in minutes, also called the rate time. The following formula represents the proportional action. The following formula represents the integral action. The following formula represents the derivative action. 29 30 5.1 PID Control PID CONTROL IN LABVIEW In the “PID” Sub palette we have the functions/SubVIs for PID Control. I recommend that you use the “PID Advanced.vi”. Example: PID Control Below we see how we can use the PID Advanvanced.vi in order to control a simulated Model. 5.2 AUTO-TUNING The LabVIEW PID and Fuzzy Logic Toolkit include a VI for auto-tuning. Tutorial: Control and Simulation in LabVIEW 31 PID Control Tutorial: Control and Simulation in LabVIEW 6 CONTROL DESIGN Control design is a process that involves developing mathematical models that describe a physical system, analyzing the models to learn about their dynamic characteristics, and creating a controller to achieve certain dynamic characteristics. 6.1 CONTROL DESIGN IN LABVIEW Control Design palette: 32 7 SYSTEM IDENTIFICATION 7.1 SYSTEM IDENTIFICATION IN LABVIEW The “System Identification Toolkit” combines data acquisition tools with system identification algorithms for accurate plant modeling. You can take advantage of LabVIEW intuitive data acquisition tools such as the DAQ Assistant to stimulate and acquire data from the plant and then automatically identify a dynamic system model. You can convert system identification models to state-space, transfer function, or pole-zero-gain form for control system analysis and design. The toolkit includes built-in functions for common tasks such as data preprocessing, model creation, and system analysis. Using other built-in utilities, you can plot the model with intuitive graphical representation as well as store the model. System Identification palette: 33 8 FUZZY LOGIC Fuzzy logic is a method of rule-based decision making used for expert systems and process control. Fuzzy logic differs from traditional Boolean logic in that fuzzy logic allows for partial membership in a set. You can use fuzzy logic to control processes represented by subjective, linguistic descriptions. A fuzzy system is a system of variables that are associated using fuzzy logic. A fuzzy controller uses defined rules to control a fuzzy system based on the current values of input variables. 8.1 FUZZY LOGIC IN LABVIEW The Fuzzy Logic palette in LabVIEW: 34 9 LABVIEW MATHSCRIPT Requires: MathScript RT Module The “LabVIEW MathScript Window” is an interactive interface in which you can enter .m file script commands and see immediate results, variables and commands history. The window includes a command-line interface where you can enter commands one-by-one for quick calculations, script debugging or learning. Alternatively, you can enter and execute groups of commands through a script editor window. As you work, a variable display updates to show the graphical / textual results and a history window tracks your commands. The history view facilitates algorithm development by allowing you to use the clipboard to reuse your previously executed commands. You can use the “LabVIEW MathScript Window” to enter commands one at time. You also can enter batch scripts in a simple text editor window, loaded from a text file, or imported from a separate text editor. The “LabVIEW MathScript Window” provides immediate feedback in a variety of forms, such as graphs and text. Example: 35 36 9.1 Error! Reference source not found. HELP You may also type help in your command window >>help Or more specific, e.g., >>help plot 9.2 EXAMPLES I advise you to test all the examples in this text in LabVIEW MathScript in order to get familiar with the program and its syntax. All examples in the text are outlined in a frame like this: >> … This is commands you should write in the Command Window. You type all your commands in the Command Window. I will use the symbol “>>” to illustrate that the commands should be written in the Command Window. Tutorial: Control and Simulation in LabVIEW 37 Error! Reference source not found. Example: Matrices Defining the following matrix The syntax is as follows: >> A = [1 2;0 3] Or >> A = [1,2;0,3] If you, for an example, want to find the answer to >>a=4 >>b=3 >>a+b MathScript then responds: ans = 7 MathScript provides a simple way to define simple arrays using the syntax: “init:increment:terminator”. For instance: >> array = 1:2:9 array = 1 3 5 7 9 defines a variable named array (or assigns a new value to an existing variable with the name array) which is an array consisting of the values 1, 3, 5, 7, and 9. That is, the array starts at 1 (the init value), increments with each step from the previous value by 2 (the increment value), and stops once it reaches (or to avoid exceeding) 9 (the terminator value). The increment value can actually be left out of this syntax (along with one of the colons), to use a default value of 1. >> ari = 1:5 ari = 1 2 3 4 5 Tutorial: Control and Simulation in LabVIEW 38 Error! Reference source not found. assigns to the variable named ari an array with the values 1, 2, 3, 4, and 5, since the default value of 1 is used as the incrementer. Note that the indexing is one-based, which is the usual convention for matrices in mathematics. This is atypical for programming languages, whose arrays more often start with zero. Matrices can be defined by separating the elements of a row with blank space or comma and using a semicolon to terminate each row. The list of elements should be surrounded by square brackets: []. Parentheses: () are used to access elements and subarrays (they are also used to denote a function argument list). >> A = [16 3 2 13; 5 10 11 8; 9 6 7 12; 4 15 14 1] A = 16 3 2 13 5 10 11 9 6 8 7 12 4 15 14 1 >> A(2,3) ans = 11 Sets of indices can be specified by expressions such as "2:4", which evaluates to [2, 3, 4]. For example, a submatrix taken from rows 2 through 4 and columns 3 through 4 can be written as: >> A(2:4,3:4) ans = 11 8 7 12 14 1 A square identity matrix of size n can be generated using the function eye, and matrices of any size with zeros or ones can be generated with the functions zeros and ones, respectively. >> eye(3) ans = 1 0 0 0 1 0 Tutorial: Control and Simulation in LabVIEW 39 Error! Reference source not found. 0 0 1 >> zeros(2,3) ans = 0 0 0 0 0 0 >> ones(2,3) ans = 1 1 1 1 1 1 9.3 USEFUL COMMANDS Here are some useful commands: Command Description eye(x), eye(x,y) Identity matrix of order x ones(x), ones(x,y) A matrix with only ones zeros(x), zeros(x,y) A matrix with only zeros diag([x y z]) Diagonal matrix size(A) Dimension of matrix A A’ Inverse of matrix A 9.4 PLOTTING This chapter explains the basic concepts of creating plots in MathScript. Topics: Basic Plot commands Example: Plotting Function plot can be used to produce a graph from two vectors x and y. The code: x = 0:pi/100:2*pi; Tutorial: Control and Simulation in LabVIEW 40 Error! Reference source not found. y = sin(x); plot(x,y) Tutorial: Control and Simulation in LabVIEW 10 WHATS NEXT? 10.1 MY BLOG For more information about LabVIEW, visit my Blog: http://home.hit.no/~hansha/ 10.2 TRAINING This Training is a part of a series with other Training Kits I have made, such as: Introduction to LabVIEW Data Acquisition in LabVIEW Control and Simulation in LabVIEW LabVIEW MathScript Linear Algebra in LabVIEW Datalogging and Supervisory Control in LabVIEW Wireless Data Acquisition in LabVIEW Intermediate Topics in LabVIEW Advanced Topics in LabVIEW These Training Kits are available for download from my blog: http://home.hit.no/~hansha 10.3 ADDITIONAL RESOURCES www.ni.com 10.4 EXAMPLES In the NI example Finder (Help→Find Examples…) you find lots of useful examples that you can play with or use as a start when creating your own applications. 41 42 Whats next? 10.5 DOCUMENTATION As part of the LabVIEW installation there comes a lots of useful documentation. 10.6 LABVIEW WIKI LabVIEW Wiki is the free LabVIEW information resource that anyone can edit. http://labviewwiki.org/Home Tutorial: Control and Simulation in LabVIEW 43 Whats next? 10.7 LABVIEW ON YOUTUBE There are lots of LabVIEW videos available at YouTube: http://www.youtube.com/results?search_query=labview&search=Search Tutorial: Control and Simulation in LabVIEW QUICK REFERENCE 44 45 Quick Reference Tutorial: Control and Simulation in LabVIEW Telemark University College Faculty of Technology Kjølnes Ring 56 N-3914 Porsgrunn, Norway www.hit.no Hans-Petter Halvorsen, M.Sc. Telemark University College Department of Electrical Engineering, Information Technology and Cybernetics Phone: +47 3557 5158 E-mail: hans.p.halvorsen@hit.no Blog: http://home.hit.no/~hansha/ Room: B-237a Telemark University College Department of Electrical Engineering, Information Technology and Cybernetics INTRODUCTION TO STATE-BASED APPLICATIONS IN LABVIEW HANS-PETTER HALVORSEN, 2010.01.15 Faculty of Technology, Postboks 203, Kjølnes ring 56, N-3901 Porsgrunn, Norway. Tel: +47 35 57 50 00 Fax: +47 35 57 54 01 PREFACE Statecharts or State Diagrams are useful in simplifying the design of applications that use complex decision-making algorithms. By constructing a statechart, you can visualize the flow of a complex decision-making algorithm and achieve a high-level view of an application. This document explains the basic concepts of creating state-based applications in LabVIEW. You should have some basic knowledge about LabVIEW, e.g., the “An Introduction to LabVIEW” training. This document is available for download at http://home.hit.no/~hansha/. In addition to LabVIEW Professional Development System, you need to install the “LabVIEW Statechart Module”. INSTALLATION REQUIREMENTS NI LabVIEW Name LabVIEW Professional Development System Required Yes NI LabVIEW Core Components Name Required LabVIEW Control Design and Simulation Module LabVIEW MathScript RT Module NI Vision Development Module Vision Builder for Automated Inspection LabVIEW Digital Filter Design Toolkit LabVIEW Modulation Toolkit LabVIEW System Identification Toolkit LabVIEW Desktop Execution Trace Toolkit LabVIEW Report Generation for Microsoft Office Toolkit LabVIEW Database Connectivity Toolkit LabVIEW Internet Toolkit NI LabVIEW SignalExpress LabVIEW Basics 1 and 2 Computer Based Training Extended Development Suite Components Name LabWindows/CVI Full Development System LabWindows/CVI Real-Time Module LabWindows/CVI PID Control Toolkit LabWindows/CVI Signal Processing Toolkit LabWindows/CVI Spectral Measurements Toolkit and Run-time Engine LabWindows/CVI SQL Toolkit Measurement Studio Enterprise Edition Required DIAdem Professional Control and Embedded Systems Option Components Name Required LabVIEW FPGA Module LabVIEW Real-Time Module LabVIEW Statechart Module Yes LabVIEW Mobile Module LabVIEW Datalogging and Supervisory Control Module LabVIEW PID and Fuzzy Logic Toolkit NI Real-Time Execution Trace Toolkit LabVIEW Simulation Interface Toolkit NI Motion Assistant NI-DAQ Base Signal processing and Communications Option Components Name Required LabVIEW FPGA Module LabVIEW Sound and Vibration Measurement Suite LabVIEW Spectral Measurement Toolkit LabVIEW Advanced Signal Processing Toolkit LabVIEW Adaptive Filter Toolkit NI Device Drivers Name FieldPoint NI-DAQmx NI LabVIEW SignalExpress NI Instrument I/O Assistant NI-IMAQ NI Measurement & Automation Explorer NI PXI Required NI-VISA TABLE OF CONTENTS Preface .................................................................................................................................................................... 2 Installation Requirements ....................................................................................................................................... 3 Table of Contents .................................................................................................................................................... vi 1 Introduction to LabVIEW ............................................................................................................................... 1 1.1 Dataflow programming.......................................................................................................................... 1 1.2 Graphical programming ......................................................................................................................... 1 1.3 Benefits .................................................................................................................................................. 2 2 Introduction to Sequential Control................................................................................................................ 3 3 Introduction to State Diagrams ..................................................................................................................... 4 4 Introduction to Sequential Function Charts (SFC) ......................................................................................... 6 5 State-machine with LabVIEW ........................................................................................................................ 8 5.1 While Loop ............................................................................................................................................. 8 5.2 Case Structure ....................................................................................................................................... 9 5.3 Shift Register........................................................................................................................................ 10 5.4 State Programming Architecture ......................................................................................................... 11 5.5 State-machine...................................................................................................................................... 12 6 A Sequential Control example in LabVIEW .................................................................................................. 15 7 Introduction to LabVIEW Statechart Module .............................................................................................. 17 7.1 Procedure for creating a Statechart application in LabVIEW .............................................................. 18 7.2 Statechart Editor.................................................................................................................................. 21 7.2.1 7.3 Statechart Development objects ................................................................................................ 23 Using a Caller VI to Execute a Statechart ............................................................................................. 25 8 Tutorial: Create a Statechart ....................................................................................................................... 28 9 Advanced Topics in LabVIEW Statechart Module ........................................................................................ 41 9.1 Using Regions and Substates ............................................................................................................... 41 9.2 Using Orthogonal Regions and State History....................................................................................... 41 vii Table of Contents 9.3 10 Splitting and Merging Transition Segments ......................................................................................... 41 Whats Next? ................................................................................................................................................ 43 10.1 My Blog ................................................................................................................................................ 43 10.2 Training ................................................................................................................................................ 43 10.3 Additional Resources ........................................................................................................................... 43 10.4 Examples .............................................................................................................................................. 43 10.5 Documentation .................................................................................................................................... 44 10.6 LabVIEW Wiki....................................................................................................................................... 44 10.7 LabVIEW on YouTube .......................................................................................................................... 45 Quick Reference .................................................................................................................................................... 46 Tutorial: Introduction to State-based Applications in LabVIEW 1 INTRODUCTION TO LABVIEW LabVIEW (short for Laboratory Virtual Instrumentation Engineering Workbench) is a platform and development environment for a visual programming language from National Instruments. The graphical language is named "G". Originally released for the Apple Macintosh in 1986, LabVIEW is commonly used for data acquisition, instrument control, and industrial automation on a variety of platforms including Microsoft Windows, various flavors of UNIX, Linux, and Mac OS X. The latest version of LabVIEW is version LabVIEW 2009, released in August 2009. Visit National Instruments at www.ni.com. The code files have the extension “.vi”, which is an abbreviation for “Virtual Instrument”. LabVIEW offers lots of additional Add-Ons and Toolkits. This paper is part of a series with LabVIEW tutorials, such as: Introduction to LabVIEW Data Acquisition in LabVIEW Control and Simulation in LabVIEW LabVIEW MathScript Linear Algebra in LabVIEW Datalogging and Supervisory Control in LabVIEW Wireless Data Acquisition in LabVIEW Intermediate Topics in LabVIEW Advanced Topics in LabVIEW Each tutorial may be used independently of each other. 1.1 DATAFLOW PROGRAMMING The programming language used in LabVIEW, also referred to as G, is a dataflow programming language. Execution is determined by the structure of a graphical block diagram (the LV-source code) on which the programmer connects different function-nodes by drawing wires. These wires propagate variables and any node can execute as soon as all its input data become available. Since this might be the case for multiple nodes simultaneously, G is inherently capable of parallel execution. Multi-processing and multi-threading hardware is automatically exploited by the built-in scheduler, which multiplexes multiple OS threads over the nodes ready for execution. 1.2 GRAPHICAL PROGRAMMING LabVIEW ties the creation of user interfaces (called front panels) into the development cycle. LabVIEW programs/subroutines are called virtual instruments (VIs). Each VI has three components: a block diagram, a front panel, and a connector panel. The last is used to represent the VI in the block diagrams of other, calling VIs. Controls and indicators on the front panel allow an operator to input data into or extract data from a running virtual instrument. However, the front panel can also serve as a programmatic interface. Thus a virtual instrument can either be run as a program, with the front panel serving as a user interface, or, when dropped as a node onto the block diagram, the front panel defines the inputs and outputs for the given node through the connector pane. This implies each VI can be easily tested before being embedded as a subroutine into a larger program. 1 2 Introduction to LabVIEW The graphical approach also allows non-programmers to build programs simply by dragging and dropping virtual representations of lab equipment with which they are already familiar. The LabVIEW programming environment, with the included examples and the documentation, makes it simple to create small applications. This is a benefit on one side, but there is also a certain danger of underestimating the expertise needed for good quality "G" programming. For complex algorithms or large-scale code, it is important that the programmer possess an extensive knowledge of the special LabVIEW syntax and the topology of its memory management. The most advanced LabVIEW development systems offer the possibility of building stand-alone applications. Furthermore, it is possible to create distributed applications, which communicate by a client/server scheme, and are therefore easier to implement due to the inherently parallel nature of G-code. 1.3 BENEFITS One benefit of LabVIEW over other development environments is the extensive support for accessing instrumentation hardware. Drivers and abstraction layers for many different types of instruments and buses are included or are available for inclusion. These present themselves as graphical nodes. The abstraction layers offer standard software interfaces to communicate with hardware devices. The provided driver interfaces save program development time. The sales pitch of National Instruments is, therefore, that even people with limited coding experience can write programs and deploy test solutions in a reduced time frame when compared to more conventional or competing systems. A new hardware driver topology (DAQmxBase), which consists mainly of G-coded components with only a few register calls through NI Measurement Hardware DDK (Driver Development Kit) functions, provides platform independent hardware access to numerous data acquisition and instrumentation devices. The DAQmxBase driver is available for LabVIEW on Windows, Mac OS X and Linux platforms. Tutorial: Introduction to State-based Applications in LabVIEW 2 INTRODUCTION TO SEQUENTIAL CONTROL Sequential control is crucial in many control applications, as in chemical batch processes. A sequential control procedure can be represented graphically by e.g. one of the following two methods: A State diagram, also denoted a State machine A Sequential function chart (SFC) State diagrams and SFC are quite similar, as they have the same basic elements: States with actions to be executed when the state is active Transitions from one active state to another Sequential control can be implemented using graphical programming of state diagrams or SFCs in proper programming tools. For example, state diagrams are supported by the LabVIEW Statechart Module. Different PLC (Programmable Logic Controller) tools support SFC. For more details about sequential control, se the article “Sequential Control” by Finn Haugen. A link to the article is available from http://home.hit.no/~hansha. 3 3 INTRODUCTION TO STATE DIAGRAMS State diagrams have states with actions to be executed when the state is active. They have transitions from one active state to another taking place if the transition condition is logically true. Below we see a typical state diagram: A state diagram represents a state machine. States of a state machine are either active or passive. Only one state is active at a time. The state machine always starts in a particular state defined as the initial state, and it ends (stops) after the final state. Special symbols or colors may be used for the initial state and the final state. See the Figure above. Associated with a state are one or more actions. An action may be a control action executed by a controller. Actions may be listed as indicated below: State 1 actions: o Action 1: Valve V1 is open; o Action 2: Motor M1 runs; State 2 actions: o Action 1: Valve V1 is closed; o Action 2: Heater H1 is on; The actions for a given state can be listed in a box attached to the state symbol, see Figure below. However, the diagram may then become overloaded by symbols. Therefore, in more comprehensive state diagrams, it may be better to just list the actions in a separate document. 4 5 Introduction to State Diagrams Transitions bring the state machine from one state to another. A transition can go only from an active state which is presently active. A transition takes place only if its transition condition is TRUE. Transition conditions are in the form of logical expressions having value either TRUE or FALSE. For more details about state diagrams, se the article “Sequential Control” by Finn Haugen. A link to the article is available from http://home.hit.no/~hansha. Tutorial: Introduction to State-based Applications in LabVIEW 4 INTRODUCTION TO SEQUENTIAL FUNCTION CHARTS (SFC) Sequential Function Charts describe control sequences in graphical form. State Diagrams and Sequential function charts (SFC) techniques are very similar. They have states/steps (in SFC the term steps is used) with actions to be executed when the state is active. They have transitions from one active state to another taking place if the transition condition is logically true. Sequential function chart (SFC) is a graphical programming language often used for PLCs (PLC - Programmable Logic Controller). Below we see a typical SFC chart: The Sequential Function Charts break a sequential task down into Steps, Transitions and Actions. These are drawn graphically to describe a sequence of interactions as seen above. Steps: Every step can execute one or more actions. A step can be either active or inactive. When it becomes active, it's actions are executed Transitions: There are transitions between every step. When a Step is active and the following transition become true the successor step becomes active and the preceding step becomes inactive. Each transition has associated events which are called transition conditions. The transition conditions must combine to make a simple Boolean result, True or False. Step Actions: Every action is associated with a step. The step can have none or several actions associated. If there is no associated action to the step, it will be considered as a WAIT function. Each step/action association shall have an associated action qualifier. 6 7 Introduction to Sequential Function Charts (SFC) The Program Flow is as follows: A step becomes active when its preceding transition activates (that is the transition is true, while the step before that transition is active.) A step becomes inactive when it's subsequent transition becomes true In Parallel branches, all the initial steps become active when the preceding transition activates A parallel branch end when all the steps before the branch end are be active, and the subsequent transition becomes true Many systems have sequential operation requirements and Sequential Function Charts (SFC’s) have become a popular method of accurately specifying sequential control requirements. SFC’s have many advantages for software development both in the design stage as well as the implementation and testing, maintaining and fault finding stages, such as: Design Stage o Detailed clear graphical specification o Non software people can specify / verify Implementation o Straight forward conversion from specification to code o Structured testing / debugging Maintenance of Software o Readily understood by engineer modifying software Machine Maintenance o Allows quick accurate fault diagnosis Tutorial: Introduction to State-based Applications in LabVIEW 5 STATE-MACHINE WITH LABVIEW The State Machine approach in LabVIEW uses a Case structure inside a While loop to handle the different states in the program, and the transitions between them. The Shift Register is used to save data from and between the different states. Below we shortly repeat the While Loop, the Case structure and the Shift Register before we dig into the principles of the state-machine. For more details about basic LabVIEW programming techniques, refer to the tutorial “Introduction to LabVIEW”. The tutorial is available for download from: http://home.hit.no/~hansha. 5.1 WHILE LOOP A While loop repeats the sub diagram inside it until the conditional terminal, an input terminal, receives a particular Boolean value. The Boolean value depends on the continuation behavior of the While Loop. Right-click the conditional terminal and select Stop if True or Continue if True from the shortcut menu. You also can wire an error cluster to the conditional terminal, right-click the terminal, and select Stop on Error or Continue while Error from the shortcut menu. Note! The While Loop always executes at least once. Below we see an empty While loop: After you create a While Loop, you can use shift registers to pass values from one iteration to the next. If you wire an array to a While Loop, you can read and process every element in that array by enabling auto-indexing. Se example below. 8 9 State-machine with LabVIEW In order to convert a While Loop into a For Loop, right-click the While Loop and select “Replace with For Loop” from the shortcut menu. To convert a While Loop into a Timed Loop, right-click the While Loop and select “Replace with Timed Loop” from the shortcut menu. 5.2 CASE STRUCTURE The Case Structure has one or more sub diagrams, or cases, exactly one of which executes when the structure executes. The value wired to the selector terminal determines which case to execute and can be Boolean, string, integer, or enumerated type. You may right-click the structure border to add or delete cases. Use the Labeling tool to enter value(s) in the case selector label and configure the value(s) handled by each case. Below we see an empty Case structure: Below we see an example of a Case structure with 2 cases, a “True” case and a “False” case. Depending of the Boolean input value, the Numeric1 and Numeric2 is either Added or Subtracted. Tutorial: Introduction to State-based Applications in LabVIEW 10 State-machine with LabVIEW You may also connect an error cluster directly to a case structure, like this: The case structure automatically switches to a “No Error” case and an “Error” case. 5.3 SHIFT REGISTER Use shift registers on For Loops and While Loops to transfer values from one loop iteration to the next. Shift registers are similar to static variables in text-based programming languages. A shift register appears as a pair of terminals, directly opposite each other on the vertical sides of the loop border. The right terminal 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. Create a shift register by right-clicking the left or right border of a loop and selecting Add Shift Register from the shortcut menu. Tutorial: Introduction to State-based Applications in LabVIEW 11 State-machine with LabVIEW 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. To initialize a shift register, wire any value from outside the loop to the left terminal. If you do not initialize the shift register, the loop uses the value written to the shift register when the loop last executed or the default value for the data type if the loop has never executed. Use a loop with an uninitialized shift register to run a VI repeatedly so that each time the VI runs, the initial output of the shift register is the last value from the previous execution. Use an uninitialized shift register to preserve state information between subsequent executions of a VI. After the loop executes, the last value stored in the shift register remains at the right terminal. If you wire the right terminal outside the loop, the wire transfers the last value stored in the shift register. You can add more than one shift register to a loop. If you have multiple operations within a loop, use multiple shift registers to store the data values from those different processes in the structure. Shift Register Example: Create and Run this example to see what happens. 5.4 STATE PROGRAMMING ARCHITECTURE Creating VIs using the State Machine approach is very useful when creating (large) applications. In general, a state machine is a model of behavior composed of a finite number of states, transitions between those states, and actions. It is similar to a "flow graph" where we can inspect the way in which the logic runs when certain conditions are met. Tutorial: Introduction to State-based Applications in LabVIEW 12 State-machine with LabVIEW Sometimes, you may want to change the order of the sequence, repeat one item in the sequence more often than the other items, stop a sequence immediately, or have items in the sequence that may execute only when certain conditions are met. Although your program may not have any such requirements, there is always the possibility that the program must be modified in the future. Therefore, a state programming architecture is a good choice, even if a sequential programming structure is sufficient. The following list describes more complex programming requirements that justify the use of a state programming architecture for an application. You need to change the order of the sequence You must repeat an item in the sequence more often than other items You want some items in the sequence to execute only when certain conditions are met 5.5 STATE-MACHINE Tutorial: Introduction to State-based Applications in LabVIEW 13 State-machine with LabVIEW The State Machine approach in LabVIEW uses a Case structure inside a While loop to handle the different states in the program, and the transitions between them. The Shift Register is used to save data from and between the different states. Below we see examples of a state machine principle implemented in LabVIEW. Simple State Machine principle State Machine with multiple transitions depending on the State: More advanced State Machine using Shift Registers: Tutorial: Introduction to State-based Applications in LabVIEW 14 State-machine with LabVIEW Templates for State-machines in LabVIEW are available for download at: http://home.hit.no/~hansha Tutorial: Introduction to State-based Applications in LabVIEW 6 A SEQUENTIAL CONTROL EXAMPLE IN LABVIEW This example illustrates how we may use the state-machine principle in LabVIEW to create a sequential control application. This example uses a state machine for sequential control of the position of a bicycle. The state-machine is implemented with: An overall Case-structure which defines the states and contains the actions of each state A Shift-register which remembers which state is the active state An internal Case-structure inside each state (Case in the overall Case-structure) together with proper Boolean comparison functions implementing the transition conditions. The state-machine controls a simulated process (bicycle position) given by the following dynamic model: Where x is position and v is speed. The speed is manipulated by the state-machine. This model is implemented in a Simulation Loop which runs in parallel with the While loop. Data (variables) are exchanged between these loops using local variables. The arrow on a Vertical Pointer Slide is replaced with a picture of a bicycle. The procedure to substitute any graphical part of an indicator or control on the Front panel is as follows: Right-click on the item (graphical part), e.g. the arrow of a Vertical Pointer Slide. Select Advanced / Customize in the menu that is opened. Click the Tool button in the toolbar of the new window that is opened. Right-click on the arrow on the slider, and select the picture you want. Etc. How to use it? Use this VI as a template for your own state-machine controller for any simulated dynamic system. To control a real (physical) process instead, just substitute the simulated process with read and/or write functions for analog and/or digital I/O (input/output). The Front Panel looks like this: 15 16 A Sequential Control example in LabVIEW The Block Diagram looks like this: In order to get the feeling with state machines, while loops, case structures and shift registers, try to reproduce the example. The example is created by Finn Haugen, Telemark University College. Tutorial: Introduction to State-based Applications in LabVIEW 7 INTRODUCTION TO LABVIEW STATECHART MODULE The NI LabVIEW Statechart Module provides a programming model that you can use to design applications at a higher level than was previously possible. With the LabVIEW Statechart Module, you can develop statechart diagrams, define behaviors with LabVIEW dataflow programming. Statecharts expand the classic state diagram with the additional features of hierarchy, concurrency, and comprehensive actions. LabVIEW statecharts are especially useful for programming event-response applications such as intricate user interfaces and advanced state machines used to implement dynamic system controllers, machine control logic, and digital communication protocols. Using the LabVIEW Statechart Module involves the following two steps: Using the Statechart Editor window to build a statechart. Creating a VI that executes the statechart. This VI also sends information to, and receives information from, the statechart. Building a Statechart Building a statechart involves defining the following items: States Actions and static reactions these states execute Transitions between states Actions these transitions execute Triggers When you build a statechart, you define unique states in which the statechart can be. You also define transitions between these states, when the statechart can take these transitions, and what actions these transitions can take. You then define triggers that cause the statechart to begin evaluating a certain transition. For example, consider a statechart that you use to control a chemical process. You can specify that the statechart moves from State 1 to State 2 after receiving the Valve Open trigger. States and transitions also have associated actions, which you use to modify output and state data associated with the statechart. Creating a VI that Executes the Statechart After you define the valid triggers and configure the statechart to react to those triggers, you must send those triggers to the statechart. You send triggers to the statechart by creating a VI, known as the Caller VI, to send triggers at a specific time. For example, you can configure the caller VI to send the Stop trigger after you click the Stop front panel button. The caller VI also sends input data to the statechart so the statechart can act on that data. The caller VI receives data that the statechart modifies as a result of a state or transition action. You then can use this data in other parts of the caller VI or send this data to other VIs. The following figure shows how a caller VI interacts with a statechart. 17 18 Introduction to LabVIEW Statechart Module The figure above shows how the caller VI sends data to the statechart, which returns output data to the caller VI. If the statechart is asynchronous, the caller VI also might send a trigger to the statechart. Sending a trigger to the statechart causes the statechart to begin executing. 7.1 PROCEDURE FOR CREATING A STATECHART APPLICATION IN LABVIEW The procedure for creating a statechart application in LabVIEW with the LabVIEW Statechart Module is as follows: Step1: In the New dialog select “Statechart”. Step 2: Name the Statechart Tutorial: Introduction to State-based Applications in LabVIEW 19 Introduction to LabVIEW Statechart Module Step3: The Project Explorer for the Statechart application appears: As you see, the LabVIEW Statechart Module automatically generates a set of Vis and Controls. LabVIEW Statechart Palette: LabVIEW Statechart Module offers the following Functions and Objects in the Statechart palette: Tutorial: Introduction to State-based Applications in LabVIEW 20 Introduction to LabVIEW Statechart Module Statechart Communication Functions: Use the Statechart Communication functions to execute a statechart, send triggers to a statechart, and determine whether a particular state is active. You can place these functions on a block diagram. Statechart Communication palette: Run Statechart Executes an instance of the linked statechart. You typically place this function inside a loop in the caller VI. Example: Tutorial: Introduction to State-based Applications in LabVIEW 21 Introduction to LabVIEW Statechart Module Send External Trigger Sends a trigger to the external queue of an instance of the linked statechart. You can use this function in the caller VI or in a VI that runs parallel to the caller VI. Se example above IsIn Determines whether the specified state is active. An active state is one that a statechart is currently in. You can use this function in a guard, an action, or a subVI that a guard or action calls. Send Internal Trigger Sends a trigger to the internal queue of the statechart. You can use this function within only an action or in a subVI that an action calls. Statechart Development Objects: Use the Statechart Development objects, consisting of states, regions, “pseudostates”, and connectors, to construct statecharts. Note! You can place these objects only on a statechart diagram. Statechart Development palette: The different objects are explained below. 7.2 STATECHART EDITOR Tutorial: Introduction to State-based Applications in LabVIEW 22 Introduction to LabVIEW Statechart Module You use the Statechart Editor window to edit a statechart. You can display the Statechart Editor window in one of the following ways: Double-click the “Diagram.vi” item in the Project Explorer window of the statechart. Right-click the “Diagram.vi” item and select Open from the shortcut menu. Right-click a Run Statechart function that links to the statechart and select View»Statechart Diagram from the shortcut menu. Statechart Editor Window: The Statechart Editor window, which displays a statechart diagram, is similar to the LabVIEW window that displays a block diagram. In both of these windows, you can place objects from the Functions palette on the diagram, use the LabVIEW tools to manipulate objects, and connect objects together. However, the Statechart Editor window is different from the LabVIEW window in the following ways: You can place only Statechart Development objects on a statechart diagram. You cannot place LabVIEW VIs, functions, or structures directly on a statechart diagram. Tutorial: Introduction to State-based Applications in LabVIEW 23 Introduction to LabVIEW Statechart Module The LabVIEW block diagram window displays the Run button on the toolbar. The Statechart Editor window displays the “Generate Code “button on the toolbar. Clicking this button generates code for the statechart. The LabVIEW block diagram has a front panel window. The Statechart Editor window does not have a front panel window. On the LabVIEW block diagram, you use the wiring tool to create wires between VIs and functions. In the Statechart Editor window, you use the wiring tool to create transitions between states and other objects. The LabVIEW block diagram provides options for debugging VIs. The Statechart Editor window does not provide any debugging options. You debug statecharts by using a separate window that you can access while the statechart is running. The Statechart Editor window disables many LabVIEW pull-down menu items that do not apply to statecharts. 7.2.1 STATECHART DEVELOPMENT OBJECTS Use the Statechart Development objects to construct statecharts. You can place these objects on a statechart diagram. The Statechart Development objects consist of states, regions, and connectors. The Statechart Development palette: The Statechart Development objects are as follows: State Defines a state, which is a unique condition in which the statechart can be. You must place all states within a region. Note! The top-level statechart diagram represents a region. All states must have at least one incoming transition. Tutorial: Introduction to State-based Applications in LabVIEW 24 Introduction to LabVIEW Statechart Module Initial Specifies the first state that the enclosing region enters when the statechart enters that region. To specify this state, create a transition from the Initial pseudostate to the state that you want to enter first. You can place this pseudostate within only a region or at the top level of a statechart diagram. Each region must have one and only one Initial pseudostate. Terminal Specifies a state that can terminate the execution of the enclosing region. To specify this state, create a transition from a state to a Terminal pseudostate. You can place this pseudostate within only a region. You can place more than one Terminal pseudostate in a region. Junction Connects common elements of multiple transitions together. For example, you can use a Junction connector to specify that multiple transitions use the same action, even though each transition might have a different trigger. You can place this connector only in a region. Region Defines the area in which you can place states and pseudostates. Each region must contain an Initial pseudostate and at least one substate. Note! The top-level statechart diagram represents a region. You can place regions within only a state. Fork Splits one incoming transition segment into multiple outgoing segments. You can place this connector within only a state. Tutorial: Introduction to State-based Applications in LabVIEW 25 Introduction to LabVIEW Statechart Module Join Merges multiple incoming transition segments into one outgoing segment. You can place this connector within only a state. Port Indicates where a transition leaves a state or connector. Ports also indicate where a transition passes through a region. When you are editing a statechart, ports appear automatically as you create transitions. You can place ports manually only when you are viewing a state as a subdiagram. Shallow History Specifies that, when the statechart leaves and then returns to a region, the statechart enters the highest-level substates that were active when the statechart left the region. To use the Shallow History pseudostate, place this pseudostate in a region and then create a transition from a state to this pseudostate. Deep History Specifies that, when the statechart leaves and then returns to a region, the statechart enters the lowest-level substates that were active when the statechart left the region. To use the Deep History pseudostate, place this pseudostate in a region and then create a transition from a state to this pseudostate. 7.3 USING A CALLER VI TO EXECUTE A STATECHART The caller VI is the VI you create that contains a “Run Statechart” function. This function creates and executes an instance of a statechart. Executing a statechart means sending input data to a statechart. You also can use the caller VI to send triggers to a statechart. The caller VI has a different structure depending on whether the statechart is asynchronous or synchronous. The following sections provide information about these differences. Executing asynchronous statecharts involves the following two processes: Executing the statechart by using the “Run Statechart” function. Sending triggers to the external queue by using the “Send External Trigger” function. In this situation, the VI that contains the “Run Statechart” function is the caller VI. You can send triggers to the external queue from another VI or a parallel loop in the caller VI. The following figure shows a caller VI that both executes an asynchronous statechart and sends triggers to the external queue. Tutorial: Introduction to State-based Applications in LabVIEW 26 Introduction to LabVIEW Statechart Module In the figure above, the Statechart Loop, which is a While Loop, executes the statechart. The Inputs control contains any input data of the types that you defined. The Outputs indicator returns output data from the statechart. The Instance Name constant specifies Statechart 1 as the name of the statechart instance. The Trigger Loop, which can execute in parallel with the Statechart Loop, contains an Event structure. This Event structure handles events that occur within the VI. In this case, an event occurs when you click the Button front panel control. When you click this control, the Event structure detects this event and the Send External Trigger function sends the Trigger1 trigger to the Statechart 1 statechart instance. Note! This example uses the caller VI to send triggers to an external queue. However, as long as the caller VI is running and the statechart is in memory, you can use any VI to send triggers to an external queue. This behavior means that you can place the Trigger Loop and Statechart Loop in separate VIs. Statechart Editor: Open the Statechart Diagram (in the Statechart Editor) as follows: Right-click on the “Run Statechart” VI and select View → Statechart Diagram. Tutorial: Introduction to State-based Applications in LabVIEW 27 Introduction to LabVIEW Statechart Module Project Explorer: Open the Project Explorer as follows: Right-click on the “Run Statechart” VI and select View → Statechart. Tutorial: Introduction to State-based Applications in LabVIEW 8 TUTORIAL: CREATE A STATECHART In this Tutorial you will learn how to create a statechart from scratch. In this example we will create the following application: When you push the different buttons, the current state will be displayed in the “Current Activity” indicator This Tutorial goes through the following steps: Step 1: Creating and Configuring the Statechart Step 2: Defining States Step 3: Creating a Transition Step 4: Creating a Trigger and Configuring a Transition Step 5: Creating and Configuring the Terminal Transitions Step 6: Creating and Configuring the Initial pseudostate and Transition Step 7: Defining the Type of Output Data Step 8: Defining the Type of State Data Step 9: Configuring a State Entry Action Step 10: Configuring the Action of a Transition Step 11: Duplicating the Transition Node Step 12: Generating Code for the Statechart Step 13: Creating the Caller VI Step 14: Debugging Let’s start the Tutorial: Step 1: Creating and Configuring the Statechart Complete the following steps to create and configure the statechart. 1. Launch LabVIEW and display the Getting Started window. 28 29 Tutorial: Create a Statechart 2. 3. Select File»New to launch the New dialog box. Select Other Files»Statechart from the Create New tree. 4. 5. Click the OK button. LabVIEW prompts you to save the statechart. Enter the name “Tutorial” as the name of your statechart (Note! It has the ending .lvsc) and save the statechart in a convenient location on disk. LabVIEW displays a Project Explorer window that contains the necessary support files. This project item represents the “Tutorial.lvsc” file in which LabVIEW stores statechart information. 6. 7. 8. Right-click the “Tutorial.lvsc” item and select Properties. LabVIEW launches the Properties dialog box. Select the “Statechart Code Generation” item from the Category list. LabVIEW displays options relating to statechart code generation. Tutorial: Introduction to State-based Applications in LabVIEW 30 Tutorial: Create a Statechart 9. Select Asynchronous from the Usage pull-down menu. This action specifies that the statechart is asynchronous. 10. Click the OK button to save changes and return to the Project Explorer window. Step 2: Defining States The next step is creating the states that comprise the statechart. A state is a unique condition in which the statechart can be. This statechart consists of three states: Menu, Play, and Pause. Complete the following steps to create these states. 1. In the Project Explorer window, double-click the Diagram.vi item to launch the Statechart Editor window. This window displays the statechart diagram. You build a statechart by placing statechart objects on the statechart diagram. 2. 3. If you do not see the Functions palette, select View»Functions Palette to display this palette. On this palette, select Statechart»Statechart Development to display the Statechart Development palette. Tutorial: Introduction to State-based Applications in LabVIEW 31 Tutorial: Create a Statechart 4. 5. Click the State object. Move the cursor over the statechart diagram. Click to place the top left corner of the state, drag the cursor diagonally to establish the size of the state, and click again to place the state on the statechart diagram. 6. Notice the state is labeled State. Double-click this label to enable text editing and enter “Menu” as the new label. 7. Move the cursor over the black border of the Menu state until the cursor changes to the Positioning tool. 8. Press the <Ctrl> key and click and drag the cursor to the right of the Menu state. This action creates copy of the state. 9. Label this new state “Play”. 10. Create another new state labeled “Pause”. Place this state to the right of the Play state. 11. Return to the Statechart Development palette and place a “Terminal” pseudostate below the Play state. The diagram should look like this: Step 3: Creating a Transition The next step is defining the ways in which the statechart can move between states. To define this behavior, you use transitions to connect one state to another visually. Complete the following steps to create transitions between two states. 1. 2. 3. 4. Move the cursor over the right border of the Menu state and change the cursor to the Wiring tool. Click the state border. As you move the cursor across the statechart diagram, LabVIEW draws a dotted line between the state and the Wiring tool. Move the cursor over the left border of the Play state. A gray box appears under the cursor. Click the border to finish the transition. LabVIEW creates a transition between the two states. Tutorial: Introduction to State-based Applications in LabVIEW 32 Tutorial: Create a Statechart The statechart diagram should look like this: Step 4: Creating a Trigger and Configuring a Transition The next step is specifying that the statechart takes the transition only after receiving a specific event, also called a trigger. By default, transitions are configured to react to the NULL trigger. However, the caller VI that executes this statechart does not send the NULL trigger. Therefore, you must configure this transition to react to a different trigger. Each statechart has a list of triggers from which you can choose when configuring a transition. Configuring a transition involves creating a trigger and then associating that trigger with the transition. Complete the following steps to configure the transition. 1. Double-click the transition node between the Menu and Play states. This action launches the Configure Transition dialog box. You use this dialog box to configure transitions. The first tab in this dialog box is the Triggers/Groups tab. Notice that the NULL trigger is selected by default in the Triggers and Groups list. Every statechart has this trigger by default. 2. Click the “Edit Triggers and Groups” button to launch the Edit Triggers and Groups dialog box. You use this dialog box to create and modify triggers. Tutorial: Introduction to State-based Applications in LabVIEW 33 Tutorial: Create a Statechart 3. 4. 5. 6. 7. 8. 9. Click the Create Trigger button to create a new trigger, which appears in the Triggers and Groups list. Enter “Play” as the new trigger name. Click the OK button to save changes and return to the Configure Transition dialog box. Notice the new trigger appears in the Triggers list. In the Triggers/Groups list, place a checkmark in the Play checkbox to specify that this trigger causes the statechart to take the transition. Remove the checkmark from the NULL checkbox. Click the OK button to save changes and return to the statechart diagram. Save the statechart by selecting File»Save in the Statechart Editor window. You also can press the <Ctrl-S> keys. Notice the blue rectangle on the transition node. This rectangle indicates that you have specified a non-NULL trigger for the transition. If you move the cursor over the transition node, the Context Help window displays the properties of the transition, including the trigger. If you do not see the Context Help window, press the <Ctrl-H> keys to display this window. Create and configure the following transitions and triggers. Remember also to deselect the NULL trigger for each transition. From the “Play” state to the “Menu” state. Configure this transition to react to the “Menu” trigger. From the “Pause” state to the “Play” state. Configure this transition to react to the “Play” trigger. From the “Play” state to the “Pause” state. Configure this transition to react to the “Pause” trigger. The statechart should look like this: Tutorial: Introduction to State-based Applications in LabVIEW 34 Tutorial: Create a Statechart Step 5: Creating and Configuring the Terminal Transitions Create a transition from the “Menu” state to the “Terminal” pseudostate. Configure this transition to react only to a new trigger, Stop. This transition specifies that if the statechart is in the Menu state and receives the Stop trigger, the statechart terminates. Tip! Right-click the transition node and select either Rotate or Reverse to ensure the node faces the proper direction. Then, save the statechart by pressing the <Ctrl-S> keys. The statechart diagram should now look like this: Step 6: Creating and Configuring the Initial pseudostate and Transition Place an Initial pseudostate, located on the Statechart Development palette, to the left of the “Menu” state. Create a transition between this pseudostate and the “Menu” state. Notice the Generate Code button no longer is broken. The statechart should look like this: Tutorial: Introduction to State-based Applications in LabVIEW 35 Tutorial: Create a Statechart Step 7: Defining the Type of Output Data If you want the statechart to modify data, you first must define the type of data. This process involves creating the controls and/or indicators that represent the statechart data. Complete the following steps to define the statechart output data. Later in this part of the tutorial, you configure the statechart to modify this data. 1. 2. 3. 4. 5. 6. Double-click the Outputs.ctl item in the project Explorer. LabVIEW displays the Control Editor window for this type definition. Notice the numeric control Numeric inside the Outputs cluster. Right-click this control and select Change to Indicator to change this control to a numeric indicator. Right-click the Numeric indicator and select Replace»String Indicator. This action replaces the numeric indicator with a string indicator. Double-click the String label and enter Current Activity as the new label. Press the <Ctrl-S> keys to save this type definition. Close the Control Editor window to return to the Project Explorer window. Step 8: Defining the Type of State Data State data is different from output data. State data is accessible from only the statechart, whereas output data also is accessible from a VI that calls the statechart. Use state data to define data types that other VIs do not need to access. Complete the following steps to define the statechart state data. 1. 2. 3. 4. 5. In the Project Explorer window, double-click the StateData.ctl item. Right-click the Data control and select Change to Indicator. This action replaces the numeric control with a numeric indicator. Double-click the Data label and enter Counter as the new label. Press the <Ctrl-S> keys to save this type definition. Close the Control Editor window to return to the Project Explorer window. Tutorial: Introduction to State-based Applications in LabVIEW 36 Tutorial: Create a Statechart Step 9: Configuring a State Entry Action The next step is configuring each state to modify the Current Activity indicator that you defined earlier. You accomplish this task by defining an entry action for a state. An entry action is LabVIEW block diagram code that the statechart executes immediately after entering a state. Complete the following steps to configure the Menu state to update this indicator. 1. 2. Double-click the Diagram.vi item to display the Statechart Editor window. Double-click the border of the Menu state. This action launches the Configure State dialog box. Note! When you configure a state, a wrench icon window. The state also changes color. 3. 4. 5. 6. appears on the state () in the Statechart Editor Notice the Outputs cluster element on the right side of this block diagram. Click this cluster element and select Outputs»Current Activity. This element now displays Outputs.Current Activity, which indicates you can write to the value of the type definition you defined. Move the cursor over the input of this cluster element until the cursor changes to the Wiring tool. Right-click the input and select Create»Constant. LabVIEW places a string constant on the block diagram. Enter Menu as the value of the constant. Tutorial: Introduction to State-based Applications in LabVIEW 37 Tutorial: Create a Statechart 7. This entry action code means that, immediately after entering the Menu state, the statechart changes the Current Activity indicator to read Menu. Later in this tutorial, you will display the value of this indicator in the VI that calls the statechart. 8. Click the OK button to save changes and return to the statechart diagram. 9. The next step is defining the “Play” and “Pause” states to update the Current Activity indicator appropriately. Configure the Entry Action for each state to update this indicator to “Playing” or “Paused”, respectively. 10. Save the statechart. Step 10: Configuring the Action of a Transition The transition from the “Menu” state to the “Terminal” pseudostate also causes a change in the activity of the statechart. Complete the following steps to configure this transition. Double-click the transition node in between the “Menu” state and “Terminal” pseudostate. This action launches the Configure Transition dialog box. Click the Action tab. Write the block diagram code that changes the value of the “Current Activity” indicator to “Stopped”. Click the OK button to save changes and return to the statechart diagram. Note! The transition node you just configured now displays two blue rectangles. The second blue rectangle indicates the transition has a specified action. Step 11: Duplicating the Transition Node The next step is creating transitions from the Play and Pause states to the Terminal pseudostate. Instead of configuring additional transition nodes, you can duplicate the transition node you configured already. Complete the following steps to duplicate this transition node. 1. 2. 3. Press the <Ctrl> key and click and drag the transition node you just configured. Move this node under the Play state. Click the bottom border of the Play state to initiate a transition segment. Tutorial: Introduction to State-based Applications in LabVIEW 38 Tutorial: Create a Statechart 4. 5. 6. 7. Move the cursor over the incoming tunnel of the transition node until LabVIEW displays a tip strip that reads Segment In. Click again to complete the transition segment. Create a transition segment from the other side of this node to the Terminal pseudostate. Right-click the transition node and select either Rotate or Reverse to ensure the node faces the proper direction. Repeat steps 1–7 to create an additional transition node from the Pause state to the Terminal pseudostate. All three states now have a transition to the Terminal pseudostate. Save the statechart. Step 12: Generating Code for the Statechart The next step is generating code for the statechart. This code is contained in a single Run Statechart function that you place on the block diagram of the caller VI. Complete the following steps to generate code for this statechart. 1. Display the Statechart Editor window. 2. 3. Click the “Generate Code” button Close the Statechart Editor window. , which is located on the toolbar of this window. Note! You also can generate code by right-clicking the .lvsc file in the Project Explorer window and selecting Generate Code from the shortcut menu. Step 13: Creating the Caller VI The next step is to create the caller VI to execute and send triggers to the statechart. This VI contains two functions, Run Statechart and Send External Trigger, that you must link to the statechart. Run Statechart Executes an instance of the linked statechart. You typically place this function inside a loop in the caller VI. Send External Trigger Sends a trigger to the external queue of an instance of the linked statechart. You can use this function in the caller VI or in a VI that runs parallel to the caller VI. Complete the following steps. 1. 2. 3. 4. Select File»New VI from the Project Explorer window Create 2 While Loops called “Statechart Loop” and “Trigger Loop” Add the “Run Statechart” VI in the “Statechart Loop” Add “Send External Trigger” function in the “Trigger Loop” Tutorial: Introduction to State-based Applications in LabVIEW 39 Tutorial: Create a Statechart 5. 6. Link “Run Statechart” and “Send External Trigger” to the statechart. Right-click and select “Link to statechart…” Finish the Caller VI so it looks like this: 7. The Front Panel should look like this: Tutorial: Introduction to State-based Applications in LabVIEW 40 Tutorial: Create a Statechart 8. Press the <Ctrl-R> keys to run the caller VI. Click the front panel buttons and notice how the Current Activity indicators changes according to the state. Step 14: Debugging Right-click the Run Statechart function and select “Debug Statechart…”. This action displays the statechart in the Statechart Debugging window. Click the “Highlight Execution” button enable statechart execution highlighting. , located on the toolbar of the Statechart Debugging window, to Run the Caller VI and see how the debugging works. Tutorial: Introduction to State-based Applications in LabVIEW 9 ADVANCED TOPICS IN LABVIEW STATECHART MODULE In this chapter we will mention some of the more advance features in the LabVIEW Statechart Module. 9.1 USING REGIONS AND SUBSTATES We recall the following objects from the Statechart Development palette: Region Defines the area in which you can place states and pseudostates. Each region must contain an Initial pseudostate and at least one substate. The top-level statechart diagram represents a region. You can place regions within only a state. Port Indicates where a transition leaves a state or connector. Ports also indicate where a transition passes through a region. When you are editing a statechart, ports appear automatically as you create transitions. You can place ports manually only when you are viewing a state as a subdiagram. 9.2 USING ORTHOGONAL REGIONS AND STATE HISTORY We recall the following objects from the Statechart Development palette: Shallow History Specifies that, when the statechart leaves and then returns to a region, the statechart enters the highest-level substates that were active when the statechart left the region. To use the Shallow History pseudostate, place this pseudostate in a region and then create a transition from a state to this pseudostate. Deep History Specifies that, when the statechart leaves and then returns to a region, the statechart enters the lowest-level substates that were active when the statechart left the region. To use the Deep History pseudostate, place this pseudostate in a region and then create a transition from a state to this pseudostate. 9.3 SPLITTING AND MERGING TRANSITION SEGMENTS We recall the following objects from the Statechart Development palette: Fork Splits one incoming transition segment into multiple outgoing segments. You can place this connector within only a state. Join Merges multiple incoming transition segments into one outgoing segment. You can place this connector within only a state. 41 42 Advanced Topics in LabVIEW Statechart Module Tutorial: Introduction to State-based Applications in LabVIEW 10 WHATS NEXT? 10.1 MY BLOG For more information about LabVIEW, visit my Blog: http://home.hit.no/~hansha/ 10.2 TRAINING This Tutorial is a part of a series with other Tutorials I have made, such as: Introduction to LabVIEW Data Acquisition in LabVIEW Control and Simulation in LabVIEW LabVIEW MathScript Linear Algebra in LabVIEW Datalogging and Supervisory Control in LabVIEW Wireless Data Acquisition in LabVIEW Intermediate Topics in LabVIEW Advanced Topics in LabVIEW These Tutorials are available for download from my blog: http://home.hit.no/~hansha 10.3 ADDITIONAL RESOURCES www.ni.com 10.4 EXAMPLES In the NI example Finder (Help→Find Examples…) you find lots of useful examples that you can play with or use as a start when creating your own applications. 43 44 Whats Next? 10.5 DOCUMENTATION As part of the LabVIEW installation there is lots of useful documentation. 10.6 LABVIEW WIKI LabVIEW Wiki is the free LabVIEW information resource that anyone can edit. http://labviewwiki.org/Home Tutorial: Introduction to State-based Applications in LabVIEW 45 Whats Next? 10.7 LABVIEW ON YOUTUBE There are lots of LabVIEW videos available at YouTube: http://www.youtube.com/results?search_query=labview&search=Search Tutorial: Introduction to State-based Applications in LabVIEW QUICK REFERENCE 46 47 Quick Reference Tutorial: Introduction to State-based Applications in LabVIEW Telemark University College Faculty of Technology Kjølnes Ring 56 N-3914 Porsgrunn, Norway www.hit.no Hans-Petter Halvorsen, M.Sc. Telemark University College Department of Electrical Engineering, Information Technology and Cybernetics Phone: +47 3557 5158 E-mail: hans.p.halvorsen@hit.no Blog: http://home.hit.no/~hansha/ Room: B-237a Telemark University College Department of Electrical Engineering, Information Technology and Cybernetics DATABASE COMMUNICATION IN LABVIEW HANS-PETTER HALVORSEN, 2010.01.15 Faculty of Technology, Postboks 203, Kjølnes ring 56, N-3901 Porsgrunn, Norway. Tel: +47 35 57 50 00 Fax: +47 35 57 54 01 PREFACE This document explains the basic concepts of a database system and how to communicate with a database from LabVIEW. You should have some basic knowledge about LabVIEW, e.g., the “An Introduction to LabVIEW” training. This document is available for download at http://home.hit.no/~hansha/. In addition to LabVIEW Professional Development System, you need to install the “LabVIEW Database Connectivity Toolkit”. For more information about LabVIEW and Databases, visit my Blog: http://home.hit.no/~hansha/ Some text in this document is based on text from www.wikipedia.org and “LabVIEW Database Connectivity Toolkit User Manual”. INSTALLATION REQUIREMENTS NI LabVIEW Name Required LabVIEW Professional Development System Yes NI LabVIEW Core Components Name Required LabVIEW Control Design and Simulation Module LabVIEW MathScript RT Module NI Vision Development Module Vision Builder for Automated Inspection LabVIEW Digital Filter Design Toolkit LabVIEW Modulation Toolkit LabVIEW System Identification Toolkit LabVIEW Desktop Execution Trace Toolkit LabVIEW Report Generation for Microsoft Office Toolkit LabVIEW Database Connectivity Toolkit Yes LabVIEW Internet Toolkit NI LabVIEW SignalExpress LabVIEW Basics 1 and 2 Computer Based Training Extended Development Suite Components Name Required LabWindows/CVI Full Development System LabWindows/CVI Real-Time Module LabWindows/CVI PID Control Toolkit LabWindows/CVI Signal Processing Toolkit LabWindows/CVI Spectral Measurements Toolkit and Run-time Engine LabWindows/CVI SQL Toolkit Measurement Studio Enterprise Edition 3 DIAdem Professional Control and Embedded Systems Option Components Name Required LabVIEW FPGA Module LabVIEW Real-Time Module LabVIEW Statechart Module LabVIEW Mobile Module LabVIEW Datalogging and Supervisory Control Module LabVIEW PID and Fuzzy Logic Toolkit NI Real-Time Execution Trace Toolkit LabVIEW Simulation Interface Toolkit NI Motion Assistant NI-DAQ Base Signal processing and Communications Option Components Name Required LabVIEW FPGA Module LabVIEW Sound and Vibration Measurement Suite LabVIEW Spectral Measurement Toolkit LabVIEW Advanced Signal Processing Toolkit LabVIEW Adaptive Filter Toolkit NI Device Drivers Name FieldPoint NI-DAQmx NI LabVIEW SignalExpress NI Instrument I/O Assistant NI-IMAQ NI Measurement & Automation Explorer NI PXI Required NI-VISA TABLE OF CONTENTS Preface .................................................................................................................................................................... 2 Installation Requirements ....................................................................................................................................... 3 Table of Contents .................................................................................................................................................... vi 1 2 3 4 Introduction to LabVIEW ............................................................................................................................... 1 1.1 Dataflow programming.......................................................................................................................... 1 1.2 Graphical programming ......................................................................................................................... 1 1.3 Benefits .................................................................................................................................................. 2 Database Systems .......................................................................................................................................... 3 2.1 RDBMS Components.............................................................................................................................. 3 2.2 Data warehouse ..................................................................................................................................... 3 2.3 Relational Database ............................................................................................................................... 3 2.4 Real-time databases .............................................................................................................................. 4 2.5 Database Management Systems ........................................................................................................... 4 2.6 MDAC ..................................................................................................................................................... 4 2.6.1 ODBC ............................................................................................................................................. 5 2.6.2 OLE DB........................................................................................................................................... 5 2.6.3 ADO (ActiveX Data Objects) .......................................................................................................... 5 Relational Databases ..................................................................................................................................... 6 3.1 Tables..................................................................................................................................................... 6 3.2 Unique Keys and Primary Key ................................................................................................................ 6 3.3 Foreign Key ............................................................................................................................................ 8 3.4 Views ..................................................................................................................................................... 9 3.5 Functions ............................................................................................................................................... 9 3.6 Stored procedures ................................................................................................................................. 9 3.7 Triggers ................................................................................................................................................ 10 Structured Query Language (SQL) ............................................................................................................... 11 vi vii 5 Table of Contents 4.1 Queries ................................................................................................................................................ 11 4.2 Data manipulation ............................................................................................................................... 12 4.3 Data definition ..................................................................................................................................... 13 4.4 Data types ............................................................................................................................................ 13 4.4.1 Character strings ......................................................................................................................... 13 4.4.2 Bit strings .................................................................................................................................... 13 4.4.3 Numbers ..................................................................................................................................... 13 4.4.4 Date and Time ............................................................................................................................. 14 Database Modelling ..................................................................................................................................... 15 5.1 ER Diagram .......................................................................................................................................... 15 5.2 Microsoft Visio ..................................................................................................................................... 16 EXERCISES ......................................................................................................................................................... 17 6 Microsoft SQL Server ................................................................................................................................... 19 6.1 Introduction ......................................................................................................................................... 19 6.2 Requirements ...................................................................................................................................... 19 6.3 SQL Server Express .............................................................................................................................. 19 6.4 AdventureWorks.................................................................................................................................. 19 6.5 SQL Server Management Studio .......................................................................................................... 20 6.6 Create a new Database ........................................................................................................................ 20 6.7 Backup/Restore ................................................................................................................................... 22 6.8 Example Database ............................................................................................................................... 23 EXERCISES ......................................................................................................................................................... 25 7 Microsoft Office Access ............................................................................................................................... 26 7.1 Introduction ......................................................................................................................................... 26 7.2 Example Database ............................................................................................................................... 26 EXERCISES ......................................................................................................................................................... 28 8 LabVIEW Database Connectivity Toolkit ...................................................................................................... 30 8.1 Connect to the Database ..................................................................................................................... 30 Tutorial: Database Communication in LabVIEW viii 9 Table of Contents 8.1.1 DSN ............................................................................................................................................. 31 8.1.2 UDL.............................................................................................................................................. 33 8.1.3 Connection String ....................................................................................................................... 34 8.2 Reading Data from the Database ........................................................................................................ 34 8.3 Writing Data to the Database .............................................................................................................. 37 8.4 Using Stored Procedures ..................................................................................................................... 39 8.5 Creating and Droping Tables ............................................................................................................... 39 8.6 Using the Database Connectivity Toolkit Utility VIs ............................................................................ 40 8.7 Performing Advanced Database Operations ....................................................................................... 41 Creating and Using Tables ........................................................................................................................... 43 EXERCISES ......................................................................................................................................................... 45 10 Creating and Using Views ............................................................................................................................ 46 EXERCISES ......................................................................................................................................................... 46 11 Creating and using Stored Procedures ........................................................................................................ 47 Exercises ........................................................................................................................................................... 48 12 Creating and Using Triggers ......................................................................................................................... 49 EXERCISES ......................................................................................................................................................... 49 13 cREATING AND USING fUNCTIONS .............................................................................................................. 50 EXERCISES ......................................................................................................................................................... 50 14 SQL Toolkit ................................................................................................................................................... 51 14.1 15 Installation ........................................................................................................................................... 51 Whats Next? ................................................................................................................................................ 54 15.1 My Blog ................................................................................................................................................ 54 15.2 Training ................................................................................................................................................ 54 15.3 Additional Resources ........................................................................................................................... 54 15.4 Examples .............................................................................................................................................. 54 15.5 Documentation .................................................................................................................................... 55 15.6 LabVIEW Wiki....................................................................................................................................... 55 Tutorial: Database Communication in LabVIEW ix Table of Contents 15.7 LabVIEW on YouTube .......................................................................................................................... 56 Quick Reference .................................................................................................................................................... 57 Tutorial: Database Communication in LabVIEW 1 INTRODUCTION TO LABVIEW LabVIEW (short for Laboratory Virtual Instrumentation Engineering Workbench) is a platform and development environment for a visual programming language from National Instruments. The graphical language is named "G". Originally released for the Apple Macintosh in 1986, LabVIEW is commonly used for data acquisition, instrument control, and industrial automation on a variety of platforms including Microsoft Windows, various flavors of UNIX, Linux, and Mac OS X. The latest version of LabVIEW is version LabVIEW 2009, released in August 2009. Visit National Instruments at www.ni.com. The code files have the extension “.vi”, which is a abbreviation for “Virtual Instrument”. LabVIEW offers lots of additional Add-Ons and Toolkits. This paper is part of a series with LabVIEW papers: Introduction to LabVIEW Data Acquisition in LabVIEW Control and Simulation in LabVIEW LabVIEW MathScript Linear Algebra in LabVIEW Datalogging and Supervisory Control in LabVIEW Wireless Data Acquisition in LabVIEW Intermediate Topics in LabVIEW Advanced Topics in LabVIEW Each paper may be used independently of each other. 1.1 DATAFLOW PROGRAMMING The programming language used in LabVIEW, also referred to as G, is a dataflow programming language. Execution is determined by the structure of a graphical block diagram (the LV-source code) on which the programmer connects different function-nodes by drawing wires. These wires propagate variables and any node can execute as soon as all its input data become available. Since this might be the case for multiple nodes simultaneously, G is inherently capable of parallel execution. Multi-processing and multi-threading hardware is automatically exploited by the built-in scheduler, which multiplexes multiple OS threads over the nodes ready for execution. 1.2 GRAPHICAL PROGRAMMING LabVIEW ties the creation of user interfaces (called front panels) into the development cycle. LabVIEW programs/subroutines are called virtual instruments (VIs). Each VI has three components: a block diagram, a front panel, and a connector panel. The last is used to represent the VI in the block diagrams of other, calling VIs. Controls and indicators on the front panel allow an operator to input data into or extract data from a running virtual instrument. However, the front panel can also serve as a programmatic interface. Thus a virtual instrument can either be run as a program, with the front panel serving as a user interface, or, when dropped as a node onto the block diagram, the front panel defines the inputs and outputs for the given node through the connector pane. This implies each VI can be easily tested before being embedded as a subroutine into a larger program. 1 2 Introduction to LabVIEW The graphical approach also allows non-programmers to build programs simply by dragging and dropping virtual representations of lab equipment with which they are already familiar. The LabVIEW programming environment, with the included examples and the documentation, makes it simple to create small applications. This is a benefit on one side, but there is also a certain danger of underestimating the expertise needed for good quality "G" programming. For complex algorithms or large-scale code, it is important that the programmer possess an extensive knowledge of the special LabVIEW syntax and the topology of its memory management. The most advanced LabVIEW development systems offer the possibility of building stand-alone applications. Furthermore, it is possible to create distributed applications, which communicate by a client/server scheme, and are therefore easier to implement due to the inherently parallel nature of G-code. 1.3 BENEFITS One benefit of LabVIEW over other development environments is the extensive support for accessing instrumentation hardware. Drivers and abstraction layers for many different types of instruments and buses are included or are available for inclusion. These present themselves as graphical nodes. The abstraction layers offer standard software interfaces to communicate with hardware devices. The provided driver interfaces save program development time. The sales pitch of National Instruments is, therefore, that even people with limited coding experience can write programs and deploy test solutions in a reduced time frame when compared to more conventional or competing systems. A new hardware driver topology (DAQmxBase), which consists mainly of G-coded components with only a few register calls through NI Measurement Hardware DDK (Driver Development Kit) functions, provides platform independent hardware access to numerous data acquisition and instrumentation devices. The DAQmxBase driver is available for LabVIEW on Windows, Mac OS X and Linux platforms. Tutorial: Database Communication in LabVIEW 2 DATABASE SYSTEMS A database is an integrated collection of logically related records or files consolidated into a common pool that provides data for one or more multiple uses. One way of classifying databases involves the type of content, for example: bibliographic, full-text, numeric, and image. Other classification methods start from examining database models or database architectures. The data in a database is organized according to a database model. The relational model is the most common. A Database Management System (DBMS) consists of software that organizes the storage of data. A DBMS controls the creation, maintenance, and use of the database storage structures of organizations and of their end users. It allows organizations to place control of organization-wide database development in the hands of Database Administrators (DBAs) and other specialists. In large systems, a DBMS allows users and other software to store and retrieve data in a structured way. Database management systems are usually categorized according to the database model that they support, such as the network, relational or object model. The model tends to determine the query languages that are available to access the database. One commonly used query language for the relational database is SQL, although SQL syntax and function can vary from one DBMS to another. A great deal of the internal engineering of a DBMS is independent of the data model, and is concerned with managing factors such as performance, concurrency, integrity, and recovery from hardware failures. In these areas there are large differences between products. 2.1 RDBMS COMPONENTS A Relational Database Management System (DBMS) consists of the following components: Interface drivers - A user or application program initiates either schema modification or content modification. These drivers are built on top of SQL. They provide methods to prepare statements, execute statements, fetch results, etc. An important example is the ODBC driver. SQL engine - This component interprets and executes the SQL query. It comprises three major components (compiler, optimizer, and execution engine). Transaction engine - Transactions are sequences of operations that read or write database elements, which are grouped together. Relational engine - Relational objects such as Table, Index, and Referential integrity constraints are implemented in this component. Storage engine - This component stores and retrieves data records. It also provides a mechanism to store metadata and control information such as undo logs, redo logs, lock tables, etc. 2.2 DATA WAREHOUSE A data warehouse stores data from current and previous years — data extracted from the various operational databases of an organization. It becomes the central source of data that has been screened, edited, standardized and integrated so that it can be used by managers and other end-user professionals throughout an organization. 2.3 RELATIONAL DATABASE 3 4 2 A relational database matches data using common characteristics found within the data set. The resulting groups of data are organized and are much easier for people to understand. For example, a data set containing all the real-estate transactions in a town can be grouped by the year the transaction occurred; or it can be grouped by the sale price of the transaction; or it can be grouped by the buyer's last name; and so on. Such a grouping uses the relational model (a technical term for this is schema). Hence, such a database is called a "relational database." The software used to do this grouping is called a relational database management system. The term "relational database" often refers to this type of software. Relational databases are currently the predominant choice in storing financial records, manufacturing and logistical information, personnel data and much more. Strictly, a relational database is a collection of relations (frequently called tables). 2.4 REAL-TIME DATABASES A real-time database is a processing system designed to handle workloads whose state may change constantly. This differs from traditional databases containing persistent data, mostly unaffected by time. For example, a stock market changes rapidly and dynamically. Real-time processing means that a transaction is processed fast enough for the result to come back and be acted on right away. Real-time databases are useful for accounting, banking, law, medical records, multi-media, process control, reservation systems, and scientific data analysis. As computers increase in power and can store more data, real-time databases become integrated into society and are employed in many applications 2.5 DATABASE MANAGEMENT SYSTEMS There are Database Management Systems (DBMS), such as: Microsoft SQL Server Oracle Sybase dBase Microsoft Access MySQL from Sun Microsystems (Oracle) DB2 from IBM etc. This document will focus on Microsoft Access and Microsoft SQL Server. 2.6 MDAC The Microsoft Data Access Components (MDAC) is the framework that makes it possible to connect and communicate with the database. MDAC includes the following components: Tutorial: Database Communication in LabVIEW 5 2 ODBC (Open Database Connectivity) OLE DB ADO (ActiveX Data Objects) MDAC also installs several data providers you can use to open a connection to a specific data source, such as an MS Access database. 2.6.1 ODBC Open Database Connectivity (ODBC) is a native interface that is accessed through a programming language that can make calls into a native library. In MDAC this interface is defined as a DLL. A separate module or driver is needed for each database that must be accessed. 2.6.2 OLE DB OLE allows MDAC applications access to different types of data stores in a uniform manner. Microsoft has used this technology to separate the application from the data store that it needs to access. This was done because different applications need access to different types and sources of data, and do not necessarily need to know how to access technology-specific functionality. The technology is conceptually divided into consumers and providers. The consumers are the applications that need access to the data, and the provider is the software component that exposes an OLE DB interface through the use of the Component Object Model (or COM). 2.6.3 ADO (ACTIVEX DATA OBJECTS) ActiveX Data Objects (ADO) is a high level programming interface to OLE DB. It uses a hierarchical object model to allow applications to programmatically create, retrieve, update and delete data from sources supported by OLE DB. ADO consists of a series of hierarchical COM-based objects and collections, an object that acts as a container of many other objects. A programmer can directly access ADO objects to manipulate data, or can send an SQL query to the database via several ADO mechanisms. Tutorial: Database Communication in LabVIEW 3 RELATIONAL DATABASES A relational database matches data using common characteristics found within the data set. The resulting groups of data are organized and are much easier for people to understand. For example, a data set containing all the real-estate transactions in a town can be grouped by the year the transaction occurred; or it can be grouped by the sale price of the transaction; or it can be grouped by the buyer's last name; and so on. Such a grouping uses the relational model (a technical term for this is schema). Hence, such a database is called a "relational database." The software used to do this grouping is called a relational database management system. The term "relational database" often refers to this type of software. Relational databases are currently the predominant choice in storing financial records, manufacturing and logistical information, personnel data and much more. 3.1 TABLES The basic units in a database are tables and the relationship between them. Strictly, a relational database is a collection of relations (frequently called tables). 3.2 UNIQUE KEYS AND PRIMARY KEY In relational database design, a unique key or primary key is a candidate key to uniquely identify each row in a table. A unique key or primary key comprises a single column or set of columns. No two distinct rows in a table can have the same value (or combination of values) in those columns. Depending on its design, a table may have arbitrarily many unique keys but at most one primary key. A unique key must uniquely identify all possible rows that exist in a table and not only the currently existing rows. Examples of unique keys are Social Security numbers or ISBNs. A primary key is a special case of unique keys. The major difference is that for unique keys the implicit NOT NULL constraint is not automatically enforced, while for primary keys it is enforced. Thus, the values in unique key columns may or may not be NULL. Another difference is that primary keys must be defined using another syntax. Primary keys are defined with the following syntax: CREATE TABLE table_name ( 6 7 Relational Databases id_col INT, col2 CHARACTER VARYING(20), ... CONSTRAINT tab_pk PRIMARY KEY(id_col), ... ) If the primary key consists only of a single column, the column can be marked as such using the following syntax: CREATE TABLE table_name ( id_col INT PRIMARY KEY, col2 CHARACTER VARYING(20), ... ) The definition of unique keys is syntactically very similar to primary keys. Likewise, unique keys can be defined as part of the CREATE TABLE SQL statement. CREATE TABLE table_name ( id_col INT, col2 CHARACTER VARYING(20), key_col SMALLINT, ... CONSTRAINT key_unique UNIQUE(key_col), ... ) Or if the unique key consists only of a single column, the column can be marked as such using the following syntax: CREATE TABLE table_name ( id_col INT PRIMARY KEY, col2 CHARACTER VARYING(20), ... key_col SMALLINT UNIQUE, Tutorial: Database Communication in LabVIEW 8 Relational Databases ... ) 3.3 FOREIGN KEY In the context of relational databases, a foreign key is a referential constraint between two tables. The foreign key identifies a column or a set of columns in one table that refers to a column or set of columns in another table. The columns in the referencing table must be the primary key or other candidate key in the referenced table. The values in one row of the referencing columns must occur in a single row in the referenced table. Thus, a row in the referencing table cannot contain values that don't exist in the referenced table. This way references can be made to link information together and it is an essential part of database normalization. Multiple rows in the referencing table may refer to the same row in the referenced table. Most of the time, it reflects the one (master table, or referenced table) to many (child table, or referencing table) relationship. The referencing and referenced table may be the same table, i.e. the foreign key refers back to the same table. Such a foreign key is known as self-referencing or recursive foreign key. A table may have multiple foreign keys, and each foreign key can have a different referenced table. Each foreign key is enforced independently by the database system. Therefore, cascading relationships between tables can be established using foreign keys. Improper foreign key/primary key relationships or not enforcing those relationships are often the source of many database and data modeling problems. Foreign keys can be defined as part of the CREATE TABLE SQL statement. CREATE TABLE table_name ( id INTEGER PRIMARY KEY, col2 CHARACTER VARYING(20), col3 INTEGER, ... CONSTRAINT col3_fk FOREIGN KEY(col3) REFERENCES other_table(key_col), ... ) If the foreign key is a single column only, the column can be marked as such using the following syntax: CREATE TABLE table_name ( id INTEGER PRIMARY KEY, col2 CHARACTER VARYING(20), col3 INTEGER REFERENCES other_table(column_name), ... ) Tutorial: Database Communication in LabVIEW 9 3.4 Relational Databases VIEWS In database theory, a view consists of a stored query accessible as a virtual table composed of the result set of a query. Unlike ordinary tables in a relational database, a view does not form part of the physical schema: it is a dynamic, virtual table computed or collated from data in the database. Changing the data in a table alters the data shown in subsequent invocations of the view. Views can provide advantages over tables: Views can represent a subset of the data contained in a table Views can join and simplify multiple tables into a single virtual table Views can act as aggregated tables, where the database engine aggregates data (sum, average etc) and presents the calculated results as part of the data Views can hide the complexity of data; for example a view could appear as Sales2000 or Sales2001, transparently partitioning the actual underlying table Views take very little space to store; the database contains only the definition of a view, not a copy of all the data it presents Views can limit the degree of exposure of a table or tables to the outer world Syntax: CREATE VIEW <ViewName> AS … 3.5 FUNCTIONS In SQL databases, a user-defined function provides a mechanism for extending the functionality of the database server by adding a function that can be evaluated in SQL statements. The SQL standard distinguishes between scalar and table functions. A scalar function returns only a single value (or NULL), whereas a table function returns a (relational) table comprising zero or more rows, each row with one or more columns. User-defined functions in SQL are declared using the CREATE FUNCTION statement. Syntax: CREATE FUNCTION <FunctionName> (@Parameter1 <datatype>, @ Parameter2 <datatype>, …) RETURNS <datatype> AS … 3.6 STORED PROCEDURES Tutorial: Database Communication in LabVIEW 10 Relational Databases A stored procedure is executable code that is associated with, and generally stored in, the database. Stored procedures usually collect and customize common operations, like inserting a tuple into a relation, gathering statistical information about usage patterns, or encapsulating complex business logic and calculations. Frequently they are used as an application programming interface (API) for security or simplicity. Stored procedures are not part of the relational database model, but all commercial implementations include them. Stored procedures are called or used with the following syntax: CALL procedure(…) or EXECUTE procedure(…) Stored procedures can return result sets, i.e. the results of a SELECT statement. Such result sets can be processed using cursors by other stored procedures by associating a result set locator, or by applications. Stored procedures may also contain declared variables for processing data and cursors that allow it to loop through multiple rows in a table. The standard Structured Query Language provides IF, WHILE, LOOP, REPEAT, CASE statements, and more. Stored procedures can receive variables, return results or modify variables and return them, depending on how and where the variable is declared. 3.7 TRIGGERS A database trigger is procedural code that is automatically executed in response to certain events on a particular table or view in a database. The trigger is mostly used for keeping the integrity of the information on the database. For example, when a new record (representing a new worker) added to the employees table, new records should be created also in the tables of the taxes, vacations, and salaries. The syntax is as follows: CREATE TRIGGER <TriggerName> ON <TableName> FOR INSERT, UPDATE, DELETE AS … Tutorial: Database Communication in LabVIEW 4 STRUCTURED QUERY LANGUAGE (SQL) SQL (Structured Query Language) is a database computer language designed for managing data in relational database management systems (RDBMS). 4.1 QUERIES The most common operation in SQL is the query, which is performed with the declarative SELECT statement. SELECT retrieves data from one or more tables, or expressions. Standard SELECT statements have no persistent effects on the database. Queries allow the user to describe desired data, leaving the database management system (DBMS) responsible for planning, optimizing, and performing the physical operations necessary to produce that result as it chooses. A query includes a list of columns to be included in the final result immediately following the SELECT keyword. An asterisk ("*") can also be used to specify that the query should return all columns of the queried tables. SELECT is the most complex statement in SQL, with optional keywords and clauses that include: The FROM clause which indicates the table(s) from which data is to be retrieved. The FROM clause can include optional JOIN subclauses to specify the rules for joining tables. The WHERE clause includes a comparison predicate, which restricts the rows returned by the query. The WHERE clause eliminates all rows from the result set for which the comparison predicate does not evaluate to True. The GROUP BY clause is used to project rows having common values into a smaller set of rows. GROUP BY is often used in conjunction with SQL aggregation functions or to eliminate duplicate rows from a result set. The WHERE clause is applied before the GROUP BY clause. The HAVING clause includes a predicate used to filter rows resulting from the GROUP BY clause. Because it acts on the results of the GROUP BY clause, aggregation functions can be used in the HAVING clause predicate. The ORDER BY clause identifies which columns are used to sort the resulting data, and in which direction they should be sorted (options are ascending or descending). Without an ORDER BY clause, the order of rows returned by an SQL query is undefined. Example: The following is an example of a SELECT query that returns a list of expensive books. The query retrieves all rows from the Book table in which the price column contains a value greater than 100.00. The result is sorted in ascending order by title. The asterisk (*) in the select list indicates that all columns of the Book table should be included in the result set. SELECT * FROM Book WHERE price > 100.00 ORDER BY title; The example below demonstrates a query of multiple tables, grouping, and aggregation, by returning a list of books and the number of authors associated with each book. 11 12 Structured Query Language (SQL) SELECT Book.title,count(*) AS Authors FROM Book JOIN Book_author ON Book.isbn = Book_author.isbn GROUP BY Book.title Example output might resemble the following: Title Authors ------------------------------SQL Examples and Guide 4 The Joy of SQL 1 An Introduction to SQL 2 Pitfalls of SQL 1 4.2 DATA MANIPULATION The Data Manipulation Language (DML) is the subset of SQL used to add, update and delete data. The acronym CRUD refers to all of the major functions that need to be implemented in a relational database application to consider it complete. Each letter in the acronym can be mapped to a standard SQL statement: Operation SQL Create INSERT Read (Retrieve) SELECT Update UPDATE Delete (Destroy) DELETE Example: INSERT INSERT adds rows to an existing table, e.g.,: INSERT INTO My_table field1, field2, field3) VALUES ('test', 'N', NULL) Example: UPDATE UPDATE modifies a set of existing table rows, e.g.,: UPDATE My_table SET field1 = 'updated value' WHERE field2 = 'N' Example: DELETE Tutorial: Database Communication in LabVIEW 13 Structured Query Language (SQL) DELETE removes existing rows from a table, e.g.,: DELETE FROM My_table WHERE field2 = 'N' 4.3 DATA DEFINITION The Data Definition Language (DDL) manages table and index structure. The most basic items of DDL are the CREATE, ALTER, RENAME and DROP statements: CREATE creates an object (a table, for example) in the database. DROP deletes an object in the database, usually irretrievably. ALTER modifies the structure an existing object in various ways—for example, adding a column to an existing table. Example: CREATE Create a Database Table CREATE TABLE My_table ( my_field1 INT, my_field2 VARCHAR(50), my_field3 DATE NOT NULL, PRIMARY KEY (my_field1) ) 4.4 DATA TYPES Each column in an SQL table declares the type(s) that column may contain. ANSI SQL includes the following datatypes. 4.4.1 CHARACTER STRINGS CHARACTER(n) or CHAR(n) — fixed-width n-character string, padded with spaces as needed CHARACTER VARYING(n) or VARCHAR(n) — variable-width string with a maximum size of n characters NATIONAL CHARACTER(n) or NCHAR(n) — fixed width string supporting an international character set NATIONAL CHARACTER VARYING(n) or NVARCHAR(n) — variable-width NCHAR string 4.4.2 BIT STRINGS BIT(n) — an array of n bits BIT VARYING(n) — an array of up to n bits 4.4.3 NUMBERS Tutorial: Database Communication in LabVIEW 14 Structured Query Language (SQL) INTEGER and SMALLINT FLOAT, REAL and DOUBLE PRECISION NUMERIC(precision, scale) or DECIMAL(precision, scale) 4.4.4 DATE AND TIME DATE TIME TIMESTAMP INTERVAL Tutorial: Database Communication in LabVIEW 5 DATABASE MODELLING 5.1 ER DIAGRAM In software engineering, an Entity-Relationship Model (ERM) is an abstract and conceptual representation of data. Entity-relationship modeling is a database modeling method, used to produce a type of conceptual schema or semantic data model of a system, often a relational database, and its requirements in a top-down fashion. Diagrams created using this process are called entity-relationship diagrams, or ER diagrams or ERDs for short. There are many ER diagramming tools. Some of the proprietary ER diagramming tools are ERwin, Enterprise Architect and Microsoft Visio. Microsoft SQL Server has also a built-in tool for creating Database Diagrams. 15 16 5.2 Database Modelling MICROSOFT VISIO Microsoft Visio is a diagramming program for creating different kinds of diagrams. Visio have a template for creating Database Model Diagrams. In the Database menu Visio offers lots of functionality regarding your database model. Tutorial: Database Communication in LabVIEW 17 Database Modelling “Reverse Engineering” is the opposite procedure, i.e., extraction of a database schema from an existing database into a database model in Microsoft Visio. EXERCISES Exercise: Database Diagram Create the following tables in an ER Diagram using MS Visio. CUSTOMER o CustomerId (PK) o FirstName o LastName o Address o Phone o PostCode o PostAddress PRODUCT o ProductId (PK) o ProductName o ProductDescription o Price o ProductCode ORDER o OrderId (PK) o OrderNumber o OrderDescription o CustomerId (FK) ORDER_DETAIL Tutorial: Database Communication in LabVIEW 18 Database Modelling o o o OrderDetailId (PK) OrderId (FK) ProductId (FK) Database Diagram: Tutorial: Database Communication in LabVIEW 6 MICROSOFT SQL SERVER 6.1 INTRODUCTION Microsoft SQL Server is a relational model database server produced by Microsoft. Its primary query languages are T-SQL and ANSI SQL. The latest version is Microsoft SQL Server 2008. Microsoft SQL Server homepage: www.microsoft.com/sqlserver The Microsoft SQL Server comes in different versions, such as: SQL Server Developer Edition SQL Server Enterprise Edition SQL Server Web Edition SQL Server Express Edition Etc. The SQL Server Express Edition is a freely-downloadable and -distributable version. 6.2 REQUIREMENTS In order to install SQL Server 2008, you need: Microsoft .NET Framework 3.5 SP1 Windows Installer 4.5 Windows PowerShell 1.0 Note: You must have administrative rights on the computer to install Microsoft SQL Server 2008. 6.3 SQL SERVER EXPRESS The SQL Server Express Edition is a freely-downloadable and -distributable version. However, the Express edition has a number of technical restrictions which make it undesirable for large-scale deployments, including: Maximum database size of 4 GB per. The 4 GB limit applies per database (log files excluded); but in some scenarios users can access more data through the use of multiple interconnected databases. Single physical CPU, multiple cores 1 GB of RAM (runs on any size RAM system, but uses only 1 GB) SQL Server Express offers a GUI tools for database management in a separate download and installation package, called SQL Server Management Studio Express. 6.4 ADVENTUREWORKS The AdventureWorks is a sample Database with lots of examples, etc. 19 20 Microsoft SQL Server You should install this sample Database because some of the examples in this document will use the AdventureWorks database. 6.5 SQL SERVER MANAGEMENT STUDIO SQL Server Management Studio is a GUI tool included with SQL Server for configuring, managing, and administering all components within Microsoft SQL Server. The tool includes both script editors and graphical tools that work with objects and features of the server. As mentioned earlier, version of SQL Server Management Studio is also available for SQL Server Express Edition, for which it is known as SQL Server Management Studio Express. A central feature of SQL Server Management Studio is the Object Explorer, which allows the user to browse, select, and act upon any of the objects within the server. It can be used to visually observe and analyze query plans and optimize the database performance, among others. SQL Server Management Studio can also be used to create a new database, alter any existing database schema by adding or modifying tables and indexes, or analyze performance. It includes the query windows which provide a GUI based interface to write and execute queries. 6.6 CREATE A NEW DATABASE It is quite simple to create a new database in Microsoft SQL Server. Just right-click on the “Databases” node and select “New Database…” Tutorial: Database Communication in LabVIEW 21 Microsoft SQL Server There are lots of settings you may set regarding your database, but the only information you must fill in is the name of your database: Tutorial: Database Communication in LabVIEW 22 6.7 Microsoft SQL Server BACKUP/RESTORE An important task in database systems is to take backup of the database with regular intervals, e.g., during the night when the system is not in use. Database backup and Restore: Tutorial: Database Communication in LabVIEW 23 6.8 Microsoft SQL Server EXAMPLE DATABASE Examples and exercises in this training are based on some basic tables. The Example Database consists of the following Tables: Tutorial: Database Communication in LabVIEW 24 Microsoft SQL Server CUSTOMER o CustomerId (PK) o FirstName o LastName o Address o Phone o PostCode o PostAddress PRODUCT o ProductId (PK) o ProductName o ProductDescription o Price o ProductCode ORDER o OrderId (PK) o OrderNumber o OrderDescription o CustomerId (FK) ORDER_DETAIL o OrderDetailId (PK) o OrderId (FK) o ProductId (FK) Tutorial: Database Communication in LabVIEW 25 Microsoft SQL Server EXERCISES Exercise: New Database Create a new Database in MS SQL Server called TEST_SQLSERVER. Exercise: Database Diagram Create the tables in the Example Database using the Diagram Designer Tool in Microsoft SQL Server. Exercise: Database Script Create the tables in the Example Database Tables using SQL Code. Save the Tables as a SQL Script file (.sql). Use The Query Tool in Microsoft SQL Server. Exercise: ODBC Create an ODBC connection for the Database. Tutorial: Database Communication in LabVIEW 7 MICROSOFT OFFICE ACCESS 7.1 INTRODUCTION Microsoft Office Access, previously known as Microsoft Access, is a relational database management system from Microsoft that combines the relational Microsoft Jet Database Engine with a graphical user interface and software development tools. It is a member of the Microsoft Office suite of applications and is included in the Professional and higher versions for Windows. Access stores data in its own format based on the Access Jet Database Engine. Microsoft Access is used by programmers and non-programmers to create their own simple database solutions. Microsoft Access is a file server-based database. Unlike client-server relational database management systems (RDBMS), e.g., Microsoft SQL Server, Microsoft Access does not implement database triggers, stored procedures, or transaction logging. All database tables, queries, forms, reports, macros, and modules are stored in the Access Jet database as a single file. This makes Microsoft Access useful in small applications, teaching, etc. because it is easy to move from one computer to another. 7.2 EXAMPLE DATABASE I will present an example database in Microsoft Access 2007 which will be used in some of the examples and exercises in this document. The database consists of the following tables: CUSTOMER o CustomerId (PK) o FirstName o LastName o Address o Phone o PostCode o PostAddress PRODUCT o ProductId (PK) o ProductName o ProductDescription o Price o ProductCode ORDER o OrderId (PK) o OrderNumber o OrderDescription o CustomerId (FK) ORDER_DETAIL o OrderDetailId (PK) o OrderId (FK) o ProductId (FK) 26 27 Microsoft Office Access ODBC Connection: Administrative Tools → Data Sources (ODBC) Tutorial: Database Communication in LabVIEW 28 Microsoft Office Access EXERCISES Exercise: Database Create a new Database in MS Access called TEST. Exercise: Database Tables Tutorial: Database Communication in LabVIEW 29 Microsoft Office Access Create the tables in the Example Database Tables using the Diagram Designer Tool in Microsoft SQL Server. Exercise: ODBC Create an ODBC connection for the Database. Tutorial: Database Communication in LabVIEW 8 LABVIEW DATABASE CONNECTIVITY TOOLKIT LabVIEW offers an additional Toolkit called “LabVIEW Database Connectivity Toolkit”. With this toolkit you can communicate with different databases, such as SQL Server, Oracle, etc. Functions Palette: Connectivity → Database The following list describes the main features of the Database Connectivity Toolkit: Works with any provider that adheres to the Microsoft ActiveX Data Object (ADO) standard. Works with any database driver that complies with ODBC or OLE DB. Maintains a high level of portability. In many cases, you can port an application to another database by changing the connection information you pass to the DB Tools Open Connection VI. Converts database column values from native data types to standard Database Connectivity Toolkit data types, further enhancing portability. Permits the use of SQL statements with all supported database systems, even non-SQL systems. Includes VIs to retrieve the name and data type of a column returned by a SELECT statement. Creates tables and selects, inserts, updates, and deletes records without using SQL statements. Some of the text in this chapter is based on the “LabVIEW Database Connectivity Toolkit User Manual”. 8.1 CONNECT TO THE DATABASE Before you can access data in a table or execute SQL statements, you must establish a connection to a database. You may use different methods in order to connect to the database: ODBC Data Source Name (DSN) Universal Data Link (UDL) Connection String These different methods are explained below. For all of these methods, you will use the same VI: 30 31 LabVIEW Database Connectivity Toolkit Connecting to a database is where most errors occur because each database management system (DBMS) uses different parameters for the connection and different levels of security. The different standards also use different methods of connecting to databases. For example, ODBC uses Data Source Names (DSN) for the connection, whereas the Microsoft ActiveX Data Object (ADO) standard uses Universal Data Links (UDL) for the connection. The “DB Tools Open Connection.vi” VI supports all these methods for connecting to a database. When you are finished with reading from the database and writing to the database, you should always close the Connection. Use the “DB Tools Close Connection.vi”. 8.1.1 DSN A DSN (ODBC Data Source Name (DSN)) is the name of the data source, or database, to which you are connecting. The DSN also contains information about the ODBC driver and other connection attributes including paths, security information, and read-only status of the database. Two main types of DSNs exist: machine DSNs and file DSNs. Machine DSNs are in the system registry and apply to all users of the computer system or to a single user. DSNs that apply to all users of a computer system are system DSNs. DSNs that apply to single users are user DSNs. A file DSN is a text file with a .dsn extension and is accessible to anyone with proper permissions. File DSNs are not restricted to a single user or computer system. Use the ODBC Data Source Administrator to create and configure DSNs. In the Control Panel, Administrative Tools, you find the ODBC Data Source Administrator tool. Tutorial: Database Communication in LabVIEW 32 LabVIEW Database Connectivity Toolkit Example: DSN This Example specifies a DSN called MS Access to open a connection to that specific database. Example: DSN from File You can use a path to specify a file DSN. This example specifies a path to a file DSN called “access.dsn” to open a connection to the database. Example: DSN with UserId and Password Most Database systems (DBMS – Database Management Systems) also require a UserId and a Password. Tutorial: Database Communication in LabVIEW 33 LabVIEW Database Connectivity Toolkit 8.1.2 UDL Whereas you must create a DSN to connect to a database using ODBC, you use UDL (Universal Data Link) to connect to databases that use ADO and OLE DB. A UDL is similar to a DSN in that it describes more than just the data source. A UDL specifies what OLE DB provider is used, server information, the user ID and password, the default database, and other related information. In order to create a new UDL file, create an empty text file and change the file extension of this document from .txt to .udl. You then can double-click the UDL file to display the Data Link Properties dialog box. Example: UDL Connect to a Database using UDL: Tutorial: Database Communication in LabVIEW 34 LabVIEW Database Connectivity Toolkit 8.1.3 CONNECTION STRING Rather than including an existing UDL in an application, you also can use an ODBC connection string with the Microsoft ActiveX Data Object (ADO) standard. A connection string is written like this: PROVIDER=SQLOLEDB;DATA SOURCE=server_name;UID=user_name;PWD=password;DATABASE=database_name; You could use more parameters, but the parameters used above are the most common ones. 8.2 READING DATA FROM THE DATABASE Reading data from a database table is similar to writing data to the database. You open a connection to the database, select the data from a table, and then close the connection. The “DB Tools Select Data.vi" is used to read data from the Database: Example: Select Data from MS Access The following example gets data from the CUSTOMER table in MS Access. The Front Panel looks like this: Tutorial: Database Communication in LabVIEW 35 LabVIEW Database Connectivity Toolkit Notice in Figures 5-4 and 5-5 that the database data is returned as a two-dimensional array of variants. As the name implies, the Microsoft ActiveX Data Object (ADO) standard is based on ActiveX, which defines variants as its data types. Variants work well in languages such as Visual Basic that are not strongly typed. Because LabVIEW is strongly typed, you must use the Database Variant To Data function to convert the variant data to a LabVIEW data type before you can display the data in standard indicators such as graphs, charts, and LEDs. Example: Select Data from MS Access The following example gets data from the CUSTOMER table in MS Access and converts the data to text. The Front Panel looks like this: Tutorial: Database Communication in LabVIEW 36 LabVIEW Database Connectivity Toolkit You may read from more than one table if you use a comma-delimited string to specify multiple table names: You may select which columns you want to read by using the “Columns” input: You may also restrict which data to receive using the “optional Clause” input: Tutorial: Database Communication in LabVIEW 37 LabVIEW Database Connectivity Toolkit Example: Read Data Using some VIs from the “Advanced” palette, create the following example: 8.3 WRITING DATA TO THE DATABASE Writing data to a database with the LabVIEW Database Connectivity Toolkit is similar to reading data to a file. You open a connection, insert the data, and close the connection when you are finished. The “DB Tools Insert Data.vi" is used to write data to the Database: Tutorial: Database Communication in LabVIEW 38 LabVIEW Database Connectivity Toolkit Example: Write Data Create the following block diagram: Front Panel: Tutorial: Database Communication in LabVIEW 39 LabVIEW Database Connectivity Toolkit Example: Write Data Create the following block diagram using some VIs from the “Advanced” palette. 8.4 USING STORED PROCEDURES 8.5 CREATING AND DROPING TABLES You may use standard SQL syntax in order to create: CREATE TABLE <TableName> (…) Or you may use the “DB Tools Create Table.vi” in order to create a table. You may use standard SQL syntax in order to drop tables (delete tables): DROP TABLE <TableName> Or you may use the “DB Tools Drop Table.vi” in order to drop/delete a table. Tutorial: Database Communication in LabVIEW 40 8.6 LabVIEW Database Connectivity Toolkit USING THE DATABASE CONNECTIVITY TOOLKIT UTILITY VIS In the “Utility” palette there are several useful VIs for getting more information about tables, saving to text files, etc. Here is a short description of the VIs located in the “Utility” palette: This VI lists the tables in the database identified by connection reference. This VI lists the columns present in table. The column information includes the name, the data type, and the defined size of the column. This VI sets properties on the object as determined by the inputs. This VI gets properties of the object as determined by the inputs. Tutorial: Database Communication in LabVIEW 41 LabVIEW Database Connectivity Toolkit This VI Returns a string containing the formatted date and time, and identifies the string as a date/time string so other VIs can interpret it. This VI begins, commits, or rolls back a transaction for any type of reference. This VI saves the recordset identified by the recordset reference to either an XML or ADTG file. The ADTG file format is a proprietary format that only the LabVIEW Database Connectivity Toolkit can interpret. The ADTG format results in a smaller file than the XML format. This VI loads a recordset from a file and returns a recordset reference that identifies this recordset. You can retrieve data from this recordset like any other recordset, but some properties might not be available on this recordset. 8.7 PERFORMING ADVANCED DATABASE OPERATIONS When creating real programs you will soon need some of the VIs in the “Advanced” palette. Here is a short description of some of the VIs located in the “Advanced” palette: This VI Executes an SQL query and returns a recordset reference that you must eventually free with the DB Tools Free Object VI. Tutorial: Database Communication in LabVIEW 42 LabVIEW Database Connectivity Toolkit This VI retrieves the data in the recordset identified by the recordset reference input. You can convert each element in the array to its native LabVIEW data type using the “Database Variant To Data function”. This VI frees an object by destroying its associated reference and returns a different reference object. Tutorial: Database Communication in LabVIEW 9 CREATING AND USING TABLES The SQL syntax for creating a Table is as follows: CREATE TABLE <TableName> ( <ColumnName> <datatype> … ) The SQL syntax for inserting Data into a Table is as follows: INSERT INTO <TableName> (<Column1>, <Column2>, …) VALUES(<Data for Column1>, <Data for Column2>, …) Example: Insert Data into Tables We will insert some data into our tables: The following SQL Query inserts some example data into these tables: --CUSTOMER INSERT INTO [CUSTOMER] ([FirstName],[LastName],[Address],[Phone],[PostCode],[PostAddress]) VALUES ('Per', 'Nilsen', 'Vipeveien 12', '12345678', '1234', 'Porsgrunn') GO INSERT INTO [CUSTOMER] ([FirstName],[LastName],[Address],[Phone],[PostCode],[PostAddress]) VALUES ('Tor', 'Hansen', 'Vipeveien 15', '77775678', '4455', 'Bergen') GO 43 44 Creating and Using Tables INSERT INTO [CUSTOMER] ([FirstName],[LastName],[Address],[Phone],[PostCode],[PostAddress]) VALUES ('Arne', 'Nilsen', 'Vipeveien 17', '12345778', '4434', 'Porsgrunn') GO --PRODUCT INSERT INTO [PRODUCT] ([ProductName],[ProductDescription],[Price],[ProductCode]) VALUES ('Product A', 'This is product A', 1000, 'A-1234') GO INSERT INTO [PRODUCT] ([ProductName],[ProductDescription],[Price],[ProductCode]) VALUES ('Product B', 'This is product B', 1000, 'B-1234') GO INSERT INTO [PRODUCT] ([ProductName],[ProductDescription],[Price],[ProductCode]) VALUES ('Product C', 'This is product C', 1000, 'C-1234') GO --ORDER INSERT INTO [ORDER] ([OrderNumber],[OrderDescription],[CustomerId]) VALUES ('10001', 'This is Order 10001', 1) GO INSERT INTO [ORDER] ([OrderNumber],[OrderDescription],[CustomerId]) VALUES ('10002', 'This is Order 10002', 2) GO INSERT INTO [ORDER] ([OrderNumber],[OrderDescription],[CustomerId]) VALUES ('10003', 'This is Order 10003', 3) GO --ORDER_DETAIL INSERT INTO [ORDER_DETAIL] ([OrderId],[ProductId]) VALUES (1, 1) GO INSERT INTO [ORDER_DETAIL] ([OrderId],[ProductId]) VALUES (1, 2) GO INSERT INTO [ORDER_DETAIL] ([OrderId],[ProductId]) VALUES (1, 3) GO INSERT INTO [ORDER_DETAIL] ([OrderId],[ProductId]) VALUES (2, 1) GO INSERT INTO [ORDER_DETAIL] ([OrderId],[ProductId]) VALUES (2, 2) GO INSERT INTO [ORDER_DETAIL] ([OrderId],[ProductId]) VALUES (3, 3) GO INSERT INTO [ORDER_DETAIL] ([OrderId],[ProductId]) VALUES (3, 1) GO INSERT INTO [ORDER_DETAIL] ([OrderId],[ProductId]) VALUES (3, 2) GO INSERT INTO [ORDER_DETAIL] ([OrderId],[ProductId]) VALUES (3, 3) GO Executing the following Queries then gives: select * from CUSTOMER select * from PRODUCT Tutorial: Database Communication in LabVIEW 45 Creating and Using Tables select * from [ORDER] select * from ORDER_DETAIL EXERCISES Run the queries above from LabVIEW. Tutorial: Database Communication in LabVIEW 10 CREATING AND USING VIEWS In database theory, a view consists of a stored query accessible as a virtual table composed of the result set of a query. Unlike ordinary tables in a relational database, a view does not form part of the physical schema: it is a dynamic, virtual table computed or collated from data in the database. Changing the data in a table alters the data shown in subsequent invocations of the view. Views can provide advantages over tables: Views can represent a subset of the data contained in a table Views can join and simplify multiple tables into a single virtual table Views can act as aggregated tables, where the database engine aggregates data (sum, average etc) and presents the calculated results as part of the data Views can hide the complexity of data; for example a view could appear as Sales2000 or Sales2001, transparently partitioning the actual underlying table Views take very little space to store; the database contains only the definition of a view, not a copy of all the data it presents Depending on the SQL engine used, views can provide extra security Views can limit the degree of exposure of a table or tables to the outer world Just as functions (in programming) can provide abstraction, so database users can create abstraction by using views. In another parallel with functions, database users can manipulate nested views, thus one view can aggregate data from other views. Syntax: CREATE VIEW <ViewName> AS … EXERCISES Create a simple view based on the example tables and run the view from LabVIEW. 46 11 CREATING AND USING STORED PROCEDURES A stored procedure is a subroutine available to applications accessing a relational database system. Typical uses for stored procedures include data validation (integrated into the database) or access control mechanisms. Furthermore, stored procedures are used to consolidate and centralize logic that was originally implemented in applications. Large or complex processing that might require the execution of several SQL statements is moved into stored procedures, and all applications call the procedures only. A stored procedure is a precompiled collection of SQL statements and optional control-of-flow statements, similar to a macro. Each database and data provider supports stored procedures differently. Stored procedures offer the following benefits to your database applications: Performance—Stored Procedures are usually more efficient and faster than regular SQL queries because SQL statements are parsed for syntactical accuracy and precompiled by the DBMS when the stored procedure is created. Also, combining a large number of SQL statements with conditional logic and parameters into a stored procedure allows the procedures to perform queries, make decisions, and return results without extra trips to the database server. Maintainability—Stored Procedures isolate the lower-level database structure from the application. As long as the table names, column names, parameter names, and types do not change from what is stated in the stored procedure, you do not need to modify the procedure when changes are made to the database schema. Stored procedures are also a way to support modular SQL programming because after you create a procedure, you and other users can reuse that procedure without knowing the details of the tables involved. Security—When creating tables in a database, the Database Administrator can set EXECUTE permissions on stored procedures without granting SELECT, INSERT, UPDATE, and DELETE permissions to users. Therefore, the data in these tables is protected from users who are not using the stored procedures. Stored procedures are similar to user-defined functions. The major difference is that functions can be used like any other expression within SQL statements, whereas stored procedures must be invoked using the CALL statement. The syntax for creating a Stored Procedure is as follows: CREATE PROCEDURE <ProcedureName> @<Parameter1> <datatype> … Example: Create a Stored Procedure This Procedure gets Customer Data based on a specific Order Number. IF EXISTS (SELECT name FROM sysobjects WHERE name = 'sp_CustomerOrders' AND type = 'P') DROP PROCEDURE sp_CustomerOrders GO CREATE PROCEDURE sp_CustomerOrders 47 48 Creating and using Stored Procedures @OrderNumber varchar(50) AS /*------------------------------------------------------------------------Last Updated Date: 2009.11.03 Last Updated By: hans.pr.halvorsen@hit.no Description: Get Customer Information from a specific Order Number -------------------------------------------------------------------------*/ SET NOCOUNT ON declare @CustomerId int select @CustomerId = CustomerId from [ORDER] where OrderNumber = @OrderNumber select CustomerId, FirstName, LastName, [Address], Phone from CUSTOMER where CustomerId=@CustomerId SET NOCOUNT OFF Og Example: Using a Stored Procedure Using the Stored procedure like this exec sp_CustomerOrders '10002' gives the following result: EXERCISES Run the Stored Procedure created above from LabVIEW. Tutorial: Database Communication in LabVIEW 12 CREATING AND USING TRIGGERS A database trigger is procedural code that is automatically executed in response to certain events on a particular table or view in a database. The trigger is mostly used for keeping the integrity of the information on the database. For example, when a new record (representing a new worker) added to the employees table, new records should be created also in the tables of the taxes, vacations, and salaries. Triggers are commonly used to: prevent changes (e.g. prevent an invoice from being changed after it's been mailed out) log changes (e.g. keep a copy of the old data) audit changes (e.g. keep a log of the users and roles involved in changes) enhance changes (e.g. ensure that every change to a record is time-stamped by the server's clock, not the client's) enforce business rules (e.g. require that every invoice have at least one line item) execute business rules (e.g. notify a manager every time an employee's bank account number changes) replicate data (e.g. store a record of every change, to be shipped to another database later) enhance performance (e.g. update the account balance after every detail transaction, for faster queries) The major features of database triggers, and their effects, are: do not accept parameters or arguments (but may store affected-data in temporary tables) cannot perform commit or rollback operations because they are part of the triggering SQL statement can cancel a requested operation can cause mutating table errors, if they are poorly written. Microsoft SQL Server supports triggers either after or instead of an insert, update, or delete operation. Syntax: CREATE TRIGGER <TriggerName> ON <TableName> FOR INSERT, UPDATE, DELETE AS … EXERCISES Create a Trigger that adds “+47” to all Phone numbers in the CUSTOMER table. Test and see if the Trigger works properly by inserting and updating some data in the CUSTOMER table. 49 13 CREATING AND USING FUNCTIONS In SQL databases, a user-defined function provides a mechanism for extending the functionality of the database server by adding a function that can be evaluated in SQL statements. The SQL standard distinguishes between scalar and table functions. A scalar function returns only a single value (or NULL), whereas a table function returns a (relational) table comprising zero or more rows, each row with one or more columns. Stored Procedures vs. Functions: Only functions can return a value (using the RETURN keyword). Stored procedures can use RETURN keyword but without any value being passed[1] Functions could be used in SELECT statements, provided they don’t do any data manipulation and also should not have any OUT or IN OUT parameters. Functions must return a value, but for stored procedures this is not compulsory. A function can have only IN parameters, while stored procedures may have OUT or IN OUT parameters. A function is a subprogram written to perform certain computations and return a single value. A stored procedure is a subprogram written to perform a set of actions, and can return multiple values using the OUT parameter or return no value at all. User-defined functions in SQL are declared using the CREATE FUNCTION statement. Syntax: CREATE FUNCTION <FunctionName> (@Parameter1 <datatype>, @ Parameter2 <datatype>, …) RETURNS <datatype> AS … EXERCISES Create a simple function that finds number of order for a specific customer and use it in the following query: “Select FirstName, LastName, fn_NumberOfOrders(CustomerId) from CUSTOMER” 50 14 SQL TOOLKIT I have made a simple and easy to-use SQL Toolkit. The SQL Toolkit is available for download from my Blog: http://home.hit.no/~hansha/ 14.1 INSTALLATION The installation procedure is as follows: 1. 2. 3. 4. 5. Download the zip file SQLToolkit.zip from my Blog Unzip the file Copy "SQLToolkit.mnu" to ...\LabVIEW 2009\menus\Categories\ Copy "SQLToolkit.llb" to ...\LabVIEW 2009\vi.lib\ The SQL Toolkit is ready to use and in the Functions palette in LabVIEW a new palette named "SQL" will appear. The SQL Toolkit palette in available in LabVIEW: The SQL Toolkit contains the following VIs: “SQL Open.vi” - This VI open a connection to the database specified in the Connection string. The connection string may be as follows: “PROVIDER=SQLOLEDB; DATA SOURCE=xxx;UID=xxx;PWD=xxx;DATABASE=xxx” You need to replace the “xxx” with the parameters from your database. “SQL Select.vi” -This VI get data from the database specified in the SQL Query. The output is a 2D string array with data. “SQL Execute.vi” - This VI executes a Query with no return Data, e.g., an INSERT statement “SQL Close.vi” - This VI Close the connection to the database opened by "SQL Open.vi" 51 52 SQL Toolkit Two examples are also included: “SQL – Example 1.vi” – This example selects data from a table. The example uses “SQL Select.vi” in order to get data from the database. Front panel: Block Diagram: “SQL – Example 2.vi” – This example inserts data into a table. The example uses “SQL Execute.vi” in order to insert data into the database. No data is returned. Front panel: Tutorial: Database Communication in LabVIEW 53 SQL Toolkit Block Diagram: Tutorial: Database Communication in LabVIEW 15 WHATS NEXT? 15.1 MY BLOG For more information about LabVIEW, visit my Blog: http://home.hit.no/~hansha/ 15.2 TRAINING This Training is a part of a series with other Training Kits I have made, such as: Introduction to LabVIEW Data Acquisition in LabVIEW Control and Simulation in LabVIEW LabVIEW MathScript Linear Algebra in LabVIEW Datalogging and Supervisory Control in LabVIEW Wireless Data Acquisition in LabVIEW Intermediate Topics in LabVIEW Advanced Topics in LabVIEW These Training Kits are available for download from my blog: http://home.hit.no/~hansha 15.3 ADDITIONAL RESOURCES www.ni.com 15.4 EXAMPLES In the NI example Finder (Help→Find Examples…) you find lots of useful examples that you can play with or use as a start when creating your own applications. 54 55 Whats Next? 15.5 DOCUMENTATION As part of the LabVIEW installation there comes a lots of useful documentation. 15.6 LABVIEW WIKI LabVIEW Wiki is the free LabVIEW information resource that anyone can edit. http://labviewwiki.org/Home Tutorial: Database Communication in LabVIEW 56 Whats Next? 15.7 LABVIEW ON YOUTUBE There are lots of LabVIEW videos available at YouTube: http://www.youtube.com/results?search_query=labview&search=Search Tutorial: Database Communication in LabVIEW QUICK REFERENCE 57 58 Quick Reference Tutorial: Database Communication in LabVIEW Telemark University College Faculty of Technology Kjølnes Ring 56 N-3914 Porsgrunn, Norway www.hit.no Hans-Petter Halvorsen, M.Sc. Telemark University College Department of Electrical Engineering, Information Technology and Cybernetics Phone: +47 3557 5158 E-mail: hans.p.halvorsen@hit.no Blog: http://home.hit.no/~hansha/ Room: B-237a Telemark University College Department of Electrical Engineering, Information Technology and Cybernetics OPC AND REAL-TIME SYSTEMS IN LABVIEW HANS-PETTER HALVORSEN, 2010.01.27 Faculty of Technology, Postboks 203, Kjølnes ring 56, N-3901 Porsgrunn, Norway. Tel: +47 35 57 50 00 Fax: +47 35 57 54 01 PREFACE OPC (OLE for process control) is a standard interface between numerous data sources, – such as programmable logic controllers (PLCs), remote terminal units (RTUs), and sensors on a factory floor – to HMI/SCADA applications, application tools, and databases. With OPC, your device-side server and application software can communicate without your duplicating device driver development and providing support for hardware feature changes. The OPC Foundation defines the standards that allow any client to access any OPC-compatible device. INSTALLATION REQUIREMENTS NI LabVIEW Name Required LabVIEW Professional Development System Yes NI LabVIEW Core Components Name Required LabVIEW Control Design and Simulation Module LabVIEW MathScript RT Module NI Vision Development Module Vision Builder for Automated Inspection LabVIEW Digital Filter Design Toolkit LabVIEW Modulation Toolkit LabVIEW System Identification Toolkit LabVIEW Desktop Execution Trace Toolkit LabVIEW Report Generation for Microsoft Office Toolkit LabVIEW Database Connectivity Toolkit LabVIEW Internet Toolkit NI LabVIEW SignalExpress LabVIEW Basics 1 and 2 Computer Based Training Extended Development Suite Components Name Required LabWindows/CVI Full Development System LabWindows/CVI Real-Time Module LabWindows/CVI PID Control Toolkit LabWindows/CVI Signal Processing Toolkit LabWindows/CVI Spectral Measurements Toolkit and Run-time Engine LabWindows/CVI SQL Toolkit Measurement Studio Enterprise Edition iii DIAdem Professional Control and Embedded Systems Option Components Name Required LabVIEW FPGA Module LabVIEW Real-Time Module Yes LabVIEW Statechart Module LabVIEW Mobile Module LabVIEW Datalogging and Supervisory Control Module LabVIEW PID and Fuzzy Logic Toolkit NI Real-Time Execution Trace Toolkit LabVIEW Simulation Interface Toolkit NI Motion Assistant NI-DAQ Base Signal processing and Communications Option Components Name Required LabVIEW FPGA Module LabVIEW Sound and Vibration Measurement Suite LabVIEW Spectral Measurement Toolkit LabVIEW Advanced Signal Processing Toolkit LabVIEW Adaptive Filter Toolkit NI Device Drivers Name Required FieldPoint Yes NI-DAQmx Yes NI LabVIEW SignalExpress NI Instrument I/O Assistant NI-IMAQ NI Measurement & Automation Explorer Yes NI PXI NI-VISA In addition the following software will be needed in this Tutorial: NI OP Servers (Evaluation version available from www.ni.com) MatrikonOPC Simulation Server (free download from http://matrikon.com/) TABLE OF CONTENTS Preface .................................................................................................................................................................... 2 Installation Requirements ....................................................................................................................................... iii Table of Contents .................................................................................................................................................... vi 1 2 Introduction to LabVIEW ............................................................................................................................... 1 1.1 Dataflow programming.......................................................................................................................... 1 1.2 Graphical programming ......................................................................................................................... 1 1.3 Benefits .................................................................................................................................................. 2 1.4 LabVIEW MathScript RT Module ........................................................................................................... 2 Introduction to OPC ....................................................................................................................................... 3 2.1 OPC Server ............................................................................................................................................. 4 2.2 OPC Client .............................................................................................................................................. 6 2.3 Tags ........................................................................................................................................................ 6 2.4 Why Do We Need OPC Standards? ........................................................................................................ 6 3 Introduction to Real-Time Systems ............................................................................................................... 7 4 Introduction to Embedded Systems .............................................................................................................. 8 5 Multithreading in LabVIEW ......................................................................................................................... 10 6 7 5.1 Multitasking ......................................................................................................................................... 10 5.2 Multithreading ..................................................................................................................................... 10 DataSocket ................................................................................................................................................... 12 6.1 Architecture ......................................................................................................................................... 12 6.2 DataSocket Server ............................................................................................................................... 13 6.3 DataSocket in LabVIEW........................................................................................................................ 13 OPC Servers from National Instruments...................................................................................................... 15 7.1 NI OPC Servers ..................................................................................................................................... 15 7.1.1 7.2 OPC Quick Client ......................................................................................................................... 16 Shared Variable Engine ........................................................................................................................ 18 vi vii Table of Contents 8 MatrikonOPC Simulation Server .................................................................................................................. 19 9 10 8.1 MatrikonOPC Server ............................................................................................................................ 19 8.2 Aliases .................................................................................................................................................. 20 8.3 Matrikon OPC Explorer (Client) ........................................................................................................... 21 Using OPC from LabVIEW ............................................................................................................................ 23 9.1 OPC URL ............................................................................................................................................... 23 9.2 Read OPC Data ..................................................................................................................................... 24 9.3 Write OPC Data .................................................................................................................................... 25 LabVIEW Datalogging and Supervisory Control ........................................................................................... 27 10.1 Functions and VIs Palettes ................................................................................................................... 28 10.2 DSC Module Controls Palettes ............................................................................................................. 28 10.3 Citadel Database .................................................................................................................................. 29 10.4 Historical Data Viewer ......................................................................................................................... 29 10.5 Distributed System Manager ............................................................................................................... 30 10.6 SQL Server............................................................................................................................................ 31 Exercises ........................................................................................................................................................... 32 11 12 LabVIEW I/O Server ..................................................................................................................................... 52 11.1 Connect LabVIEW to OPC Tags by Creating an I/O Server ................................................................... 52 11.2 Create Shared Variables that Connect to the OPC Tags through the I/O Server ................................. 53 11.3 Viewing Shared Variables with Distributed System Manager ............................................................. 54 11.4 Using OPC Tag Data in LabVIEW .......................................................................................................... 55 LabVIEW Real-Time Module ........................................................................................................................ 59 12.1 Real-Time Development in LabvIEW ................................................................................................... 59 13 Compact FieldPoint ..................................................................................................................................... 62 14 Whats Next? ................................................................................................................................................ 70 14.1 My Blog ................................................................................................................................................ 70 14.2 Training ................................................................................................................................................ 70 Quick Reference .................................................................................................................................................... 71 Tutorial: OPC and Real-Time Systems in LabVIEW viii Table of Contents Tutorial: OPC and Real-Time Systems in LabVIEW 1 INTRODUCTION TO LABVIEW LabVIEW (short for Laboratory Virtual Instrumentation Engineering Workbench) is a platform and development environment for a visual programming language from National Instruments. The graphical language is named "G". Originally released for the Apple Macintosh in 1986, LabVIEW is commonly used for data acquisition, instrument control, and industrial automation on a variety of platforms including Microsoft Windows, various flavors of UNIX, Linux, and Mac OS X. The latest version of LabVIEW is version LabVIEW 2009, released in August 2009. Visit National Instruments at www.ni.com. The code files have the extension “.vi”, which is an abbreviation for “Virtual Instrument”. LabVIEW offers lots of additional Add-Ons and Toolkits. This paper is part of a series with LabVIEW papers: Introduction to LabVIEW Data Acquisition in LabVIEW Control and Simulation in LabVIEW Linear Algebra in LabVIEW Database Communication in LabVIEW Datalogging and Supervisory Control in LabVIEW Intermediate Topics in LabVIEW Advanced Topics in LabVIEW Etc. Each paper may be used independently of each other. 1.1 DATAFLOW PROGRAMMING The programming language used in LabVIEW, also referred to as G, is a dataflow programming language. Execution is determined by the structure of a graphical block diagram (the LV-source code) on which the programmer connects different function-nodes by drawing wires. These wires propagate variables and any node can execute as soon as all its input data become available. Since this might be the case for multiple nodes simultaneously, G is inherently capable of parallel execution. Multi-processing and multi-threading hardware is automatically exploited by the built-in scheduler, which multiplexes multiple OS threads over the nodes ready for execution. 1.2 GRAPHICAL PROGRAMMING LabVIEW ties the creation of user interfaces (called front panels) into the development cycle. LabVIEW programs/subroutines are called virtual instruments (VIs). Each VI has three components: a block diagram, a front panel, and a connector panel. The last is used to represent the VI in the block diagrams of other, calling VIs. Controls and indicators on the front panel allow an operator to input data into or extract data from a running virtual instrument. However, the front panel can also serve as a programmatic interface. Thus a virtual instrument can either be run as a program, with the front panel serving as a user interface, or, when dropped as a node onto the block diagram, the front panel defines the inputs and outputs for the given node through the connector pane. This implies each VI can be easily tested before being embedded as a subroutine into a larger program. 1 2 Introduction to LabVIEW The graphical approach also allows non-programmers to build programs simply by dragging and dropping virtual representations of lab equipment with which they are already familiar. The LabVIEW programming environment, with the included examples and the documentation, makes it simple to create small applications. This is a benefit on one side, but there is also a certain danger of underestimating the expertise needed for good quality "G" programming. For complex algorithms or large-scale code, it is important that the programmer possess an extensive knowledge of the special LabVIEW syntax and the topology of its memory management. The most advanced LabVIEW development systems offer the possibility of building stand-alone applications. Furthermore, it is possible to create distributed applications, which communicate by a client/server scheme, and are therefore easier to implement due to the inherently parallel nature of G-code. 1.3 BENEFITS One benefit of LabVIEW over other development environments is the extensive support for accessing instrumentation hardware. Drivers and abstraction layers for many different types of instruments and buses are included or are available for inclusion. These present themselves as graphical nodes. The abstraction layers offer standard software interfaces to communicate with hardware devices. The provided driver interfaces save program development time. The sales pitch of National Instruments is, therefore, that even people with limited coding experience can write programs and deploy test solutions in a reduced time frame when compared to more conventional or competing systems. A new hardware driver topology (DAQmxBase), which consists mainly of G-coded components with only a few register calls through NI Measurement Hardware DDK (Driver Development Kit) functions, provides platform independent hardware access to numerous data acquisition and instrumentation devices. The DAQmxBase driver is available for LabVIEW on Windows, Mac OS X and Linux platforms. For more information about LabVIEW, visit my Blog: http://home.hit.no/~hansha/ 1.4 LABVIEW MATHSCRIPT RT MODULE The LabVIEW MathScript RT Module is an add-on module to LabVIEW. With LabVIEW MathScript RT Module you can: Deploy your custom .m files to NI real-time hardware Reuse many of your scripts created with The MathWorks, Inc. MATLAB® software and others Develop your .m files with an interactive command-line interface Embed your scripts into your LabVIEW applications using the MathScript Node Tutorial: OPC and Real-Time Systems in LabVIEW 2 INTRODUCTION TO OPC [Source: Wikipedia, National Instruments] OLE for Process Control (OPC), which stands for Object Linking and Embedding (OLE) for Process Control, is the original name for a standard specification developed in 1996. The standard specifies the communication of real-time plant data between control devices from different manufacturers. After the initial release, the OPC Foundation was created to maintain the standard. OPC Foundation: http://www.opcfoundation.org/. In 1994 a group of vendors representing a broad spectrum of disciplines in industrial segment formed what is now known as the OPC Foundation. The OPC Foundation put forth the goal of developing a single client/server specification that would allow any vendor to develop software and applications that could share data in a fast, robust fashion, and do it in a way that would eliminate the proprietary schemes that forced these same vendors to duplicate development efforts. The OPC Foundation developed the first specification called Data Access Specification 1.0a that was released in early 1996. Using this specification, vendors were able to quickly develop client server software. A major goal of the OPC Foundation and the Data Access specification was to eliminate the need of client application vendor's to develop their own proprietary set of communications drivers. While OPC originally stood for “OLE for Process Control”, the official stance of the OPC Foundation is that OPC is no longer an acronym and the technology is simply known as “OPC”. One of the reasons behind this is while OPC is heavily used within the process industries. As of June, 2006, "OPC is a series of standards specifications". OPC consists of seven current standards and two emerging standards. The OPC Specification was based on the OLE, COM, and DCOM technologies developed by Microsoft for the Microsoft Windows operating system family. The specification defined a standard set of objects, interfaces and methods for use in process control and manufacturing automation applications to facilitate interoperability. The most common OPC specification is OPC Data Access, which is used to read and write real-time data. When vendors refer to OPC generically, they typically mean OPC Data Access. The OPC specifications: OPC Data Access (DA) OPC Alarms and Events OPC Batch OPC Data eXchange OPC Historical Data Access OPC Security OPC XML-DA OPC Unified Architecture (UA) Note! LabVIEW supports only the OPC Data Access specification. OPC servers provide a method for many different software packages to access data from a process control device, such as a PLC (Programmable Logic Controller) or DCS (Distributed Control System). Traditionally, any time a package needed access to data from a device, a custom interface, or driver, had to be written. The 3 4 Introduction to OPC purpose of OPC is to define a common interface that is written once and then reused by any business, SCADA, HMI, or custom software packages. Once an OPC server is written for a particular device, it can be reused by any application that is able to act as an OPC client. OPC servers use Microsoft’s OLE technology (also known as the Component Object Model, or COM) to communicate with clients. COM technology permits a standard for real-time information exchange between software applications and process hardware to be defined. 2.1 OPC SERVER The basic concept in OPC is that we have an OPC Server and one or more OPC Clients that communicate with the server in order to write or read data. An OPC server has implemented a set of services, and the clients are using these services. OPC Server OPC Client OPC Client … At a high level, an OPC server is comprised of several objects: the server, the group, and the item. The OPC server object maintains information about the server and serves as a container for OPC group objects. The OPC group object maintains information about itself and provides the mechanism for containing and logically organizing OPC items. The OPC Groups provide a way for clients to organize data. For example, the group might represent items in a particular operator display or report. Data can be read and written. The OPC Items represent connections to data sources within the server. An OPC Item, from the custom interface perspective, is not accessible as an object by an OPC Client. Therefore, there is no external interface defined for an OPC Item. All access to OPC Items is via an OPC Group object that contains the OPC item, or simply where the OPC Item is defined. Associated with each item are a Value, Quality and Time Stamp. Tutorial: OPC and Real-Time Systems in LabVIEW 5 Introduction to OPC Note! The items are not the data sources, they are just connections to them. For example, the tags in a DCS system exist regardless of whether an OPC client is currently accessing them. The OPC Item should be thought of as simply specifying the address of the data, not as the actual physical source of the data that the address references. Although OPC is primarily designed for accessing data from a networked server, OPC interfaces can be used in many places within an application. At the lowest level they can get raw data from the physical devices into a SCADA or DCS, or from the SCADA or DCS system into the application. The architecture and design makes it possible to construct an OPC Server which allows a client application to access data from many OPC Servers provided by many different OPC vendors running on different nodes via a single object. In this Tutorial we will use some OPC Server for test purposes: MatrikonOPC Server for Simulation: MatrikonOPC Simulation is free for non-production use and can be distributed openly. It is a fully functioning application without restriction. MatrikonOPC Simulation Server is a free utility used to help test and troubleshoot OPC applications (clients) and connections. Testing applications on “live” OPC servers may result in loss of actual production data. The MatrikonOPC Simulation Server creates a simulated environment so that in the event of a problem, no real process data is lost. MatrikonOPC Explorer is an OPC Client application for testing and configuring OPC connections. http://www.matrikonopc.com/downloads/178/index.aspx NI OPC Servers: The National Instruments OPC Servers provides a single consistent interface to communicate with multiple devices, saving you from learning new communication protocols or spending time understanding new applications. The combination of NI OPC Servers and LabVIEW provides a single platform for delivering high performance measurements and control to both new and existing industrial systems. NI OPC servers connect through the OPC client in LabVIEW Datalogging and Supervisory Control (DSC) Module to enable you develop a fully fledged HMI/SCADA system with PLCs, PACs and smart sensors. An evaluation version is available here: http://sine.ni.com/nips/cds/view/p/lang/en/nid/4584 Tutorial: OPC and Real-Time Systems in LabVIEW 6 2.2 Introduction to OPC OPC CLIENT An OPC Client can connect to OPC Servers provided by one or more vendors. 2.3 TAGS Tags are used a lot in the process industry and are normally assigned to a piece of information. A tag consists of a name describing a single point of information so a process system can consists of hundreds and even thousands of tags. The OPC server has one tag for each measurement points and controller points in the plant and it is the responsibility of the OPC server to get the information from the controllers. This is one of the reasons for the complexity of the servers, they need to have drivers for a lot of controllers and measurement systems. 2.4 WHY DO WE NEED OPC STANDARDS? With hundreds of major hardware and software vendors, you have the difficult task of making sure that your client application can communicate with any device and driver. Before OPC, you had to write separate client application code to communicate with each device because each device driver used a different API. OPC provides an industry-standard interface - a single API - so client applications can retrieve process variables, such as temperature, pressure, flow rate, or position, and set control variables, such as the current or discrete output on an I/O module. OPC offers the following benefits: Single API for all OPC servers so that you can reuse the code for your client application with each device. Opportunity to develop client applications in development environments that take advantage of COM and ActiveX, such as Microsoft Visual Basic, Visual C++, Excel, and Internet Explorer. Browser through which you can select OPC items available to clients. An OPC item is a channel or variable in a real-world device (normally an I/O point) that a device server monitors or controls. Distributed and remote access through DCOM. You can access devices connected to other computers on the network. Tutorial: OPC and Real-Time Systems in LabVIEW 3 INTRODUCTION TO REAL-TIME SYSTEMS A real-time system means a computer based system where one or more of the applications must be able to synchronize with a physical process. Real-time means that the computer system is monitoring the states of the physical process and must respond to changes of one or more of these states within a maximum time. A real-time system can then be used for monitoring of different parameters in the physical process for presentation, warnings, alarm situations and for control. A real-time operating system (RTOS) is a multitasking operating system intended for real-time applications. Such applications include embedded systems (programmable thermostats, household appliance controllers), industrial robots, spacecraft, and industrial control. LabVIEW Real-Time Module: The National Instruments LabVIEW Real-Time Module is an add-on component for the LabVIEW Development System. When installed, this software compiles NI LabVIEW graphical code and optimizes it for the selected real-time target. Using the LabVIEW Real-Time Module, you can develop and deploy applications to all NI real-time hardware targets including PXI, Compact FieldPoint, FieldPoint, CompactRIO, and standard desktop PCs. The embedded RTOS for these targets is a single dedicated kernel that provides maximum reliability for embedded code. 7 4 INTRODUCTION TO EMBEDDED SYSTEMS An embedded system is a computer system designed to perform one or a few dedicated functions often with real-time computing constraints. It is embedded as part of a complete device often including hardware and mechanical parts. By contrast, a general-purpose computer, such as a personal computer, is designed to be flexible and to meet a wide range of end-user needs. Embedded systems control many devices in common use today. Embedded systems are controlled by one or more main processing cores that is typically either a microcontroller or a digital signal processor (DSP). The key characteristic is however being dedicated to handle a particular task, which may require very powerful processors. For example, air traffic control systems may usefully be viewed as embedded, even though they involve mainframe computers and dedicated regional and national networks between airports and radar sites. Since the embedded system is dedicated to specific tasks, design engineers can optimize it reducing the size and cost of the product and increasing the reliability and performance. Some Examples of Embedded systems: Fuji PXG5 PID Controller: Compact FieldPoint (from National Instruments): Embedded hardware and Real-Time systems from National Instruments 8 9 Introduction to Embedded Systems Embedded applications have unique requirements such as deterministic behavior. With LabVIEW Real-Time, real time controllers, and data acquisition hardware from NI you can create applications with deterministic, real-time performance. You can develop and debug your application using LabVIEW graphical programming, and download time-critical application components to run embedded on Real-Time hardware. Tutorial: OPC and Real-Time Systems in LabVIEW 5 MULTITHREADING IN LABVIEW A multicore system is a single-processor CPU that contains two or more cores, with each core housing independent microprocessors. A multicore microprocessor performs multiprocessing in a single physical package. Multicore systems share computing resources that are often duplicated in multiprocessor systems, such as the L2 cache and front-side bus. Multicore systems provide performance that is similar to multiprocessor systems but often at a significantly lower cost because a motherboard with support for multiple processors, such as multiple processor sockets, is not required. 5.1 MULTITASKING In computing, multitasking is a method by which multiple tasks, also known as processes, share common processing resources such as a CPU. With a multitasking OS, such as Windows XP, Vista, etc., you can simultaneously run multiple applications. Multitasking refers to the ability of the OS to quickly switch between each computing task to give the impression the different applications are executing multiple actions simultaneously. 5.2 MULTITHREADING Multithreading extends the idea of multitasking into applications, so you can subdivide specific operations within a single application into individual threads. Each of the threads can run in parallel. The OS divides processing time not only among different applications, but also among each thread within an application. In a multithreaded National Instruments LabVIEW program, an example application might be divided into four threads - a user interface thread, a data acquisition thread, network communication, and a logging thread. You can prioritize each of these so that they operate independently. Thus, in multithreaded applications, multiple tasks can progress in parallel with other applications that are running on the system. Multithreading in LabVIEW 10 11 Multithreading in LabVIEW LabVIEW automatically divides each application into multiple execution threads. The complex tasks of thread management are transparently built into the LabVIEW execution system. Multitasking in LabVIEW LabVIEW uses preemptive multithreading on OSs that offer this feature. LabVIEW also uses cooperative multithreading. OSs and processors with preemptive multithreading employ a limited number of threads, so in certain cases, these systems return to using cooperative multithreading. The execution system preemptively multitasks VIs using threads. However, a limited number of threads are available. For highly parallel applications, the execution system uses cooperative multitasking when available threads are busy. Also, the OS handles preemptive multitasking between the application and other tasks. Tutorial: OPC and Real-Time Systems in LabVIEW 6 DATASOCKET DataSocket is a technology for sharing data between applications or different data sources. The DataSocket control provides a simple interface through which it can interact with OPC servers, such as National Instruments FieldPoint, from any ActiveX container, including Visual Basic and Visual C++. You can connect to an OPC server with DataSocket using an OPC URL, which is similar to the URLs used in a Web browser. URLs provide a standard mechanism for referring to locations. You already know how to use URLs to locate things on the Web, and you can locate OPC data items with DataSocket using a similar URL model: opc://machine_name/server_name/item_name With DataSocket, you can share live data with one or more client applications on a network without worrying about data formats and network protocols. Your LabVIEW applications can easily share live data with a variety of clients, including Visual Basic applications, Web browsers, Visual C++, Microsoft Excel, LabWindows/CVI, and other LabVIEW applications. Using DataSocket technology, you can publish and receive data from any application in the same way, giving you the power to connect diverse applications easily. Many typical instrumentation solutions involve a single local application for acquisition, logging, analysis, and presentation. However, because of the rise in popularity of the Internet and company intranets, and the need to remotely monitor and control your data acquisition, you often need to exchange live data with other applications on different computers around the world. DataSocket for LabVIEW simplifies live data exchange between different applications on one computer or between computers connected through a network. Although a variety of different technologies exist today to share data between applications, including TCP/IP and dynamic data exchange (DDE), most of these tools are not targeted for live data transfer to multiple clients. With TCP/IP, you have to convert your data into an unstructured stream of bytes in the broadcasting application and then parse the stream of bytes back into its original format in subscribing applications. DataSocket, however, simplifies live data transfer. It implements an easy-to-use, high-performance programming interface that is designed specifically for sharing and publishing live data in measurement and automation applications. In addition, DataSocket features interapplication connectivity, rich data types, and security to make sharing data easy. DataSocket is included with LabVIEW. If you are comfortable programming with COM, you can write programs using either the OPC Custom API or Automation API, depending on the programming environment in which you are developing your OPC client. If you do not want to program with COM, use the DataSocket control, an ActiveX control for sharing data between applications and devices. DataSocket offers the following benefits: Simple API, helpful to developers who don't want to program with COM. Access to the OPC server custom interface, which enables your applications to run faster than applications that access the automation interface. DataSocket is not an extra layer but rather a direct connection to OPC servers, and DataSocket always accesses the custom interface, regardless of the ActiveX container in which you are developing. Easy integration with National Instruments products such as LabVIEW. 6.1 ARCHITECTURE 12 13 DataSocket DataSocket is a single, unified, end-user application programming interface (API) for connecting to data from a number of sources – local files, files on FTP or Web servers, and data items on OPC Servers. A DataSocket application specifies the data location by using a familiar networking standard, the URL. Just as a Web browser uses a URL to connect to a Web page, a DataSocket application uses a URL to connect to data. By using an industry-standard URL, you can quickly and easily bring data into or share data from your DataSocket applications. opc://machine_name/server_name/item_name machine_name [optional] - Computer on which the OPC server is installed. DataSocket can access OPC servers on other computers using DCOM. If the machine name is omitted, DataSocket directly connects to the OPC server on the computer on which it is running. server_name - OPC server (provided with the hardware) to connect to. item_name - OPC item on the specific OPC server. An item is a channel or variable (normally an I/O point) in a real-world device that a device server monitors or controls. Example FieldPoint item: FP Res\FP-DI-330 @1\Channel 1 UpdateRate=n in milliseconds [optional] - Maximum rate at which the OPC server will indicate that an item’s value has changed. The server should use an update rate as close as possible to the rate requested by the client. If this parameter is omitted, the default is 100 ms. The following example sets the update rate to 1000 ms: UpdateRate=1000 DeadBand=n in % of range [optional] - Percentage change required before the server notifies your application of a value change. Not all servers support this option. If omitted, this parameter defaults to 0%. The following example sets the deadband to 10%: DeadBand=10 For example, the following URL connects to the sine item on the National Instruments OPCDemo server on the local machine. The options at the end of the URL specify an update rate of 1000 ms and a deadband of 10%. opc:/National Instruments.OPCDemo/sine?UpdateRate=1000&DeadBand=10 6.2 DATASOCKET SERVER With the DataSocket Server, a lightweight, stand-alone component, programs using DataSocket can broadcast live measurement data at high rates across the Internet to multiple remote clients concurrently. These client applications use DataSocket to subscribe to the live measurement data. Because the DataSocket Server is a stand-alone component, it simplifies network (TCP/IP) programming by automatically managing connections to clients and automatically converting your measurement data to and from the stream of bytes sent across the network. You do not have to write the parsing code. And because the DataSocket Server can run on any machine on your network, it also improves performance and provides security by isolating the Web connections from your acquisition application. 6.3 DATASOCKET IN LABVIE W The DataSocket palette in LabVIEW: Tutorial: OPC and Real-Time Systems in LabVIEW 14 DataSocket Description of the DataSocket VIs in LabVIEW. DataSocket Select URL Displays a dialog box for the user to select a data source and returns the URL to that data. DataSocket Open Opens a data connection you specify in URL. DataSocket Read Dequeues the next available data value from the client-side buffer associated with the connection you specify in connection in and returns the data. DataSocket Write Writes data to the connection you specify in connection in. DataSocket Close Closes a data connection you specify in connection id. Tutorial: OPC and Real-Time Systems in LabVIEW 7 OPC SERVERS FROM NATIONAL INSTRUMENTS National Instruments offers different OPC Servers, such as: NI OPC Servers FieldPoint OPC Server Variable Engine Etc. If you browse for OPC servers and OPC Items on your computer it probably looks something like this: Below we go through the basic functionality in these OPC Servers. 7.1 NI OPC SERVERS The National Instruments OPC Servers provides a single consistent interface to communicate with multiple devices, saving you from learning new communication protocols or spending time understanding new applications. The combination of NI OPC Servers and LabVIEW provides a single platform for delivering high performance measurements and control to both new and existing industrial systems. NI OPC servers connect through the OPC client in LabVIEW Datalogging and Supervisory Control (DSC) Module to enable you develop a full fledged HMI/SCADA system with PLCs, PACs and smart sensors. NI OPC Servers are a 32-bit windows application that provides a means of bringing data and information from a wide range of industrial devices and systems into client applications on your windows PC. Our OPC Server application enables the sharing of manufacturing or production data between a variety of applications ranging from human machine interface software and data historians, to large MES and ERP applications. 15 16 OPC Servers from National Instruments 7.1.1 OPC QUICK CLIENT The OPC Quick Client has been developed to assist in the test and development of the OPC Data Access 1.0 and 2.0 Servers. The OPC Quick Client does not fully support OPC DA 3.0. The OPC Quick Client supports both local and remote OPC server connections. Remote connections are handled through the operating system's DCOM interface. Tutorial: OPC and Real-Time Systems in LabVIEW 17 OPC Servers from National Instruments To start using the OPC Quick Client, do the following: 1. 2. 3. Create a server connection which will be used to connect to an OPC server. Next, add a group to the connection which contains varying properties (such as update rate, dead band and time bias). Finally, add items to the individual groups (which contain properties such as an initial active state, data type and access path). A server connection provides a link between an OPC server and this client. Groups are added through this connection. To create a new server connection, click Edit | New Server Connection.... Alternatively, click the New Server toolbar button. A group is used to organize a collection of items with a common set of properties. The group also specifies the following properties: group name, update rate, time bias, percent dead band, Language ID, active state and the data connection type. To create a new group, click Edit | New Group. Alternatively, click New Group in the toolbar. Items represent data that may be accessed via an OPC server. An item specifies the following properties: Item ID, access path, requested data type and active state. To define an item using the Item Editor dialog, click Edit | New Item. Alternatively, click New Item on the toolbar. Tutorial: OPC and Real-Time Systems in LabVIEW 18 7.2 OPC Servers from National Instruments SHARED VARIABLE ENGINE LabVIEW contains an OPC server called the Shared Variable Engine. The Shared Variable Engine supports OPC Data Access 2.x and OPC Data Access 3.0. You can publish data from the Shared Variable Engine using LabVIEW shared variables. To connect to the Shared Variable Engine from a third-party OPC client, use the ProgID National Instruments.Variable Engine. If the OPC client allows you to browse for OPC servers, you can locate the National Instruments.Variable Engine under OPC version 2.x or 3.0, depending on which versions the client supports. Tutorial: OPC and Real-Time Systems in LabVIEW 8 MATRIKONOPC SIMULATION SERVER MatrikonOPC Simulation is free for non-production use and can be distributed openly. It is a fully functioning application without restriction. MatrikonOPC Simulation Server is a free utility used to help test and troubleshoot OPC applications (clients) and connections. Testing applications on “live” OPC servers may result in loss of actual production data. The MatrikonOPC Simulation Server creates a simulated environment so that in the event of a problem, no real process data is lost. MatrikonOPC Explorer is an OPC Client application for testing and configuring OPC connections. Download MatrikonOPC Simulation Server and MatrikonOPC Explorer her: http://www.matrikonopc.com/downloads/178/index.aspx Watch this video: http://www.matrikonopc.com/training/opc-multimedia-tutorial/opcda_pop.html 8.1 MATRIKONOPC SERVER … 19 20 MatrikonOPC Simulation Server View Tags: Open the MatrikonOPC Explorer wher you browse for available Items (Tags). 8.2 ALIASES MatrikonOPC servers, including this one, provide the ability to create user-defined aliases that can be used in place of regular OPC items. This feature is particularly useful when the item path for a given server is very complex or difficult to remember, for example: Com1.Radio1.Unit1.41.4.123. Servers can also be configured so that client applications have access to configured aliases only, rather than every available item. To insert a new alias, perform the following steps: 1. Open the MatrikonOPC Server for Simulation Configuration window. Tutorial: OPC and Real-Time Systems in LabVIEW 21 MatrikonOPC Simulation Server 2. 3. 4. 5. Click on the Alias Configuration node in the Current Configuration panel to open the Alias Configuration panel. Right-click your mouse and select the Insert New Alias option, or Press the Insert button on the keyboard, to launch the Insert New Alias window. Fill in a name for the alias, and enter a valid item path. The item path can be found by browsing the server’s address space (use the ellipsis button next to this field). Save this alias when finished. It will now be visible to OPC clients under the Configured Aliases heading. For more detailed scaling options, please consult the MatrikonOPC Server for Simulation User’s Manual. 8.3 MATRIKON OPC EXPLORER (CLIENT) MatrikonOPC Explorer is an OPC Client application for testing and configuring OPC connections. The MatrikonOPC Explorer lists all the available OPC Servers in the upper left corner. MatrikonOPC Explorer lists OPC servers on your computer (localhost) or in the network. Tutorial: OPC and Real-Time Systems in LabVIEW 22 MatrikonOPC Simulation Server Click Connect on order to connect to the server. Tutorial: OPC and Real-Time Systems in LabVIEW 9 USING OPC FROM LABVIEW You can use LabVIEW as an OPC client by connecting to an OPC server through a DataSocket connection. The DataSocket palette in LabVIEW: Description of the DataSocket VIs in LabVIEW: DataSocket Select URL Displays a dialog box for the user to select a data source and returns the URL to that data. DataSocket Open Opens a data connection you specify in URL. DataSocket Read Dequeues the next available data value from the client-side buffer associated with the connection you specify in connection in and returns the data. DataSocket Write Writes data to the connection you specify in connection in. DataSocket Close Closes a data connection you specify in connection id. 9.1 OPC URL A typical URL for an OPC Item could be: opc://localhost/Matrikon.OPC.Simulation/Random.Int4 or in general: opc://machine_name/server_name/item_name 23 24 Using OPC from LabVIEW You may use the “DataSocket Select URL” VI in order to find an OPC Item. Using the “DataSocket Select URL” displays the “Select URL” window: This VI is nice to have when you dont know the exact name of the OPC URL. If you know the URL in advance you use the “DataSocket Open” VI specify in the input URL. Like this: 9.2 . This VI opens a data connection you READ OPC DATA You use DataSocket Read in order to get data from a specific Item in the OPC server. Example: Tutorial: OPC and Real-Time Systems in LabVIEW 25 Using OPC from LabVIEW or using the specific URL directly like this: The DataSocket Read VI have several outputs in addition to the Value (data). All OPC Items have the following properties: Value Timestamp Status Quality 9.3 WRITE OPC DATA You use DataSocket Write in order to write data to a specific Item in the OPC server. Tutorial: OPC and Real-Time Systems in LabVIEW 26 Using OPC from LabVIEW Note! In order to write data to an OPC Item it must have the Write property set. Example: or using the specific URL directly like this: Tutorial: OPC and Real-Time Systems in LabVIEW 10 LABVIEW DATALOGGING AND SUPERVISORY CONTROL The LabVIEW Datalogging and Supervisory Control (DSC) Module extends the LabVIEW graphical development environment with additional functionality for the rapid development of distributed measurement, control, and high-channel-count monitoring applications. The DSC Module also enhances the LabVIEW shared variable. Use the shared variable to access and pass data among several VIs in a LabVIEW project or across a network. A shared variable can represent a value or an I/O point. With the DSC Module, you can log data automatically; add alarming, scaling, and security to the shared variable; and configure the shared variable programmatically. The DSC Module also provides tools for graphing historical or real-time trends, enhancing the security of front panels, and writing custom I/O servers. You can read or write to OLE for Process Control (OPC) connections, programmable logic controllers (PLC), or custom I/O servers that you write. To run applications built with LabVIEW, the DSC Module on a computer without the DSC Module installed, you must install the “DSC Module Run-Time System” on that computer. The DSC Module Run-Time System contains components that enable the DSC Module features in the built applications. The DSC Module includes the following components: Functions and VIs Palettes DSC Module Controls Palettes Citadel Database Historical Data Viewer Distributed System Manager These components are described in more detail below. Most of the LabVIEW DSC functionality is available from the Tools menu (“Tools → DSC Module”). 27 28 LabVIEW Datalogging and Supervisory Control 10.1 FUNCTIONS AND VIS PALETTES The DSC Module installs the following palettes: Alarms & Events Historical Tags Shared Variables Engine Control Security The DSC Module also includes the Historical Trend Express VI and the Real-Time Trend Express VI. 10.2 DSC MODULE CONTROLS PALETTES The DSC Module installs the following controls palettes to help you build user interfaces that resemble a plant or system and to view real-time data from the plant or system: 2D Controls 3D Controls Vessels Alarm Controls Trend Controls The DSC Module also includes the Historical Trend control and the Real-Time Trend control. Tutorial: OPC and Real-Time Systems in LabVIEW 29 LabVIEW Datalogging and Supervisory Control 10.3 CITADEL DATABASE The DSC Module logs shared variable data to the Citadel database. The Citadel database stores historical data, alarms, and events. You can access and view Citadel data using the Historical Data Viewer and using the “Historical VIs”. 10.4 HISTORICAL DATA VIEW ER Use the Historical Data Viewer to view data stored in the Citadel database. Select “Tools → DSC Module → View Historical” Data to launch the Measurement & Automation Explorer (MAX). Expand the “Historical Data” category to select a database that appears under “Citadel 5 Universe”. You also can use the Call HDV VI to launch the Historical Data Viewer programmatically. Tutorial: OPC and Real-Time Systems in LabVIEW 30 LabVIEW Datalogging and Supervisory Control Data Logger: 10.5 DISTRIBUTED SYSTEM MANAGER Use the Shared Variable Monitor to view the current value of a shared variable and its status and alarm state. Select “Tools → Distributed System Manager” to launch the Distributed System Manager. Tutorial: OPC and Real-Time Systems in LabVIEW 31 LabVIEW Datalogging and Supervisory Control 10.6 SQL SERVER The DSC Module requires the Microsoft SQL Server 2005 Express Edition (SQL Express). This component is installed by default when you install the DSC Module. During the installation process, the DSC Module installer creates an instance of SQL Express named CITADEL. To prevent unauthorized access to SQL Express, the installer also generates a password for the default SQL Express administrator sa. The default password is the computer ID. Complete the following steps to find the computer ID using the NI License Manager. 1. 2. Launch the NI License Manager by selecting “Start → All Programs → National Instruments → NI License Manager”. Click the Display Computer Information button on the toolbar. The SQL Server database is used for configurations, etc., while the Citadel database is used for Datalogging. Tutorial: OPC and Real-Time Systems in LabVIEW 32 LabVIEW Datalogging and Supervisory Control EXERCISES In the following exercises we will build an application in LabVIEW using the functionality from the LabVIEW DSC Module. The Tasks are as follows: Task 1: Open and Run the Example Task 2: Creating a New Project Library Task 3: Creating a Periodic I/O Server Task 4: Deploying the Periodic I/O Server Task 5: Creating Shared Variables Task 6: Configuring Data Logging Task 7: Configuring Alarming Task 8: Enabling Logging Task 9: Create the LabVIEW Application Task 10: Use the LabVIEW DSC Functions and VIs Task 11: Viewing Real-Time Data Task 12: Viewing Alarms using the Distributed System Manager Task 1: Open and Run the Example Open DSC Tank Simulator.vi. The Example is available from: http://home.hit.no/~hansha/ The example does not use any DSC functionality so far. In the next exercise you will create a DSC application based on this example. Task 2: Creating a New Project Library Tutorial: OPC and Real-Time Systems in LabVIEW 33 LabVIEW Datalogging and Supervisory Control In this exercise you will learn how to create a new LabVIEW project and a project library. The project allows you to manage shared variables, project libraries, and VIs in one window. LabVIEW project libraries are collections of VIs, type definitions, shared variables, palette menu files, and other files, including other project libraries. Complete the following steps to create a LabVIEW project library. Click the Empty Project link in the Getting Started window. The Project Explorer window appears. Right-click My Computer in the Project Explorer window and select New → Library from the shortcut menu. Select File → Save All. The Name the Project dialog box appears. Enter “Tank System” in the File name text box. Click the OK button. The Name the Library dialog box appears. Enter “Tank System IO Server” in the File name text box. Click the OK button. You now have a project containing a project library. In the following exercise you will use the project library in the project to create a periodic I/O server. Task 3: Creating a Periodic I/O Server A server is an application that communicates with and manages input/output devices such as PLCs, remote input/output devices, remote Shared Variable Engines, and data acquisition (DAQ) plug-in devices. These servers read selected input items and write to them on demand. The DSC Module can connect to any OPC-compliant server and to many third-party device servers. You also can create custom I/O servers. You will build a periodic I/O server in the following exercise. The periodic I/O server will run as a service and publish NI Publish-Subscribe Protocol (NI-PSP) data items to the network. Complete the following steps to add the periodic I/O server to the project. Right-click the Tank System IO Server.lvlib project library in the Project Explorer window and select New → I/O Server from the shortcut menu. The Create New I/O Server dialog box appears. Tutorial: OPC and Real-Time Systems in LabVIEW 34 LabVIEW Datalogging and Supervisory Control Select Custom VI – Periodic from the I/O Server Type list and click the Continue button. The Configure Custom VI – Periodic I/O Server dialog box appears. Click the New button to display the Select VI step of the Custom VI-based Server – Periodic Wizard. Select the DSC Tank Simulator.vi. Click the Next button in the Custom VI-based Server – Periodic Wizard to advance to the Select Controls and Indicators To Publish step. Tutorial: OPC and Real-Time Systems in LabVIEW 35 LabVIEW Datalogging and Supervisory Control Here you will select Controls and Indicators you want to publish as shared variables. Remove the checkmark from the stop checkbox in the Controls list. You will publish the remaining controls and indicators. Click the Next button to advance to the Select Method To Stop The Server page. Select Stop the following While Loops and Place a checkmark in the While Loop checkbox. Click the Next button to advance to the Configure Server Distribution Component step. Tutorial: OPC and Real-Time Systems in LabVIEW 36 LabVIEW Datalogging and Supervisory Control Leave the default options and click Next. The Server Distribution Component page appears The DSC Module displays a summary of the files that the Custom VI-based Server – Periodic Wizard will create from the Server Distribution Component page. Click the Build button. The wizard displays the Build status dialog box as it creates a VI template file, a registration VI, and a support DLL and VIs. Tutorial: OPC and Real-Time Systems in LabVIEW 37 LabVIEW Datalogging and Supervisory Control After the wizard creates the periodic I/O server, the Configure Custom VI – Periodic I/O Server dialog box appears with the name of the periodic I/O server and the data items it contains. Click the OK button. LabVIEW adds the periodic I/O server to the Tank System IO Server project library. Tutorial: OPC and Real-Time Systems in LabVIEW 38 LabVIEW Datalogging and Supervisory Control Right-click the Custom VI – Periodic1 item in the Project Explorer window and select Rename from the shortcut menu. Rename the periodic I/O server “Tank1”. The Project Explorer window appears as shown below. Task 4: Deploying the Periodic I/O Server Now you must deploy the periodic I/O server so that the data items in the I/O server are available for use in other VIs and across the network. In this exercise you will deploy the periodic I/O server and view the I/O server data in the Shared Variable Monitor. Note! The periodic I/O server runs continuously in the background until you undeploy the library in the Project Explorer window that contains the I/O server. Complete the following steps to deploy the Tank1 periodic I/O server and view the data. Right-click the Tank System IO Server.lvlib project library under the My Computer item and select Deploy All from the shortcut menu to deploy the project library. Tutorial: OPC and Real-Time Systems in LabVIEW 39 LabVIEW Datalogging and Supervisory Control Click the Done button to close the Deploy dialog box when the deployment is complete. Select Tools→ Distributed System Manager. Expand Tank System IO Server → Tank1 in the left pane. Notice that the controls and indicators of the I/O server appear under Tank1. Because you have deployed the project library, the I/O server is running and each control and indicator is an I/O data item. Click the Tank1.Input Flow Rate [GPM] control and enter a value of 10 and click the OK button. Notice that the values of Tank1.Tank Level [Gallons] and Tank1.Tank Output Flowrate [GPM] begin increasing. Close Distributed System Manager. The periodic I/O server continues to run. Tutorial: OPC and Real-Time Systems in LabVIEW 40 LabVIEW Datalogging and Supervisory Control Task 5: Creating Shared Variables In this exercise you will add the network-published shared variables that represent the data items in the periodic I/O server to the Tank System Shared Variables project library. Complete the following steps to add the Tank System Shared Variables project library to the Tank System project. Right-click My Computer in the Project Explorer window and select New → Library from the shortcut menu. Right-click the new project library you created and select Create Bound Variables from the shortcut menu to display the Create Bound Variables dialog box. Tutorial: OPC and Real-Time Systems in LabVIEW 41 LabVIEW Datalogging and Supervisory Control Select Network Items. Expand Tank System IO Server →Tank1 in the Network tree. The shared variables appear under Tank1. Select each shared variable with the data type DBL and click the Add button to add each variable to the Added variables list. Click the OK button. The Create Bound Variables dialog box closes and the shared variables appear in the Multiple Variable Editor window. Click the Done button to close the Multiple Variable Editor window. Select File → Save All in the Project Explorer. The Name the Library dialog box appears. Enter “Tank System Shared Variables” in the File name text box. Click the OK button. LabVIEW binds the shared variables in the Tank System Shared Variables project library to the corresponding items on the network. Tutorial: OPC and Real-Time Systems in LabVIEW 42 LabVIEW Datalogging and Supervisory Control Task 6: Configuring Data Logging When you add logging to a shared variable, the DSC Module logs shared variable data, including the shared variable value, timestamp, whether the value is in an alarm state, and the quality of the value. The DSC Module logs all data to the Citadel database. Complete the following steps to add logging for the Tank Level [Gallons] shared variable. Right-click the Tank System Shared Variables.lvlib project library and select Multiple Variable Editor. Tutorial: OPC and Real-Time Systems in LabVIEW 43 LabVIEW Datalogging and Supervisory Control Set the following for the Tank Level [Gallons] shared variable in the Multiple Variable Editor: Task 7: Configuring Alarming An alarm is an abnormal condition on a shared variable or a user-defined condition. An alarm occurs if a shared variable value goes out of its defined alarm limits or if a shared variable has bad status. In this exercise you will add an alarm for the Tank Level [Gallons] shared variable. Set the following for the Tank Level [Gallons] shared variable in the Multiple Variable Editor: Task 8: Enabling Logging Complete the following steps to enable data logging and alarm and event logging for the Tank System Shared Variables project library. Right-click the Tank System Shared Variables.lvlib project library in the Project Explorer window and select Properties from the shortcut menu. The Project Library Properties dialog box appears. Tutorial: OPC and Real-Time Systems in LabVIEW 44 LabVIEW Datalogging and Supervisory Control Select DSC Settings: Database from the Category list. Verify that the options in the DSC Settings: Database page appear similar to the Figure below. The Enable Data Logging option turns on data logging for the project library. localhost specifies the local computer. Use localhost instead of the name of the computer to reduce the changes you must make if you move this project to another computer. The Enable Alarms and Events Logging option turns on event logging for the project library. The Use the same database for alarms and events option ensures that the DSC Module logs alarms and events for this project library to the same database that it logs data. You can change the Database name that appears in the Project Library Properties dialog box to a more useful or descriptive name. Task 9: Create the LabVIEW application In this exercise you will create a VI to display data on a front panel. You do not need to add any code to the block diagram. Complete the following steps to create a front panel to display the data items in the periodic I/O server. Right-click My Computer in the Project Explorer window and select New→ VI from the shortcut menu. A new VI front panel and block diagram appear. Select the Tank Level [Gallons] shared variable from the Tank System Shared Variables.lvlib project library in the Project Explorer window and drag the shared variable onto the front panel. The shared variable appears as a numeric control. Notice the triangle that appears next to the control. The triangle indicates that this control has been configured for data binding. Tutorial: OPC and Real-Time Systems in LabVIEW 45 LabVIEW Datalogging and Supervisory Control Right-click the Tank Level [Gallons] control and select Change to Indicator from the shortcut menu. Right-click the Tank Level [Gallons] indicator and select Replace → DSC Module → Vessels → Open Tank from the shortcut menu. Right-click the Tank Level [Gallons] indicator and select Properties from the shortcut menu. The Properties dialog box appears. Select the Data Binding tab in the Properties dialog box. Tutorial: OPC and Real-Time Systems in LabVIEW 46 LabVIEW Datalogging and Supervisory Control Place a checkmark in the Blink while Alarm On checkbox to configure the control to blink when the water level reaches 75, the default alarm you set in the Configuring Alarming section of this document. For the Input Flowrate [GPM] shared variable: Select the Input Flowrate [GPM] shared variable from the Tank System Shared Variables.lvlib project library in the Project Explorer window and drag the shared variable onto the front panel. Right-click the Input Flowrate [GPM] control and select Replace → Num Ctrls → Pointer Slide. For the Tank Valve [%] shared variable: Select the Tank Valve [%] shared variable from the Tank System Shared Variables.lvlib project library in the Project Explorer window and drag the shared variable onto the front panel. Right-click the Tank Valve [%] control and select Replace → Num Ctrls → Pointer Slide. Select File → Save As. The Name the VI dialog box appears. Enter “Tank System HMI” in the File name text box. Click the OK button. Click the Run Continuously button to run the VI. The VI should function in the same way as the example you ran in the first exercise. Below we sew the final Project Explorer: Tutorial: OPC and Real-Time Systems in LabVIEW 47 LabVIEW Datalogging and Supervisory Control Below we see the final application: Task 10: Use the LabVIEW DSC Functions and VIs In this task you will use the LabVIEW DSC Functions and VIs palette. Read Historical Data: Block Diagram: Front Panel: Tutorial: OPC and Real-Time Systems in LabVIEW 48 LabVIEW Datalogging and Supervisory Control Read Alarm Data: Block Diagram: Front Panel: Tutorial: OPC and Real-Time Systems in LabVIEW 49 LabVIEW Datalogging and Supervisory Control Task 11: Viewing Real-Time Data You can use the DSC Module to view live data. The Real-Time Trend Express VI displays live data from a shared variable on an XY graph. In the following exercise you will add the ability to view live data to the Tank System VI. Place the Real-Time Trend Express VI, available on the DSC Module palette, on the block diagram. The Configure Real-Time Trend dialog box appears. Select the Tank Level [Gallons] shared variable and select Add. Place a waveform chart on the front panel. Wire the trend data output of the Real-Time Trend Express VI to the waveform chart on the block diagram. Place a While Loop around the waveform chart and Express Real-Time Trend control. Run the VI. Tutorial: OPC and Real-Time Systems in LabVIEW 50 LabVIEW Datalogging and Supervisory Control Front Panel Task 12: Viewing Alarms using the Distributed System Manager Open the Distributed System Manager from Tools → Distributed System Manager. Tutorial: OPC and Real-Time Systems in LabVIEW 51 LabVIEW Datalogging and Supervisory Control Tutorial: OPC and Real-Time Systems in LabVIEW 11 LABVIEW I/O SERVER 11.1 CONNECT LABVIEW TO OPC TAGS BY CREATING AN I/O SERVER In this section, create a LabVIEW interface to the OPC tags called an I/O Server. The I/O Server automatically updates LabVIEW with the current tag values at a rate you specify. In the Getting Started window of LabVIEW, click “File → New Project”. This opens a new LabVIEW Project. If the Context Help window is not visible, press “Ctrl+H” to display the window. Keep this window open for helpful information about items under your cursor. In the LabVIEW Project window, right-click My Computer and select “New → I/O Server”, as shown in the Figure below. Select OPC Client in the “Create New I/O Server” window and click Continue. Choose “National Instruments.NIOPCServers” from the Registered OPC servers field and set Update rate (ms) to 100. This creates a connection from LabVIEW to the OPC tags, which updates every 100 ms. 52 53 LabVIEW I/O Server Select OK. A library is automatically created in your project explorer window to manage the I/O Server. Save the project as “OPCDemoProject” and the library as “OPCDemoLibrary” by selecting “File → Save All” from the project explorer window. 11.2 CREATE SHARED VARIABLES THAT CONNECT TO THE OPC TAGS THROUGH THE I/O SERVER In this section, create shared variables, which are bound to the OPC tags, giving you native access in LabVIEW to PLC data. With the shared variable, you can share data across LabVIEW applications on a single computer or across the network. Create new shared variables that are bound to the PLCs’ OPC tags. In the LabVIEW Project window, right-click My Computer and select “New → Library”. This creates a new library for the shared variables, which are used to connect to the PLCs’ OPC tags. Right-click the newly created library and select “Create Bound Variables…”. Tutorial: OPC and Real-Time Systems in LabVIEW 54 LabVIEW I/O Server In the Create Bound Variables window, select the OPC tags to bind the shared variables to by browsing down to the simulated sine data from the OPC server as shown in the Figure below. Select all the sine items and click Add and OK. This creates shared variables that are bound to the PLCs’ OPC tags and loads them into the Multiple Variable Editor. In the Multiple Variable Editor, select Done. This adds the new shared variables to the library that was created earlier. Note! The LabVIEW DSC Module enhances shared variables by adding the ability to log data, alarms, and events directly to a database without ever writing a LabVIEW application. Save the new library as “OPCItems.lvlib” in the project explorer window by right-clicking the library and selecting Save As. Deploy the shared variables by right-clicking the “OPCItems” library and selecting Deploy. This publishes the shared variables, making them available on the network to other computers, OPC clients, and the LabVIEW Real-Time PAC. You now have access to PLC data natively in LabVIEW through the shared variables. 11.3 VIEWING SHARED VARIABLES WITH DISTRIBUTED SYSTEM MANAGER From the Project Explorer window, select “Tools → Distributed System Manager”. This opens a window that you can use to manage your shared variables in various ways (view, deploy, undeploy, etc.). In the Tree pane of the Variable Manager, expand the “localhost” item under the “My Systems” category. Right-click the “OPCItems” library, and select “Watch List” to display the shared variables, which are bound to the PLCs’ OPC tags. The shared variables will be updating with the simulated sine data. Tutorial: OPC and Real-Time Systems in LabVIEW 55 LabVIEW I/O Server 11.4 USING OPC TAG DATA IN LABVIEW From the project explorer, right-click My Computer and select “New → VI”. This creates a new virtual instrument or VI. A VI is used to create a user interface and executable graphical code. By default, you see the Front Panel, which is the user interface of the VI. Select “View → Controls Palette” or right-click anywhere on the Front Panel to bring up the Controls palette. Select a waveform chart from the Controls palette by selecting “Express → Graph Indicators → Chart”, and place it on the Front Panel, as shown in the Figure below. Tutorial: OPC and Real-Time Systems in LabVIEW 56 LabVIEW I/O Server In the VI, select “Window → Show Block Diagram” or press Ctrl+E to show the Block Diagram. The Block Diagram is where you build the behavior of your application. Notice the icon on the Block Diagram, which represents the chart on the Front Panel. By passing data into this terminal, you can display it in the chart on the Front Panel. In the project explorer, expand the “OPCItems” library and select the Sine1 shared variable. Drag and drop the Sine1 shared variable from the project explorer to the Block Diagram of the VI. The shared variable acts as a source of data to other terminals on the Block Diagram. Select “View → Tools Palette” or press Shift+right-click to show the Tools palette, which contains various tools for building the Block Diagram. By default you use the Automatic Tool Selection tool, which selects the appropriate tool based on the location of the cursor. Select the Connect Wire tool as shown in the Figure below. This tool is used to wire terminals together on the Block Diagram. Use the Connect Wire tool to wire the Sine1 shared variable to the waveform chart by clicking on the Sine1 shared variable and then on the waveform chart, as shown in the Figure below. Now data flows from the shared variable to the waveform chart when the VI is running. Open the Functions palette by selecting “View → Functions Palette” or right-clicking anywhere on the Block Diagram. The Functions palette contains hundreds of analysis functions, control functions, and structures for graphical programming. Tutorial: OPC and Real-Time Systems in LabVIEW 57 LabVIEW I/O Server Select a while loop from the Functions palette by navigating to “Express → Execution Control → While Loop”. This allows you to wrap a while loop around a section of code. The while loop causes the code within it to execute continuously until stopped by the user or additional logic in the VI. A timed loop, which is an advanced while loop, contains additional configuration options for timing and execution control. Convert the while loop into a timed loop by right-clicking the while loop and selecting Replace with Timed Loop. To configure the timed loop, double-click the timed loop input node In the Loop Timing Attributes field, set Period to 100 ms and click OK. This configures the timed loop to execute the contained code every 100 ms. Click the Run button on the toolbar to execute the VI. Click Close on the Deploy… window once the deployment completes. When the application begins executing, you see the Sine1 sine wave displayed on the waveform chart. Tutorial: OPC and Real-Time Systems in LabVIEW 58 LabVIEW I/O Server Congratulations! You successfully accessed PLC data in your LabVIEW application, so you can incorporate powerful analysis and control functions in your solution. Tutorial: OPC and Real-Time Systems in LabVIEW 12 LABVIEW REAL-TIME MODULE The National Instruments LabVIEW Real-Time Module extends the LabVIEW development environment to deliver deterministic, real-time performance. Develop your application on a host computer using graphical programming and then download the application to run on an independent hardware target with a real-time OS (RTOS). The National Instruments LabVIEW Real-Time Module is an add-on component for the LabVIEW Development System. When installed, this software compiles NI LabVIEW graphical code and optimizes it for the selected real-time target. Using the LabVIEW Real-Time Module, you can develop and deploy applications to all NI real-time hardware targets including PXI, Compact FieldPoint, FieldPoint, CompactRIO, and standard desktop PCs. The embedded RTOS (Real-Time Operating System) for these targets is a single dedicated kernel that provides maximum reliability for embedded code. With the LabVIEW Professional Development System and LabVIEW Real-Time Module, you can create a stand-alone executable and download it to an hardware target with one simple step. You can permanently embed the code on the nonvolatile memory of the real-time system so it starts automatically when the system boots for autonomous field applications. Each hardware target contains an embedded processor running an RTOS. The LabVIEW Real-Time Module embeds compiled code on the hardware target and runs it independently of the host computer. Assign the appropriate execution priority to each real-time task. The embedded RTOS then uses a combination of round-robin and preemptive scheduling to ensure deterministic execution of your time-critical tasks. 12.1 REAL-TIME DEVELOPMENT IN LABVIEW Developing real-time programs in LabVIEW is nearly identical to developing standard LabVIEW applications for your PC. When developing real-time (RT) programs in LabVIEW, you develop on a host Windows computer, and then download and run them on a real-time hardware target. 59 60 LabVIEW Real-Time Module When developing real-time applications in LabVIEW, you use the LabVIEW Project Explorer to organize your programs (VIs) and categorize them by the hardware platform that they will run on. Note that you develop your code on a general-purpose Windows computer, and then connect to your real-time hardware using Ethernet. To test your LabVIEW Real-Time program on your hardware platform, simply click on the run arrow and your application will automatically be transferred to your real-time hardware via Ethernet and begin running. You can use standard NI debugging tools such as highlight execution, single stepping, and breakpoints from your development system even though your real-time program is actually running on a separate system. When you have finalized your real-time program, you can build an EXE in LabVIEW and download it to your real-time hardware as a startup application. After rebooting your real-time hardware, your program will automatically run in a reliable, stand-alone fashion. You start a new Real-Time Project from your Getting Started window. Tutorial: OPC and Real-Time Systems in LabVIEW 61 LabVIEW Real-Time Module Select either “Real-Time Project” in the New group or select “Real-Time Project” in the Targets selector and then “Go”. The Real-Time project is also available from the Tools menu. Tutorial: OPC and Real-Time Systems in LabVIEW 13 COMPACT FIELDPOINT Compact FieldPoint is an easy-to-use, highly expandable industrial control and measurement system composed of rugged and dependable I/O modules and intelligent communication interfaces. Download your NI LabVIEW application onto the embedded real-time controller for stand-alone data logging, monitoring, and advanced control. Plus, connect to virtually any sensor type with the wide variety of I/O modules, such as thermocouples, resistance temperature detectors (RTDs), strain gages, 4-20 mA sensors, and a variety of digital signals from 5-30 VDC and 0-250 VAC. The Compact FieldPoint I/O modules filter, calibrate, and scale raw sensor signals to engineering units and perform self-diagnostics to look for problems, such as an open thermocouple. With Compact FieldPoint you can: Deploy real-time embedded controllers for stand-alone data logging, advanced analysis, and process control. Access I/O points nearby or miles away on the network using the same simple read and write software framework. Connect virtually any sensor directly to the wide variety of high-accuracy analog and discrete I/O modules. Download your NI LabVIEW application to the embedded controller for reliable, stand-alone operation. Compact FieldPoint is very easy to use and can help you quickly begin performing industrial control and measurement. Getting started is a simple three-step process: 1. 2. 3. Install the hardware Configure the controller Read or write the I/O channels 62 63 Compact FieldPoint Tight integration between the LabVIEW software environment and real-time hardware targets, such as Compact FieldPoint, make your control development process quick and easy. You can take advantage of powerful graphical development using industry-standard LabVIEW to rapidly implement your control system. 1. 2. 3. First, develop the program on a Windows host computer using graphical programming blocks. Next, download the application to an embedded controller such the NI cFP-2000/cFP-2220. Finally, deploy your application for dependable long-term execution that performs reliably both with and without a network connection. Once your application is deployed, you can access the embedded application through any Web browser by connecting to the embedded Web server of the real-time Compact FieldPoint controller. Example: Create and Deploy a LabVIEW program for your Compact FieldPoint In order to configure and use your Compact FieldPoint you need to do the following steps. Step 1: Connect the Compact FieldPoint to your PC Connect your Compact FieldPoint system to your PC using an Ethernet cross-over cable. If you use a Switch or Hub you may use a standard Ethernet cable. Step 2: Install and Configure the Compact FieldPoint You use the Measurement & Automation Explorer (MAX) to configure your Compact FieldPoint system. Go to “Remote Systems”. The system should now be automatically detected. You may need to configure the IP settings. Step 3: Find your Devices Click on your Compact FieldPoint node and right-click and select “Find Devices”. Tutorial: OPC and Real-Time Systems in LabVIEW 64 Compact FieldPoint All your Compact FieldPoint modules (controller, I/modules) should now appear. In our case we have acFP-2000 controller and a cFP-AIO-610 I/O module. Step 4: Start an Empty Project in LabVIEW Start LabVIEW and select “Empty Project” in the Getting Started window. Tutorial: OPC and Real-Time Systems in LabVIEW 65 Compact FieldPoint Right-click on the Project node and select “Targets and Devices…” Select your Compact FieldPoint device from the list (Real-Time FieldPoint): Tutorial: OPC and Real-Time Systems in LabVIEW 66 Compact FieldPoint When you click OK, all your modules will be automatically inserted into your Project. If you click on your I/O module, you will see all your I/O channels for that module: Tutorial: OPC and Real-Time Systems in LabVIEW 67 Compact FieldPoint Step 5: Create your VI Right-click on your controller and select New→VI Go to your I/O module in the project tree and select your channel, e.g., Input 0. Drag the channel to your Block Diagram and the code for that channel will be automatically created. Tutorial: OPC and Real-Time Systems in LabVIEW 68 Compact FieldPoint Step 6: Finish your Program Finish your program, e.g., read Input 0 and plot the values in a Chart. Block Diagram: Here are your Project Explorer and the Front Diagram: Tutorial: OPC and Real-Time Systems in LabVIEW 69 Compact FieldPoint Step 6: Deployment Click the Run button to start test and deploy your program. LabVIEW then automatically start to check your could and download it to the controller. Step 6: Finish Your system should now be ready to use. Tutorial: OPC and Real-Time Systems in LabVIEW 14 WHATS NEXT? 14.1 MY BLOG For more information about LabVIEW, visit my Blog: http://home.hit.no/~hansha/ 14.2 TRAINING This Training is a part of a series with other Training Kits I have made, such as: Introduction to LabVIEW Data Acquisition in LabVIEW Control and Simulation in LabVIEW LabVIEW MathScript Linear Algebra in LabVIEW Datalogging and Supervisory Control in LabVIEW Wireless Data Acquisition in LabVIEW Intermediate Topics in LabVIEW Advanced Topics in LabVIEW These Training Kits are available for download from my blog: http://home.hit.no/~hansha 70 QUICK REFERENCE 71 72 Quick Reference Tutorial: OPC and Real-Time Systems in LabVIEW Telemark University College Faculty of Technology Kjølnes Ring 56 N-3914 Porsgrunn, Norway www.hit.no Hans-Petter Halvorsen, M.Sc. Telemark University College Department of Electrical Engineering, Information Technology and Cybernetics Phone: +47 3557 5158 E-mail: hans.p.halvorsen@hit.no Blog: http://home.hit.no/~hansha/ Room: B-237a Telemark University College Department of Electrical Engineering, Information Technology and Cybernetics LINEAR ALGEBRA IN LABVIEW HANS-PETTER HALVORSEN, 9. DESEMBER 2009 Faculty of Technology, Postboks 203, Kjølnes ring 56, N-3901 Porsgrunn, Norway. Tel: +47 35 57 50 00 Fax: +47 35 57 54 01 PREFACE This document explains the basic concepts of Linear Algebra and how you may use LabVIEW for calculation of these problems. You should have some basic knowledge about LabVIEW, e.g., the “An Introduction to LabVIEW” training. This document is available for download at http://home.hit.no/~hansha/. For more information about LabVIEW, visit my Blog: http://home.hit.no/~hansha/ INSTALLATION REQUIREMENTS NI LabVIEW Name Required LabVIEW Professional Development System Yes NI LabVIEW Core Components Name Required LabVIEW Control Design and Simulation Module LabVIEW MathScript RT Module Yes NI Vision Development Module Vision Builder for Automated Inspection LabVIEW Digital Filter Design Toolkit LabVIEW Modulation Toolkit LabVIEW System Identification Toolkit LabVIEW Desktop Execution Trace Toolkit LabVIEW Report Generation for Microsoft Office Toolkit LabVIEW Database Connectivity Toolkit LabVIEW Internet Toolkit NI LabVIEW SignalExpress LabVIEW Basics 1 and 2 Computer Based Training Extended Development Suite Components Name Required LabWindows/CVI Full Development System LabWindows/CVI Real-Time Module LabWindows/CVI PID Control Toolkit LabWindows/CVI Signal Processing Toolkit LabWindows/CVI Spectral Measurements Toolkit and Run-time Engine LabWindows/CVI SQL Toolkit Measurement Studio Enterprise Edition iii DIAdem Professional Control and Embedded Systems Option Components Name Required LabVIEW FPGA Module LabVIEW Real-Time Module LabVIEW Statechart Module LabVIEW Mobile Module LabVIEW Datalogging and Supervisory Control Module LabVIEW PID and Fuzzy Logic Toolkit NI Real-Time Execution Trace Toolkit LabVIEW Simulation Interface Toolkit NI Motion Assistant NI-DAQ Base Signal processing and Communications Option Components Name Required LabVIEW FPGA Module LabVIEW Sound and Vibration Measurement Suite LabVIEW Spectral Measurement Toolkit LabVIEW Advanced Signal Processing Toolkit LabVIEW Adaptive Filter Toolkit NI Device Drivers Name FieldPoint NI-DAQmx NI LabVIEW SignalExpress NI Instrument I/O Assistant NI-IMAQ NI Measurement & Automation Explorer Required NI PXI NI-VISA TABLE OF CONTENTS Preface .................................................................................................................................................................... 2 Installation Requirements ....................................................................................................................................... iii Table of Contents .................................................................................................................................................... vi 1 2 3 Introduction to LabVIEW ............................................................................................................................... 1 1.1 Dataflow programming.......................................................................................................................... 1 1.2 Graphical programming ......................................................................................................................... 1 1.3 Benefits .................................................................................................................................................. 2 1.4 LabVIEW MathScript RT Module ........................................................................................................... 2 Introduction to Linear Algebra ...................................................................................................................... 3 2.1.1 Transpose ...................................................................................................................................... 3 2.1.2 Diagonal ........................................................................................................................................ 3 2.1.3 Matrix Multiplication .................................................................................................................... 3 2.1.4 Matrix Addition ............................................................................................................................. 3 2.1.5 Determinant .................................................................................................................................. 4 2.1.6 Inverse Matrices ........................................................................................................................... 4 2.2 Eigenvalues ............................................................................................................................................ 4 2.3 Solving Linear Equations ........................................................................................................................ 5 2.4 LU factorization ..................................................................................................................................... 5 2.5 The Singular Value Decomposition (SVD) .............................................................................................. 6 Linear Algebra Palette in LabVIEW ................................................................................................................ 7 3.1 Vectors ................................................................................................................................................... 8 3.2 Matrices ................................................................................................................................................. 8 3.2.1 Transpose ...................................................................................................................................... 9 3.2.2 Diagonal ........................................................................................................................................ 9 3.2.3 Matrix Multiplication .................................................................................................................. 11 3.2.4 Matrix Addition ........................................................................................................................... 11 vi vii Table of Contents 3.2.5 Determinant ................................................................................................................................ 12 3.2.6 Inverse Matrices ......................................................................................................................... 13 3.3 Eigenvalues .......................................................................................................................................... 14 3.4 Solving Linear Equations ...................................................................................................................... 14 3.5 LU factorization ................................................................................................................................... 16 3.6 The Singular Value Decomposition (SVD) ............................................................................................ 17 4 LabVIEW MathScript RT Module ................................................................................................................. 18 5 LabVIEW MathScript .................................................................................................................................... 19 5.1 Help...................................................................................................................................................... 20 5.2 Examples .............................................................................................................................................. 20 5.3 Useful commands ................................................................................................................................ 23 5.4 Flow Control ........................................................................................................................................ 23 5.4.1 If-else Statement ......................................................................................................................... 23 5.4.2 Switch and Case Statement ........................................................................................................ 24 5.4.3 For loop ....................................................................................................................................... 24 5.4.4 While loop ................................................................................................................................... 25 5.5 6 Plotting ................................................................................................................................................ 26 Linear Algebra Examples using LabVIEW MathScript .................................................................................. 28 6.1 Vectors ................................................................................................................................................. 28 6.2 Matrices ............................................................................................................................................... 28 6.2.1 Transpose .................................................................................................................................... 29 6.2.2 Diagonal ...................................................................................................................................... 29 6.2.3 Triangular .................................................................................................................................... 30 6.2.4 Matrix Multiplication .................................................................................................................. 30 6.2.5 Matrix Addition ........................................................................................................................... 31 6.2.6 Determinant ................................................................................................................................ 32 6.2.7 Inverse Matrices ......................................................................................................................... 33 6.3 Eigenvalues .......................................................................................................................................... 33 Tutorial: Linear Algebra in LabVIEW viii 7 8 Table of Contents 6.4 Solving Linear Equations ...................................................................................................................... 34 6.5 LU factorization ................................................................................................................................... 35 6.6 The Singular Value Decomposition (SVD) ............................................................................................ 37 6.7 Commands ........................................................................................................................................... 37 MathScript Node ......................................................................................................................................... 39 7.1 Transferring MathScript Nodes between Computers ......................................................................... 40 7.2 Examples .............................................................................................................................................. 41 7.3 Exercises .............................................................................................................................................. 44 Whats Next? ................................................................................................................................................ 45 8.1 My Blog ................................................................................................................................................ 45 8.2 Training ................................................................................................................................................ 45 8.3 MathScript Functions .......................................................................................................................... 45 Quick Reference .................................................................................................................................................... 47 Tutorial: Linear Algebra in LabVIEW 1 INTRODUCTION TO LABVIEW LabVIEW (short for Laboratory Virtual Instrumentation Engineering Workbench) is a platform and development environment for a visual programming language from National Instruments. The graphical language is named "G". Originally released for the Apple Macintosh in 1986, LabVIEW is commonly used for data acquisition, instrument control, and industrial automation on a variety of platforms including Microsoft Windows, various flavors of UNIX, Linux, and Mac OS X. The latest version of LabVIEW is version LabVIEW 2009, released in August 2009. Visit National Instruments at www.ni.com. The code files have the extension “.vi”, which is an abbreviation for “Virtual Instrument”. LabVIEW offers lots of additional Add-Ons and Toolkits. This paper is part of a series with LabVIEW papers: Introduction to LabVIEW Linear Algebra in LabVIEW Data Acquisition and Instrument Control in LabVIEW Control Design and Simulation in LabVIEW Signal Processing in LabVIEW Datalogging and Supervisory Control in LabVIEW System identification in LabVIEW Model based Control in LabVIEW Advanced Topics in LabVIEW Each paper may be used independently of each other. 1.1 DATAFLOW PROGRAMMING The programming language used in LabVIEW, also referred to as G, is a dataflow programming language. Execution is determined by the structure of a graphical block diagram (the LV-source code) on which the programmer connects different function-nodes by drawing wires. These wires propagate variables and any node can execute as soon as all its input data become available. Since this might be the case for multiple nodes simultaneously, G is inherently capable of parallel execution. Multi-processing and multi-threading hardware is automatically exploited by the built-in scheduler, which multiplexes multiple OS threads over the nodes ready for execution. 1.2 GRAPHICAL PROGRAMMING LabVIEW ties the creation of user interfaces (called front panels) into the development cycle. LabVIEW programs/subroutines are called virtual instruments (VIs). Each VI has three components: a block diagram, a front panel, and a connector panel. The last is used to represent the VI in the block diagrams of other, calling VIs. Controls and indicators on the front panel allow an operator to input data into or extract data from a running virtual instrument. However, the front panel can also serve as a programmatic interface. Thus a virtual instrument can either be run as a program, with the front panel serving as a user interface, or, when dropped as a node onto the block diagram, the front panel defines the inputs and outputs for the given node through the connector pane. This implies each VI can be easily tested before being embedded as a subroutine into a larger program. 1 2 Introduction to LabVIEW The graphical approach also allows non-programmers to build programs simply by dragging and dropping virtual representations of lab equipment with which they are already familiar. The LabVIEW programming environment, with the included examples and the documentation, makes it simple to create small applications. This is a benefit on one side, but there is also a certain danger of underestimating the expertise needed for good quality "G" programming. For complex algorithms or large-scale code, it is important that the programmer possess an extensive knowledge of the special LabVIEW syntax and the topology of its memory management. The most advanced LabVIEW development systems offer the possibility of building stand-alone applications. Furthermore, it is possible to create distributed applications, which communicate by a client/server scheme, and are therefore easier to implement due to the inherently parallel nature of G-code. 1.3 BENEFITS One benefit of LabVIEW over other development environments is the extensive support for accessing instrumentation hardware. Drivers and abstraction layers for many different types of instruments and buses are included or are available for inclusion. These present themselves as graphical nodes. The abstraction layers offer standard software interfaces to communicate with hardware devices. The provided driver interfaces save program development time. The sales pitch of National Instruments is, therefore, that even people with limited coding experience can write programs and deploy test solutions in a reduced time frame when compared to more conventional or competing systems. A new hardware driver topology (DAQmxBase), which consists mainly of G-coded components with only a few register calls through NI Measurement Hardware DDK (Driver Development Kit) functions, provides platform independent hardware access to numerous data acquisition and instrumentation devices. The DAQmxBase driver is available for LabVIEW on Windows, Mac OS X and Linux platforms. For more information about LabVIEW, visit my Blog: http://home.hit.no/~hansha/ 1.4 LABVIEW MATHSCRIPT RT MODULE The LabVIEW MathScript RT Module is an add-on module to LabVIEW. With LabVIEW MathScript RT Module you can: Deploy your custom .m files to NI real-time hardware Reuse many of your scripts created with The MathWorks, Inc. MATLAB® software and others Develop your .m files with an interactive command-line interface Embed your scripts into your LabVIEW applications using the MathScript Node Tutorial: Linear Algebra in LabVIEW 2 INTRODUCTION TO LINEAR ALGEBRA Given a matrix A: Example: 2.1.1 TRANSPOSE The Transpose of matrix A: 2.1.2 DIAGONAL The Diagonal elements of matrix A is the vector The Diagonal matrix Λ is given by: Given the Identity matrix I: 2.1.3 MATRIX MULTIPLICATION Given the matrices and , then 2.1.4 MATRIX ADDITION 3 4 Introduction to Linear Algebra Given the matrices and , then 2.1.5 DETERMINANT Given a matrix , then the Determinant is given: Given a 2x2 matrix Then Notice that and 2.1.6 INVERSE MATRICES The inverse of a quadratic matrix is defined by: if For a 2x2 matrix we have: The inverse 2.2 Given is given by EIGENVALUES , then the Eigenvalues is defined as: Tutorial: Linear Algebra in LabVIEW 5 2.3 Introduction to Linear Algebra SOLVING LINEAR EQUATIONS Given the linear equation with the solution: (Assuming that the inverse of A exists) Example: The equations may be written where 2.4 LU FACTORIZATION LU factorization of is given by where L is a lower triangular matrix U is a upper triangular matrix Or sometimes LU factorization of is given by where D is a diagonal matrix Tutorial: Linear Algebra in LabVIEW 6 2.5 Introduction to Linear Algebra THE SINGULAR VALUE D ECOMPOSITION (SVD) The Singular value Decomposition (SVD) of the matrix is given by where U is a orthogonal matrix V is a orthogonal matrix S is a diagonal singular matrix Tutorial: Linear Algebra in LabVIEW 3 LINEAR ALGEBRA PALETTE IN LABVIEW For an Introduction to LabVIEW, see the training: “An Introduction to LabVIEW”. You may download it from my Blog: http://home.hit.no/~hansha/ Use the Linear Algebra Palette in order to solve Linear Algebra problems with the use of Graphical programming. In the Matrix Sub Palette we have the following functions: LabVIEW uses arrays to represents vectors and matrices. A vector is represented as a one dimensional array, while a matrix is represented as a two dimensional array. 7 8 Linear Algebra Palette in LabVIEW In the Array, Matrix & Cluster Palette available from the Front Panel, we have the basic array and matrix controls: 3.1 VECTORS Given a vector x Example: Vectors Implementing a vector in the Front Panel: 3.2 MATRICES Given a matrix A: Tutorial: Linear Algebra in LabVIEW 9 Linear Algebra Palette in LabVIEW Example: Matrices Front Panel: 3.2.1 TRANSPOSE The Transpose of matrix A: Example: Transpose Front Panel: Block Diagram: 3.2.2 DIAGONAL The Diagonal elements of matrix A is the vector Tutorial: Linear Algebra in LabVIEW 10 Linear Algebra Palette in LabVIEW Example: Diagonal Front Panel: Block Diagram: The Diagonal matrix Λ is given by: Given the Identity matrix I: Example: Identity Matrix Front Panel: Block Diagram: Tutorial: Linear Algebra in LabVIEW 11 Linear Algebra Palette in LabVIEW 3.2.3 MATRIX MULTIPLICATION Given the matrices and , then where Example: Matrix Multiplication Front Panel: Block Diagram: Note! → Prove this in LabVIEW 3.2.4 MATRIX ADDITION Tutorial: Linear Algebra in LabVIEW 12 Linear Algebra Palette in LabVIEW Given the matrices and , then Example: Matrix Addition Front Panel: Block Diagram: Note! There is no special function for matrix addition, just use the standard add function in the Numeric palette. 3.2.5 DETERMINANT Given a matrix , then the Determinant is given: Given a 2x2 matrix Then Example: Determinant Front Panel: Tutorial: Linear Algebra in LabVIEW 13 Linear Algebra Palette in LabVIEW Block Diagram: Notice that and → Prove this in LabVIEW 3.2.6 INVERSE MATRICES The inverse of a quadratic matrix is defined by: if For a 2x2 matrix we have: The inverse is given by Example: Inverse Front Panel: Tutorial: Linear Algebra in LabVIEW 14 Linear Algebra Palette in LabVIEW Block Diagram: Notice that: → Prove this in LabVIEW 3.3 EIGENVALUES Given , then the Eigenvalues is defined as: Example: Eigenvalues Front Panel: Block Diagram: 3.4 SOLVING LINEAR EQUATIONS Given the linear equation Tutorial: Linear Algebra in LabVIEW 15 Linear Algebra Palette in LabVIEW with the solution: (Assuming that the inverse of A exists) Example: Solving Linear Equations The equations may be written where The solution is: Front Panel: Block Diagram: Or: Tutorial: Linear Algebra in LabVIEW 16 3.5 Linear Algebra Palette in LabVIEW LU FACTORIZATION LU factorization of is given by where L is a lower triangular matrix U is a upper triangular matrix Example: LU Factorization Front Panel: Block Diagram: Or sometimes LU factorization of is given by where D is a diagonal matrix Example: LU Factorization Front Panel: Tutorial: Linear Algebra in LabVIEW 17 Linear Algebra Palette in LabVIEW Block Diagram: 3.6 THE SINGULAR VALUE D ECOMPOSITION (SVD) The Singular value Decomposition (SVD) of the matrix is given by where U is a orthogonal matrix V is a orthogonal matrix S is a diagonal singular matrix Example: SVD Decomposition Front Panel: Block Diagram: Tutorial: Linear Algebra in LabVIEW 4 LABVIEW MATHSCRIPT RT MODULE You can work with LabVIEW MathScript through either of two interfaces: the “LabVIEW MathScript Interactive Window” or the “MathScript Node”. You can work with LabVIEW MathScript RT Module through both interactive and programmatic interfaces. For an interactive interface in which you can load, save, design, and execute your .m file scripts, you can work with the “MathScript Interactive Window”. To deploy your .m file scripts as part of a LabVIEW application and combine graphical and textual programming, you can work with the “MathScript Node”. The LabVIEW MathScript RT Module complements traditional LabVIEW graphical programming for such tasks as algorithm development, signal processing, and analysis. The LabVIEW MathScript RT Module speeds up these and other tasks by giving users a single environment in which they can choose the most effective syntax, whether textual, graphical, or a combination of the two. In addition, you can exploit the best of LabVIEW and thousands of publicly available .m file scripts from the web, textbooks, or your own existing m-script applications. LabVIEW MathScript RT Module is able to process your files created using the current MathScript syntax and, for backwards compatibility, files created using legacy MathScript syntaxes. LabVIEW MathScript RT Module can also process certain of your files utilizing other text-based syntaxes, such as files you created using MATLAB software. Because the MathScript RT engine is used to process scripts contained in a MathScript Windows or MathScript Node, and because the MathScript RT engine does not support all syntaxes, not all existing text-based scripts are supported. LabVIEW MathScript RT Module supports most of the functionality available in MATLAB, the syntax is also similar. For more details, see http://zone.ni.com/devzone/cda/tut/p/id/3257 18 5 LABVIEW MATHSCRIPT Requires: MathScript RT Module The “LabVIEW MathScript Window” is an interactive interface in which you can enter .m file script commands and see immediate results, variables and commands history. The window includes a command-line interface where you can enter commands one-by-one for quick calculations, script debugging or learning. Alternatively, you can enter and execute groups of commands through a script editor window. As you work, a variable display updates to show the graphical / textual results and a history window tracks your commands. The history view facilitates algorithm development by allowing you to use the clipboard to reuse your previously executed commands. You can use the “LabVIEW MathScript Window” to enter commands one at time. You also can enter batch scripts in a simple text editor window, loaded from a text file, or imported from a separate text editor. The “LabVIEW MathScript Window” provides immediate feedback in a variety of forms, such as graphs and text. Example: 19 20 5.1 LabVIEW MathScript HELP You may also type help in your command window >>help Or more specific, e.g., >>help plot 5.2 EXAMPLES I advise you to test all the examples in this text in LabVIEW MathScript in order to get familiar with the program and its syntax. All examples in the text are outlined in a frame like this: >> … This is commands you should write in the Command Window. You type all your commands in the Command Window. I will use the symbol “>>” to illustrate that the commands should be written in the Command Window. Tutorial: Linear Algebra in LabVIEW 21 LabVIEW MathScript Example: Matrices Defining the following matrix The syntax is as follows: >> A = [1 2;0 3] Or >> A = [1,2;0,3] If you, for an example, want to find the answer to >>a=4 >>b=3 >>a+b MathScript then responds: ans = 7 MathScript provides a simple way to define simple arrays using the syntax: “init:increment:terminator”. For instance: >> array = 1:2:9 array = 1 3 5 7 9 defines a variable named array (or assigns a new value to an existing variable with the name array) which is an array consisting of the values 1, 3, 5, 7, and 9. That is, the array starts at 1 (the init value), increments with each step from the previous value by 2 (the increment value), and stops once it reaches (or to avoid exceeding) 9 (the terminator value). The increment value can actually be left out of this syntax (along with one of the colons), to use a default value of 1. >> ari = 1:5 ari = 1 2 3 4 5 Tutorial: Linear Algebra in LabVIEW 22 LabVIEW MathScript assigns to the variable named ari an array with the values 1, 2, 3, 4, and 5, since the default value of 1 is used as the incrementer. Note that the indexing is one-based, which is the usual convention for matrices in mathematics. This is atypical for programming languages, whose arrays more often start with zero. Matrices can be defined by separating the elements of a row with blank space or comma and using a semicolon to terminate each row. The list of elements should be surrounded by square brackets: []. Parentheses: () are used to access elements and subarrays (they are also used to denote a function argument list). >> A = [16 3 2 13; 5 10 11 8; 9 6 7 12; 4 15 14 1] A = 16 3 2 13 5 10 11 9 6 8 7 12 4 15 14 1 >> A(2,3) ans = 11 Sets of indices can be specified by expressions such as "2:4", which evaluates to [2, 3, 4]. For example, a submatrix taken from rows 2 through 4 and columns 3 through 4 can be written as: >> A(2:4,3:4) ans = 11 8 7 12 14 1 A square identity matrix of size n can be generated using the function eye, and matrices of any size with zeros or ones can be generated with the functions zeros and ones, respectively. >> eye(3) ans = 1 0 0 0 1 0 Tutorial: Linear Algebra in LabVIEW 23 LabVIEW MathScript 0 0 1 >> zeros(2,3) ans = 0 0 0 0 0 0 >> ones(2,3) ans = 1 1 1 1 1 1 5.3 USEFUL COMMANDS Here are some useful commands: Command Description eye(x), eye(x,y) Identity matrix of order x ones(x), ones(x,y) A matrix with only ones zeros(x), zeros(x,y) A matrix with only zeros diag([x y z]) Diagonal matrix size(A) Dimension of matrix A A’ Inverse of matrix A 5.4 FLOW CONTROL This chapter explains the basic concepts of flow control in MathScript. The topics are as follows: If-else statement Switch and case statement For loop While loop 5.4.1 IF-ELSE STATEMENT Tutorial: Linear Algebra in LabVIEW 24 LabVIEW MathScript The if statement evaluates a logical expression and executes a group of statements when the expression is true. The optional elseif and else keywords provide for the execution of alternate groups of statements. An end keyword, which matches the if, terminates the last group of statements. The groups of statements are delineated by the four keywords—no braces or brackets are involved. Example: If-Else Statement Test the following code: n=5 if n > 2 M = eye(n) elseif n < 2 M = zeros(n) else M = ones(n) end 5.4.2 SWITCH AND CASE STATEMENT The switch statement executes groups of statements based on the value of a variable or expression. The keywords case and otherwise delineate the groups. Only the first matching case is executed. There must always be an end to match the switch. Example: Switch and Case Statement Test the following code: n=2 switch(n) case 1 M = eye(n) case 2 M = zeros(n) case 3 M = ones(n) end 5.4.3 FOR LOOP The for loop repeats a group of statements a fixed, predetermined number of times. A matching end delineates the statements. Example: For Loop Test the following code: Tutorial: Linear Algebra in LabVIEW 25 LabVIEW MathScript m=5 for n = 1:m r(n) = rank(magic(n)); end r 5.4.4 WHILE LOOP The while loop repeats a group of statements an indefinite number of times under control of a logical condition. A matching end delineates the statements. Example: While Loop Test the following code: m=5; while m > 1 m = m - 1; zeros(m) end Tutorial: Linear Algebra in LabVIEW 26 5.5 LabVIEW MathScript PLOTTING This chapter explains the basic concepts of creating plots in MathScript. Topics: Basic Plot commands Example: Plotting Function plot can be used to produce a graph from two vectors x and y. The code: x = 0:pi/100:2*pi; y = sin(x); plot(x,y) produces the following figure of the sine function: Example: Plotting Three-dimensional graphics can be produced using the functions surf, plot3 or mesh. [X,Y] = meshgrid(-10:0.25:10,-10:0.25:10); f = sinc(sqrt((X/pi).^2+(Y/pi).^2)); mesh(X,Y,f); axis([-10 10 -10 10 -0.3 1]) Tutorial: Linear Algebra in LabVIEW 27 LabVIEW MathScript xlabel('{\bfx}') ylabel('{\bfy}') zlabel('{\bfsinc} ({\bfR})') hidden off This code produces the following 3D plot: Tutorial: Linear Algebra in LabVIEW 28 6 Linear Algebra Examples using LabVIEW MathScript LINEAR ALGEBRA EXAMPLES USING LABVIEW MATHSCRIPT Requires: MathScript RT Module Linear algebra is a branch of mathematics concerned with the study of matrices, vectors, vector spaces (also called linear spaces), linear maps (also called linear transformations), and systems of linear equations. MathScript are well suited for Linear Algebra. 6.1 VECTORS Given a vector x Example: Vectors Given the following vector >> x=[1; 2; 3] x = 1 2 3 The Transpose of vector x: >> x' ans = 1 2 3 The Length of vector x: Orthogonality: 6.2 MATRICES Tutorial: Linear Algebra in LabVIEW 29 Linear Algebra Examples using LabVIEW MathScript Given a matrix A: Example: Matrices Given the following matrix: >> A=[0 1;-2 -3] A = 0 1 -2 -3 6.2.1 TRANSPOSE The Transpose of matrix A: Example: Transpose Given the matrix: >> A' ans = 0 -2 1 -3 6.2.2 DIAGONAL The Diagonal elements of matrix A is the vector Example: Diagonal Find the diagonal elements of matrix A: Tutorial: Linear Algebra in LabVIEW 30 Linear Algebra Examples using LabVIEW MathScript >> diag(A) ans = 0 -3 The Diagonal matrix Λ is given by: Given the Identity matrix I: Example: Identity Matrix Get the 3x3 Identity matrix: >> eye(3) ans = 1 0 0 0 1 0 0 0 1 6.2.3 TRIANGULAR Lower Triangular matrix L: Upper Triangular matrix U: 6.2.4 MATRIX MULTIPLICATION Given the matrices and , then where Tutorial: Linear Algebra in LabVIEW 31 Linear Algebra Examples using LabVIEW MathScript Example: Matrix Multiplication Matrix multiplication: >> A=[0 1;-2 -3] A = 0 1 -2 -3 >> B=[1 0;3 -2] B = 1 0 3 -2 >> A*B ans = 3 -2 -11 6 Note! 6.2.5 MATRIX ADDITION Given the matrices and , then Example: Matrix Addition Matrix addition: >> A=[0 1;-2 -3] >> B=[1 0;3 -2] >> A+B ans = 1 1 Tutorial: Linear Algebra in LabVIEW 32 Linear Algebra Examples using LabVIEW MathScript 1 -5 6.2.6 DETERMINANT Given a matrix , then the Determinant is given: Given a 2x2 matrix Then Example: Determinant Find the determinant: A = 0 1 -2 -3 >> det(A) ans = 2 Notice that and Example: Determinant Determinants: >> det(A*B) ans = -4 >> det(A)*det(B) Tutorial: Linear Algebra in LabVIEW 33 Linear Algebra Examples using LabVIEW MathScript ans = -4 >> det(A') ans = 2 >> det(A) ans = 2 6.2.7 INVERSE MATRICES The inverse of a quadratic matrix is defined by: if For a 2x2 matrix we have: The inverse is given by Example: Inverse Matrices Inverse matrix: A = 0 1 -2 -3 >> inv(A) ans = -1.5000 -0.5000 1.0000 0 Notice that: → Prove this in MathScript 6.3 EIGENVALUES Tutorial: Linear Algebra in LabVIEW 34 Linear Algebra Examples using LabVIEW MathScript Given , then the Eigenvalues is defined as: Example: Eigenvalues Find the Eigenvalues: A = 0 1 -2 -3 >> eig(A) ans = -1 -2 6.4 SOLVING LINEAR EQUATIONS Given the linear equation with the solution: (Assuming that the inverse of A exists) Example: Solving Linear Equations Solving the following equation: The equations may be written where Tutorial: Linear Algebra in LabVIEW 35 Linear Algebra Examples using LabVIEW MathScript The solution is: A = 1 2 3 4 >> b=[5;6] b = 5 6 >> x=inv(A)*b x = -4.0000 4.5000 In MathScript you could also write “x=A\b”, which should give the same answer. This syntax can also be used when the inverse of A don’t exists. Example: Solving Linear Equations Illegal operation: >> A=[1 2;3 4;7 8] >> x=inv(A)*b ??? Error using ==> inv Matrix must be square. >> x=A\b x = -3.5000 4.1786 6.5 LU FACTORIZATION LU factorization of is given by where L is a lower triangular matrix U is a upper triangular matrix The MathScript syntax is [L,U]=lu(A) Tutorial: Linear Algebra in LabVIEW 36 Linear Algebra Examples using LabVIEW MathScript Example: LU Factorization Find L and U: >> A=[1 2;3 4] >> [L,U]=lu(A) L = 0.3333 1.0000 1.0000 0 3.0000 4.0000 0 0.6667 U = Or sometimes LU factorization of is given by where D is a diagonal matrix The MathScript syntax is [L,U,P]=lu(A) Example: LU Factorization Find L, U and P: >> A=[1 2;3 4] A = 1 2 3 4 >> [L,U,P]=lu(A) L = 1.0000 0 0.3333 1.0000 3.0000 4.0000 0 0.6667 U = P = Tutorial: Linear Algebra in LabVIEW 37 Linear Algebra Examples using LabVIEW MathScript 6.6 0 1 1 0 THE SINGULAR VALUE D ECOMPOSITION (SVD) The Singular value Decomposition (SVD) of the matrix is given by where U is a orthogonal matrix V is a orthogonal matrix S is a diagonal singular matrix Example: SVD Decomposition Find S, V and D: >> A=[1 2;3 4]; >> [U,S,V] = svd(A) U = -0.4046 -0.9145 -0.9145 0.4046 5.4650 0 0 0.3660 -0.5760 0.8174 -0.8174 -0.5760 S = V = 6.7 COMMANDS Command Description Tutorial: Linear Algebra in LabVIEW 38 [L,U]=lu(A) Linear Algebra Examples using LabVIEW MathScript LU Factorization [L,U,P]=lu(A) [U,S,V] = svd(A) Singular Value Decomposition (SVD ) Tutorial: Linear Algebra in LabVIEW 7 MATHSCRIPT NODE The “MathScript Node” offers an intuitive means of combining graphical and textual code within LabVIEW. The figure below shows the “MathScript Node” on the block diagram, represented by the blue rectangle. Using “MathScript Nodes”, you can enter .m file script text directly or import it from a text file. You can define named inputs and outputs on the MathScript Node border to specify the data to transfer between the graphical LabVIEW environment and the textual MathScript code. You can associate .m file script variables with LabVIEW graphical programming, by wiring Node inputs and outputs. Then you can transfer data between .m file scripts with your graphical LabVIEW programming. The textual .m file scripts can now access features from traditional LabVIEW graphical programming. The MathScript Node is available from LabVIEW from the Functions Palette: Mathematics → Scripts & Formulas 39 40 MathScript Node If you click Ctrl+H you get help about the MathScript Node: Click “Detailed help” in order to get more information about the MathScript Node. Use the NI Example Finder in order to find examples: 7.1 TRANSFERRING MATHSCRIPT NODES BETWEEN COMPUTERS If a script in a MathScript Node calls a user-defined function, LabVIEW uses the default search path list to link the function call to the specified .m file. After you configure the default search path list and save the VI that contains the MathScript Node, you do not need to reconfigure the MathScript search path list when you open the VI on a different computer because LabVIEW looks for the .m file in the directory where the .m file was Tutorial: Linear Algebra in LabVIEW 41 MathScript Node located when you last saved the VI. However, you must maintain the same relative path between the VI and the .m file. 7.2 EXAMPLES Example: Using the MathScript Node Here is an example of how you use the MathScript Node. On the left border you connect input variables to the script, on the right border you have output variables. Right-click on the border and select “Add Input” or “Add Output”. Example: Calling a Windows DLL: Example: Using m-files in the MathScript Node: Use the LabVIEW MathScript to create a m-file script (or you may use MATLAB to create the same script): Tutorial: Linear Algebra in LabVIEW 42 MathScript Node Right-click on the border of the MathScript Node and select “Import”, and then select the m-file you want to import into the Node. Tutorial: Linear Algebra in LabVIEW 43 MathScript Node Right-click on the right border and select “Add Output”. Then right-click on the output variable and select “Create Indicator”. Block Diagram: The result is as follows (click the Run button): If you, e.g., add the following command in the MathScript Node: plot(x), the following window appears: Tutorial: Linear Algebra in LabVIEW 44 7.3 MathScript Node EXERCISES Use the MathScript Node and test the same examples you did in the previous chapter (Chapter 6 - “Linear Algebra Examples using LabVIEW MathScript”) Tutorial: Linear Algebra in LabVIEW 8 WHATS NEXT? 8.1 MY BLOG For more information about LabVIEW, visit my Blog: http://home.hit.no/~hansha/ 8.2 TRAINING This Training is a part of a series with other Training Kits I have made, such as: Introduction to LabVIEW Data Acquisition in LabVIEW Control and Simulation in LabVIEW LabVIEW MathScript Linear Algebra in LabVIEW Datalogging and Supervisory Control in LabVIEW Wireless Data Acquisition in LabVIEW Intermediate Topics in LabVIEW Advanced Topics in LabVIEW These Training Kits are available for download from my blog: http://home.hit.no/~hansha 8.3 MATHSCRIPT FUNCTIONS In the Help system there is detailed information about all the MathScript functions available. In addition to the MathScript RT Module functions, different add-on modules and toolkits installs additional functions. The LabVIEW Control Design and Simulation Module and LabVIEW Digital Filter Design Toolkit installs a lots of additional functions. 45 46 MathScript Node Tutorial: Linear Algebra in LabVIEW QUICK REFERENCE 47 48 Quick Reference Tutorial: Linear Algebra in LabVIEW Telemark University College Faculty of Technology Kjølnes Ring 56 N-3914 Porsgrunn, Norway www.hit.no Hans-Petter Halvorsen, M.Sc. Telemark University College Department of Electrical Engineering, Information Technology and Cybernetics Phone: +47 3557 5158 E-mail: hans.p.halvorsen@hit.no Blog: http://home.hit.no/~hansha/ Room: B-237a Telemark University College Department of Electrical Engineering, Information Technology and Cybernetics WIRELESS DATA ACQUISITION IN LABVIEW HANS-PETTER HALVORSEN, 2010.01.21 Faculty of Technology, Postboks 203, Kjølnes ring 56, N-3901 Porsgrunn, Norway. Tel: +47 35 57 50 00 Fax: +47 35 57 54 01 PREFACE It's not just phones and computers that can communicate wirelessly with the outside world. Wireless sensors appear both in medicine, in buildings and especially in industrial applications. It is developed more standardized radio network for wireless sensors. Zigbee is probably the most famous, where more than 300 large and small companies working to develop solutions. For industrial use requires special safety requirements. Radio network must have sufficient coverage to obtain an acceptable error rate. The network should have redundancy so that the random outcome can be repaired automatically. It is achieved in that messages can go several ways from the sensors to the centers. Also, the network for error handling and error correction so that random errors are corrected. Because of these requirements it has been shown that ZigBee is not always suitable for use in the industrial context. This particularly applies it in process control, where resistance to electromagnetic noise and encryption of the signals is important. A wireless standard specifically designed to satisfy industrial requirements is Wireless HART. This is based on the same physical radio technology such as ZigBee, but specifies additional frequency hopping to mitigate interference, better encryption and that provides for lower power consumption. Currently, the wireless sensors have been used for monitoring, where a human operator must decide whether the process parameters should be changed or not. The objective is that the technology will prove to be robust enough to also be used to process control where the changes in the industrial processes should happen automatically without human intervention. This will be the next major challenge for systems based on wireless technology. Wireless technology has many potential benefits for remote monitoring applications; however, it has been slow to see adoption in industry because of the complexities of programming and deploying a reliable, secure, and high-performance wireless system. NI Wi-Fi data acquisition (DAQ) devices meet these challenges by combining IEEE 802.11 wireless or Ethernet communication, direct sensor connectivity, and the flexibility of NI LabVIEW software. Some Application Areas for Wireless technology such as Wi-Fi monitoring: Challenges with wireless data acquisition technology: Proprietary protocols and network hardware Incomplete I/O offerings High-speed waveform measurements Lack of interoperability between suppliers Integration with existing wired systems Non-standard vendor-defined solutions National Instruments (NI), the vendor of the LabVIEW programming environment delivers several solutions for wireless monitoring and data acquisition. NI Wi-Fi data acquisition (NI Wi-Fi DAQ) devices combine IEEE 802.11b/g wireless or Ethernet communication, direct sensor connectivity, and the flexibility of NI-DAQmx software for remote monitoring of electrical, physical, mechanical, and acoustic signals This document introduces wireless data acquisition features and teaches you how you can simplify wireless remote measurements without compromising on the security or performance of a cabled data acquisition solution. INSTALLATION REQUIREMENTS NI LabVIEW Name Required LabVIEW Professional Development System Yes NI LabVIEW Core Components Name Required LabVIEW Control Design and Simulation Module LabVIEW MathScript RT Module NI Vision Development Module Vision Builder for Automated Inspection LabVIEW Digital Filter Design Toolkit LabVIEW Modulation Toolkit LabVIEW System Identification Toolkit LabVIEW Desktop Execution Trace Toolkit LabVIEW Report Generation for Microsoft Office Toolkit LabVIEW Database Connectivity Toolkit LabVIEW Internet Toolkit NI LabVIEW SignalExpress LabVIEW Basics 1 and 2 Computer Based Training Extended Development Suite Components Name Required LabWindows/CVI Full Development System LabWindows/CVI Real-Time Module LabWindows/CVI PID Control Toolkit LabWindows/CVI Signal Processing Toolkit LabWindows/CVI Spectral Measurements Toolkit and Run-time Engine LabWindows/CVI SQL Toolkit Measurement Studio Enterprise Edition iii DIAdem Professional Control and Embedded Systems Option Components Name Required LabVIEW FPGA Module LabVIEW Real-Time Module LabVIEW Statechart Module LabVIEW Mobile Module LabVIEW Datalogging and Supervisory Control Module LabVIEW PID and Fuzzy Logic Toolkit NI Real-Time Execution Trace Toolkit LabVIEW Simulation Interface Toolkit NI Motion Assistant NI-DAQ Base Signal processing and Communications Option Components Name Required LabVIEW FPGA Module LabVIEW Sound and Vibration Measurement Suite Yes LabVIEW Spectral Measurement Toolkit Yes LabVIEW Advanced Signal Processing Toolkit Yes LabVIEW Adaptive Filter Toolkit NI Device Drivers Name Required FieldPoint NI-DAQmx Yes NI LabVIEW SignalExpress NI Instrument I/O Assistant NI-IMAQ NI Measurement & Automation Explorer NI PXI Yes NI-VISA TABLE OF CONTENTS Preface ......................................................................................................................................................................i Installation Requirements ....................................................................................................................................... iii Table of Contents .................................................................................................................................................... vi 1 2 Wireless Technology ...................................................................................................................................... 1 1.1 Bluetooth ............................................................................................................................................... 2 1.2 Wireless USB .......................................................................................................................................... 3 1.3 ZigBee (IEEE 802.15.4) ........................................................................................................................... 3 1.4 Wi-Fi (IEEE 802.11) ................................................................................................................................ 4 Wireless Sensor Network (WSN) ................................................................................................................... 1 2.1 2.1.1 ZigBee (IEEE 802.15.4) .................................................................................................................. 2 2.1.2 IEEE 802.11 ................................................................................................................................... 3 2.1.3 WirelessHART................................................................................................................................ 3 2.2 3 4 Wireless Standards ................................................................................................................................ 1 Wireless Mesh Network (WMN)............................................................................................................ 3 Introduction to LabVIEW ............................................................................................................................... 6 3.1 Dataflow programming.......................................................................................................................... 6 3.2 Graphical programming ......................................................................................................................... 6 3.3 Benefits .................................................................................................................................................. 6 Introduction to Data Acquisition (DAQ) ........................................................................................................ 8 4.1 Introduction to DAQ - Data Acquisition ................................................................................................. 8 4.1.1 Physical input/output signals ........................................................................................................ 9 4.1.2 DAQ device/hardware .................................................................................................................. 9 4.1.3 Driver software ........................................................................................................................... 10 4.1.4 Your software application (Application software) ...................................................................... 11 4.2 MAX – Measurement and Automation Explorer ................................................................................. 11 4.3 NI-DAQmx ............................................................................................................................................ 12 vi vii Table of Contents 4.3.1 DAQ Assistant ............................................................................................................................. 13 5 Introduction to Wireless Data Acquisition (Wi-Fi DAQ) .............................................................................. 14 6 NI Wireless DAQ Devices ............................................................................................................................. 16 7 6.1 NI WLS-9234 ........................................................................................................................................ 17 6.2 NI WAP-3701 ....................................................................................................................................... 18 6.3 NI UES-3880 ......................................................................................................................................... 19 6.4 PS-5 Power Supply ............................................................................................................................... 20 NI WSN Devices ........................................................................................................................................... 21 7.1 7.1.1 NI WSN-9791 - WSN Ethernet Gateway...................................................................................... 23 7.1.2 NI WSN-3212 - Thermocouple Input Node ................................................................................. 23 7.1.3 NI WSN-3202 - Analog Input Node ............................................................................................. 23 7.2 8 Devices ................................................................................................................................................. 22 LabVIEW Drivers .................................................................................................................................. 23 NI Sound and Vibration Measurement Suite ............................................................................................... 26 8.1 NI Sound and Vibration Assistant ........................................................................................................ 26 8.2 Sound and Vibration Analysis VIs for LabVIEW.................................................................................... 27 Quick Reference .................................................................................................................................................... 28 Tutorial: Wireless Data Acquisition in LabVIEW 1 WIRELESS TECHNOLOGY Wireless technology and wireless networks are widely used today, but it’s quite new in industrial automation systems. There are different technologies and wireless standards available: Bluetooth Wireless USB ZigBee (IEEE 802.15.4) Wi-Fi (IEEE 802.11) Different wireless technologies: 1 2 Wireless Technology The Figure below compare the different wireless technologies: Wi-Fi and ZigBee are the primary wireless technologies for measurement and control systems. 1.1 BLUETOOTH Tutorial: Wireless Data Acquisition in LabVIEW 3 Wireless Technology 1.2 WIRELESS USB 1.3 ZIGBEE (IEEE 802.15.4) Tutorial: Wireless Data Acquisition in LabVIEW 4 1.4 Wireless Technology WI-FI (IEEE 802.11) Tutorial: Wireless Data Acquisition in LabVIEW 5 Wireless Technology Tutorial: Wireless Data Acquisition in LabVIEW 2 WIRELESS SENSOR NETWORK (WSN) Source: www.wikipedia.org A wireless sensor network (WSN) consists of spatially distributed autonomous sensors to cooperatively monitor physical or environmental conditions, such as temperature, sound, vibration, pressure, motion or pollutants. The development of wireless sensor networks was motivated by military applications such as battlefield surveillance. They are now used in many industrial and civilian application areas, including industrial process monitoring and control, machine health monitoring, environment and habitat monitoring, healthcare applications, home automation, and traffic control. In addition to one or more sensors, each node in a sensor network is typically equipped with a radio transceiver or other wireless communications device, a small microcontroller, and an energy source, usually a battery. The applications for WSNs are varied, typically involving some kind of monitoring, tracking, or controlling. Specific applications include habitat monitoring, object tracking, nuclear reactor control, fire detection, and traffic monitoring. In a typical application, a WSN is scattered in a region where it is meant to collect data through its sensor nodes. 2.1 WIRELESS STANDARDS Several standards are currently either ratified or under development for wireless sensor networks. ZigBee is a proprietary mesh-networking specification intended for uses such as embedded sensing, medical data collection, consumer devices like television remote controls, and home automation. Zigbee is promoted by a large consortium of industry players. WirelessHART is an extension of the HART Protocol and is specifically designed for Industrial applications like Process Monitoring and Control. 1 2 Wireless Sensor Network (WSN) 2.1.1 ZIGBEE (IEEE 802.15.4) ZigBee is a low-cost, low-power, wireless mesh networking proprietary standard. The low cost allows the technology to be widely deployed in wireless control and monitoring applications, the low power-usage allows longer life with smaller batteries, and the mesh networking provides high reliability and larger range. Read more about ZigBee: ZigBee Alliance: http://www.zigbee.org/ Wikipedia: http://en.wikipedia.org/wiki/ZigBee Tutorial: Wireless Data Acquisition in LabVIEW 3 Wireless Sensor Network (WSN) 2.1.2 IEEE 802.11 Wireless DAQ Products form National Instruments use the Wi-Fi IEEE 802.11 standard. NI WSN Measurement Systems use the ZigBee (IEEE 802.15.4) standard. Read more about wireless technology and products from National Instruments: NI Wireless Data Acquisition: http://sine.ni.com/np/app/main/p/ap/daq/lang/en/pg/1/sn/n17:daq,n24:Wireless NI Wireless Remote Monitoring: http://www.ni.com/wireless/remote_monitoring.htm NI Wireless Devices: http://www.ni.com/wireless/ NI Wireless Sensor Networks: http://www.ni.com/wsn/ 2.1.3 WIRELESSHART WirelessHART is an open-standard wireless networking technology developed by HART Communication Foundation. Developed as a multi-vendor, interoperable wireless standard, WirelessHART was defined specifically for the requirements of Process field device networks Read more about WirelessHART: HART Communication Foundation: http://www.hartcomm.org/ Wikipedia: http://en.wikipedia.org/wiki/WirelessHART 2.2 WIRELESS MESH NETWORK (WMN) Mesh networking is a type of networking where each node in the network may act as an independent router, regardless of whether it is connected to another network or not. It allows for continuous connections and reconfiguration around broken or blocked paths by “hopping” from node to node until the destination is reached. A mesh network whose nodes are all connected to each other is a fully connected network. Mesh networks differ from other networks in that the component parts can all connect to each other via multiple hops. A wireless mesh network (WMN) is a communications network made up of radio nodes organized in a mesh topology. Wireless mesh networks often consist of mesh clients, mesh routers and gateways. The mesh clients are often laptops, cell phones and other wireless devices while the mesh routers forward traffic to and from the gateways which may but need not connect to the Internet. The coverage area of the radio nodes working as a single network is sometimes called a mesh cloud. Access to this mesh cloud is dependent on the radio nodes working in harmony with each other to create a radio network. A mesh network is reliable and offers redundancy. When one node can no longer operate, the rest of the nodes can still communicate with each other, directly or through one or more intermediate nodes. Tutorial: Wireless Data Acquisition in LabVIEW 4 Wireless Sensor Network (WSN) Wireless mesh architecture is a first step towards providing high-bandwidth network over a specific coverage area. Wireless mesh architecture’s infrastructure is, in effect, a router network minus the cabling between nodes. It's built of peer radio devices that don't have to be cabled to a wired port like traditional WLAN access points (AP) do. Mesh architecture sustains signal strength by breaking long distances into a series of shorter hops Below we see an example of a Wireless Mesh Topology: Wireless Mess Networks (WMN) is widely used in Wireless Sensor Networks (WSN). Tutorial: Wireless Data Acquisition in LabVIEW 5 Wireless Sensor Network (WSN) Tutorial: Wireless Data Acquisition in LabVIEW 3 INTRODUCTION TO LABVIEW Sources: www.Wikipedia.org, www.ni.com LabVIEW (short for Laboratory Virtual Instrumentation Engineering Workbench) is a platform and development environment for a visual programming language from National Instruments. The graphical language is named "G". Originally released for the Apple Macintosh in 1986, LabVIEW is commonly used for data acquisition, instrument control, and industrial automation on a variety of platforms including Microsoft Windows, various flavors of UNIX, Linux, and Mac OS X. The latest version of LabVIEW is version LabVIEW 2009, released in August 2009. Visit National Instruments at www.ni.com. The code files have the extension “.vi”, which is a abbreviation for “Virtual Instrument”. LabVIEW offers lots of additional Add-Ons and Toolkits. 3.1 DATAFLOW PROGRAMMING The programming language used in LabVIEW, also referred to as G, is a dataflow programming language. Execution is determined by the structure of a graphical block diagram (the LV-source code) on which the programmer connects different function-nodes by drawing wires. These wires propagate variables and any node can execute as soon as all its input data become available. Since this might be the case for multiple nodes simultaneously, G is inherently capable of parallel execution. Multi-processing and multi-threading hardware is automatically exploited by the built-in scheduler, which multiplexes multiple OS threads over the nodes ready for execution. 3.2 GRAPHICAL PROGRAMMING LabVIEW ties the creation of user interfaces (called front panels) into the development cycle. LabVIEW programs/subroutines are called virtual instruments (VIs). Each VI has three components: a block diagram, a front panel, and a connector panel. The last is used to represent the VI in the block diagrams of other, calling VIs. Controls and indicators on the front panel allow an operator to input data into or extract data from a running virtual instrument. However, the front panel can also serve as a programmatic interface. Thus a virtual instrument can either be run as a program, with the front panel serving as a user interface, or, when dropped as a node onto the block diagram, the front panel defines the inputs and outputs for the given node through the connector pane. This implies each VI can be easily tested before being embedded as a subroutine into a larger program. The graphical approach also allows non-programmers to build programs simply by dragging and dropping virtual representations of lab equipment with which they are already familiar. The LabVIEW programming environment, with the included examples and the documentation, makes it simple to create small applications. This is a benefit on one side, but there is also a certain danger of underestimating the expertise needed for good quality "G" programming. For complex algorithms or large-scale code, it is important that the programmer possess an extensive knowledge of the special LabVIEW syntax and the topology of its memory management. The most advanced LabVIEW development systems offer the possibility of building stand-alone applications. Furthermore, it is possible to create distributed applications, which communicate by a client/server scheme, and are therefore easier to implement due to the inherently parallel nature of G-code. 3.3 BENEFITS 6 7 Introduction to LabVIEW One benefit of LabVIEW over other development environments is the extensive support for accessing instrumentation hardware. Drivers and abstraction layers for many different types of instruments and buses are included or are available for inclusion. These present themselves as graphical nodes. The abstraction layers offer standard software interfaces to communicate with hardware devices. The provided driver interfaces save program development time. The sales pitch of National Instruments is, therefore, that even people with limited coding experience can write programs and deploy test solutions in a reduced time frame when compared to more conventional or competing systems. A new hardware driver topology (DAQmxBase), which consists mainly of G-coded components with only a few register calls through NI Measurement Hardware DDK (Driver Development Kit) functions, provides platform independent hardware access to numerous data acquisition and instrumentation devices. The DAQmxBase driver is available for LabVIEW on Windows, Mac OS X and Linux platforms. Tutorial: Wireless Data Acquisition in LabVIEW 4 INTRODUCTION TO DATA ACQUISITION (DAQ) This chapter explains the basic concepts of using DAQ in LabVIEW. Topics: Introduction to DAQ - Data Acquisition MAX – Measurement and Automation Explorer NI-DAQmx Driver software LabVIEW is very powerful when it comes to creating DAQ applications. LabVIEW includes a set of VIs that let you configure, acquire data from, and send data to DAQ devices. Often, one device can perform a variety of functions, such as analog-to-digital (A/D) conversion, digital-to-analog (D/A) conversion, digital I/O, and counter/timer operations. Each device supports different DAQ and signal generation speeds. Also, each DAQ device is designed for specific hardware, platforms and operating systems. National Instruments, the inventor of LabVIEW, also make DAQ devices, so the integration with the DAQ devices from NI and the LabVIEW software is seamless and makes it easy to do I/O operations from the LabVIEW environment. 4.1 INTRODUCTION TO DAQ - DATA ACQUISITION The purpose of data acquisition is to measure an electrical or physical phenomenon such as voltage, current, temperature, pressure, or sound. PC-based data acquisition uses a combination of modular hardware, application software, and a computer to take measurements. While each data acquisition system is defined by its application requirements, every system shares a common goal of acquiring, analyzing, and presenting information. Data acquisition systems incorporate signals, sensors, actuators, signal conditioning, data acquisition devices, and application software. So summing up, Data Acquisition is the process of: Acquiring signals from real-world phenomena Digitizing the signals Analyzing, presenting and saving the data The DAQ system has the following parts involved, see Figure: 8 9 Introduction to Data Acquisition (DAQ) The parts are: Physical input/output signals DAQ device/hardware Driver software Your software application (Application software) For an Introduction to Data Acquisition, see this webcast: http://zone.ni.com/wv/app/doc/p/id/wv-169 4.1.1 PHYSICAL INPUT/OUTPUT SIGNALS A physical input/output signal is typically a voltage or current signal. 4.1.2 DAQ DEVICE/HARDWARE DAQ hardware acts as the interface between the computer and the outside world. It primarily functions as a device that digitizes incoming analog signals so that the computer can interpret them A DAQ device (Data Acquisition Hardware) usually has these functions: Analog input Analog output Digital I/O Counter/timers We have different DAQ devices, such as: “Desktop DAQ devices” where you need to plug a PCI DAQ board into your computer. The software is running on a computer. “Portable DAQ devices” for connection to the USB port, Wi-Fi connections, etc. The software is running on a computer “Distributed DAQ devices” where the software is developed on your computer and then later downloaded to the distributed DAQ device. Wi-Fi DAQ Devices Tutorial: Wireless Data Acquisition in LabVIEW 10 Introduction to Data Acquisition (DAQ) Wireless: 4.1.3 DRIVER SOFTWARE Driver software is the layer of software for easily communicating with the hardware. It forms the middle layer between the application software and the hardware. Driver software also prevents a programmer from having to do register-level programming or complicated commands in order to access the hardware functions. Driver software from National Instruments: NI-DAQmx NI-DAQmx Base The DAQ Assistant, included with NI-DAQmx, is a graphical, interactive guide for configuring, testing, and acquiring measurement data. With a single click, you can even generate code based on your configuration, making it easier and faster to develop complex operations. Because DAQ Assistant is completely menu-driven, you will make fewer programming errors and drastically decrease the time from setting up your DAQ system to taking your first measurement. Tutorial: Wireless Data Acquisition in LabVIEW 11 Introduction to Data Acquisition (DAQ) NI-DAQmx Base offers a subset of NI-DAQmx functionality on Windows and Linux, Mac OS X, Windows Mobile and Windows CE. 4.1.4 YOUR SOFTWARE APPLICATION (APPLICATION SOFTWARE) Application software adds analysis and presentation capabilities to the driver software. Your software application normally does such tasks as: Real-time monitoring Data analysis Data logging Control algorithms Human machine interface (HMI) In order to create your DAQ application you need a programming development tool, such as LabVIEW. 4.2 MAX – MEASUREMENT AND AUTOMATION EXPLORER Measurement & Automation Explorer (MAX) provides access to your National Instruments devices and systems. With MAX, you can: Configure your National Instruments hardware and software Create and edit channels, tasks, interfaces, scales, and virtual instruments Execute system diagnostics View devices and instruments connected to your system Update your National Instruments software In addition to the standard tools, MAX can expose item-specific tools you can use to configure, diagnose, or test your system, depending on which NI products you install. As you navigate through MAX, the contents of the application menu and toolbar change to reflect these new tools. Tutorial: Wireless Data Acquisition in LabVIEW 12 4.3 Introduction to Data Acquisition (DAQ) NI-DAQMX The NI-DAQmx Driver software is the layer of software for easily communicating with the hardware. It forms the middle layer between the application software and the hardware. Driver software also prevents a programmer from having to do register-level programming or complicated commands in order to access the hardware functions. The DAQmx palette in LabVIEW: Tutorial: Wireless Data Acquisition in LabVIEW 13 Introduction to Data Acquisition (DAQ) 4.3.1 DAQ ASSISTANT The DAQ Assistant, included with NI-DAQmx, is a graphical, interactive guide for configuring, testing, and acquiring measurement data. With a single click, you can even generate code based on your configuration, making it easier and faster to develop complex operations. Because DAQ Assistant is completely menu-driven, you will make fewer programming errors and drastically decrease the time from setting up your DAQ system to taking your first measurement. Tutorial: Wireless Data Acquisition in LabVIEW 5 INTRODUCTION TO WIRELESS DATA ACQUISITION (WI-FI DAQ) Source: www.ni.com Wi-Fi DAQ is: Simple – Direct sensors connectivity and graphical programming Secure – Highest commercially available data encryption and authentication Wireless – 802.11g Wi-Fi data acquisition is an extension of PC-based data acquisition to measurement applications where cables are inconvenient or uneconomical. NI Wi-Fi data acquisition (DAQ) devices combine IEEE 802.11g wireless or Ethernet communication; direct sensor connectivity; and the flexibility of NI-DAQmx driver software for remote monitoring of electrical, physical, mechanical, and acoustical signals. NI Wi-Fi DAQ devices can stream data on each channel at up to 250 kS/s. In addition, built-in NIST-approved 128-bit AES encryption and advanced network authentication methods offer the highest commercially available network security. With the flexibility of NI LabVIEW graphical programming and the ubiquity of 802.11 network infrastructure, NI Wi-Fi DAQ makes it easy to incorporate wireless connectivity into new or existing PC-based measurement or control systems. The Data Flow in Wi-Fi DAQ is as follows: 14 15 Introduction to Wireless Data Acquisition (Wi-Fi DAQ) Unlike most wireless sensors or wireless sensor networks, wireless data acquisition devices are meant to stream data continuously back to a host PC or laptop. A wireless sensor node is typically a low-power, autonomous battery-operated device intended for long-term deployment in applications where measurements are needed only every few minutes, hours, or even days. Wi-Fi data acquisition devices, on the other hand, behave in much the same way as a USB data acquisition device – a host PC collects data continuously (in real time) as the device acquires it. The data acquisition device may be battery-operated, but the focus is on the measurement versus the battery life. Also, Wi-Fi data acquisition devices use the near-ubiquitous wireless networking standard, IEEE 802.11 because of its higher bandwidth and broader applicability. Finally, because NI Wi-Fi data acquisition uses the same NI-DAQmx driver software as other NI data acquisition devices, you can develop your applications using NI LabVIEW, LabWindows™/CVI; ANSI C/C++; or Microsoft C#, Visual Basic, or Visual Basic .NET. More Information about Wi-Fi DAQ: Watch the Wi-Fi DAQ Tour: http://sine.ni.com/np/app/culdesac/p/ap/daq/lang/en/pg/1/sn/n17:daq,n21:10423/docid/wv-795 Wi-Fi DAQ Webcast: http://zone.ni.com/wv/app/doc/p/id/wv-794 Tutorial: Wireless Data Acquisition in LabVIEW 6 NI WIRELESS DAQ DEVICES Common components in Wi-Fi DAQ are as follows: DAQ Devices Wireless Access Points (WAP) or a Wireless Router Network Switches How do I connect to an NI Wi-Fi DAQ device? When setting up your NI Wi-Fi DAQ device, you may choose to connect to an existing enterprise network through a wireless access point or set up your own network with a wireless router. For existing IT infrastructure, NI Wi-Fi DAQ devices support WPA Enterprise and WPA2 Enterprise (IEEE 802.11i). If you set up your own network, you may use WEP, WPA Personal (WPA-PSK), or WPA2 Personal (WPA2-PSK) security. NI Wi-Fi DAQ devices also support ad hoc or peer-to-peer networks, which do not require any routers or access points. However, ad hoc support is inconsistent across wireless network interface cards and is not secure. Communication through a wireless access point or wireless router is the preferred mode of operation. How do I program NI Wi-Fi DAQ devices? All NI Wi-Fi and Ethernet DAQ devices use the same NI-DAQmx measurement services and driver software as other National Instruments PCI, PXI, and USB DAQ devices. NI-DAQmx measurement services software controls every aspect of your data acquisition system from configuration to programming. With NI-DAQmx software, you can quickly configure and acquire measurements using the DAQ Assistant and automatically generate code to get your application started quickly. NI-DAQmx also features virtual channels that automatically scale raw data into engineering units. Because you can use the same driver API to program new NI Wi-Fi DAQ devices, incorporating wireless connectivity into your existing applications is easy. Wi-Fi DAQ Devices from National Instruments: 16 17 NI Wireless DAQ Devices TUC have the following wireless DAQ devices availible: NI WLS-9234 - Wireless 4-Channel Accelerometer and Microphone Input NI WAP-3701 - Wireless access points (WAPs) add wireless connectivity to all Ethernet-based NI programmable automation NI UES-3880 - An eight-port unmanaged entry-level switch for networking between NI Ethernet-based controllers and devices using standard Ethernet protocols PS-5 Power Supply 6.1 NI WLS-9234 The NI WLS-9234 is a four-channel IEEE 802.11 wireless or Ethernet C Series dynamic signal acquisition module for making high-accuracy audio frequency measurements from integrated electronic piezoelectric (IEPE) and non-IEPE sensors. 4-Channel, 51.2 kS/s/ch, 24-Bit, ±5 V IEPE Input IEEE 802.11b/g (Wi-Fi) wireless and Ethernet communications interfaces 51.2 kS/s per-channel maximum sampling rate; ±5 V input 24-bit resolution; 102 dB dynamic range; antialiasing filters Software-selectable AC/DC coupling; AC-coupled (0.5 Hz) Software-selectable IEPE signal conditioning (0 or 2 mA) Tutorial: Wireless Data Acquisition in LabVIEW 18 NI Wireless DAQ Devices The NI WLS-9234 is a four-channel IEEE 802.11 wireless or Ethernet C Series dynamic signal acquisition module for making high-accuracy audio frequency measurements from integrated electronic piezoelectric (IEPE) and non-IEPE sensors. The WLS-9234 delivers 102 dB of dynamic range and incorporates software-selectable AC/DC coupling and IEPE signal conditioning for accelerometers and microphones. The four input channels simultaneously digitize signals at rates up to 51.2 kHz per channel with built-in antialiasing filters that automatically adjust to your sampling rate. The WLS-9234 is well-suited for noise and vibration analysis applications. The NI Sound and Vibration Measurement Suite, which specifically addresses these applications, has two components: the NI Sound and Vibration Assistant and LabVIEW Analysis VIs (functions) for power spectra, frequency response (FRF), fractional octave analysis, sound-level measurements, order spectra, order maps, order extraction, sensor calibration, human vibration filters, and torsional vibration. WLS-9234 has 4 BNC connectors. The BNC connector is used for RF signal connections. The BNC connector is one of several radio frequency (RF) connectors on the market today. 6.2 NI WAP-3701 WAP – Wireless Access Point The NI WAP-3701 wireless access points (WAPs) add wireless connectivity to all Ethernet-based NI programmable automation controllers (PACs). A WAP-37x1 can connect wireless devices to a wired network and has an IP address so other wireless clients can access the device. A WAP-37x1 can also serve as a Dynamic Host Configuration Protocol (DHCP) server and configure other WAP-37x1 devices as wireless clients. A single WAP-37x1 typically supports up to 30 client devices, with the range depending on the wireless antennae selection. It also serves as a wireless bridge and allows two devices to talk to each other. EEE 802.11g/b wireless access point, client, and bridge Web-based management software included Tutorial: Wireless Data Acquisition in LabVIEW 19 NI Wireless DAQ Devices 64- and 128-bit wired equivalent privacy (WEP) security Redundant dual 24 VDC power inputs Metal enclosure, IP30 rated; Class I, Division 2 hazardous locations DIN-rail mounting support 6.3 NI UES-3880 UES – Unmanaged Ethernet Switch The NI UES-3880 is an eight-port unmanaged entry-level switch for networking between NI Ethernet-based controllers and devices using standard Ethernet protocols. To network with NI programmable automation controllers (PACs), the UES-3880 provides industrial features including -40 to 70 °C operating temperature; Class I, Division 2 and ATEX Class 1, Zone 2 certifications for hazardous locations; and redundant dual 24 VDC power inputs. Tutorial: Wireless Data Acquisition in LabVIEW 20 6.4 NI Wireless DAQ Devices PS-5 POWER SUPPLY PS – Power Supply The PS-5 is a DIN-rail-mountable 24 VDC power supply that provides 5 A of current and is rated for operation from -25C to 60C. Two PS-5 supplies can be wired in parallel to provide up to 10 A. The PS-5 is recommended for industrial installations. The PS-4 is a DIN-rail-mountable 24 V power supply in FieldPoint packaging. The PS-3 and PS-2 are power supply "bricks" with a universal IEC power input. The PS-3 can also operate as a float charger for 12 VDC batteries. The PS-1 is a wall-mount power supply. Tutorial: Wireless Data Acquisition in LabVIEW 7 NI WSN DEVICES A wireless sensor network (WSN) is a wireless network consisting of spatially distributed autonomous devices that use sensors to monitor physical or environmental conditions. These autonomous devices, or nodes, combine with routers and a gateway to create a typical WSN system. The distributed measurement nodes communicate wirelessly to a central gateway, which provides a connection to the wired world where you can collect, process, analyze, and present your measurement data. To extend distance and reliability in a WSN, you can use routers to gain an additional communication link between end nodes and the gateway. The proprietary NI WSN protocol is based on IEEE 802.15.4 and ZigBee technology. The IEEE 802.15.4 communication standard defines the Physical and Medium Access Control layers in the networking model, providing communication in three frequency bands including the 2.4 GHz ISM band. ZigBee builds on the 802.15.4 standard with the network and application layers, offering features such as device coordination, reliability through mesh networking topologies, and the functionality to create user-defined profiles that allow for customization and flexibility within the protocol. What is the difference between NI Wi-Fi data acquisition (DAQ) and NI WSN devices? NI Wi-Fi DAQ devices combine IEEE 802.11b/g (Wi-Fi) wireless or Ethernet communication, direct sensor connectivity, and the flexibility of NI-DAQmx software for a breadth of remote measurement and control options. Externally powered, NI Wi-Fi DAQ devices can stream continuous waveform data on each channel at more than 50 kS/s and offer the highest commercially available network security (WPA2 Enterprise). NI WSN devices deliver low-power measurement nodes that operate for up to three years on 4 AA batteries and can be deployed for long-term, remote operation. The wireless measurement nodes communicate with a central gateway using a protocol based on IEEE 802.15.4 (ZigBee) to offer mesh routing capabilities that extend network distance and reliability. NI WSN systems support lower data rates to preserve power, are easily programmed using I/O variables, and currently accommodate thermocouple and ±10 V measurements. 21 22 NI WSN Devices Many of the WSN systems today are based on ZigBee or IEEE 802.15.4 protocols due to their low-power consumption. ZigBee builds on the 802.15.4 layers to provide security, reliability through mesh networking topologies, and interoperability with other devices and standards. 7.1 DEVICES Tutorial: Wireless Data Acquisition in LabVIEW 23 NI WSN Devices 7.1.1 NI WSN-9791 - WSN ETHERNET GATEWAY The NI WSN-9791 Ethernet gateway coordinates communication between distributed measurement nodes and the host controller in your NI wireless sensor network (WSN). The gateway has a 2.4 GHz, IEEE 802.15.4 radio based on ZigBee technology to collect measurement data from the sensor network and a 10/100 Mbits/s Ethernet port to provide flexible connectivity to a Windows or LabVIEW Real-Time OS host controller. 7.1.2 NI WSN-3212 - THERMOCOUPLE INPUT NODE The NI WSN-3212 measurement node is a wireless device that provides four 24-bit thermocouple input channels and four bidirectional digital channels that you can configure on a per-channel basis for input, sinking output, or sourcing output. 7.1.3 NI WSN-3202 - ANALOG INPUT NODE The NI WSN-3202 measurement node is a wireless device that provides four ±10 V analog input channels and four bidirectional digital channels that you can configure on a per-channel basis for input, sinking output, or sourcing output. 7.2 LABVIEW DRIVERS Tutorial: Wireless Data Acquisition in LabVIEW 24 NI WSN Devices National Instruments offer the NI-WSN software. With NI-WSN software you can easily configure your network in the Measurement & Automation Explorer (MAX) utility. MAX provides an intuitive user interface to add and remove measurement nodes and configure wireless settings. NI-WSN software provides seamless LabVIEW integration so that you can quickly and easily extract measurement data from your WSN. After adding the NI WSN Ethernet gateway to a LabVIEW Project, the nodes configured with the gateway in MAX automatically populate in the LabVIEW Project, giving you instant access to their I/O and properties. Simply drag and drop I/O variables from the LabVIEW Project to a LabVIEW Block Diagram for data extraction, analysis, and presentation. Tutorial: Wireless Data Acquisition in LabVIEW 25 NI WSN Devices National Instruments also offer WSN drivers for WSN equipments from other vendors: http://zone.ni.com/devzone/cda/tut/p/id/5435 Tutorial: Wireless Data Acquisition in LabVIEW 8 NI SOUND AND VIBRATION MEASUREMENT SUITE The NI Sound and Vibration Measurement Suite has two components: the NI Sound and Vibration Assistant and LabVIEW Analysis VIs (functions) for power spectra, frequency response (FRF), fractional octave analysis, sound-level measurements, order spectra, order maps, order extraction, sensor calibration, human vibration filters, and torsional vibration. 8.1 NI SOUND AND VIBRATION ASSISTANT There are many built-in steps available for immediate use in the Sound and Vibration Assistant. You can instantly configure a measurement and analysis application with: Hardware I/O – generation and acquisition of signals from a variety of devices, including data acquisition devices and modular instruments Signal processing – filtering, windowing, and averaging Time-domain analysis – sound- and vibration-level measurements ANSI and IEC fractional-octave analysis Frequency-domain analysis – power spectrum, frequency response, power-in-band, peak search, and distortion Order analysis – tachometer processing, order power spectrum, order tracking, and order extraction Report generation – ability to drag and drop signals to Microsoft Excel or export data to Microsoft Word or UFF58 files 26 27 NI Sound and Vibration Measurement Suite You may reuse your measurement applications developed with the Sound and Vibration Assistant in LabVIEW by converting projects into LabVIEW block diagrams. With the LabVIEW full-featured graphical programming environment, you can further automate your application or customize your analysis. 8.2 SOUND AND VIBRATION ANALYSIS VIS FOR LABVIEW With the sound and vibration analysis VIs in LabVIEW, you can develop a variety of custom audio, acoustic, and vibration applications. Functionality includes: Full, 1/3, 1/6, 1/12, and 1/24 octave analysis with linear A, B, or C weighting Baseband, zoom, and subset power spectrum Peak search and power in band Frequency response (FRF) Filtering Swept sine Distortion analysis (THD, THD+N, IMD) Noise measurements (SNR) Human vibration weighting filters Torsional vibration Tachometer signal processing Order tracking, spectrum, and order extraction Waterfall display for power, octave, and order spectra Shaft centerline, orbit, Bode, and polar plot format File input and output to UFF58 Tutorial: Wireless Data Acquisition in LabVIEW QUICK REFERENCE 28 29 Quick Reference Tutorial: Wireless Data Acquisition in LabVIEW Telemark University College Faculty of Technology Kjølnes Ring 56 N-3914 Porsgrunn, Norway www.hit.no Hans-Petter Halvorsen, M.Sc. Telemark University College Department of Electrical Engineering, Information Technology and Cybernetics Phone: +47 3557 5158 E-mail: hans.p.halvorsen@hit.no Blog: http://home.hit.no/~hansha/ Room: B-237a