You are on page 1of 444

LabVIEW Real-Time Application Development Course Manual

TM

Course Software Version 8.0 March 2006 Edition Part Number 323843B-01 LabVIEW Real-Time Course Manual
Copyright 20042006 National Instruments Corporation. All rights reserved. Under the copyright laws, this publication may not be reproduced or transmitted in any form, electronic or mechanical, including photocopying, recording, storing in an information retrieval system, or translating, in whole or in part, without the prior written consent of National Instruments Corporation. National Instruments respects the intellectual property of others, and we ask our users to do the same. NI software is protected by copyright and other intellectual property laws. Where NI software may be used to reproduce software or other materials belonging to others, you may use NI software only to reproduce materials that you may reproduce in accordance with the terms of any applicable license or other legal restriction. Trademarks National Instruments, NI, ni.com, and LabVIEW are trademarks of National Instruments Corporation. Refer to the Terms of Use section on ni.com/legal for more information about National Instruments trademarks. Other product and company names mentioned herein are trademarks or trade names of their respective companies. Members of the National Instruments Alliance Partner Program are business entities independent from National Instruments and have no agency, partnership, or joint-venture relationship with National Instruments. Patents For patents covering National Instruments products, refer to the appropriate location: HelpPatents in your software, the patents.txt file on your CD, or ni.com/legal/patents.

Worldwide Technical Support and Product Information ni.com National Instruments Corporate Headquarters 11500 North Mopac Expressway Austin, Texas 78759-3504 USA Tel: 512 683 0100 Worldwide Offices Australia 1800 300 800, Austria 43 0 662 45 79 90 0, Belgium 32 0 2 757 00 20, Brazil 55 11 3262 3599, Canada 800 433 3488, China 86 21 6555 7838, Czech Republic 420 224 235 774, Denmark 45 45 76 26 00, Finland 385 0 9 725 725 11, France 33 0 1 48 14 24 24, Germany 49 0 89 741 31 30, India 91 80 41190000, Israel 972 0 3 6393737, Italy 39 02 413091, Japan 81 3 5472 2970, Korea 82 02 3451 3400, Lebanon 961 0 1 33 28 28, Malaysia 1800 887710, Mexico 01 800 010 0793, Netherlands 31 0 348 433 466, New Zealand 0800 553 322, Norway 47 0 66 90 76 60, Poland 48 22 3390150, Portugal 351 210 311 210, Russia 7 095 783 68 51, Singapore 1800 226 5886, Slovenia 386 3 425 4200, South Africa 27 0 11 805 8197, Spain 34 91 640 0085, Sweden 46 0 8 587 895 00, Switzerland 41 56 200 51 51, Taiwan 886 02 2377 2222, Thailand 662 278 6777, United Kingdom 44 0 1635 523545 For further support information, refer to the Additional Information and Resources appendix. To comment on National Instruments documentation, refer to the National Instruments Web site at ni.com/info and enter the info code feedback.

Contents
Student Guide
A. B. C. D. E. F. G. NI Certification .....................................................................................................vi Course Description ...............................................................................................vii What You Need to Get Started .............................................................................vii Installing the Course Software..............................................................................viii Removing Course Material ...................................................................................viii Course Goals.........................................................................................................viii Course Conventions ..............................................................................................x

Lesson 1 Introduction to Real-Time


Exercise 1-1 Project Specification Document .......................................................1-22

Lesson 2 Configuring Your Hardware


Exercise 2-1 Exercise 2-1 A Exercise 2-1 B Exercise 2-2 Configure Hardware .........................................................................2-22 Compact FieldPoint Configuration...................................................2-23 PXI Configuration ............................................................................2-31 Targeting Real-Time Hardware........................................................2-38

Lesson 3 Real-Time Architecture: Design


Exercise 3-1 Exercise 3-2 Exercise 3-3 Priority Levels ..................................................................................3-54 Inter-Thread Communication ...........................................................3-56 Project Flowchart..............................................................................3-78

Lesson 4 Timing Applications and Acquiring Data


Exercise 4-1 A Exercise 4-1 B Exercise 4-2 A Exercise 4-2 B cFP Software Sleep........................................................................4-19 PXI - Hardware Sleep.......................................................................4-21 cFP-Time-Critical.............................................................................4-24 PXI-Time-Critical.............................................................................4-34

Lesson 5 Communication
Exercise 5-1 Exercise 5-2 Exercise 5-3 Exercise 5-4 Using RT Wizards ............................................................................5-23 Target Program.................................................................................5-27 Completed Project Host VI ..............................................................5-47 Project Host VI (Optional) ...............................................................5-49

National Instruments Corporation

iii

LabVIEW Real-Time Course Manual

Contents

Lesson 6 Verifying Your Application


Exercise 6-1 Exercise 6-2 Exercise 6-3 Exercise 6-4 Debug Exercise.................................................................................6-33 Verify Timing Behavior ...................................................................6-35 Verify Memory Usage......................................................................6-36 Execution Trace................................................................................6-38

Lesson 7 Deploying Your Application


Exercise 7-1 Deploying an Application.................................................................7-31 Exercise 7-2 A cFP - Remote Panels.........................................................................7-33 Exercise 7-2 B PXI - Remote Panels ........................................................................7-38

Lesson 8 Advanced Topics


Exercise 8-1 A cFP - Timed Loops ...........................................................................8-22 Exercise 8-1 B PXI - Timed Loops...........................................................................8-27

Appendix A Course Project Resources


A. Course Project Specification Document ...............................................................A-2 B. Course Project Requirements Document ..............................................................A-3 C. Course Project Flowcharts ....................................................................................A-8

Appendix B Additional Information about LabVIEW Real-Time


A. Implementing Redundancy in Your System .........................................................B-2 B. Using LabWindows/CVI DLLs in LabVIEW Real-Time ....................................B-4

Appendix C Instructors Notes


A. Course Setup .........................................................................................................C-1 B. Course Shut-Down................................................................................................C-1

Appendix D Real-Time Systems Appendix E Additional Information and Resources Course Evaluation

LabVIEW Real-Time Course Manual

iv

ni.com

Student Guide
Thank you for purchasing the LabVIEW Real-Time Application Development course kit. This course manual and the accompanying software are used in the 3-day, hands-on LabVIEW Real-Time Application Development course. You can apply the full purchase price of this course kit toward the corresponding course registration fee if you register within 90 days of purchasing the kit. Visit ni.com/training to register for a course and to access course schedules, syllabi, and training center location information.

National Instruments Corporation

LabVIEW Real-Time Course Manual

Student Guide

A. NI Certification
The LabVIEW Real-Time Application Development course is part of a series of courses designed to build your proficiency with LabVIEW and help you prepare for exams to become an NI Certified LabVIEW Developer and NI Certified LabVIEW Architect. The following illustration shows the courses that are part of the LabVIEW training series. Refer to ni.com/training for more information about NI Certification.
Courses New User Begin Here LabVIEW Basics I* LabVIEW Basics II* Skills learned: LabVIEW environment navigation Basic application creation using LabVIEW Experienced User LabVIEW Intermediate I* LabVIEW Intermediate II* Skills learned: Modular application development Structured design and development practices Memory management and VI performance improvement Advanced User LabVIEW Advanced Application Development Skills learned: Large application design Code reuse maximization Object-oriented programming in LabVIEW

Certifications Certified LabVIEW Associate Developer Exam Skills tested: LabVIEW environment knowledge Certified LabVIEW Developer Exam Skills tested: LabVIEW application development expertise Certified LabVIEW Architect Exam Skills tested: LabVIEW application development mastery

Hardware-Based Courses: Data Acquisition and Signal Conditioning Modular Instruments Instrument Control Machine Vision Motion Control LabVIEW Real-Time
*Core courses are strongly recommended to realize maximum productivity gains when using LabVIEW.

LabVIEW Real-Time Course Manual

vi

ni.com

Student Guide

B. Course Description
The LabVIEW Real-Time Application Development course teaches you to use LabVIEW Real-Time to develop a deterministic and reliable application. Most LabVIEW applications run on a general-purpose operating system (OS) like Windows, Linux, Solaris, or Mac OS. Some applications require deterministic real-time performance that general-purpose operating systems cannot guarantee. The LabVIEW Real-Time Module extends the capabilities of LabVIEW to address the need for deterministic real-time performance. This course assumes you have a level of experience with LabVIEW equivalent to completing the material in the LabVIEW Basics I: Introduction course. In addition, you should be familiar with the Windows operating system and computer components such as the mouse, keyboard, connection ports, and plug-in slots, and have experience writing algorithms in the form of flowcharts or block diagrams.. The course is divided into lessons, each covering a topic or a set of topics. Each lesson consists of the following parts: An introduction that describes what you will learn. A discussion of the topics. A set of exercises that reinforces the topics presented in the discussion. A summary that outlines important concepts and skills taught in the lesson.

C. What You Need to Get Started


Before you use this course manual, make sure you have the following items: Computer running Windows 2000/XP LabVIEW Full Development System version 8.0 or later LabVIEW Real-Time Module version 8.0 or later Temperature Chamber including a 12 Volt fan, lamp, and a J-type thermocouple One of the following RT target computers: PXI Chassis with an NI PXI-8176 or compatible controller and an NI PXI-6040 or compatible DAQ device NI FieldPoint-2000 or 2010 network module with an NI FieldPoint-PWM-520 module and terminal block and an NI FieldPoint-TC-120 module and terminal block
vii LabVIEW Real-Time Course Manual

National Instruments Corporation

Student Guide

LabVIEW Real-Time Application Development Course Manual LabVIEW Real-Time Application Development CD, which contains the following files: Filename
Exercises

Description a folder containing all files needs to complete the exercises a folder containing the solutions to each exercise

Solutions

D. Installing the Course Software


Complete the following steps to install the course software. 1. Insert the course CD in your computer. The LabVIEW Real Time Setup dialog box appears. 2. Click Next. 3. Click Next to begin the installation. 4. Click Finish to exit the Setup Wizard. 5. The installer places the Exercises and Solutions folders at the top level of the C:\ directory. Exercise files are located in the C:\Exercises\LabVIEW Real Time\ folder.

E. Removing Course Material


You can remove the course material using the Add or Remove Programs feature on the Windows Control Panel.

F. Course Goals
This course presents the following topics: Concepts of real-time and determinism Configuring and communicating with real-time hardware Understanding memory usage, multithreading, priorities, and shared resource in LabVIEW Real-Time Optimizing real-time tasks Developing a deterministic, reliable application

LabVIEW Real-Time Course Manual

viii

ni.com

Student Guide

This course does not present any of the following topics: Information and concepts covered in LabVIEW Basics I: Introduction course Control, PID, and/or Fuzzy Logic theory Analog-to-digital (A/D) theory Operation of GPIB, RS-232, Motion, CAN, or VISA Every built-in LabVIEW object, function, or library VI; refer to the LabVIEW Help for more information about LabVIEW features not described in this course Development of a complete application for any student in the class; refer to the NI Example Finder, available by selecting HelpFind Examples for example VIs you can use and incorporate into VIs you create

National Instruments Corporation

ix

LabVIEW Real-Time Course Manual

Student Guide

G. Course Conventions
The following conventions are used in this course manual: The symbol leads you through nested menu items and dialog box options to a final action. The sequence FilePage SetupOptions directs you to pull down the File menu, select the Page Setup item, and select Options from the last dialog box. This icon denotes a tip, which alerts you to advisory information. This icon denotes a note, which alerts you to important information. This icon denotes a caution, which advises you of precautions to take to avoid injury, data loss, or a system crash. bold Bold text denotes items that you must select or click in the software, such as menu items and dialog box options. Bold text also denotes parameter names, controls and buttons on the front panel, dialog boxes, sections of dialog boxes, menu names, and palette names. Italic text denotes variables, emphasis, a cross-reference, or an introduction to a key concept. Italic text also denotes text that is a placeholder for a word or value that you must supply. Text in this font denotes text or characters that you enter from the keyboard, sections of code, programming examples, and syntax examples. This font also is used for the proper names of disk drives, paths, directories, programs, subprograms, subroutines, device names, functions, operations, variables, filenames, and extensions. Bold text in this font denotes the messages and responses that the computer automatically prints to the screen. This font also emphasizes lines of code that are different from the other examples. Italic text in this font denotes text that is a placeholder for a word or value that you must supply.

italic

monospace

monospace bold

monospace italic

LabVIEW Real-Time Course Manual

ni.com

Lesson 1 Introduction to Real-Time

Lesson 1 Introduction to Real-Time

Topics A. What is Real-Time? B. RT Host C. RT Target

Introduction to Real-Time
This lesson introduces real-time concepts such as real-time, determinism, and jitter. This lesson also discusses the parts of an RT system including the host and the target. Use the Getting Started with LabVIEW Real-Time Module to get started with the LabVIEW Real-Time Module quickly. To view a PDF version of the manual, select HelpSearch in the LabVIEW Real-Time Bookshelf, then click the Getting Started with LabVIEW Real-Time Module link.

National Instruments Corporation

1-1

LabVIEW Real-Time Course Manual

Lesson 1 Introduction to Real-Time

What is Real Time?


Real-time response is the ability to reliably and, without fail, respond to an event, or perform an operation, within a guaranteed time period

A. What is Real Time?


The LabVIEW Real-Time Module combines LabVIEW graphical programming with the power of a real-time operating system, enabling you to build deterministic real-time applications. A misconception about real time is that it means quick. More accurately, real time means in-time. In other words, a real-time system ensures that responses occur in time, or on time. With general purpose operating systems, you cannot ensure that your response occurs within any given time period, and calculations might finish much later or earlier than you expect them to. In order for a system to be a real-time system, all parts of it need to be real-time. For example, even though a program runs in a real-time operating system, it does not mean that the program behaves with real-time characteristics. The program may rely on something that does not behave in real-time, which then causes the program not to behave in real-time. Terms that frequently describe real-time systems are determinism, loop cycle time, and jitter. Before learning more about real time, you must understand these terms.

LabVIEW Real-Time Course Manual

1-2

ni.com

Lesson 1 Introduction to Real-Time

Real-Time Terms
DeterminismA characteristic of a system that describes how reliably it can respond to events or perform operations within a given time limit Loop Cycle TimeThe time taken to execute one cycle of a loop JitterThe variation of loop cycle time from the desired loop cycle time EmbeddedCharacterizes a computer system that is typically a component within a larger system. Embedded systems usually operate in a headless fashionthat is, there is no user interface, such as a keyboard, monitor, and mouse

Determinism is a characteristic of a system that describes how reliably it can respond to external events or perform operations within a given time limit. High determinism is a characteristic of real-time systems and guarantees that your calculations and operations occur within a given time. Deterministic systems are predictable. This is an important characteristic for applications such as controls. In a control application, the control program measures inputs, makes calculations based on the inputs, and then outputs values that are a result of those calculations. Real-time systems can guarantee that the calculations finish on time, all of the time. Many applications that require a real-time operating system are cyclical, such as a control application. The time between the start of each cycle, T, is called the loop cycle time (or sample period). 1/T is the loop rate or sample rate. Even with real-time operating systems, the loop cycle time can vary between cycles. The amount of time that the loop cycle time varies from the desired time is called jitter. The maximum amount that a loop cycle time varies from the desired loop cycle time is called maximum jitter. The term embedded encompasses many application areas, but characterizes a computer system that is typically a component within a larger system. These embedded systems operate in a headless fashion. A headless system has no user interface, such as a keyboard, monitor, or mouse. In many cases, embedded applications operate within restrictions on the amount of RAM and other resources that you can use, as well as the amount of physical space the embedded application can occupy. Embedded hardware ranges from industrial computers like PXI/CompactPCI that sit within larger machine monitoring and control systems to thin-client Web servers running on a chip.

National Instruments Corporation

1-3

LabVIEW Real-Time Course Manual

Lesson 1 Introduction to Real-Time

Maximum Jitter
Desired Loop Time

Jitter Range Maximum Jitter

Loop Iteration

1 2 3 4 5 Loop Time (seconds)

All systems have some jitter, but the jitter is lower for real-time systems than for general purpose operating systems. The jitter associated with real-time systems can range within nanoseconds. General purpose operating systems have high or unbounded maximum jitter that may vary from time to time and is inconsistent. Refer to Lesson 3, Real-Time Architecture: Design, for programming techniques to reduce jitter.

LabVIEW Real-Time Course Manual

1-4

ni.com

Lesson 1 Introduction to Real-Time

Operating Systems
Processor time is shared between programs Operating systems can preempt high priority VIs
Many programs run in the backgroundscreen savers, disk utilities, virus software, and so on It must service interruptskeyboard, mouse, Ethernet, and so on

Cannot guarantee determinismthat is, it is a non-deterministic system

Operating Systems
LabVIEW applications running in Windows are not guaranteed to run in real-time, because Windows is not a real-time operating system. Windows cannot ensure that code always finishes within specific time limits. The time your code takes to execute in Windows depends on many factors, such as other programs running like screen saver or virus software. Windows also has to service interrupts from devices such as a USB port, keyboard, mouse, and other peripherals that can delay execution of code. You can increase the probability of programs running deterministically in Windows by disabling all other programs such as screen savers, disk utilities, and virus software. You can further increase determinism by disabling drivers for devices with interrupts such as the keyboard, mouse, and Ethernet card. Finally, for better determinism, you can write a device driver in Windows to get the most direct access to hardware possible. Nevertheless, increasing determinism does not ensure that code always executes with real-time behavior. This is because Windows can preempt your LabVIEW programs, even if you use time-critical priority. Refer to Lesson 3, Real-Time Architecture: Design, to learn more about priorities. With the LabVIEW Real-Time Module, your programs run in a separate real-time operating system. You do not need to disable programs or write device drivers in order to achieve real-time performance. A real-time operating system enables users to prioritize tasks so that the most critical task can always take control of the processor when needed.

National Instruments Corporation

1-5

LabVIEW Real-Time Course Manual

Lesson 1 Introduction to Real-Time

Real-Time Operating Systems


Ensure that high-priority tasks execute first Do not require user input from peripherals (keyboard, and so on) LabVIEW Real-Time Module executes VIs on the following: Hardware targets running the Venturcom Phar Lap Embedded Tool Suite (ETS) Computers running the Venturcom Real-Time Extension (RTX) This course focuses on the ETS platform

Real-Time Operating Systems


National Instruments designed the LabVIEW Real-Time Module to execute VIs on two different real-time operating systems. The LabVIEW Real-Time Module can execute VIs on hardware targets running the real-time operating system for the Venturcom Phar Lap Embedded Tool Suite (ETS) and on computers running the Venturcom Real-Time Extension (RTX). Venturcom Phar Lap ETS provides a real-time operating system that runs on NI Real-Time Series hardware to meet the requirements of embedded applications that need to behave deterministically or have extended reliability requirements. Venturcom RTX adds a real-time subsystem (RTSS) to Windows. Venturcom RTX enables you to run Windows and the RTSS at the same time on the same computer. The RTSS has a priority-based real-time execution system independent of the Windows scheduler. RTSS scheduling supersedes Windows scheduling to ensure deterministic real-time performance of applications running in the RTSS. For more information about Phar Lap ETS or RTX, refer to the Venturcom Web site at www.vci.com. This course focuses on the ETS real-time platform.

LabVIEW Real-Time Course Manual

1-6

ni.com

Lesson 1 Introduction to Real-Time

Selecting an Operating System


General Purpose OS Data acquisition Offline analysis Data presentation Real-Time OS Closed loop control Time-critical decisions Extended run time Stand alone operation Increased reliability

Selecting an Operating System


If you only must acquire real-time data, then you might not need a real-time operating system. National Instruments has many data acquisition (DAQ) devices that can acquire data in real-time even though they are controlled by programs running in Windows. The DAQ device has an onboard hardware clock that makes sure that data is acquired at constant rates. With technologies such as bus mastering, direct memory access (DMA) transfer, and data buffering, the I/O device can collect and transfer data automatically to RAM without involving the CPU. However, consider an application where every data point needs to be acquired and analyzed by software before we can determine if an event has occurred that requires a response. Similarly, consider an application where every acquired point must be handled by software in order to determine the output of a control loop. In both these cases, the software and the operating system must behave deterministically. You must to predict their timing characteristicsand those characteristics must be the same for any data set, at any time. In these applications, the software must be involved in the loop; therefore, you need a real-time operating system to guarantee response within a fixed amount of time. In addition, applications requiring extended run times or stand alone operation are often implemented with real-time operating systems.

National Instruments Corporation

1-7

LabVIEW Real-Time Course Manual

Lesson 1 Introduction to Real-Time

Real-Time Development Tools


Compiler Linker Software Debugger System Analysis Tools RTOS Hardware Microprocessor I/O Device LabVIEW Real-Time Target LabVIEW Real-Time

Execution Trace Tool

Real-Time Development Tools


The tools provided for real-time development consist of code development tools including the compiler, the linker, and the debugger. In addition, system analysis tools provide advanced insight into optimizing real-time applications. The LabVIEW Real-Time Module is the application environment that serves as the complete development and debugging tool. For more advanced diagnostics, the LabVIEW Execution Trace Toolkit offers complete real-time application analysis. All LabVIEW Real-Time Module deployment platforms are based on a common hardware and software architecture. Each hardware target uses computing components such as a microprocessor, RAM, non-volatile memory, and an I/O bus interface. The embedded software consists of a real-time operating system (RTOS), driver software, and a specialized version of the LabVIEW Run-Time Engine.

LabVIEW Real-Time Course Manual

1-8

ni.com

Lesson 1 Introduction to Real-Time

LabVIEW Real-Time System Using ETS


Host Computer RT Target

Develop

Download

Execute

LabVIEW Real-Time System Using ETS


This slide illustrates the basic hardware architecture of a LabVIEW Real-Time system. First, in order to ensure determinism, you must offload any time-critical task from Windows and delegate it to a real-time engine or target. Therefore, you have two systemsthe first system is Windows based. On this machine, called the host, you develop an application. When you are ready, you can download the application to the target processor. The second processor runs a real-time operating system of the Venturcom Phar Lap ETS. The software that runs on the target platforms is referred to as the LabVIEW Real-Time Engine (RT Engine). The RT Engine has the job of executing code, controlling any connected I/O, and communicating back to the host machine. Several kinds of National Instruments real-time hardware platforms exist upon which real-time applications can run. You can maintain a user interface for the ongoing embedded application. If not, you can deploy the application and gather back information as required. Various hardware architectures allow different communication protocols between the host and target machines, such as TCP/IP or VI server.

National Instruments Corporation

1-9

LabVIEW Real-Time Course Manual

Lesson 1 Introduction to Real-Time

Discussion Exercise 1-1 Project Specification Document


Time to complete: 10 min.

Note The puzzle symbol shown above indicates that you must complete this exercise for the course project. Look for this symbol on all course project exercises. Exercises are located at the end of each lesson.

OBJECTIVE

Read and discuss the Project Specification document and determine if real time is necessary for this application.

LabVIEW Real-Time Course Manual

1-10

ni.com

Lesson 1 Introduction to Real-Time

RT Host
Host Computer

B. Real-Time Host
A real-time system consists of software and hardware components. The software components include LabVIEW, the RT Engine, and VIs you build using LabVIEW. The hardware components of a real-time system include a host computer and an RT target. The host computer is a computer with LabVIEW and the LabVIEW Real-Time Module installed on which you develop the VIs for the real-time system. After developing the real-time system VIs, you can download and run the VIs on the RT target. The host computer can run VIs that communicate with the VIs running on the RT target.

National Instruments Corporation

1-11

LabVIEW Real-Time Course Manual

Lesson 1 Introduction to Real-Time

Real-Time Targets
PCI Plug-In Device
Real-time component for PCs

Desktop PCs
Determinism for PCI systems

Real-Time PXI Embedded Controllers


High speed, high channel density, I/O variety

RT Compact FieldPoint LabVIEW Real-Time


Small footprint, harsh environments

RT Compact Vision System


Compact and distributed machine vision

CompactRIO
Reconfigurable Embedded System

C. Real-Time Targets
An RT target refers to Real-Time Series hardware or the real-time subsystem (RTSS) that runs the Real-Time Engine and VIs you create using LabVIEW. You can deploy the LabVIEW Real-Time Module with a variety of real-time targets Real-Time Series Plug-in Devices, Desktop PCs, Real-Time PXI embedded controllers, Real-Time Compact FieldPoint controllers, and Compact Vision Controllers.

LabVIEW Real-Time Course Manual

1-12

ni.com

Lesson 1 Introduction to Real-Time

Real-Time Hardware Configurations


PCI Plug-In Device
Real-time component for PCs

Single Box

Desktop PCs
Determinism for PCI systems

Real-Time PXI Embedded Controllers


High speed, high channel density, I/O variety

Host-Target

RT Compact FieldPoint
Small footprint, harsh environments

RT Compact Vision System


Compact and distributed machine vision

CompactRIO
Reconfigurable Embedded System

There are two basic configurations for RT targets. Single-box configurations are those in which the real-time component is integrated within hardware that also contains a general purpose operating system. Real-Time Series PCI plug-in devices or desktop PCs can serve in this type of configuration. Host-target configurations are ones in which the real-time application is downloaded to the target from a host system. The real-time application executes in an embedded fashion on the hardware target. Real-Time PXI embedded controllers, Real-Time Compact FieldPoint controllers, and Compact Vision Controllers are examples of hosttarget configurations. Desktop PCs can run real-time applications in either configuration, depending on implementation. If you use the desktop PC in a single-box configuration, it must be running the RTX operating system. You can use a desktop PC as a target when running the ETS operating system.

National Instruments Corporation

1-13

LabVIEW Real-Time Course Manual

Lesson 1 Introduction to Real-Time

RT TargetHost-Target Configuration
Standard desktop computerIdeal for low cost implementation NI Real-Time Series PXI ControllerIdeal for high-speed, high channel count acquisition NI Real-Time Series FieldPoint Module Ideal for distributed real-time I/O applications NI 1450 Series Compact Vision System Acquires, processes, and displays images for IEEE1394 cameras CompactRIOEmbedded system with real-time controller, reconfigurable FPGA chassis, and industrial I/O modules.

Host-Target Configuration (ETS Only)


A networked Real-Time Series device is a networked hardware platform with an embedded processor with a real-time operating system (ETS) that runs the RT Engine and LabVIEW VIs. You can use a separate host computer to communicate with and control VIs on a networked Real-Time Series device through an Ethernet connection, but the device is an independent computer. Some examples of networked Real-Time Series devices include the following: Standard desktop computerA standard desktop PC used as a real-time system running LabVIEW Real-Time for ETS Targets. NI Real-Time Series PXI ControllersA networked device that installs in an NI PXI chassis and communicates with NI PXI modules installed in the chassis. You can write VIs that use all the I/O capabilities of the PXI modules, SCXI modules, and other signal conditioning devices installed in a PXI chassis. The RT Engine also supports features of the Real-Time Series PXI controller. NI Real-Time Series FieldPoint Network ModulesA networked device designed for distributed real-time I/O applications. NI 1450 Series Compact Vision SystemA distributed, real-time imaging system that acquires, processes, and displays images from IEEE 1394 cameras. Refer to the NI CVS-1450 Series User Manual for information about using the NI 1450 Series Compact Vision System with LabVIEW.

LabVIEW Real-Time Course Manual

1-14

ni.com

Lesson 1 Introduction to Real-Time

RT TargetPXI Embedded Controller


Processor PXI Backplane

Connect to host

Memory DAQ Devices SCXI Modules

PXI Embedded Controller


PXI is based on the CompactPCI standard. A typical system consists of a chassis, a controller, and a choice of I/O modules. The controller performs the same function as a desktop CPU. It includes a processor, permanent storage, memory, and so on. When used as a real-time system, the LabVIEW application is downloaded to the embedded processor on the controller. As the application runs, it accesses data from the I/O modules in the system. You can disconnect an application deployed on a PXI system from the host computer and run the application headlessno monitor, keyboard, or mouse. With PXI, you can create rugged real-time applications and deploy them as headless stand-alone systems. For example, in the automotive industry, engineers use real-time PXI systems to test the algorithm for an adaptive cruise control system. The control algorithm is downloaded to the real-time PXI controller. The PXI system is placed in a test vehicle and the plug-in I/O modules are connected to the engine. As the vehicle is driven around the test track, the PXI system simulates the adaptive cruise control system. Engineers can monitor the performance of the control system and make adjustments as necessary. In this example, LabVIEW Real-Time and PXI are used for rapid control prototyping of an adaptive cruise control system.

National Instruments Corporation

1-15

LabVIEW Real-Time Course Manual

Lesson 1 Introduction to Real-Time

RT Target[c]FP Network Module


Watchdog Timer Removable CompactFlash memory (FP-2020 only) Onboard static memory Dedicated processor User-defined DIP switches and LEDs Serial port Backup power supply connection Ethernet port

Compact FieldPoint Network Module


The cFP-20xx has many features that enable it to act as a stand-alone device. Because most stand-alone devices reside in remote or inaccessible locations, these system must be reliable to eliminate the need for constant maintenance. The dedicated processor in the cFP-20xx runs a real-time operating system that executes the LabVIEW Real-Time Module application deterministically. The reliability of the real-time operating system also reduces the chances of system malfunction. The cFP-20xx includes a Watchdog timer that monitors the overall operation of the FieldPoint system. When the watchdog senses that the system has a malfunction, it can run a separate maintenance routine or even reboot the FieldPoint system. The operation of the watchdog is user-defined by a protocol. The cFP-20xx also includes user-defined dip switches and bi-color and tri-color LEDs that can provide user interaction in a stand-alone system. For instance, the LEDs can signify certain states of operation, while you can configure DIP switches to specify the startup state of the compact FieldPoint system. The onboard static memory consists of 32 MB memory for the cFP-2000, and 64 MB memory for the cFP-2010 and cFP-2020. The cFP-2020 also features a slot that accepts removable CompactFlash cartridges, ranging in capacity from 64 to 512 MB. CompactFlash cartridges contain solid-state, nonvolatile memory for storing your downloaded application or for performing embedded data logging.

LabVIEW Real-Time Course Manual

1-16

ni.com

Lesson 1 Introduction to Real-Time

The cFP-20xx includes a second set of screw terminals to connect a backup power supply. The system automatically switches to this second power supply, when it senses a problem with the first power supply. The serial port allows the cFP-20xx to connect to existing systems. In addition, the CFP-20xx can connect other serial devices such as a serial LED that can display information for the operator. You can use the Compact FieldPoint I/O modules for industrial environments, where space is limited, or where placing a standard desktop computer is not an option. You can mount the systems on DIN rails to increase space on the factory floor and also place the systems in locations with stringent temperature demands. A FieldPoint 2000 based system can operate efficiently in environments from 25 to 60 Celsius.

National Instruments Corporation

1-17

LabVIEW Real-Time Course Manual

Lesson 1 Introduction to Real-Time

RT TargetSingle-Box Configuration
Real-Time Series Plug-In Device RTOS runs on embedded processor DAQ daughterboard on embedded PCI bus

Single-Box Configuration
An NI PCI-7041 plug-in device is a plug-in device with an embedded processor. The NI PCI-7041 plug-in device contains a processor device and DAQ daughterboard. The processor device contains a microprocessor with a real-time operating system that runs the RT Engine and LabVIEW VIs. You can use the host computer to communicate with and control VIs running on the NI PCI-7041 plug-in device through an Ethernet connection or shared memory.

LabVIEW Real-Time Course Manual

1-18

ni.com

Lesson 1 Introduction to Real-Time

RT TargetReal-Time Subsystem (RTX only)


RT Target and RT Host reside on the same microprocessor RT Target
RT Task RT Task RTX Real-Time Kernel Hardware Abstraction Layer (HAL) Microprocessor RT Task

RT Host
Windows Task Windows Task

Windows Kernel

RT Target on the Real-Time Subsystem (RTX Only)


When you use the LabVIEW Real-Time Module for real-time extension (RTX) targets, the RT Engine runs on the real-time subsystem (RTSS) of the host computer. The RTSS creates the x:\RTXROOT directory, where x is the Windows root drive, to store all of the RT target files. Like Real-Time Series hardware targets, the RTSS provides a realtime platform where you can execute LabVIEW VIs deterministically. You can communicate with and control VIs running on the RTSS from LabVIEW in Windows. VIs running on the RTSS can use an NI PCI-7831 plug-in device for data acquisition. Refer to Lesson 4, Timing Applications and Acquiring Data, for information about deterministic data acquisition using LabVIEW.

National Instruments Corporation

1-19

LabVIEW Real-Time Course Manual

Lesson 1 Introduction to Real-Time

Choosing the Right Target Platform

PXI Loop Speed I/O Count Rugged Scalability 3rd-party RT HW Distributed


Best High Better Best Yes Better

[c]FP
Good High Best Better No Best

PCI-7041 PC (ETS)
Better Low Good No Best Low Better Yes Good

PC (RTX)
Best Low Better Yes

Target Platform Comparison


The various platforms of NI Real-Time Series hardware encompass a wide spectrum of application needs. To find the best platform for your type of application, match the platform that best fits your system requirements. For example, if you are looking for a highly distributive system with a high channel count and your timing needs are less than 1 kHz, then FieldPoint may be the best choice for you. Real-Time Series plug-in boards suit applications requiring a small control component to be added to a Windows-based computer. PXI RT ideally suits high-performance, real-time applications requiring tight synchronization across a variety of I/O and precise input and output sampling rates. Compact FieldPoint RT ideally suits industrial applications requiring a small footprint, high-reliability, distributed, and industrially rated hardware. The specifications used to classify the ruggedness of each target is the mean time between failures (MTBF). MTBF values for PXI range from 169,000 hours to 280,000 hours. The MTBF value for FieldPoint is 459,188 hours (52 years).

LabVIEW Real-Time Course Manual

1-20

ni.com

Lesson 1 Introduction to Real-Time

SummaryMatching Quiz
1. Jitter 2. Deterministic 3. Embedded 4. Loop Cycle Time
A. System that can reliably respond to events or can perform operations within a given time limit B. Deviation of an I/O measurement C. Time taken to execute one cycle of a loop D. Variation of loop cycle time from the desired loop cycle time E. Hardware that is installed in a mobile unit F. Computer system that is typically a component within a larger system

Summary
Real-TimeReal-time response is the ability to reliably and, without fail, respond to an event, or perform an operation, within a guaranteed time period. DeterminismA characteristic of a system that describes how reliably it can respond to events or perform operations within a given time limit. Loop Cycle TimeThe time taken to execute one cycle of a loop. JitterThe variation of loop cycle time from the desired loop cycle time. EmbeddedCharacterizes a computer system that is typically a component within a larger system. HostA computer with LabVIEW and the LabVIEW Real-Time Module installed in which you develop the VIs for the real-time system. TargetReal-Time Series hardware or the RTSS that runs the RT Engine and VIs you create using LabVIEW. There are three types of RT targets: Real-Time Series plug-in devices, networked Real-Time Series devices, and the RTSS.

National Instruments Corporation

1-21

LabVIEW Real-Time Course Manual

Lesson 1

Introduction to Real-Time

Exercise 1-1
Objective:

Project Specification Document

Read and discuss the Project Specification document and determine if real time is necessary for this application. When beginning a project for a customer, you may receive a project specification document. This is a general document, and you must meet further with the customer to clarify the project needs to produce a requirements document. In a later exercise, you will receive a more detailed requirements document for the course project. In this course, customer refers to the person requesting the project. This can be a client, coworker, manager, and so on. In this exercise, read the Project Specification document and determine if and why real time is necessary. Look for needs that set a real-time system apart from other systems.

Start of Specification Document

Overview
A temperature chamber provides a two-stage temperature ramp for the incubation of cells. This application controls the temperature chamber. The temperature in the chamber is achieved through the control of a lamp and a fan. The fan also simulates disturbance to the temperature chamber. Temperature ranges are confined from room temperature to 75 C.

User Interface
The user interface allows the user to select a range of temperatures and times. Each temperature is held for the time specified by the user in the order entered. A graph shows actual temperature versus time and setpoint versus time. The user can start the test from the user interface, abort the test, and apply disturbance to the temperature chamber.

Data Logged
The header for the data file includes the user interface inputs and beginning time stamp for the control profile. Data logged includes temperature, time stamp, setpoint, and lamp power, as well as whether disturbance was applied. All data are logged every time the temperature is read.

Specifications
The temperature should be measured, recorded, and used to calculate output to the lamp. Also, an output should be applied within a set response rate (loop cycle). Two different labs are using this system. One needs the

LabVIEW Real-Time Course Manual

1-22

ni.com

Lesson 1

Introduction to Real-Time

response rate at 10 Hz with a maximum of 1 Hz deviation, and the second needs the response rate at 100 Hz with a maximum of 0.5 Hz deviation. The system should start automatically on power up. External systems should be able to view and utilize current data through a UDP connection at user-specified addresses. The system must respond to the Abort command as soon as possible.
End of Specification Document

Discussion
1. Is real time appropriate for this project?

2. If so, what are some of the project needs that require real time?

When considering the project needs, look for requirements that specify a need for real-time response. Real-time response is the ability to respond reliably and without fail to an event, or to perform an operation, within a given time period.

End of Exercise 1-1

National Instruments Corporation

1-23

LabVIEW Real-Time Course Manual

Lesson 1

Introduction to Real-Time

Self Review
Quiz
1. Which characteristic does not describe a real-time system? a. Small, bounded jitter b. Fast c. Reliable d. Predictable

2. Which can be an RT target? (multiple answer) a. RT Series FieldPoint module b. PC installed with Microsoft Windows c. RT Series PXI Embedded controller d. RT Series plug-in device

Job Aid
Use the following checklist to aid in understanding the difference between real-time and non-real time systems. Deterministic systems are predictable. Real-time operating systems are highly deterministic. Embedded systems usually have no monitor, keyboard, or mouse. Jitter is the variation of loop cycle time from the desired loop cycle time. Non-real time systems have very large or unbounded jitter.

LabVIEW Real-Time Course Manual

1-24

ni.com

Lesson 1

Introduction to Real-Time

Notes

National Instruments Corporation

1-25

LabVIEW Real-Time Course Manual

Lesson 1

Introduction to Real-Time

Notes

LabVIEW Real-Time Course Manual

1-26

ni.com

Lesson 2 Configuring Your Hardware

Lesson 2 Configuring Your Hardware

Topics A. Hardware Setup and Installation B. Configuring the Target C. Configuring Your Input and Output D. Connecting to the Target

Introduction
In this lesson, you will learn how to configure your target hardware and the I/O hardware used in the class project. You can apply this knowledge to configuring other types of I/O hardware as well. In addition, you will learn how to download a VI to the target, connect to it, and disconnect from it. This gives you the knowledge to run pre-existing code on an RT target in development mode.

National Instruments Corporation

2-1

LabVIEW Real-Time Course Manual

Lesson 2 Configuring Your Hardware

Hardware Setup and Installation


Refer to the Quick Start Guide for your target hardware for hardware setup and installation instructions Target hardware arrives pre-installed with operating system Note: Classroom systems have been pre-installed and set up

A. Hardware Setup and Installation


Each target hardware type has its own hardware setup and installation instructions. Refer to the Quick Start Guide for your target hardware for instructions. A summary for the cFP-20xx Network Module Quick Start Guide and RT Series PXI Embedded Controllers Quick Start Guide is included here.

Installing the cFP-20xx Network Module


To install the cFP-20xx, complete the following steps: 1. Mount the Compact FieldPoint backplane on a 35 mm DIN rail, on a panel, or in a standard 19-inch rack. Before using any of these mounting methods, record the serial number from the back of the backplane. 2. Install the cFP-20xx controller on the backplane. 3. Install I/O modules on the backplane. 4. Install the connector blocks on the backplane. 5. Connect the cFP-20xx to your network. 6. Wire power to the Compact FieldPoint system. 7. Power on the cFP-20xx: Check the DIP switches on the controller, ensuring that the RESET IP switch is not enabled. Plug in each power supply to the Compact FieldPoint system. The cFP-20xx runs a power-on self test (POST) that takes several seconds. You should see the POWER and STATUS LEDs come on. After about five seconds, the STATUS LED begins flashing.

LabVIEW Real-Time Course Manual

2-2

ni.com

Lesson 2 Configuring Your Hardware

Installing the RT Series PXI Embedded Controllers


Complete the following steps to install the RT series PXI embedded controllers: 1. Plug in your chassis before installing the RT Series PXI controller. The power cord grounds the chassis and protects it from electrical damage while you install the module. Caution To protect both yourself and the chassis from electrical hazards, leave the chassis off until you finish installing the RT Series PXI controller. 2. Remove or open any doors or covers blocking access to the system controller slot (Slot 1) in the chassis. 3. Touch the metal part of the case to discharge any static electricity that might be on your clothes or body. 4. Make sure the injector/ejector handle is in its downward position. Align the RT Series PXI controller with the card guides on the top and bottom of the system controller slot. Caution Do not raise the injector/ejector handle as you insert the RT Series PXI controller. The module will not insert properly unless the handle is in its downward position so that it does not interfere with the injector rail on the chassis. 5. Hold the handle as you slowly slide the module into the chassis until the handle catches on the injector/ejector rail. 6. Raise the injector/ejector handle until the module firmly seats into the backplane receptacle connectors. The front panel of the RT Series PXI controller should be even with the front panel of the chassis. 7. Tighten the four bracket-retaining screws on the top and bottom of the front panel to secure the RT Series PXI controller to the chassis. 8. (Optional) To add Fast Ethernet to your RT Series PXI system, plug in the PXI-8211 card using the same procedure described in steps 2 through 7. Install any additional PXI cards into the chassis using the same procedure described in steps 2 through 7. 9. Ensure proper installation. 10. Replace or close any doors or covers to the chassis.

National Instruments Corporation

2-3

LabVIEW Real-Time Course Manual

Lesson 2 Configuring Your Hardware

Target ConfigurationNetworked Devices


1. Install LabVIEW Real-Time Module on the host computer 2. Use Measurement and Automation Explorer (MAX) to configure Compact FieldPoint, FieldPoint, and PXI systems
Note: Host computer must be on the same subnet to configure RT Series target systems

B. Target Configuration
You must install the LabVIEW Real-Time Module on the host computer before you can begin developing real-time applications. Use the host computer to develop applications and then download them across the network to the RT Series target system. The host computer must be on the same subnet as the target system for you to configure the RT Series target system.

LabVIEW Real-Time Course Manual

2-4

ni.com

Lesson 2 Configuring Your Hardware

Target ConfigurationNetwork Settings

Configured [c]FP system Unconfigured PXI system

Configuring RT Series Networked Devices


If you have an RT Series controller with the RT Engine pre-installed (cFP-20xx, PXI-814x RT, PXI-8156B RT, and PXI-817x RT), continue with the configuration instructions below. If you have an RT-compatible controller with Windows pre-installed, you must reboot your controller into RT mode before completing the following instructions. To configure an RT Series Networked device, complete the following steps: 1. Connect the Compact FieldPoint Network Module and/or the RT Series PXI controller to the network and power on the module/controller. 2. Double-click the Measurement & Automation Explorer (MAX) icon on the desktop of the host computer. 3. Expand Remote Systems in the left pane of MAX. The system appears listed under Remote Systems with its serial number as its default name. In the figure shown above, the Compact FieldPoint system has already been configured and the PXI system needs to be configured. 4. Select the system in MAX and select the Network Settings tab in the right pane. Enter the appropriate network settings. You can select Obtain an IP Address Automatically (DHCP) if you are unsure of the correct network settings. Contact your system administrator if you need more help. 5. Click the Apply button. 6. Click the Yes button to reboot.

National Instruments Corporation

2-5

LabVIEW Real-Time Course Manual

Lesson 2 Configuring Your Hardware

After you configure the networked RT system, you can view it in MAX even if it is not on the same subnet. To do this complete the following steps: 1. Right-click Remote Systems and select Create New. 2. Select Remote Device (not on the local subnet) and click Next 3. Enter the IP address of the Remote System and click Finish.

LabVIEW Real-Time Course Manual

2-6

ni.com

Lesson 2 Configuring Your Hardware

Target ConfigurationInstall Software

Reinstall or upgrade software from MAX

Installing or Upgrading Software on RT Series Networked Devices


Use the Measurement & Automation Explorer (MAX) to download any driver software or updates to the RT Engine. Launch MAX and select ViewRefresh to list any RT Engines on your local network. Complete the following steps to install or upgrade the software on your remote system: 1. Select your remote system from the configuration tree. 2. Select the Software option. 3. Select Install software. The Select software to download dialog box appears. 4. Enable or disable the check boxes to choose the software you want to install to the remote system. 5. Click OK to begin downloading the software. If you have multiple software versions installed on your host machine, by default the most recent version is the one available for download.

National Instruments Corporation

2-7

LabVIEW Real-Time Course Manual

Lesson 2 Configuring Your Hardware

Input and Output Hardware Configuration


Use MAX to configure the remote I/O hardware Refer to product-specific documentation for assistance You configure the [c]FP and PXI hardware in the next exercise

C. Input and Output Hardware Configuration


You must configure any National Instruments RT-compatible device before you can access it from a LabVIEW Real-Time Module application targeted to the remote system. The next exercise guides you through the configuration of the hardware used in the Compact FieldPoint and PXI systems for this course. For more information about using any NI products in MAX, refer to the product-specific documentation.

LabVIEW Real-Time Course Manual

2-8

ni.com

Lesson 2 Configuring Your Hardware

Exercise 2-1 Configure Hardware


Time to complete: 40 min.

Instructor Note: If the equipment is not set up before class, this exercise may take longer than the estimated time.

OBJECTIVE

Configure the Compact FieldPoint or the PXI target systems and the I/O hardware using Measurement and Automation Explorer (MAX).

National Instruments Corporation

2-9

LabVIEW Real-Time Course Manual

Lesson 2 Configuring Your Hardware

Connecting to the Target


For LabVIEW to connect to the RT target you must configure the target in a project 1. Create a project 2. Create a real-time target 3. Connect to the target 4. Add VIs to the target

D. Connecting to the Target


In order to deploy VIs using LabVIEW Real-Time you must create a project and configure a real-time target in the project.

LabVIEW Real-Time Course Manual

2-10

ni.com

Lesson 2 Configuring Your Hardware

LabVIEW Projects
Projects manage files and targets Use folders and libraries to organize files
LabVIEW files (.vi, .vit, .ctl) Other files (data files, documentation)

Targets represent systems you can run VIs on


Host computer Real-time systems FPGA systems PDA systems

Projects also allow you to build executables or use source control

LabVIEW projects allow you to manage files and targets as you develop a system. Projects are controlled with a Project Explorer window. A project can contain LabVIEW files, such as VIs, custom controls, type definitions, and templates, as well as supporting files, such as documentation, data files or configuration files. You can organize items in a project into folders and libraries. Each project can have multiple targets, representing the host computer as well as real-time, FPGA, and PDA systems. When you place a VI in a target in the Project Explorer, the VI becomes targeted to that system and has palettes appropriate to the target. Projects also allow you to perform tasks such as building executables and interacting with source control programs.

National Instruments Corporation

2-11

LabVIEW Real-Time Course Manual

Lesson 2 Configuring Your Hardware

Folders and Libraries


Folders allow you to organize files in the project
No relation to directories on disk

Libraries allow you to group a set of VIs, controls, and variables


Libraries create a namespace Items in a Library can be public/private All shared variables must be in a library

Folders

Library

You can organize items in a project into folders and libraries. Folders are a strictly organizational tool. They allow you to group items within a project. Folders do not have any effect upon the hard disk location of files inside them because items in a project are linked to files on disk by a reference. Items in a project must not have the same organization as the files on a disk and deleting a file from the project does not remove it from the disk. Libraries allow you to group and control a set of VIs, controls, and variables. Like a folder, a library does not effect the location of files on a disk. However, files in a library are explicitly linked to that library, adding a file in a library to a project adds the entire library. LabVIEW reports an error if a file cannot locate the library it is a part of, or if a library cannot locate files that are part of it. Libraries define a namespace, which means that files inside a library cannot have name conflicts with files outside of a library. This allows you to have multiple VIs with the same name in memory at the same time, as long as each VI is included in a separate library. You can define each item in a library as public or private. VIs outside of the library can use public items, but VIs can use private items only within the same library. Defining public and private items for a library allows you to provide a controlled interface to anyone using the library and prevents users of the library from directly accessing low-level, private items. Libraries are also required to use shared variables. See Lesson 3, Real-Time Architecture: Design, and Lesson 5, Communication, for more information about shared variables.

LabVIEW Real-Time Course Manual

2-12

ni.com

Lesson 2 Configuring Your Hardware

Creating a Project
Select FileNew Project to create a blank project Project Starts with the My Computer Target
Place any VIs that run on the host computer in the My Computer target

Select FileNew Project to create a blank project. A blank project starts with the My Computer target that represents the host computer. Place any VIs that run on the host computer as part of your project in the My Computer target.

National Instruments Corporation

2-13

LabVIEW Real-Time Course Manual

Lesson 2 Configuring Your Hardware

Creating a Real-Time Target


Right-click the project to add targets outside of the host computer (PXI, cFP, and so on) Right-click My Computer to add internal targets (PCI Plug-In Devices)

To add an external target, right-click the top level project entry in the project explorer and select NewTargets and Devices. Examples of external targets include RT PXI, Compact FieldPoint, and RT Desktop systems. To add an internal target, such as a PCI plug-in device, right-click the My Computer target and select NewTargets and Devices. Note You cannot add non-real-time desktop computers to a project as targets.

LabVIEW Real-Time Course Manual

2-14

ni.com

Lesson 2 Configuring Your Hardware

Creating a Real-Time Target (Continued)


Choose existing devices on the local subnet Access devices on remote subnets by IP address

The Add Targets and Devices dialog box allows you to specify the location of your real-time target. LabVIEW automatically detects devices on the local subnet. You can connect to a device on a remote subnet by specifying its type and IP address.

National Instruments Corporation

2-15

LabVIEW Real-Time Course Manual

Lesson 2 Configuring Your Hardware

Connecting to a Target
Right-click the RT target and select Connect Or run a VI on the target

Right-click on a target and select Connect to establish communication with the target. LabVIEW verifies that the target responds and checks for running VIs on the target which do not match the current project. If you do not manually connect to the target, LabVIEW connects automatically when you run a VI on the target. Note You can change the IP Address of the target by right-clicking the target and selecting Properties.

LabVIEW Real-Time Course Manual

2-16

ni.com

Lesson 2 Configuring Your Hardware

Adding VIs to a Target


Any VIs placed under the target become targeted to that system
Right-click to create new VIs or add existing ones Or drag VIs from windows explorer or other project folders.

Targeted VIs have palettes that match the target system Targeted VIs are automatically deployed to the system when run

To run VIs on an RT target, add the VIs to the project tree under the appropriate target. You can add new or existing VIs by right-clicking the target or by selecting the Project menu. You also can drag items from other locations in the project tree or drag files from Windows Explorer. When you add a VI to the project tree under a target, the VI becomes targeted to that target. Real-time targeted VIs display specific real-time controls and function palettes. When you run a real-time targeted VI, LabVIEW automatically downloads and runs on the VI on the target.

National Instruments Corporation

2-17

LabVIEW Real-Time Course Manual

Lesson 2 Configuring Your Hardware

Running VIs on a Target


When you run a RT VI, the compiled code for the VI is downloaded to the RT Target. Data is exchanged between the compiled code on the RT Target and the VI on the RT Hostfront-panel communication. Ordinary LabVIEW debugging features are available.

Host PC

RT Target

After you connect to a target, you can download a VI onto the RT target. The compiled code for the VI actually downloads to the RT Engine. The communication between the compiled code and the host PC is transparent to the user. This communication method is called front-panel communication. Refer to Lesson 5, Communication, to learn more about front-panel communication and other communication methods. The Real-Time Development System can use all of the debugging features present in LabVIEW except for the call chain ring. Refer to Lesson 6, Verifying Your Application, for more information about debugging your application.

LabVIEW Real-Time Course Manual

2-18

ni.com

Lesson 2 Configuring Your Hardware

Closing a Front Panel Connection


Select the following while the VI is still running: Select FileExit
Results in this dialog box:

Right-click the target and select Disconnect


RT VIs continue to run on the target, but no longer exchange frontpanel communication or debugging information with the host Reconnecting to the target automatically opens and re-establishes a connection with any running VIs

Closing a Front Panel Connection without Closing VIs


You can exit LabVIEW on the host computer without closing the VIs on the RT target. Select FileExit to close LabVIEW on the host computer. A dialog box appears asking if you want to exit LabVIEW without closing RT Engine VIs. If you select Quit and Abort, LabVIEW aborts the VIs running on the target before exiting. If you select Quit and Disconnect, the VIs running on the RT target continue running. You also disconnect the connection with the RT target from the Project Explorer. When you disconnect, any running VIs continue to run on the target, but debugging and front panel communication are disabled. Reconnecting to the target automatically opens all VIs running on that target and re-establishes the connection for debugging and front panel communication. If you connect to a target, which has VIs running that are not in the active project, LabVIEW prompts you to abort the VIs or add them to the project before opening them.

National Instruments Corporation

2-19

LabVIEW Real-Time Course Manual

Lesson 2 Configuring Your Hardware

Exercise 2-2 Targeting Real-Time Hardware


Time to complete: 20 min.

OBJECTIVE

Create a LabVIEW project and RT target to use for the project exercises in the course.

LabVIEW Real-Time Course Manual

2-20

ni.com

Lesson 2 Configuring Your Hardware

SummaryQuiz
Explain the meaning of the following terms: Project Target Front Panel Communication

Summary
ProjectA LabVIEW file that manages files, targets, build scripts, and source control. The Project Explorer is a window in LabVIEW that allows you to view and manage all aspects of a project. TargetA piece of hardware that you can download Real-time programs to. Also the item in a project tree that represents a hardware target. Front Panel CommunicationLabVIEW on the host computer displays the front panel of the VI while the RT Engine executes the block diagram. A user-interface thread handles the communication between LabVIEW and the RT Engine.

National Instruments Corporation

2-21

LabVIEW Real-Time Course Manual

Lesson 2

Configuring Your Hardware

Exercise 2-1
Objective:

Configure Hardware

Configure the Compact FieldPoint or the PXI target systems and the I/O hardware using MAX. Throughout the course project, you use either the Compact FieldPoint system or the PXI system as your target computer. If you are using Compact FieldPoint, complete part A of any hardware-specific exercises. If you are using PXI, complete part B of any hardware-specific exercises.

IP Address
1. Determine whether your network uses DHCP (automatically obtained) or static IP addresses. a. Right-click My Network Places on the desktop and select Properties from the shortcut menu. b. Right-click Local Area Connection and select Properties. c. Select Internet Protocol (TCP/IP) and click Properties. If the Obtain an IP address automatically option is selected, your network uses DHCP. Otherwise, your network uses static IP addresses. d. Close the dialog boxes.
Note If you are attending an instructor-led course, your system is configured for static IP addresses.

2. Connect your chosen system (Compact FieldPoint or PXI) to the network. Your system may already be connected for you. a. If the system uses DHCP, connect the system to the nearest hub using an Ethernet cable. b. If the system uses static IP addresses, connect the system to the computer using a cross-over cable. If you are attending an instructor-led course, the gray Ethernet cable is a cross-over cable; regular Ethernet cables are blue.
Note

Compact FieldPoint Configuration


3. Complete Exercise 2-1A.

PXI Configuration
4. Complete Exercise 2-1B.

End of Exercise 2-1


LabVIEW Real-Time Course Manual 2-22 ni.com

Lesson 2

Configuring Your Hardware

Exercise 2-1A Compact FieldPoint Configuration


Complete the following steps to wire the system. 1. Connect a power cable to the power supply attached to the side of the temperature chamber. 2. Connect the second power supply to the Compact FieldPoint controller a. Connect the red wire to a V1 input. b. Connect the black wire to a C input. 3. Connect a power cable to the power supply now attached to the Compact FieldPoint system. 4. Connect the plugs attached to the Compact FieldPoint modules to the appropriate input on the temperature chamber.

Configuring Controller
1. Select StartAll ProgramsNational InstrumentsMeasurement and Automation. 2. Expand the Remote Systems tree by clicking [+] to verify that the remote Compact FieldPoint system is detected. In Figure 2-1, the device is called cFPSystem1. Your device may have a different name, or simply show 0.0.0.0. If no device is listed, refresh the list by selecting ViewRefresh <F5>.

National Instruments Corporation

2-23

LabVIEW Real-Time Course Manual

Lesson 2

Configuring Your Hardware

Figure 2-1. Compact FieldPoint Network Settings Tab

3. Select the device and verify that the Network Settings tab is selected as shown in Figure 2-1. 4. If the IP address is set to 0.0.0.0, select the Edit the IP settings option and click Suggested Values. MAX analyzes your network or Ethernet adapter and inserts the proper subnet mask, gateway, and DNS server, if available. Then, a dialog box prompts you for IP Address Suggestion. Choose an IP address that is not currently used on the network. The IP address listed at the top is the IP address of the host computer.
Tip If the network uses DHCP rather than static IP addresses, select the Obtain IP address from DHCP server option.

5. Record the IP address of the host computer and the target system in a convenient location. You will need both in later exercises. 6. If you want, you can enter a more descriptive name for the Compact FieldPoint network module. You also can enter comments to describe the function of the network module and the bank of I/O modules. If you have made any changes to the Network Settings tab, click Apply, to save the changes to the module.

LabVIEW Real-Time Course Manual

2-24

ni.com

Lesson 2

Configuring Your Hardware

7. Find the modules that are connected to the Compact FieldPoint backplane. Click Find Devices. 8. A dialog box allows you to specify the name of the Communications (COMM) Resource for the FieldPoint system, as shown in Figure 2-2. Click OK to accept the default.

Figure 2-2. Comm Resource Name

At this point, notice that the Data Neighborhood section under My System has been expanded to show the COMM Resource name and the modules available on the FieldPoint system.

Configuring the cFP-TC-120


The cFP-TC-120 reads the J-Type thermocouple inside the temperature chamber. 9. Select the cFP-TC-120 under the Remote Systems section. Ensure that the Channel Configuration tab is selected, as shown in Figure 2-3. 10. Select Channel 0 in the Channels list. 11. Change the Range to degrees Celsius.

National Instruments Corporation

2-25

LabVIEW Real-Time Course Manual

Lesson 2

Configuring Your Hardware

Figure 2-3. cFP-TC-120 Settings

12. Click Apply if any changes were made.

Configure the cFP-PWM-520


The cFP-PWM-520 provides pulse-width modulated output power to the lamp and fan in the temperature chamber. 13. Select the cFP-PWM-520 under the Remote Systems section. Make sure that the Channel Configuration tab is selected, as shown in Figure 2-4. 14. Select Channel 0 in the Channels list. 15. Press the <Ctrl> key on the keyboard and select Channel 1 in the Channels list.
Tip

<Ctrl>-click or <Shift>-click to select more than one channel at a time. 16. Select the checkboxes for Channel 0 and Channel 1. 17. Verify that the Attribute of Period (ms) is set to 10.

LabVIEW Real-Time Course Manual

2-26

ni.com

Lesson 2

Configuring Your Hardware

Figure 2-4. cFP-PWM-520 Settings

18. If any changes were made to the Attribute values, click Apply to accept the configuration changes.

Test the Inputs and Outputs


19. Expand the cFP-TC-120@1 under the My SystemData NeighborhoodFieldPoint Items tree. 20. Select Channel 0 and rename the channel to Temp, as shown in Figure 2-5.

National Instruments Corporation

2-27

LabVIEW Real-Time Course Manual

Lesson 2

Configuring Your Hardware

Figure 2-5. cFP-TC-120 Temp Channel Configuration

21. Click Apply. 22. Select the cFP-TC-120@1 under the My SystemData NeighborhhodFieldPoint Items section. Confirm that the I/O Data tab is selected. 23. Select the Temp channel you just named in the I/O Data tab, as shown in Figure 2-6.

LabVIEW Real-Time Course Manual

2-28

ni.com

Lesson 2

Configuring Your Hardware

Figure 2-6. Testing the Temp channel

24. Click Start, to monitor the input channel of the cFP-TC-120. Notice that the temperature for the Temp channel, listed under the value column, should be near room temperature. 25. Repeat steps 19 to 24 to rename Channel 0 of the cFP-PWM-520 to Heater and Channel 1 of the cFP-PWM-520 to Fan. 26. Select the cFP-PWM-520@2 from the My SystemData NeighborhhodFieldPoint Items section. Confirm that the I/O Data tab is selected at the bottom-center of the window. 27. Select the Heater channel you just named in the I/O Data tab. 28. Click Start to test the output channel. 29. In the Value column, double-click in the row for Channel 0 (Heater) to launch the Item Write: [Channel] dialog box. 30. Enter a value between 0 and 100 and click the Write button to change the intensity of the Heater (lamp). 31. Repeat steps 27 through 30, to perform the same test on the Fan channel.

National Instruments Corporation

2-29

LabVIEW Real-Time Course Manual

Lesson 2

Configuring Your Hardware

Figure 2-7. Testing the Fan and Heater Channels Note

You can retest the Temp channel to see how the temperature changes with the new Heater and Fan output values. 32. After all testing is done, write values of 0 to both the Heater and the Fan channel to turn them off.
Caution You must turn off the heater (lamp) and fan as stated in step 32 to return the chamber to room temperature.

33. Save the configuration by clicking Save. Enter C:\Exercises\ LabVIEW Real Time\Fieldpoint Config when prompted to enter a file name. 34. Exit MAX.

End of Exercise 2-1A

LabVIEW Real-Time Course Manual

2-30

ni.com

Lesson 2

Configuring Your Hardware

Exercise 2-1B PXI Configuration


The following steps describe how to wire the system: 1. Connect a power cable to the power supply attached to the side of the temperature chamber. 2. Connect a power cable to the PXI chassis. 3. Connect the DAQ device on the target computer to the SC-2345 using the provided DAQ cable. 4. Connect the appropriate cables from the SC-2345 to the temperature chamber. 5. Turn on the power to the PXI chassis.
Tip The lamp and fan turn on at full power if everything is connected correctly because the counters on the data acquisition device default to a high state. In a later step, you set the counters to low to turn off the lamp and fan. If you need to reboot the PXI chassis at any time during the course, repeat the process to reset the counters to a low state.

Controller Configuration
1. Select StartAll ProgramsNational InstrumentsMeasurement and Automation. 2. If you are using a PXI computer as your host computer, identify the chassis and controller used in the host computer; otherwise skip to step 8. a. Expand Devices and Interfaces under My System by clicking the plus [+] sign. If a PXI system is not shown, try refreshing the list by selecting ViewRefresh <F5>. b. Right-click the PXI system listed and select Identify As, then select the controller choice that matches the controller installed in your host computer. c. Expand the PXI system listing. d. Right-click the PXI chassis and select Identify As, then select the chassis choice that matches the chassis used for your host computer. 3. Expand the Remote Systems option by clicking [+], to verify that the remote PXI system is detected. In the example shown in Figure 2-8, the device is called PXISystem1. Your device may have a different name or simply show 0.0.0.0. If no device is listed, try refreshing the list by selecting ViewRefresh <F5>. 4. Select the PXI system under Remote Systems and verify that the Network Settings tab is selected.

National Instruments Corporation

2-31

LabVIEW Real-Time Course Manual

Lesson 2

Configuring Your Hardware

Figure 2-8. PXI Network Settings Tab

5. If the IP address is set to 0.0.0.0, select the Edit the IP settings option and click Suggest Values. MAX analyzes your network or Ethernet adapter and inserts the proper subnet mask, gateway, and DNS server, if available. It also prompts you with the IP Address Suggestion dialog box. Choose an IP address that is not being used on the network currently. The IP address listed at the top is the IP address of the host computer.
Tip If your network uses DHCP, select the Obtain IP address from DHCP server option.

6. Record the IP address of the host computer and the target system in a convenient location. You will need both in later exercises. 7. Click the Apply button. Reboot the system if prompted.
Note

After the chassis reboots, the IP address appears in the Configuration tree.

LabVIEW Real-Time Course Manual

2-32

ni.com

Lesson 2

Configuring Your Hardware

8. Identify the chassis and controller used in the target computer. a. Expand Devices and Interfaces under your remote PXI system by clicking the plus [+] sign. b. Right-click the PXI system listed and select Identify As, then select the controller choice that matches the controller installed in your target computer. c. Expand the PXI system listing. d. Right-click the PXI chassis and select Identify As, then select the chassis choice that matches the chassis used for your target computer.

Figure 2-9. Identifying the PXI Controller in the Target Computer

Configure the PXI DAQ device and SC-2345 Accessory


1. Expand your PXI system listed under Remote Systems by clicking [+] in front of the listing. 2. Expand the Device and Interfaces listing.

National Instruments Corporation

2-33

LabVIEW Real-Time Course Manual

Lesson 2

Configuring Your Hardware

3. Expand the NI-DAQmx Devices listing. Your device should be automatically detected and displayed under this listing, as shown in Figure 2-10.

Figure 2-10. PXI Network Settings Tab

4. Right-click NI-DAQmx Devices, and select Create New NI-DAQmx DeviceNI-DAQmx SCC Connector BlockSC-2345. This creates a configuration entry for the SC-2345 carrier box. 5. The SCC Connector Block Configuration dialog box appears. a. Add the SCC-TC02 to slot J1, as shown in Figure 2-11. The SCC-TC02 module amplifies and filters the thermocouple signal. b. Add the SCC-FT01 to slots J19 and J20, as shown in Figure 2-11. The SCC-FT01 is a feed-through module that can create custom circuits. The circuit used here contains a transistor to switch on and off a device based on the pulses from the Counter/Timer on the DAQ device.

LabVIEW Real-Time Course Manual

2-34

ni.com

Lesson 2

Configuring Your Hardware

Figure 2-11. SCC Connector Block Configuration Dialog Box

6. Click OK to complete the configuration.

Turn Off Lamp and Fan


Test the counter outputs on the DAQ device and reset the state to low. Mark this page so that you can repeat steps 1 to 7 whenever the PXI chassis is reset. 1. Right-click the DAQ device under NI-DAQmx Devices in the Remote Systems section and select Test Panels. 2. Select the Counter I/O tab. 3. Select Dev1/ctr0 in the Channel Name pull-down menu. 4. Set the Duty Cycle to 0 and select Start to apply the new duty cycle. The duty cycle resets to 0.10, which is the minimum value for a duty cycle.

National Instruments Corporation

2-35

LabVIEW Real-Time Course Manual

Lesson 2

Configuring Your Hardware

5. Select Stop when the lamp has turned off. 6. Repeat steps 3 through 5 for the fan attached to Dev1/ctr1. 7. Close the test panel.

Create and Test Input Channel


Create an NI-DAQmx task for the input channel that reads the thermocouple measurement. 1. Right-click the Data Neighborhood entry under your PXI system and select Create New. 2. In the Create New dialog box that appears, select NI-DAQmx Task and click Next. 3. Select Analog InputTemperatureThermocouple. 4. Expand the SCC-TC02 and select the ai0 physical channel, as shown in Figure 2-12. 5. Click Next.

Figure 2-12. Create New Dialog Box

6. Name the task Temp and click Finish. The Temp task has now been created. You can further customize tasks by selecting ranges, CJC sources, task timing, and task triggering.

LabVIEW Real-Time Course Manual

2-36

ni.com

Lesson 2

Configuring Your Hardware

7. Ensure the NI-DAQmx tab is selected and set the CJC Source to Built-In, as shown in Figure 2-13.

Figure 2-13. Temp Task Configuration

8. Save the task configuration by clicking Save. 9. Click Test, to test the Temp channel. You should see a temperature around room temperature. You can modify the counter duty cycle output for the lamp and fan and see how it varies the temperature in the chamber.
Note

10. Exit MAX.

End of Exercise 2-1B

National Instruments Corporation

2-37

LabVIEW Real-Time Course Manual

Lesson 2

Configuring Your Hardware

Exercise 2-2
Objective:

Targeting Real-Time Hardware

Create a LabVIEW project and RT target to use for the project exercises in the course. In this exercise you will learn how to run a VI on the Real-Time series hardware. 1. Launch LabVIEW by selecting StartAll ProgramsNational InstrumentsLabVIEW 8.0. 2. Create a blank project by selecting FileNew Project. 3. Right-click the Project: Untitled Project entry in the Project Explorer and select NewTargets and Devices.

Be sure to right-click the Project entry and not the My Computer entry. You can add new targets by right-clicking My Computer. However, targets under My Computer must be internal targets on the computer, such as PCI Real-Time devices.
Note

4. In the Add Targets and Devices dialog box, select Existing device on remote subnet.

LabVIEW Real-Time Course Manual

2-38

ni.com

Lesson 2

Configuring Your Hardware

5. Choose the step for your platform. Perform step a if you have a PXI target, perform step b if you have a cFP target. a. Select Real-Time PXI from the list of target types if you are using PXI.

Figure 2-14. Add Targets and Devices Dialog Box

OR b. Select FieldPoint<Module>, where <Module> is the Fieldpoint Network Module that you are using.

National Instruments Corporation

2-39

LabVIEW Real-Time Course Manual

Lesson 2

Configuring Your Hardware

Figure 2-15. Adding a cFP Target

6. Enter the IP Address for the Real-Time hardware in the IP address field. 7. Click OK. Your project now contains a target which represents your Real-Time system. LabVIEW deploys and runs any VIs you place under this target on the Real-Time system. 8. Identify your Fieldpoint modules in the project. If you are using a PXI system, skip this step and proceed with step 9. a. Expand the Fieldpoint target and observe the contents. If the cFP-TC-120 and cFP-PWM-520 IO Modules are present and have channels named Heater, Fan, and Temp, skip to step 9. b. Right-click the Fieldpoint target and select New Target or Device. c. Expand the IO Module folder in the Add Targets and Devices dialog box. d. Select both the cFP-PWM-520 and cFP-TC-120 compact Fieldpoint modules.

LabVIEW Real-Time Course Manual

2-40

ni.com

Lesson 2

Configuring Your Hardware

Figure 2-16. cFP Real Time Project

e. Click OK. f. Expand the cFP-PWM-520 device. g. Right click Channel 0, select Rename and enter Heater. h. Rename Channel 1 to Fan. i. Expand the cFP-TC-120 device. j. Rename Channel 0 to Temp. 9. Select FileSave and save your project as Real-Time Exercises.lvproj in the C:\Exercises\LabVIEW Real Time directory. Use this generic project throughout the course whenever you need to execute a simple VI on your RT target. For more complex programs, create a unique project. 10. Right-click the RT target and select Connect to ensure that LabVIEW can connect to your target. 11. Check the Close on successful completion box on the Deploy dialog box.

National Instruments Corporation

2-41

LabVIEW Real-Time Course Manual

Lesson 2

Configuring Your Hardware

Figure 2-17. Deploy Dialog Box

12. When deployment has completed click the Close button to exit the Deploy dialog box. The small green light next in the target icon should now be lit, indicating that the target is connected. 13. Right-click your RT target to the Project Explorer and select Add File. 14. Open <target type>-Blinking Light.vi located in the C:\Exercises\LabVIEW Real Time directory where <target type> is the Real-Time Series hardware that you are using. 15. Save the Project. 16. Double-click the VI to open the front panel. 17. Click Run to run the VI with the default front panel settings. Notice that the light on the temperature chamber turns on and off at the blink rate. 18. While the VI is running, remove the Ethernet cable from the real-time hardware. Notice that the light on the temperature chamber continues to blink at the specified rate without the host computer connection. This demonstrates the reliability of the real-time hardware if the host connection is ever lost. 19. Leave the ethernet cable disconnected until LabVIEW displays
Warning: Connection to the RT Target has been lost.

20. Close the Blinking Light VI. 21. Reconnect the Ethernet cable. 22. Right-click the target in the project and select Connect. LabVIEW automatically opens the Blinking Light VI in the run state because it is running on the target.

LabVIEW Real-Time Course Manual

2-42

ni.com

Lesson 2

Configuring Your Hardware

Note If LabVIEW displays an Access denied: Too many hosts connected message, the target has not yet detected the disconnection. Cancel the message, wait 30 seconds and repeat step 22.

23. Click the Stop button on the VI to stop the VI. 24. Close the VI.

End of Exercise 2-2

National Instruments Corporation

2-43

LabVIEW Real-Time Course Manual

Lesson 2

Configuring Your Hardware

Notes

LabVIEW Real-Time Course Manual

2-44

ni.com

Lesson 3 Real-Time Architecture: Design

Lesson 3 Real-Time Architecture: Design


Topics A. Target and Host Architecture B. Multithreading C. Sleeping D. Improving Determinism E. Passing Data between Threads

Introduction
When implementing a system with the LabVIEW Real-Time Module, consider whether you need to use determinism. If your application only needs the embedded qualities of the LabVIEW Real-Time Module, including the reliability of the LabVIEW Real-Time Module, the ability to off-load processing, and headless black box design, you do not need to change your programming techniques. However, if your application must be deterministic, your application must either guarantee a response to an external event within a given time or meet deadlines cyclically and predictably. When designing applications within real-time constraints, you must employ certain programming techniques to achieve determinism. When programming a LabVIEW Real-Time Module application, you can decide how to establish communication between multiple tasks or threads without disrupting determinism. This lesson discusses how to design your application to achieve determinism.

National Instruments Corporation

3-1

LabVIEW Real-Time Course Manual

Lesson 3 Real-Time Architecture: Design

Real-Time Architecture

Host Program
User Interface
Network Communication

Target Program
Normal Priority Loop
Inter-Thread Communication

Time-Critical Loop

Data Storage

Data Storage

A. Host and Target Program Architecture


The figure above demonstrates the basic architecture of a well-designed real-time program. The overall task is divided into two parts: the host program and the target program. The host program contains the user interface. The target program is divided into two parts: the time-critical loop and the normal priority loop. These loops are contained within separate VIs. Any code that must execute deterministically is placed in the time-critical loop with all other code in the normal priority loop. In most programs, the time-critical loop handles all control tasks and/or safety monitoring, and the normal priority loop handles all communication and data logging.

LabVIEW Real-Time Course Manual

3-2

ni.com

Lesson 3 Real-Time Architecture: Design

Host Program
Host Program
User Interface

Runs on the host computer Handles non-deterministic tasks Communication with the target program: that is, user interface parameters and data retrieval Data logging Data analysis Data broadcast to other systems

Host Program
The host program runs on the host computer and communicates with VIs running on the target computer. This communication may involve user interface information, data retrieval, data broadcast to other systems needing data from the target program, and any other nondeterministic task that you may need.

National Instruments Corporation

3-3

LabVIEW Real-Time Course Manual

Lesson 3 Real-Time Architecture: Design

Target Program
Higher priority processes preempt lower priority processes Processes that must be deterministic are time-critical processesall other processes should be set to a lower priority Multithreading allows you to set the priority of a process

Target Program
Normal Priority Loop
Inter-Thread Communication

TimeCritical Loop

Target Program
The target program consists of time-critical code and normal priority code. A subVI contains the time-critical code, and a second subVI contains the normal priority code. This architecture allows you to separate the portions of the program that must behave deterministically from the portions of the program that do not.

Time Critical versus Low Priority Processes


Deterministic applications often perform a critical task iteratively, so that all iterations consume a measurably precise amount of processor time. Thus, deterministic applications are valuable not for their speed, but rather for their reliability in consistently responding to inputs and supplying outputs with little jitter. A common example of a deterministic application is a time-critical control loop, which gathers information about a physical system and responds to that information with precisely timed output. For example, consider the oil industry where thousands of feet of pipes are assembled daily. As two pipes are threaded together mechanically end-to-end, the torque required to twist together the pipes increases until the pipes are fully connected. Suppose the machine connecting the pipes uses a control loop to respond to an increase in resistance between the pipes by applying more torque. Furthermore, suppose that once a critical level of torque is attained, the control loop is triggered to terminate. Under these conditions, the loop must execute deterministically because lag in the software could result in severe damage to the pipes and other equipment. Understanding multithreading is a prerequisite to understanding priority levels. Multithreading expands the idea of multitasking.

LabVIEW Real-Time Course Manual

3-4

ni.com

Lesson 3 Real-Time Architecture: Design

What Is Multithreading?
Extension of the idea of multitasking
MultitaskingAbility of the operating system to quickly switch between tasks A task is generally an entire application, such as LabVIEW

Multithreading extends the following multitasking capabilities into applications:


Subdivide specific operations within an application into individual threads Divide processing time among threads Enable assigning priorities

B. Multithreading
Multitasking refers to the ability of the operating system to quickly switch between tasks, giving the appearance of simultaneous execution of those tasks. For example, in Windows 3.1, a task is generally an entire application, such as Microsoft Word, Microsoft Excel, or LabVIEW. Each application runs for a small time slice before yielding to the next application. Windows 3.1 uses a technique known as cooperative multitasking, where the operating system relies on running applications to yield control of the processor to the operating system at regular intervals. Occasionally, applications either do not yield or yield inappropriately and cause execution problems. Windows 95 and later rely on preemptive multitasking, where the operating system can take control of the processor at any instant, regardless of the state of the application currently running. Preemptive multitasking guarantees better response to the user and higher data throughput. This minimizes the possibility of one application monopolizing the processor. Multithreading extends the idea of multitasking into applications, so that specific operations within a single application can be subdivided into individual threads, each of which can run in parallel. Then, the operating system can divide processing time not only among different applications but also among each thread within an application. For example, in a LabVIEW multithreaded program, the application might be divided into three threadsa user interface thread, a data acquisition thread, and an instrument control threadeach of which can be assigned a priority and operate independently. Thus, multithreaded applications can have multiple tasks progressing in parallel with other applications. The operating system divides processing time on the different threads similar to the way it divides processing time among entire applications in an exclusively multitasking system.

National Instruments Corporation

3-5

LabVIEW Real-Time Course Manual

Lesson 3 Real-Time Architecture: Design

Advantage of Multithreading
Differentiates between time-critical and non-critical tasks
Some time-critical tasks Control loop Safety monitoring Some non-critical tasks Communication Data logging

Real time performance needs an operating system that can give scheduling priority to time-critical tasks

Multithreading is useful when you have parts of your code that must not be deterministic or if parts of your code rely on non-deterministic I/O. To help us differentiate between deterministic tasks and non-deterministic tasks, you can evaluate whether a task is time critical or not. A control loop and safety monitoring are considered time critical because both need to execute on time, every time to ensure accuracy. Communication is not time critical because a person or computer may not respond on time, every time. Likewise, data logging is not time critical because an accurate time stamp can identify when the data is collected or calculated. What could happen to a time-critical process if a non-critical task were involved? Putting network communication tasks (non-critical task) inside the time-critical loop may harm determinism. For example, if time-critical code relies on responses from another PC over the network and if the other PC does not reply in time, the time-critical code may miss a deadline. To prevent missing deadlines, the threads can be broken up into time-critical tasks and tasks that are not time critical. In this manner, higher priority can be assigned to time-critical tasks to ensure that they always finish on time. Therefore, to have a genuine real-time operating system, the ability to assign leveled priorities is important.

LabVIEW Real-Time Course Manual

3-6

ni.com

Lesson 3 Real-Time Architecture: Design

Real-Time Multithreading Metaphor


Time-Critical Priority
(one VI only)

Normal Priority

Tasks

Ambulance

Receptionist
(Operating System)

One Mechanic
(Processor)

Real-Time Multithreading Metaphor


MECHANIC = PROCESSORIn this example, only one mechanic (Processor) performs the repairs (processing). RECEPTIONIST = OPERATING SYSTEMThe receptionist (Operating System), lines up the service requests as they arrive. He schedules them in order of arrival, unless a higher priority customer arrives, in which case the receptionist schedules that customer before the lower priority customers. ONE TOWN AMBULANCE = ONE TIME-CRITICAL PRIORITY VI ONLYIn this example, only one automobile in the town has the highest priority: the ambulance. This is recommended for LabVIEW Real-Time Module programs as well. WORK ON CARS OF EQUAL PRIORITY AT THE SAME TIME = MULTI-TASKING WITHIN EQUAL PRIORITIESThe mechanic can work on multiple cars of the same priority at the same time and progress them all to completion, working a little bit on one car and a little on the next. (Equal priority threads share the CPU.) PREEMPTIONIf the mechanic is working on lower priority cars, and a car of higher priority arrives, he puts aside lower priority cars to work on the higher priority cars. When he finishes with higher priority cars, he can return to the lower priority cars. NEVER FINISH LOW PRIORITY CARS = STARVATIONIf there always are higher priority cars that need work, then the mechanic never repairs lower priority cars.

National Instruments Corporation

3-7

LabVIEW Real-Time Course Manual

Lesson 3 Real-Time Architecture: Design

Scheduling Threads
Round-Robin Scheduling
Threads of equal priority receive equal time slices. It might take several turns for a thread to complete

Preemptive Scheduling
Higher priority thread immediately suspends execution of all lower priority threads

Scheduling Threads
There are two methods for scheduling threads: round robin and preemptive. The real-time operating system (RTOS) of the LabVIEW Real-Time Module implements a combination of the following two methods: Round-robin scheduling applies to threads of equal priority. Equal shares of CPU time are allocated between the equal priority threads. For example, each normal priority thread is allotted 10 milliseconds to run. The thread executes all the tasks it can in 10 milliseconds, and whatever is incomplete at the end of that period must wait to complete during the next allocation of time. Preemptive scheduling means that any higher priority thread that needs to execute immediately suspends execution of all lower priority threads and begins to execute. The CPU can ignore lower priority threads, thus causing starvation of those threads.

LabVIEW Real-Time Course Manual

3-8

ni.com

Lesson 3 Real-Time Architecture: Design

Round Robin Scheduling


Receptionist (Scheduler) Normal Mechanic (CPU)

Normal

Normal

Round-robin scheduling shares processor time between threads based on equal slices of time. The time slice for a LabVIEW Real-Time application is 10 milliseconds. To illustrate round-robin scheduling, recall the analogy of an automobile repair shop. In this case, one mechanic represents the CPU, and a receptionist represents the scheduler. You have multiple cars that represent the multiple threads of your system. Using round-robin scheduling, the mechanic cycles between each car for a set period of time. Round-robin scheduling guarantees each thread has some time with the processor; however, there is no prioritization of critical tasks. For example, if the imaginary town has only one ambulance and it needs to be serviced, round-robin scheduling would not allow the mechanic to give priority service.

National Instruments Corporation

3-9

LabVIEW Real-Time Course Manual

Lesson 3 Real-Time Architecture: Design

Preemptive Scheduling
Time Critical
Normal Mechanic (CPU)
Ambulance

Receptionist (Scheduler)

Normal

Normal

With preemptive scheduling, you can give priority to critical tasks. In this case, one thread can be designated as most important, that is, time-critical. When the time-critical thread needs time from the processor, the other threads will wait until the time-critical thread is finished. In the repair shop example, the ambulance is assigned time-critical priority. As a result, the mechanic services it as soon as it arrives. All other cars are delayed until the ambulance service is complete. After the ambulance service is complete, the other cars resume sharing time with the mechanic. Note A thread swap occurs when the processor switches between threads. Every thread swap takes additional time from the processor.

LabVIEW Real-Time Course Manual

3-10

ni.com

Lesson 3 Real-Time Architecture: Design

LabVIEW Real-Time Scheduling


Time Critical
Normal Mechanic (CPU)
Ambulance

Receptionist (Scheduler)

Normal

Normal

The LabVIEW Real-Time Module uses a combination of round-robin and preemptive scheduling. Each VI is assigned a priority. Thread priority determines the execution of VIs, with higher priority threads preempting lower priority threads. Threads with equal priority use roundrobin scheduling. The time-critical priority VI receives the processor resources necessary to complete the task and does not relinquish control of the processor until it cooperatively yields to the normal priority VI or until it completes the task. The normal priority VI then runs until preempted by the time-critical VI. Time-critical VIs release control of the processor by either completing the operation or by sleeping. Without sleep time built into the time-critical VI, all other operations on the system are unable to execute, causing the system to behave as though using preemptive scheduling. In the repair shop example, the ambulance is assigned time-critical priority. The mechanic services the ambulance as soon as it arrives. After the mechanic arrives at a designated sleep time or finishes service on the ambulance, the mechanic services other vehicles on a shared basis until break time is over. The mechanic then returns to working on the ambulance.

National Instruments Corporation

3-11

LabVIEW Real-Time Course Manual

Lesson 3 Real-Time Architecture: Design

LabVIEW Real-Time Scheduler


Combination of round-robin and preemptive scheduling Set only one VI to time-critical priority

Setting Priority Levels


The priority levels available include the following in order from lowest to highest priority: 1. Background 2. Normal 3. Above normal 4. High 5. Time-critical priority To set a VI as time-critical, select FileVI PropertiesExecution. You also can right-click on the icon/connector on the front panel to access the VI Properties dialog box.

LabVIEW Real-Time Course Manual

3-12

ni.com

Lesson 3 Real-Time Architecture: Design

Sleeping
Time Critical Normal Normal

No sleep in time-critical thread

Executing Waiting

Sleep added to time-critical thread

Time

Time Critical Normal Normal

Sleeping Executing Waiting

C. Sleep Mode
Because of the preemptive nature of time-critical VIs, they can monopolize processor resources. A time-critical VI might use all of the processor resources, not allowing lower priority VIs in the application to execute. You must build time-critical VIs that periodically yield or sleep, to allow lower priority tasks to execute without affecting the determinism of the time-critical code. Consider sleep mode as a programmatic tool that a VI can use to proactively remove itself from the LabVIEW and operating system scheduling mechanisms. Sleeping suspends the execution of a VI or a thread. By taking advantage of sleep mode, you can allow a lower priority VI to run by putting a higher priority VI to sleep. In the top graph, the time-critical thread starves the two normal threads, because no sleep has been placed in the time-critical thread.

National Instruments Corporation

3-13

LabVIEW Real-Time Course Manual

Lesson 3 Real-Time Architecture: Design

Starvation
A. Time Critical B. Above Normal C. Normal

No sleep causes starvation

Executing Waiting

Sleep addedmay still starve some threads

Time

A. Time Critical B. Above Normal C. Normal

Sleeping Executing Waiting

Starvation
To understand starvation, consider the following example: Three processes compete for a resource. Because Process A has a time-critical priority (highest), it runs until it finishes using the resource, thus freeing the resource. At that point, another process may use the resourcein this situation, either Process B or Process C. If Process A is ready to run again, it takes control of the resource and runs until it is finished with the timecritical section. Again, one of the two processes may run. If Process A is not put to sleep long enough for both process to run, the possibility that a lower priority process is never allowed to run can happen. This situation is called starvation. At the start, Process A has the resource and Processes B and C wait for Process A to go into sleep mode so that they may use the resource. Then, Process A goes to sleep, and the next highest priority process is allowed to run. In this case, because Process B has a higher priority than Process C, Process B may run before Process C. When the sleep time of Process A is finished, Process A takes the resource back from Process B. If this situation continues indefinitely, Process C can be blocked from the resource and become starved. In the next sleep cycle, Process A is sleeping long enough to allow Process B to run and sleep then run Process C. To prevent starvation of a lower priority process, the higher priority process must be put to sleep long enough to allow lower priority processes time to execute.

LabVIEW Real-Time Course Manual

3-14

ni.com

Lesson 3 Real-Time Architecture: Design

Sleeping
The act of suspending the execution of a VI or thread
Software-timed sleep Hardware-timed sleep

Use the operating system clock to control the rate of a software loop.

Use hardware or processor clocks to control the rate of a software loop.

Providing Sleep
You can program a sleep mode in a VI by using the Wait function or by using a timed loop. When controlling the rate of a software loop by using the Wait Until Next ms Multiple function, users only can achieve rates in 1 millisecond multiples. This means you can either run your loop at full speed providing no sleep at all, or you can achieve loop rates of 1,000 Hz, 500 Hz, 333.33 Hz, 250 Hz, 200 Hz, and so on. However, if your controller has a Pentium 3 or 4 class processor, you can use the Wait function from the Real-Time Timing subpalette or the timed loop to achieve microsecond wait times, which adds to the available loop rates. Sleep can be provided using the data acquisition hardware on the PXI platforms. Use the DAQmx timing VIs to harness the clock on your data acquisition hardware. Refer to Lesson 4, Timing Applications and Acquiring Data, to learn how to program sleep into your time-critical loop.

National Instruments Corporation

3-15

LabVIEW Real-Time Course Manual

Lesson 3 Real-Time Architecture: Design

Sleeping and Time-Critical Priority


The following features are unique to the LabVIEW Real-Time Module: If any VI in a time-critical thread goes to sleep, then the entire thread goes to sleep Do not use parallel loops in time-critical VIs, because multitasking is disabled If parallel loops are needed to achieve multiple loop rates, do not use time-critical VIsuse timed loops instead

The time-critical priority (highest) of the LabVIEW Real-Time Module threads have a unique characteristic that is different from normal LabVIEW scheduling. If any VI running in the timecritical priority (highest) thread goes to sleep, then the entire thread goes to sleep. Other VIs running on the thread are forced to sleep and cease executing until the original VI wakes up. This is only the case for the time-critical priority (highest) setting. Conversely, if two VIs (or two loops for that matter), are executing on the same thread (other than time-critical priority (highest) ), and one of them goes to sleep, the other VIs on the same thread continue to execute. In other words, the execution system of the LabVIEW Real-Time Module does not schedule time-critical priority (highest) operations from parallel VIs or loops, when any one of them sleep in the same time-critical priority (highest) thread. All other priority threads in LabVIEW RealTime, and all threads in normal LabVIEW, continue to schedule operations from parallel loops and/or VIs, in similar threads. Given the cooperative multitasking nature of scheduling multiple time-critical priority (highest) threads, it is recommended that only one VI and loop ever be used with the time-critical priority (highest) setting. This is the only way to receive a guarantee of deterministic execution. If more than one time-critical VI (or loop) is needed to achieve different loop rates, you can use a timed loop instead of a time-critical priority VI. Refer to Lesson 8, Advanced Topics, for more information about timed loops.

LabVIEW Real-Time Course Manual

3-16

ni.com

Lesson 3 Real-Time Architecture: Design

Exercise 3-1
Priority Levels
Time to complete: 10 min.

Run this VI on the Real-Time Engine. It illustrates the need for careful consideration of priorities and timing when programming in the real-time environment of embedded DAQ hardware. In this VI, a chart of a sine wave is produced. Slowly decrement the msec to wait control. With each step, the chart display should speed up, as expected. But, when the msec to wait count reaches zero, the front panel no longer updates. The reason for this unusual behavior is that the processor card can no longer communicate with the LabVIEW front panel. Because the time-critical loop has the highest priority, the thread that updates front panel objects cannot get any processor time. After a minute or two, the front panel recognize that it has lost communication with the processor card. You receive a warning message, and LabVIEW exits. You must reboot the processor card. This problem is not limited to VIs with a front panel. VIs that rely on other VIs in other threads, or VIs which communicate with a separate host LabVIEW VI using TCP/IP, or the VI Server suffer the same problem. Great care is needed in programming to ensure that all necessary threads can run on the processor card. The msec to wait control is the number of milliseconds the loop should sleep between iterations. If set to 0, the loop will not sleep at all between iterations. You must have an embedded processor card to observe the behavior described in this VI. If run on the desktop, the behavior could range from a significant slow down of your system to LabVIEW monopolizing the host processor and locking the system.

OBJECTIVE

To adjust the priority levels to understand the effects of priority levels on scheduling a VI

National Instruments Corporation

3-17

LabVIEW Real-Time Course Manual

Lesson 3 Real-Time Architecture: Design

Class ExerciseChoose Priority Level


User Interface Data Logging Serial

TCP

Signal Analysis

UDP

CAN

Buffered DAQ

When you understand priority levels, you must be able to separate your code into the timecritical components and the normal priority components. The boxes shown above are different components of a typical program. Choose which components should be in the time-critical portion of the target program, in the normal priority portion of the target program and in the host program. Time-Critical:

Normal Priority:

Host:

LabVIEW Real-Time Course Manual

3-18

ni.com

Lesson 3 Real-Time Architecture: Design

Potential Solution
Serial User Interface

Time-Critical Priority VI
Buffered DAQ CAN

Data Logging

UDP

Normal Priority VI
Separate
Data Logging Serial TCP UDP Signal Analysis

TCP

Buffered DAQ

Host VI
CAN Signal Analysis User Interface

The slide above demonstrates one possible solution to the class exercise. The user interface is on the host VI, because the target is headless. Buffered DAQ and CAN are both methods for acquiring data and implementing a control algorithm, which makes them time-critical processes. However, there are valid reasons for placing these in the normal priority VI as well. Data logging and communication are non-deterministic processes. Non-deterministic processes should be placed either in the normal priority VI or the host VI. A benefit to placing the data logging on the target rather than the host is to avoid data loss when communication between the host and target is lost. However, there are ways of buffering communication to avoid data loss. Signal processing is a normal priority process unless the signal processing is a necessary part of a control algorithm or the program is designed to provide real-time signal processing.

National Instruments Corporation

3-19

LabVIEW Real-Time Course Manual

Lesson 3 Real-Time Architecture: Design

Improving the Determinism of the Application


Choose appropriate hardware Avoid shared resources Avoid contiguous memory conflicts Avoid subVI overhead Disable non-essential options Use only one time-critical loop in an application

D. Improving Determinism
The easiest way to improve determinism is to choose a faster hardware platform. If you are unable to achieve a desired loop rate, first check your hardware to be sure it is capable of reaching the required rate. If your hardware rates are acceptable, you can improve the determinism of your application in software by avoiding shared resources, contiguous memory conflicts, and subVI overhead. Because the LabVIEW Real-Time Module Memory manager is a shared resource, using memory reduction techniques also helps to improve the determinism of an application. You learned in the last section that you should only use one time-critical loop in an application because when a time-critical loop goes to sleep, the entire thread goes to sleep. The following section explains programming methods for improving determinism.

LabVIEW Real-Time Course Manual

3-20

ni.com

Lesson 3 Real-Time Architecture: Design

Shared Resources
A shared resource in the LabVIEW Real-Time Module is anything that can only be used by one process at a time LabVIEW RT shared resources include the following:
Global Variables Shared Variables Real-Time Module Memory Manager Non-reentrant subVIs Single-threaded DLLs Networking code (TCP/IP, UDP, VI Server) * Semaphores* File I/O*

* inherently non-deterministic

Shared Resources
Certain data structures, driver libraries, and variables only can be accessed serially, one process at a time. A simple example of a shared resource common to all programming languages is the global variable. You cannot access global variables simultaneously from multiple processes. Therefore, compilers automatically protect the global variable as a shared resource while one process needs to access it. Meanwhile, if a second process tries to access the global variable while it is protected, the second process must wait until the first process has finished with the global variable. Understanding shared resources and how to identify them is an important skill when programming real-time applications. Note These operations are inherently non-deterministic. Never use them inside a timecritical priority loop if you are attempting to achieve real-time performance.

National Instruments Corporation

3-21

LabVIEW Real-Time Course Manual

Lesson 3 Real-Time Architecture: Design

Shared Resources
Before a process can begin using a shared resource, it must obtain a mutual exclusion (mutex) Process 1
Running

Shared Resource

Process 2
Waiting

After Process 1 finishes, Process 2 can proceed

Process 1
Waiting

Shared Resource

Process 2
Running

For our purposes a shared resource is defined as a software object that can run only one thread at a time. In this example, assume both processes constantly must access the shared resource. Process 1 runs at normal priority, while Process 2 runs at time-critical priority. Normally, when a time-critical thread needs to execute, it preempts all other code running on the real-time target; however, a normal priority thread can block the time-critical thread if it has not released a mutex that the time-critical thread needs. This is known as a priority inversion because the real-time operating system cannot allow the time-critical thread to preempt the normal priority thread, merely because of the mutex around a shared resource. Note A mutex is a mutual exclusion object that allows multiple threads to synchronize access to a shared resource. A mutex has two states: locked and unlocked. After a thread locks a mutex, other threads attempting to lock it will block. When the locking thread unlocks (releases) the mutex, one of the blocked threads acquires (locks) it and proceeds.

LabVIEW Real-Time Course Manual

3-22

ni.com

Lesson 3 Real-Time Architecture: Design

Shared ResourcesPriorities
Priority inversion:
Time-Critical Priority waiting

Normal priority VI blocks the higher priority VI with a mutex around the shared resource Priority inheritance:

Normal Priority running

Normal priority VI inherits higher priority to release mutex

In the example above, the shared resource is a global variable, which is shared by two VIsone set to normal priority and one set to time-critical priority. The real-time OS uses a method called priority inheritance to resolve the priority inversion as quickly as possible, by doing the following: 1. Allowing the lower priority thread to temporarily inherit the time-critical priority setting long enough to finish using the shared resource and to remove the protection. 2. After the protection is removed, the lower priority thread resumes its original lower priority setting and is taken off of the processor. 3. Now the time-critical priority thread is free to proceed and use the resource, that is, access the global variable. A result of this priority inversion is increased software jitter in the time-critical priority thread. The jitter induced by a protected global variable is small compared to the jitter induced by protecting the LabVIEW Memory Manager. Unlike accessing global variables, performing memory allocations is unbounded in time and can introduce a broad range of software jitter while parallel operations try to allocate blocks of memory in a wide variety of sizes. The larger the block of memory to be allocated, the longer the priority inheritance takes to resolve the priority inversion.

National Instruments Corporation

3-23

LabVIEW Real-Time Course Manual

Lesson 3 Real-Time Architecture: Design

Shared ResourcesSubVIs

Configure a subVI for reentrant execution if unrelated parallel processes call the same subVIallows several instances of a subVI to be called simultaneously

Reentrant subVIs do NOT act like global variables

Sharing subVIs causes priority inversions the same way global variables do. When a subVI is set to subroutine priority, that subVI can be skipped within time-critical code to avoid software jitter that would have occurred from a priority inversion. However, if you run unrelated parallel processes that call the same subVI, you can configure the subVI for reentrant execution. A reentrant subVI establishes a separate data space in memory each time it is called. A reentrant subVI allows LabVIEW RT to call several instances of a particular subVI simultaneously. Because reentrant subVIs use their own data space, you cannot use them to share or communicate data between threads. You should only use reentrancy when you must simultaneously run two or more instances of a subVI within unrelated processes that do not need to share data within the reentrant subVI. To configure a subVI for reentrancy, select VI PropertiesExecution, and then select the Reentrant Execution checkbox. Note When using this feature because each call to the subVI establishes a new unique data space for all controls and indicators in memory. For this reason, you cannot use reentrant subVIs as functional global variables. Also, configuring the DAQ VIs for reentrancy does not solve shared resource problem with NIDAQ32.dll. All DAQ VIs load the DAQ driver, NIDAQ32.dll. This dll is not multi-threaded safe, which means it cannot be called simultaneously from multiple processes.

LabVIEW Real-Time Course Manual

3-24

ni.com

Lesson 3 Real-Time Architecture: Design

Shared ResourcesMemory Management


The LabVIEW Real-Time Module manages memory automatically
The user does not explicitly have to allocate or de-allocate memory This means memory management is easy, but harder to control

The LabVIEW Real-Time Module has a memory manager that is a shared resource
You must control memory allocations to avoid shared resource conflicts with the memory manager You statically allocate memory before time-critical process begins

Memory Management
The LabVIEW Real-Time Module has a memory manager that automatically allocates and deallocates memory at run time. Allocating memory can consume a significant amount of CPU time, depending on the amount of memory needed. If you allow the LabVIEW Real-Time Module to dynamically allocate memory at run time, your application could suffer from software jitter for the following reasons: The memory manager may already be mutexed by, causing a shared resource conflict. Even if the memory manager is immediately available, allocating memory is nondeterministic because there is no upper bound on the execution time of the malloc().

National Instruments Corporation

3-25

LabVIEW Real-Time Course Manual

Lesson 3 Real-Time Architecture: Design

Preallocate Arrays
Avoid allocating arrays within a time-critical loop

Avoid allocating memory within a time-critical VI control loop. If you are using arrays in time-critical VI control loops, you can reduce jitter by preallocating arrays before entering the loop. For example, instead of using Build Array within your loop to index new data into an array, use Replace Array Subset to insert new array values into preallocated arrays.

LabVIEW Real-Time Course Manual

3-26

ni.com

Lesson 3 Real-Time Architecture: Design

Shared ResourcesMemory Management


Key points about memory management and real-time:
The LabVIEW Real-Time Module memory manager is a shared resource All memory allocations must be removed from the time-critical loop to guarantee robust, hard real-time performance Preallocate arrays outside of the time-critical loop Cast all data to the proper data type Use inplaceness when possible to reuse memory buffers Reduce the use of global variables

In general, memory allocations within a time-critical loop induce jitter and effect the deterministic properties of a LabVIEW Real-Time Module program. All memory allocations must be removed to guarantee robust hard real-time performance. You must preallocate your arrays outside of the loop if you want your application to run deterministically. Certain LabVIEW Real-Time Module functions allocate memory, such as Build Array and Bundle. Cast data to the proper data type in VIs running on the RT target. Each time LabVIEW performs a type conversion, LabVIEW makes a copy of the data buffer in memory to retain the new data type after the conversion. The LabVIEW Memory Manager must allocate memory for the copy, which might affect the determinism of time-critical VIs. Also, creating copies of the data buffer takes up memory resources on an RT target. Refer to the LabVIEW Help for more information about casting data types. Use the smallest data type possible when casting the data type. If you must convert the data type of an array, do the conversion before you build the array. Also, keep in mind that a function output reuses an input buffer only if the output and the input have the same data typerepresentation, size, and dimension. Arrays must have the same structure and number of elements for function outputs to reuse the input buffer. This ability for a function to reuse buffers is called inplaceness. LabVIEW creates an extra copy in memory of every global variable you use in a VI. Reduce the number of global variables to improve the efficiency and performance of VIs. Creating copies of the global variable takes up memory resources on an RT target.

National Instruments Corporation

3-27

LabVIEW Real-Time Course Manual

Lesson 3 Real-Time Architecture: Design

This course does not discuss all types of shared resources. Avoid semaphores, TCP/IP, UDP, VI Server, and File I/O functions within a time-critical loop. These functions are inherently non-deterministic and use shared resources. For example, semaphores are themselves shared resources, network functions use the Ethernet driver, and file I/O functions use the hard disk. These functions can introduce severe software jitter in time-critical code on account of priority inversions. Also be aware that all handshaking protocols are non-deterministic. Do not run GPIB, RS-232, TCP/IP at time-critical priority. DAQ handshaking protocols are non-deterministic and avoid using them in time-critical loops, such as burst mode and 8255 emulation mode on the 653x devices.

LabVIEW Real-Time Course Manual

3-28

ni.com

Lesson 3 Real-Time Architecture: Design

Avoid Contiguous Memory Conflicts


Same memory space is used for new arrays smaller than Array 1 Because Array 3 is larger than Array 1, other contiguous memory space must be found

Preallocate array space equal to the largest expected array size

Avoid Contiguous Memory Conflicts


LabVIEW handles many of the memory details that you normally handle in a conventional, textbased language. For example, functions that generate data must allocate storage for the data. When that data is no longer needed, LabVIEW deallocates the associated memory. When you add new information to an array or a string, LabVIEW allocates new memory to accommodate the new array or string. However, running out of memory is a concern with VIs running on an RT target. You must design memory-conscious VIs for RT targets. Always preallocate space for arrays equal to the largest array size that you might encounter. When you reboot or reset an RT target, the RTOS and the RT Engine load into memory as shown in Figure 1 of the slide above. The RT Engine uses available memory for running RT target VIs and storing data. In Figure 2, ArrayMaker.vi creates Array 1. All elements in Array 1 must be contiguous in memory. The RTOS reuses the same memory addresses if you stop a VI and then run it again with arrays of the same size or smaller. In Figure 3, ArrayMaker.vi creates Array 2. The RTOS creates Array 2 in the reserved memory space previously occupied by Array 1. Array 2 is small enough to fit in the reserved memory space that was allocated to Array 1. The extra contiguous memory used for Array 1 remains in the reserved memory space, as shown in Figure 3. When ArrayMaker.vi runs for a third time with a larger array or if another VI generates a larger array, the RT Engine must find a large enough contiguous space. In Figure 4, ArrayMaker.vi must create Array 3, larger than the previous arrays, in the available memory.

National Instruments Corporation

3-29

LabVIEW Real-Time Course Manual

Lesson 3 Real-Time Architecture: Design

Even when ArrayMaker.vi stops running, the RT Engine continues to run. Previously reserved memory is not available. If ArrayMaker.vi runs a fourth time and attempts to create an array larger than Array 3, the operation fails. There is no contiguous memory area large enough to create the array because of the memory fragmentation. You can preserve memory space by preallocating array space equal to the largest use case.

LabVIEW Real-Time Course Manual

3-30

ni.com

Lesson 3 Real-Time Architecture: Design

Avoid SubVI Overhead


Each subVI call involves a small amount of overhead SubVI overhead can be significant if you place the subVI inside a looping structure Place the looping structure, if possible, inside the subVI instead

Avoid SubVI Overhead


Calling a subVI from a VI running on an RT target adds a small amount of overhead to the overall application. Although the overhead is small, calling a subVI multiple times in a loop can add a significant amount of overhead. You can embed the loop in the subVI to reduce the overhead. The overhead involved in calling a subVI increases depending on the amount of memory that needs to be copied by the memory manager. You also can convert subVIs into subroutines by changing the VI priority. The LabVIEW execution system minimizes the overhead to call subroutines. Subroutines are short, frequently executed tasks that generally do not require user interaction. Subroutines cannot display front panel data and do not multitask with other VIs. Also, avoid using timing or dialog box functions in subroutines.

National Instruments Corporation

3-31

LabVIEW Real-Time Course Manual

Lesson 3 Real-Time Architecture: Design

Disable Non-Essential Options


Allow debugging Auto handle menus at launch

Disable Non-Essential Options


To reduce memory requirements and increase performance of VIs, disable nonessential options in the VI Properties dialog box available by selecting FileVI Properties. Select Execution from the Category pull-down menu and remove checkmarks from the Allow debugging and Auto handle menus at launch checkboxes. By disabling these options, VIs use less memory, compile more quickly, and perform better. Note The LabVIEW Real-Time Module ignores the Enable automatic error handling option.

LabVIEW Real-Time Course Manual

3-32

ni.com

Lesson 3 Real-Time Architecture: Design

Avoid Express VIs to Reduce Jitter


Increase LabVIEW ease of use and improve productivity Require additional performance overhead during execution

LabVIEW Express VIs increase LabVIEW ease of use and improve productivity with interactive dialog boxes that minimize programming for measurement applications. Express VIs require additional performance overhead during execution. Therefore, do not use Express VIs in timecritical or processor-intensive applications. Instead, develop real-time applications with standard LabVIEW VIs. Refer to the Getting Started with LabVIEW manual for more information about LabVIEW Express VIs.

National Instruments Corporation

3-33

LabVIEW Real-Time Course Manual

Lesson 3 Real-Time Architecture: Design

Passing Data Between Threads


Target Program
Normal Priority Loop
Inter-Thread Communication

TimeCritical Loop

Inter-Thread Communication Methods Good: Global Variables Better: Functional Global Variables Best: Real-Time FIFO VIs, Shared-Variable FIFOs

E. Passing Data Between Threads


After dividing tasks in an application into separate VIs of varying priorities, you might need to communicate between the different VIs on the RT target. You can use the following to send and receive data between VIs or loops in an application: Global variables Functional global variables Single-process shared-variables LabVIEW Real-Time Module FIFO VIs

LabVIEW Real-Time Course Manual

3-34

ni.com

Lesson 3 Real-Time Architecture: Design

Global VariablesGood
Target Program
Normal Priority Loop
Global Variables

TimeCritical Loop

Can cause jitter, because they are a shared resource LossyA global variable may be written to many times before being read. Good for scalar data (<32 bits)

Global Variables
A global variable is a location in memory that multiple VIs can access. While global variables are easier to program, they are not the ideal method for transferring large amounts of data. Using a global variable can be a good way to pass data smaller than 32-bits, such as scalar data, between VIs. However, global variables are a lossy form of communication, meaning the global variable can be overwritten before the data is read. Tasks in a lower priority VI might not have enough processor time to read the data before other tasks in a different VI overwrite the data. Using global variables in time-critical priority VIs in LabVIEW Real-Time can compromise determinism. A global variable is a shared resource. If one piece of code accesses a global variable, no other piece of code can access the global variable until the first piece releases the global variable. When you block the access of a time-critical VI to a global variable, forcing the time-critical VI to wait, you introduce jitter to the application and compromise the determinism of the application.

National Instruments Corporation

3-35

LabVIEW Real-Time Course Manual

Lesson 3 Real-Time Architecture: Design

Functional Global Variables (FGV)Better


Target Program
Normal Priority Loop
Functional Global Variables

TimeCritical Loop

Can have several inputs and outputs Can skip if busy Can be lossy

Functional Global Variables


You can avoid this behavior by using a functional global variable, setting it to subroutine priority, and selecting the Skip Subroutine Call if Busy option for it. With a functional global variable, the time-critical VI must not access the global if another section of code is already using the global variable. Skipping a subVI helps in time-critical VIs, because the VI does not wait for the subVI. If you skip the execution of a subVI, the subVI returns the default value for that data type and not the default indicator value. For example, the default data type value for numerics is zero, strings and arrays default to an empty string, and Boolean values default to FALSE. If you want to detect the execution of a functional global variable, wire a TRUE constant to a Boolean output on the functional global variable block diagram. If the Boolean output returns a TRUE value, the functional global variable executed. If the Boolean output returns the default value of FALSE, the functional global variable did not execute. Skip functional global variables in time-critical VIs but not in lower priority VIs. In lower priority VIs, you can wait to receive non-default values. Functional global variables can be a lossy form of communication, if a VI overwrites the shift register data before another VI reads the data.

LabVIEW Real-Time Course Manual

3-36

ni.com

Lesson 3 Real-Time Architecture: Design

Functional Global Variables

Demo: NI Example Finder Toolkits and ModulesReal-TimeMultithreaded Communication Functional Global Communication

In a functional global variable, the subVI contains a While Loop with a nested Case structure for read and write access. The above figure shows the read (get data) case and one of the write (set data) cases of the Case structure for a functional global variable. The While Loop contains uninitialized shift registers that store data. A functional global variable receives an action input that specifies which task the VI performs, as shown in the slide above by the Operation input parameter. Any subsequent calls to the functional global variable can access the most recent data. Functional global variables expand functionality beyond a simple global variable. For example, you can maintain a history of values in a functional global variable or you can set a switch to latched until read.

National Instruments Corporation

3-37

LabVIEW Real-Time Course Manual

Lesson 3 Real-Time Architecture: Design

Real-Time FIFO VIsBest


Target Program
Normal Priority Loop
Inter-Thread Communication

TimeCritical Loop

Can specify buffer size Are lossy if buffer fills up Warn of data loss Use deterministic data transfer

Real-Time FIFO VIs


Use the RT FIFO VIs to transfer data between VIs in an application. An RT FIFO acts like a fixed queue, where the first value you write to the FIFO is the first value that you can read from the FIFO. RT FIFOs and LabVIEW queues both transfer data from one VI to another. However, unlike a LabVIEW queue, an RT FIFO ensures deterministic behavior by imposing a size restriction on the data. You must define the number and size of the RT FIFO elements. Both a reader and writer can access the data in an RT FIFO at the same time, allowing RT FIFOs to work safely from within a time-critical VI. Because of the fixed-size restriction, an RT FIFO can be a lossy communication method. Writing data to an RT FIFO when the FIFO is full overwrites the oldest element. You must read data stored in an RT FIFO before the FIFO is full to ensure the transfer of every element without losing data. Check the overwrite output of the RTFIFOWrite VI to ensure that you did not overwrite data. If the RT FIFO overwrites data, the overwrite output returns a TRUE value. A larger FIFO gives the normal priority loop more time to catch up if it falls behind, which can help avoid FIFO overwrites. However, setting a FIFO to be large wastes memory.

LabVIEW Real-Time Course Manual

3-38

ni.com

Lesson 3 Real-Time Architecture: Design

Real-Time FIFO VIs

Demo: NI Example Finder


Toolkits and ModulesReal-TimeCommunicationRT FIFO Communication

Use the RTFIFOCreate VI to create a new FIFO or open a reference to a FIFO that you created in another VI. Use the RTFIFORead and RTFIFOWrite VIs to read and write data to the FIFO. Refer to the LabVIEW Help, available by selecting HelpVI, Function, & How-To Help, for VI reference information about the Real-Time FIFO VIs and the data types supported by the Real-Time FIFO VIs.

National Instruments Corporation

3-39

LabVIEW Real-Time Course Manual

Lesson 3 Real-Time Architecture: Design

Shared Variables
Shared variables are a multipurpose communication tool and can transfer the following:
Non-deterministic data between VIs (global variable) Non-deterministic data between a target and a host Non-deterministic data between hosts or between a host and other computers Deterministic data between real-time VIs or loops (Real-Time FIFO) Deterministic data between targets

Shared variables are a multi-purpose tool designed to facilitate communication in LabVIEW. You can configure shared variables to perform many tasks: Transfer non-deterministic data between VIs. In this capacity, a shared variable functions much like a global variable. This type of shared variable is called a single-process, shared variable. Transfer non-deterministic data between a target and a host. Refer to Lesson 5, Communication, for more information on communicating between a target and host. This type of shared variable is a network-published shared variable, usually with the Real-Time FIFO option enabled. Transfer non-deterministic data between hosts or between a host and other computers. Shared variables implement a publisher/subscriber model that allows non-real-time computers to communicate across a network. This type of shared variable is called a network-published shared variable. Transfer deterministic data between Real-Time VIs or loops (Real-Time FIFO). Shared variables can implement a Real-Time FIFO to transfer data between loops on an RT target. This type of variable is usually a single-process shared variable with the Real-Time FIFO option enabled. Transfer deterministic data between targets. With a dedicated network connection, shared variables can deterministically transfer data between two or more real-time targets over a network. This type of variable is called a Time-Triggered shared variable. For more information, refer to the Using Time-Triggered Networks to Communicate Deterministically Over Ethernet with the LabVIEW 8 Real-Time Module document in the NI Developer Zone. To view the document visit ni.com/info and enter rduttl.

LabVIEW Real-Time Course Manual

3-40

ni.com

Lesson 3 Real-Time Architecture: Design

Creating and Using Shared Variables


Right-click project or library to create a variablemust be part of a library Shared Variable Properties dialog box allows you to configure the variable Choose Single-process, Network-published, or Time Triggered type Configure options such as buffering and Real-Time FIFO Used much like a local or global variable on the block diagram except: Shared variables have error terminals Shared variables configured for read can return a timestamp

Items in the project tree represent shared variables. In order to create a shared variable, rightclick a target or library and select NewVariable. All variables must exist inside of a library. If you create a new variable outside of a library, LabVIEW automatically creates a library. When you create a shared variable, LabVIEW displays a Shared Variable Properties dialog box that allows you to configure the type of shared variable and any other options such as buffering and Real-Time FIFO. To use a shared variable on the block diagram, drag the shared variable from the Project Explorer window to the block diagram. Shared variable references on the block diagram work much like local or global variables. You can right-click a shared variable and select Change to Read or Change to Write to change the direction of the variable. Unlike local or global variables, shared variables contain additional terminals along with the data. Each shared variable has error in and error out terminals, and shared variables set to read can return the timestamp at which the data was written. To display the timestamp, right-click the variable and select Show Timestamp.

National Instruments Corporation

3-41

LabVIEW Real-Time Course Manual

Lesson 3 Real-Time Architecture: Design

Shared Variable Real-Time FIFOs


By enabling the Real-Time FIFO option on a single-process shared variable, you can create a variable which uses Real-Time FIFOs to transfer data

RT FIFO Enabled

When you enable the Real-Time FIFO option, LabVIEW uses Real-Time FIFOs to transfer the data that is written to and read from the shared variable. You can configure the FIFO to be single or multi-element and define the size of the FIFO. When you enable the Real-Time FIFO option, a small icon appears on references to the variable to indicate that it uses Real-Time FIFOs.

LabVIEW Real-Time Course Manual

3-42

ni.com

Lesson 3 Real-Time Architecture: Design

Programming Techniques
Initialization
The FIFO is created the first time a variable is read or written Create and initialize the FIFO by writing a meaningful value to it before your main loop Or allow for extra jitter in the first iteration of a loop using variables Reading the FIFO before a value is written returns error 2222 and a default data value Use the error to check for un-initialized variables.

Shared-variable FIFOs are created the first time a variable is read or written. This results in a slight delay. Therefore, either initialize the variable by reading or writing it before your main loop or allow for a delay in the first iteration of your loop as the FIFO is created. If you read the value of a shared variable before it has been written to in the program, LabVIEW returns error -2222 and the default value for the data type. You can use this error to determine whether the value read is a valid data point, or whether it is the default value. Alternately, if you initialize the variable by writing a meaningful value before starting the loop, you can avoid the possibility of reading the variable before it is written.

National Instruments Corporation

3-43

LabVIEW Real-Time Course Manual

Lesson 3 Real-Time Architecture: Design

Programming Techniques
Identifying Overflow and Underflow Overflow occurs when a writer writes to a multi-element FIFO that is full. Unread data is discarded to make room for new data Error 2221 indicates an overflow Underflow occurs when a reader reads from a multi-element FIFO that is empty. A default data value is returned Error 2220 indicates an underflow

Multi-element RT FIFOs have a fixed memory size and a fixed number of elements, which can be configured in the variable properties dialog. Therefore, multi-element shared variable RT FIFOs introduce the possibility for overflow and underflow errors. An overflow error occurs when a shared variable reference attempts to write to an RT FIFO that is already full. When an overflow occurs, the shared variable returns error -2221 and overwrites the oldest value in the FIFO with the new value. The oldest value is permanently lost. An underflow error occurs when a shared variable reference attempts to read an empty RT FIFO. When an underflow occurs, the shared variable returns error -2220 and returns a default value for the data item. Note that this is different from error -2222, which only applies if a variable has never been written to. Also, error -2220 applies only to multi-element FIFOs, whereas error -2222 applies to all shared variables.

LabVIEW Real-Time Course Manual

3-44

ni.com

Lesson 3 Real-Time Architecture: Design

Programming Techniques
Multiple Readers and Writers Multiple readers and writers block other operations of the same type Multiple readers of a multi-element FIFO will each remove elements, preventing either reader from getting all of the data

Only a single reader and a single writer can access a shared variable at the same time. If a single variable has multiple readers and writers, the readers and writers alternate in accessing the variable like any other resource. Variable references waiting on another reader or writer are blocked and do not continue block diagram execution. Because variables can block with multiple readers or writers, you should use caution when using variables in a time-critical loop. A variable read by a time-critical loop must not be read by any other loop and a variable written by a time-critical loop must not be written by any other loop. Failure to follow these rules can cause the time-critical loop to block and become nondeterministic. Multi-element FIFOs with multiple readers only return each value in the FIFO once. Therefore, if each reader needs to access all of the values written to the FIFO, use a separate variable for each reader.

National Instruments Corporation

3-45

LabVIEW Real-Time Course Manual

Lesson 3 Real-Time Architecture: Design

Low-Level FIFO VIs vs. Shared Variable FIFOs


Shared Variable FIFO Configuration Performance Programming Features Static Write operations must store timestamp Low-Level FIFO VIs Dynamic Faster write operations

Easier configuration Easier dynamic and general operations configuration changes Timestamp available, can be easily changed to other variable types Compatible with LV 7.x and earlier

Notes Shared variables store the timestamp of each piece of data they receive, this makes write operations slightly slower than the low-level FIFO VIs. Shared variable FIFOs can be changed to other shared-variable types. For example, without any significant changes to the block diagram code, a single-process shared variable FIFO can be changed into a network-published shared variable FIFO to communicate with the host. Shared variables debuted in LabVIEW 8.0. Real-time FIFOs are backwards compatible with previous LabVIEW versions.

LabVIEW Real-Time Course Manual

3-46

ni.com

Lesson 3 Real-Time Architecture: Design

Static vs. Dynamic Configuration


Shared Variable FIFOs are configured statically using dialog boxes Simplify programming and wiring Conserve block diagram space Low-level FIFOs are configured dynamically using block diagram code Simplify visually inspecting block diagram Simplify modifying configuration while the program is running Improves control over when the FIFO is created and destroyed

Shared variables are configured statically. This means that the properties of a shared variable are defined through interactive dialog boxes as you write your program, rather defining them at runtime as shared variables are defined for dynamically configured entities such as a Real-Time FIFO. Static configuration simplifies the programming and conserves space on your block diagram. You do not need to create controls and constants for each configuration option. Variables also do not require reference wires that can keep your diagram cleaner. In general, you must know the value of all variable properties before running the program, this means that user input or acquired data cannot determine the values of properties. You can configure some shared variable properties dynamically through VI server calls, but this requires significant programming. Dynamic configuration allows you to specify configuration settings as the program is running. For example, you can set the size of the FIFO based upon user input or by calculating loop frequencies. You also can destroy and re-create a FIFO with new properties as a program is running. For example, you could destroy the FIFO and create a new FIFO with a larger size if overflow errors happen consistently. The ability to create and destroy the FIFO is also useful for managing memory in systems where memory is limited. Dynamic configuration also simplifies determining the properties of the FIFO by inspecting the block diagram.

National Instruments Corporation

3-47

LabVIEW Real-Time Course Manual

Lesson 3 Real-Time Architecture: Design

Exercise 3-2
Inter-Thread Communication
Time to complete: 1 hour

OBJECTIVE

Use global variables, functional global variables, and real-time FIFO VIs for inter-thread communication and compare the methods.

LabVIEW Real-Time Course Manual

3-48

ni.com

Lesson 3 Real-Time Architecture: Design

Class Exercise 3-3


Project Flowchart
Time to complete: 40 min.

Instructor Note: This exercise is best completed as a group project with instructor leadership. Many successful flow chart designs are possible; students will be using the same flow chart design throughout the course. Discuss the solutions in Appendix A at the end of the exercise.

OBJECTIVE

Given a requirements document, create a project flowchart.

National Instruments Corporation

3-49

LabVIEW Real-Time Course Manual

Lesson 3 Real-Time Architecture: Design

SummaryQuiz
1. What are some methods for improving determinism? 2. What inter-thread communication method has the potential for the best determinism? 3. What inter-thread communication method is the easiest to program? 4. Multi-tasking is disabled in a time-critical thread; how does this affect your programming choices?

LabVIEW Real-Time Course Manual

3-50

ni.com

Lesson 3 Real-Time Architecture: Design

SummaryRT Architecture Review

Host Program
User Interface
Network Communication

Target Program
Normal Priority Loop
Inter-Thread Communication

Time-Critical Loop

Data Storage

Data Storage

National Instruments Corporation

3-51

LabVIEW Real-Time Course Manual

Lesson 3 Real-Time Architecture: Design

SummaryMultithreading
Multithreading allows you to differentiate between time-critical tasks and non-critical tasks LabVIEW RT uses a combination of round-robin and preemptive thread schedulingthreads with equal priority use round-robin scheduling The priority levels available include background, normal, above normal, high, and time-critical priority, in order from lowest to highest priority Sleeping is the act of suspending the execution of a VI or thread If any VI in a time-critical thread goes to sleep then the entire thread goes to sleep. Therefore, use only one time-critical VI or loop

LabVIEW Real-Time Course Manual

3-52

ni.com

Lesson 3 Real-Time Architecture: Design

Summary
Inter-thread communication methods:
Good: Global Variables Better: Functional Globals Best: Real-Time Module FIFOs or Shared Variable FIFOs

Improve determinism by:


Avoiding shared resources Avoiding contiguous memory conflicts Avoiding subVI overhead Disabling non-essential options

National Instruments Corporation

3-53

LabVIEW Real-Time Course Manual

Lesson 3

Real-Time Architecture: Design

Exercise 3-1
Objective:

Priority Levels

Adjust the priority levels to understand the effects of priority levels and timing on scheduling a VI. In this exercise, you learn the effects of changing the priority and timing of a VI on a Real-Time system. 1. Open the Real-Time Exercises project from the C:\Exercises\ LabVIEW Real-Time directory. You created this project in exercise 2-2. 2. Add the Priority Trouble VI from the C:\Exercises\LabVIEW Real-Time directory to your RT target in the Project Explorer. 3. Double-click the Priority Trouble VI to open it. 4. Select FileVI Properties. 5. Select Execution from the Category pull-down menu. Notice that the Priority is set to time critical priority (highest). This makes the VI run in the highest priority thread on the Real-Time engine. 6. Close the VI Properties dialog box. 7. Run the VI with the msec to wait control set to 10. The chart displays a sine wave. 8. Slowly decrement the msec to wait control. With each step, the chart display speeds up. However, when the msec to wait control reaches 0, the front panel no longer updates. The reason for this behavior is that the Real-Time engine can no longer communicate with the Real-Time development system front panel. Because the time-critical loop has the highest priority, the user interface thread that updates the front panel cannot use any processor time. As a result, the front panel and VI appear locked. However, the code running on the Real-Time Engine still runs normally. While the msec to wait control is greater than 0, the time-critical loop sleeps for that many milliseconds. During this sleep, the Real-Time Engine schedules non-time-critical tasks like updating the user interface or sending information over TCP/IP. 9. Click Abort. After a short period of time, the Real-Time Development System recognizes that it has lost communication with the Real-Time hardware and displays a warning message.

LabVIEW Real-Time Course Manual

3-54

ni.com

Lesson 3

Real-Time Architecture: Design

10. Press the reset button on the RT target. The reset button is a small white button on the controller that can be depressed with small object, such as a pen. Because the Priority Trouble VI is still running on the target, you must reset the target to stop the VI. 11. Use the Blinking Light VI in your project or the MAX test panels to shut off the light and fan on the temperature chamber.
Note

Wait at least 30 seconds for the Compact Fieldpoint module to reset.

End of Exercise 3-1

National Instruments Corporation

3-55

LabVIEW Real-Time Course Manual

Lesson 3

Real-Time Architecture: Design

Exercise 3-2
Objective:

Inter-Thread Communication

Use global variables, functional global variables, real-time FIFO VIs, and shared variables for inter-thread communication. In this exercise, you learn how to use three methods for inter-thread communication. This exercise is divided into three sections: Method 1: Global Variables, Method 2: Real-Time FIFOs and Method 3: Shared Variables. If time allows, complete the optional fourth section on Method 4: Functional Global Variables (Optional).

Method 1: Global Variables


1. Create a blank project by selecting FileNew Project. 2. Right-click the Untitled Project entry in the Project Explorer and select NewTargets and Devices.
Note Be sure to right-click the Project entry and not the My Computer entry. You can add new targets by right-clicking My Computer. However, targets included under My Computer must be internal targets on the computer, such as PCI Real-Time devices.

3. In the Add Targets and Devices dialog box, select Existing device on remote subnet. 4. Determine which target you are using. a. Expand Real-Time FieldPoint<Module>, where <Module> is the Fieldpoint Network Module that you are using. OR b. Expand the Real-Time PXI and select the target type if you are using PXI. 5. Ensure that the IP Address for the real-time hardware appears in the IP address field. 6. Click OK. 7. Select FileSave and save your project as Inter-Thread Communication.lvproj in the C:\Exercises\LabVIEW Real Time directory. 8. Select FileNew to open the New dialog box. 9. Ensure that a checkmark is in the Add to project checkbox and click OK. 10. Select VIFrom TemplateUserBrowse and navigate to the Normal Priority Loop.vit located in the C:\Exercises\LabVIEW Real-Time directory. 11. Ensure that the Add to project checkbox is checked and click OK.

LabVIEW Real-Time Course Manual

3-56

ni.com

Lesson 3

Real-Time Architecture: Design

12. Select FileSave. 13. Click Yes when prompted to save the new, unsaved files.
Note You will be prompted to save two VIsthe subVI Time Critical Loop and the main VI Normal Priority Loop.

14. Save the Time Critical Loop VI as Global Variable Time Critical Loop.vi in the C:\Exercises\LabVIEW Real-Time directory. 15. Save the Normal Priority Loop VI as Global Variable Normal Priority Loop.vi in the C:\Exercises\LabVIEW Real-Time directory. 16. Close the VIs.
Note If you open a VI which has been targeted to My Computer in an RT target, LabVIEW creates a copy of the VI in memory. By closing the My Computer version of the VI before dragging it, you can avoid any confusion with multiple copies of the VI.

17. Drag the Global Variable Normal Priority Loop VI from the My Computer section of the Project Explorer to the RT Target you created.

Global Variable
18. Select FileNew. 19. Ensure that the Add to project checkbox is checked and click OK. 20. Select Other FilesGlobal Variable to create a new global variable. A global variable is a VI that does not have a block diagram. 21. Place three data items in the global variable as shown in Figure 3-1. a. Control DataArray of double-precision numerics Place an Array shell on the front panel. Place a Numeric Control in the array shell. Right-click the Numeric Control and select Representation Double-Precision from the shortcut menu. Change the array name to Control Data.

National Instruments Corporation

3-57

LabVIEW Real-Time Course Manual

Lesson 3

Real-Time Architecture: Design

b. Result DataDouble-precision numeric indicator


Tip

Place a Numeric Control on the front panel. Right-click the Numeric Control and select Representation Double-Precision. Change the control name to Result Data. Place a Push Button on the front panel. Change the control name to Stop Data.

c. Stop DataPush button

When placing data in a global variable, it does not matter if you place a control or an indicator.

Figure 3-1. Data Items in Global Variable

22. Save the global variable as Communication Global Variable.vi in the C:\Exercises\LabVIEW Real-Time directory. 23. Close the global variable VI. 24. Drag the Communication Global Variable from the My Computer section of the Project Explorer to the RT Target you created.

Time-Critical SubVI
25. Double-click the Global Variable Normal Priority Loop VI in the Project Explorer to open a copy which is targeted to the RT environment. 26. Switch to the block diagram of the VI. 27. Double-click the time-critical subVI on the block diagram to open the subVI and switch to the block diagram. 28. Modify the subVI to use the newly created global variable, as shown in Figure 3-2. a. Place three instances of the Communication Global Variable that you created in step 22 by dragging the Communication global variable from the Project Explorer to the block diagram.

LabVIEW Real-Time Course Manual

3-58

ni.com

Lesson 3

Real-Time Architecture: Design

b. Use the operating tool to select the global variable data item to use in each instance. c. Right-click the Communication global variable and select Change to Read or Change to Write as appropriate for each instance. d. Connect the instances of the global variable to the existing code as shown in Figure 3-2.

Figure 3-2. Time Critical Loop Block Diagram

29. Save and close the VI to return to the main VI.

Normal Priority VI
30. Open the block diagram of the Global Variable Normal Priority Loop VI. 31. Modify the VI as shown in Figure 3-3. a. Place six instances of the Communication Global Variable on the block diagram. b. Place a Flat Sequence structure on the block diagram enclosing the time-critical subVI.
Tip Use the Search button to find a structure, function, or VI on the palette. For more information on the Search button and using palettes, run Navigating_Palettes.exe from the C:\Exercises\LabVIEW Real-Time directory.

c. Right-click the border of the Sequence structure and select Add Frame Before to insert another frame. Use the Sequence structure to guarantee that the global variables are initialized before the Time Critical or Normal Priority loops execute. Using a Sequence structure for initialization purposes is an acceptable use of a Sequence structure. d. Use the Operating tool to select the correct data item and read or write operation for each global variable.

National Instruments Corporation

3-59

LabVIEW Real-Time Course Manual

Lesson 3

Real-Time Architecture: Design

e. To initialize the three global variables in the first sequence frame, right-click each global variable and select CreateConstant. f. Wire as shown in Figure 3-3.

Figure 3-3. Normal Priority Loop Block Diagram

32. Save the VI. 33. Run the VI. Notice that the graph displays the data generated by the time critical loop. Using a global variable can help pass data smaller than 32-bits, such as scalar data, between VIs. However, global variables are a lossy form of communication, meaning the global variable can be overwritten before the data is read. Tasks in a lower priority VI might not have enough processor time to read the data before other tasks in a different VI overwrite the data. 34. Press the Stop button and close all VIs.

Method 2: Real-Time FIFOs


1. Select FileNew to open the New dialog box. 2. Ensure that the Add to project checkbox is checked and click OK. 3. Select the Normal Priority Loop.vit from the path VIFrom TemplateUser. 4. Select FileSave. 5. Click Yes when prompted to save the new, unsaved files.

LabVIEW Real-Time Course Manual

3-60

ni.com

Lesson 3

Real-Time Architecture: Design

6. Save the Time Critical Loop subVI as RT FIFO Time Critical Loop.vi in the C:\Exercises\LabVIEW Real-Time directory. 7. Save the Normal Priority Loop VI as RT FIFO Normal Priority Loop.vi in the C:\Exercises\LabVIEW Real-Time directory. 8. Close the VI. 9. Drag the RT FIFO Normal Priority Loop VI from the My Computer section of the Project Explorer to the RT Target you created. 10. Double-click the VI to open a copy that is targeted to the RT environment. 11. Switch to the block diagram of the VI.

Time-Critical SubVI
12. Double-click the time-critical subVI on the block diagram to open the subVI. 13. Modify the front panel of the VI to contain Error In and Error Out clusters. 14. Connect the clusters to the connector pane of the VI. a. Right-click the icon of the VI and select Show Connector. b. Right-click the connector and select Patterns, then select the 4x2x2x4 connector pane. c. Left-click the lower-left terminal of the connector pane, then click the Error In cluster on the front panel. d. Left-click the lower-right terminal of the connector pane, then click the Error Out cluster on the front panel. 15. Modify the block diagram to use the Real-Time FIFO VIs as shown in Figure 3-4. a. Place three instances of the RTFIFO Create VI on the block diagram. b. Provide a name and data type for each of the FIFOs. Notice that the data type matches the type of data the FIFO stores. c. Right-click the elements in array input of the RTFIFOCreate VI for the Control Data FIFO and select CreateConstant. d. Set the value of the constant to 2. The elements in array input tells the FIFO how many array items are passed each time data is written to the FIFO. e. Place a TRUE Boolean constant on the block diagram and wire it to the return existing? input of each RTFIFOCreate VI

National Instruments Corporation

3-61

LabVIEW Real-Time Course Manual

Lesson 3

Real-Time Architecture: Design

The Normal Priority Loop creates the FIFOs, therefore the time critical loop should return references to the existing FIFOs. f. Place two instances of the RTFIFORead VI on the block diagram. g. Wire the Control Data FIFO reference to one RTFIFORead VI and wire the Stop FIFO reference to the RTFIFORead VI as shown in Figure 3-4. h. Create a shift register to store the current value of the control data. If there is not any data in the FIFO, the VI should continue to use the last control data received. i. Right-click the element input of the RTFIFORead VI that is connected to the Control Data FIFO and select CreateConstant. j. Expand the array constant to show two elements and enter 1 for the first element and 0 for the second element. Setting the elements to 1 and 0 creates a square wave with an amplitude of 1 until the first data is received from the FIFO. k. Wire the constant to the left terminal of the Control Data shift register and wire the shift register through the RTFIFORead VI, as shown in Figure 3-4. l. Wire a a FALSE constant to the element input of the RTFIFORead VI that is connected to the Stop FIFO. If there is not any data in the FIFO, the default needs to be FALSE, so loop continues running. m. Place a RTFIFOWrite VI to write the Result Data to the FIFO. n. Place an Unbundle By Name function on the block diagram to access the status of the error cluster.

Figure 3-4. Real-Time FIFO Time Critical Loop

LabVIEW Real-Time Course Manual

3-62

ni.com

Lesson 3

Real-Time Architecture: Design

16. Save and close the time-critical subVI to return to the main VI.

Normal Priority VI
17. Open the block diagram of the RT FIFO Normal Priority Loop VI. 18. Modify the block diagram to use Real-Time FIFOs for the communication method as shown in Figure 3-5. a. Place three instances of the RTFIFOCreate VI on the block diagram. b. Provide a name and data type for each of the FIFOs. Notice that the data type matches the type of data the FIFO stores. c. Place two instances of the RTFIFOWrite VI on the block diagram. d. Place a RTFIFORead VI on the block diagram. e. Place a Case structure in the While Loop. f. Wire the empty output of the RTFIFO Read VI to the selector terminal of the Case structure. Only update the chart if there is data in the FIFO. g. Place three instances of the RTFIFO Delete VI on the block diagram. These VIs free any resources that are being reserved by the FIFO. h. Place an Unbundle By Name function on the block diagram to access the status of the error cluster. i. Place a Merge Errors VI and a Simple Error Handler VI on the block diagram to handle errors.

National Instruments Corporation

3-63

LabVIEW Real-Time Course Manual

Lesson 3

Real-Time Architecture: Design

j. Wire the diagram as shown in Figure 3-5.

Figure 3-5. Real-Time FIFO Normal Priority Loop

19. Save the VI. 20. Run the VI. 21. Close the VI when you are finished. Use the Real-Time FIFO VIs to transfer data between VIs in an application. A Real-Time FIFO acts like a fixed queue, where the first value you write to the FIFO is the first value that you can read from the FIFO. Real-Time FIFOs and LabVIEW queues both transfer data from one VI to another. However, unlike a LabVIEW queue, an RT FIFO ensures deterministic behavior by imposing a size restriction on the data.

Method 3: Shared Variables


1. Select FileNew to open the New dialog box. 2. Select Normal Priority Loop.vit from the path VIFrom TemplateUser. 3. Ensure that the Add to project checkbox is checked and click OK. 4. Select FileSave.

LabVIEW Real-Time Course Manual

3-64

ni.com

Lesson 3

Real-Time Architecture: Design

5. Click Yes when prompted to save the new, unsaved files. 6. Save the Time Critical Loop subVI as Shared Variable Time Critical Loop.vi in the C:\Exercises\LabVIEW Real-Time directory. 7. Save the Normal Priority Loop VI as Shared Variable Normal Priority Loop.vi in the C:\Exercises\LabVIEW Real-Time directory. 8. Close the VI. 9. Drag the Shared Variable Normal Priority Loop VI from the My Computer section of the Project Explorer to the RT Target you created.

Shared Variables
10. Right-click your RT Target in the Project Explorer and select New Library.
Note You must always create a shared variable inside a project library. Creating a shared variable outside a project library automatically creates a new library.

11. Right-click the new library and select Save. Name the library Communication Shared Variables.lvlib and save it in the C:\Exercises\LabVIEW Real-Time directory. 12. Right-click the library and select NewVariable. 13. Set the following options in the Variable category of the Shared Variable Properties dialog box. a. Name: Control Data b. Data Type: Array of Double c. Variable Type: Single-Process 14. Set the following options in the Real-Time FIFO category of the Shared Variable Properties dialog box. a. Enable Real-Time FIFO: Checked b. Multi-Element: Selected c. Custom: Selected d. Size: 10 arrays e. Array Size: 2 elements 15. Right-click the library and select NewVariable.

National Instruments Corporation

3-65

LabVIEW Real-Time Course Manual

Lesson 3

Real-Time Architecture: Design

16. Set the following options in the Variable category of the Shared Variable Properties dialog box. a. Name: Result Data b. Data Type: Double c. Variable Type: Single-Process 17. Set the following options in the Real-Time FIFO category of the Shared Variable Properties dialog box. a. Enable Real-Time FIFO: Checked b. Multi-Element: Selected c. Custom: Selected d. Number of Doubles: 10 18. Click OK to exit the Shared Variable Properties dialog box. 19. Right-click the library and select NewVariable. 20. Set the following options in the Variable category of the Shared Variable Properties dialog box. a. Name: Stop b. Data Type: Boolean c. Variable Type: Single-Process 21. Set the following options in the Real-Time FIFO category of the Shared Variable Properties dialog box. a. Enable Real-Time FIFO: Checked b. Single-Element: Selected 22. Click OK to exit the Shared Variable Properties dialog box. 23. Right-click the Communication Shared Variables.lvlib and select Save All (this Library).

Time-Critical SubVI
24. Double-click the Shared Variable Normal Priority Loop VI in the Project Explorer to open a copy which is targeted to the RT environment. 25. Modify the front panel of the VI to contain an Error In and Error Out cluster. 26. Connect the clusters to the connector pane of the VI. 27. Switch to the block diagram of the VI. 28. Double-click the time-critical subVI on the block diagram to open the subVI.

LabVIEW Real-Time Course Manual

3-66

ni.com

Lesson 3

Real-Time Architecture: Design

29. Modify the subVI to use the newly created shared variables, as shown in Figure 3-6. a. Add error in and error out clusters. b. Connect the clusters to the connector panel of the VI. c. Place a copy of each of the shared variables on the block diagram by dragging each variable from the Project Explorer. d. Right-click each shared variable and select Change to Read or Change to Write as necessary. e. Place an Unbundle By Name function on the diagram to access the status of the error cluster. f. Wire the diagram as shown in Figure 3-6. Notice that shared variables, unlike global variables, provide error clusters to control data flow.

Figure 3-6. Time Critical Loop Block Diagram

30. Save and close the VI to return you to the main VI.

Normal Priority VI
31. Open the block diagram of the Shared Variable Normal Priority Loop VI. 32. Modify the VI as shown in Figure 3-7. a. Place two copies of each shared variable on the block diagram. b. Place an Unbundle By Name function on the diagram to access the status input of the error cluster. c. Place a Merge Errors VI and a Simple Error Handler VI on the block diagram to handle errors.

National Instruments Corporation

3-67

LabVIEW Real-Time Course Manual

Lesson 3

Real-Time Architecture: Design

d. Wire as shown in Figure 3-7.

Figure 3-7. Normal Priority Loop Block Diagram

33. Save the VI. 34. Run the VI. Notice that the graph displays the data generated by the time critical loop. A shared variable provides many of the same advantages of a Real-Time FIFO. A shared variable also provides increased scalability, as it can be easily upgraded to a network-published shared variable to transfer data back to the host. The primary difference between Real-Time FIFOs and shared variables is that shared variables are configured statically, whereas Real-Time FIFOs are created and configured at run time. If you need to determine aspects of the communication mechanism at run time, such as the buffer size, you should use Real-Time FIFOs. Otherwise, use shared variables, because they reduce the amount of configuration code you need to write.

Method 4: Functional Global Variables (Optional)


1. Select FileNew to open the New dialog box. 2. Select Normal Priority Loop.vit from the path VIFrom TemplateUser. Notice that LabVIEW added the template you used in the previous section to the User folder. You no longer have to browse for the template. 3. Ensure that the Add to project checkbox is checked and click OK. 4. Select FileSave and click Yes when prompted to save the new, unsaved files. 5. Save the Time Critical Loop subVI as FGV Time Critical Loop.vi in the C:\Exercises\LabVIEW Real-Time directory. 6. Save the Normal Priority Loop VI as FGV Normal Priority Loop.vi in the C:\Exercises\LabVIEW Real-Time directory.

LabVIEW Real-Time Course Manual

3-68

ni.com

Lesson 3

Real-Time Architecture: Design

7. Close the VI. 8. Drag the FGV Normal Priority Loop VI from the My Computer section of the Project Explorer to the RT target you created.

Functional Global Variable


9. Right-click your RT target in the project and select NewVI to create a blank VI. 10. Save the VI as Communication FGV.vi in the C:\Exercises\ LabVIEW Real Time directory. 11. Complete the front panel of the VI as shown in Figure 3-8. a. Place an Enum control on the front panel, and label it Command. b. Right-click the Command control and select Edit Items to add the following items to the control:
Set Control Data Set Result Data Set Stop Data Get Control Data Get Result Data Get Stop Data

c. Place an Array of numeric controls with double-precision representation on the front panel and label it Control Data In. d. Place an Array of numeric indicators with double-precision representation on the front panel and label it Control Data Out. e. Place a Numeric Control with double-precision representation on the front panel and label it Result Data In. f. Place a Numeric indicator with double-precision representation on the front panel and label it Result Data Out. g. Place a Push Button control on the front panel and label it Stop Data In. h. Place a Square LED on the front panel and label it Stop Data Out. i. Place Error In and Error Out clusters on the front panel.

National Instruments Corporation

3-69

LabVIEW Real-Time Course Manual

Lesson 3

Real-Time Architecture: Design

Figure 3-8. Functional Global Variable Front Panel

12. Modify the connector pane and icon as shown in Figure 3-9. a. Right-click the icon for the VI and select Edit Icon to create an icon for the VI. b. Label the icon as shown in Figure 3-9. c. Select OK when you have completed editing the icon. d. Right-click the icon and select Show Connector to edit the connector pane for the VI. e. Right-click the icon and select Patterns to choose a pattern for the connector pane. The standard connector pane is on the bottom row, third column. It has a 4-2-2-4 connector pane.

LabVIEW Real-Time Course Manual

3-70

ni.com

Lesson 3

Real-Time Architecture: Design

f. Wire each control and indicator to the appropriate pane of the connector pane.

Figure 3-9. Functional Global Variable Icon and Connector Pane

13. Build the block diagram as shown in Figure 3-10.


Note The figures in this book do not use icon view for control terminals in order to save space. You can right-click a control terminal and select View As Icon to make your controls match the figures in the book. You also can select ToolsOptionsBlock Diagram and remove the checkmark from the Place front terminals as icons checkbox.

a. Wire the error clusters to a case structure. Pass the error through the Error case. b. Place a While Loop on the block diagram inside the No Error case. c. Add three shift registers to the While Loop. d. Place a TRUE Boolean constant on the block diagram and wire it to the loop conditional terminal. e. Place a Case structure inside the While Loop. f. Wire the Command terminal to the selector terminal of the Case structure. g. Right-click the border of the case structure and select Add Case for Every Value.

National Instruments Corporation

3-71

LabVIEW Real-Time Course Manual

Lesson 3

Real-Time Architecture: Design

h. Complete the Set Control Data case as shown in Figure 3-10.

Figure 3-10. Functional Global Variable Block Diagram

i. Complete the Set Result Data case as shown in Figure 3-11.

Figure 3-11. Set Result Data Case

LabVIEW Real-Time Course Manual

3-72

ni.com

Lesson 3

Real-Time Architecture: Design

j. Complete the Set Stop Data case as shown in Figure 3-12.

Figure 3-12. Set Stop Data Case

k. Complete the Get Control Data case as shown in Figure 3-13.

Figure 3-13. Get Control Data Case

National Instruments Corporation

3-73

LabVIEW Real-Time Course Manual

Lesson 3

Real-Time Architecture: Design

l. Complete the Get Result Data case as shown in Figure 3-14.

Figure 3-14. Get Results Data Case

m. Complete the Get Stop Data case as shown in Figure 3-15.

Figure 3-15. Get Stop Data Case

LabVIEW Real-Time Course Manual

3-74

ni.com

Lesson 3

Real-Time Architecture: Design

14. Wire the remaining error clusters and other terminals. 15. Select FileVI Properties, and select the Execution category. 16. Change the Priority of the VI to subroutine. Setting the priority to subroutine allows you to skip a call to the VI if the VI is already being called from another location in the code. Using subroutine priority and the Skip Subroutine Call if Busy option allows you to maintain determinism in your time-critical loop. 17. Save the VI.

Time-Critical SubVI
18. Double-click the FGV Normal Priority Loop VI in the Project Explorer to open a copy that is targeted to the RT environment. 19. Switch to the block diagram of the VI. 20. Double-click the time-critical subVI on the block diagram to open the subVI. 21. Modify the front panel of the VI to contain an Error In and Error Out cluster. 22. Connect the clusters to the connector pane of the VI. 23. Modify the block diagram of the VI to use the Communication FGV VI that you just created, as shown in Figure 3-16. a. Place three instances of the Communication FGV VI that you created on the block diagram by dragging the VI from the Project Explorer. b. Right-click the Command input for each instance of the Communication FGV VI and select the appropriate comment, then select CreateConstant to choose the operation of the FGV. c. Right-click each instance of the Communication FGV VI and select Skip Subroutine Call if Busy. The Skip Subroutine Call if Busy option instructs LabVIEW to skip the subVI if the subVI is currently being used in another thread. Selecting this option prevents the VI from stalling the time critical loop.

National Instruments Corporation

3-75

LabVIEW Real-Time Course Manual

Lesson 3

Real-Time Architecture: Design

d. Wire the error clusters through the VI as shown.

Figure 3-16. FGV Time Critical Loop Block Diagram

24. Save and close the VI.

FGV Normal Priority Loop VI


25. Open the block diagram of the FGV Normal Priority Loop VI. 26. Modify the block diagram as shown in Figure 3-17. a. Place six instances of the Communication FGV VI on the block diagram. b. Add a shift register to the While Loop. c. Initialize the Communication Functional Global Variable before the While Loop executes and before the time-critical subVI executes, by adding constants as shown in Figure 3-17. Notice that the use of Functional Global Variables provides an inherent dataflow, which provides a distinct advantage over global variables. d. Place a Merge Errors VI and a Simple Error Handler VI on the block diagram to handle errors.

Figure 3-17. FGV Normal Priority Loop Block Diagram

LabVIEW Real-Time Course Manual

3-76

ni.com

Lesson 3

Real-Time Architecture: Design

27. Save the VI. 28. Run the VI. Functional global variables can accomplish more than a simple global variable. You can ass functionality to the functional global variable. For example, you can maintain a history of values in the VI or you can set a Boolean value to latch until read. 29. Close all the VIs.

End of Exercise 3-2

National Instruments Corporation

3-77

LabVIEW Real-Time Course Manual

Lesson 3

Real-Time Architecture: Design

Exercise 3-3
Objective:

Project Flowchart
In this exercise, you analyze the requirements document for the project and develop a flowchart. 1. Read the following Requirements Document.

Given a requirements document, create a project flowchart.

The abbreviations NPL and TCL are used throughout this course. NPL stands for normal priority loop and TCL stands for time-critical loop.
Note
Start of Requirements Document

Overview
A temperature chamber provides a temperature ramp for the incubation of cells. This program controls a temperature chamber. The temperature ramp in the chamber is achieved through the control of a lamp. A fan simulates disturbance to the temperature chamber. The entire control setup is shown in Table 3-1.
Table 3-1. Overview of Control Setup

Temperature Chamber Thermocouple <--I/O-->

Target Control Communicate Log TCP/IP

Host Set control setpoint profile View temp GUI: Start, Abort, & Disturbance

Target temperature ranges are confined from room temperature to 75 C. The user inputs a range of temperatures and hold times. The sum of the hold times never exceeds 15 minutes. For example, a setpoint profile of:
[0 s, 25 C], [10 s, 30 C], [20 s, 30 C]

means to start at 25 C, ramp up to 30 C in 10 seconds, and hold at 30 C for another 10 seconds.

LabVIEW Real-Time Course Manual

3-78

ni.com

Lesson 3

Real-Time Architecture: Design

The control algorithm used for the system is PID. The system has already been modeled as a first-order system and the PID values determined. Use the following PID values: P: 15 I: 0.5 D: 0.01

For more information about PID and control theory see Appendix A. There are two separate implementations of this system. One lab needs a response rate of 10 Hz with a maximum jitter of 1 Hz. This lab is implemented using a Compact FieldPoint system. The second lab needs a response rate of 100 Hz with a maximum jitter of 0.5 Hz. This lab is implemented using a PXI system.

Implementation #1Compact FieldPoint


[c]FP-2000 or 2010 Network module [c]FP-PWM-520 module and TB-1 [c]FP-TC-120 module and TB-3 Temperature chamber: 12 volt lamp, J-type thermocouple, and a 12 volt fan to simulate disturbance

Implementation #2PXI
PXI chassis PXI Controller (recommended: PXI-8186 or PXI-8176) PXI-6040E DAQ device; counter outputs are used for pulse width modulation (PWM) to control the fan and lamp, analog input reads the temperature Signal conditioning circuit Temperature chamber: 12 volt lamp, J-type thermocouple, and 12 volt fan

Host Program
The user interface is implemented on a Windows XP computer. The user interface communicates with a data acquisition and control program running on a real-time operating system on the target hardware. The user interface allows the user to set the temperature ramp characteristics. The temperature ramp characteristics include the setpoint profile and the PID values. Although the PID values have already been determined, the user should be able to adjust these values from the user

National Instruments Corporation

3-79

LabVIEW Real-Time Course Manual

Lesson 3

Real-Time Architecture: Design

interface. Figure 3-18 shows an example user interface with the default values set. After the user has set the temperature ramp characteristics and PID values, pressing the Start button sends the data to the target program and instructs the target program to begin the temperature ramp. You can click the Disturbance button at any time during a test. In case of emergency, an Emergency Stop button is provided to stop the hardware. The target program must respond to the Emergency Stop and Apply Disturbance buttons as soon as possible. The user can also provide a name for the log file on the target, and the IP address of the target hardware. Information displayed to the user includes the current Lamp Power output to the lamp as a percentage of maximum power, an LED indicator whether the Disturbance (fan) is on or off, timestamp of last value read, and a chart displaying the actual temperature and current target setpoint. The user interface also displays the current state (Control State) of the system, which includes Idle, Configuration, and Run. The Idle state designation implies that no temperature ramp is currently running, or that there is no TCP connection to the system. The Configuration state designation implies that the control profile and PID gains are being sent to the target system. The Run state designation immediately follows the Configuration state and implies that the system is currently running a temperature ramp. If the Host has lost TCP connection to the system and reconnects while the system is in the midst of a ramp, the host displays to the user that the system is currently in the Run state and continues displaying the current data.

LabVIEW Real-Time Course Manual

3-80

ni.com

Lesson 3

Real-Time Architecture: Design

Figure 3-18. Example User Interface

The following is a summary of the major host program tasks: Transfer PID values and setpoint profile on Start command Send Emergency Stop command through TCP as needed Send Disturbance command through TCP as needed Receive and chart TCP data from target

Target Program
When idle, the target program waits for configuration data and the Start command from the host. When received, the program configures the system. After you configure the system, the program begins the temperature ramp. The program must monitor continually for the Emergency Stop command and the Disturbance command during the temperature ramp, and implement them as soon as possible. After the temperature ramp is completed or terminated, the program waits for the next set of configuration data from the host.

National Instruments Corporation

3-81

LabVIEW Real-Time Course Manual

Lesson 3

Real-Time Architecture: Design

Figure 3-19 shows a high level flowchart of the expected behavior of the target program. It illustrates the expected four states of the target program: Initialize, Configuration, Run, and Close.

Initialize Resource, Variables, etc.

Get Configuration Data from Host

Run TCL and NPL Loops

Unrecoverable Error? No

Yes

Close Resources

No

Config Request Complete? Yes

Figure 3-19. High-Level Flow Chart of the Target Program

During the Run state, this program retrieves the temperature from a thermocouple and a time stamp specifying when the temperature was read. The data retrieved determines whether to increase, hold, or decrease the temperature by using PID control to determine output levels for the lamp. Disturbance to the system is simulated by turning on the fan. A disturbance selection sends full power to the fan until the disturbance is deselected. This program also logs the retrieved data on the target. This data must be accurately time-stamped. The system must log the data in a tab-delimited ASCII file. Data is logged for every temperature read. Logging of data must not affect the system determinism in any form. Table 3-2 shows an example of the expected log file.
Table 3-2. Log File

Setpoint (C) Temp (C) 28 28 25.00 26.01

Disturbance Time Stamp Lamp Power (T/F) 36:00:00 36:00:01 80 % 75 % F F

Setpoint, temperature, time stamp, lamp power, and disturbance is sent to the host program at each cycle through TCP using port 1080 for the user interface.

LabVIEW Real-Time Course Manual

3-82

ni.com

Lesson 3

Real-Time Architecture: Design

The following is a summary of the major target program tasks:


End of Requirements Document

Monitor for configuration data and start command Implement configuration data when received Control temperature chamber as specified Monitor for Emergency Stop and Disturbance commands Implement Emergency Stop and Disturbance commands Transfer data to host through TCP Log data to file

National Instruments Corporation

3-83

LabVIEW Real-Time Course Manual

Lesson 3

Real-Time Architecture: Design

2. Referring to the Requirements Document, create a flowchart for the time-critical loop on the target.

LabVIEW Real-Time Course Manual

3-84

ni.com

Lesson 3

Real-Time Architecture: Design

3. Referring to the Requirements Document, create a flowchart for the normal priority VI on the target.

National Instruments Corporation

3-85

LabVIEW Real-Time Course Manual

Lesson 3

Real-Time Architecture: Design

4. Referring to the Requirements Document, create a flowchart for the code that runs on the host.

LabVIEW Real-Time Course Manual

3-86

ni.com

Lesson 3

Real-Time Architecture: Design

Note A solution flowchart is included in Appendix A and in the C:\Solutions\LabVIEW Real Time folder. This flowchart is the model for future

project exercises. You may want to compare these flowcharts to the ones you just created. Many successful flowcharts are possible; the flowcharts used for the course project are well designed, but also contains many drawbacks that you explore in later lessons.

End of Exercise 3-3

National Instruments Corporation

3-87

LabVIEW Real-Time Course Manual

Lesson 3

Real-Time Architecture: Design

Self-Review
Quiz
1. Which method can increase your system determinism most effectively and easily? a. Reduce the use of shared resources. b. Remove unnecessary code. c. Purchase and implement faster hardware. d. Use Real-Time FIFOs to communicate between the time-critical thread and the normal priority thread. 2. Which is NOT an example of a shared resource? a. Timing VIs b. Global Variables c. Memory Manager d. File I/O

Job Aid
Use the following job aid to determine the best inter-thread application method for a given situation. Global Variables: excellent choice when transferring data that is only accessed once in the time-critical subVI, when jitter is not important and when care has been taken to avoid race conditions. Functional Global Variables: excellent choice when using in a time-critical loop where losing an iteration of data is acceptable and where reduced jitter is desired. Real-Time FIFOs: excellent choice when data loss is not acceptable and when reduced jitter is important. Use Real-Time FIFOs when you need to configure the communication parameters dynamically. Shared Variables: Same benefits as Real-Time FIFOs, shared variables also reduce configuration code and are easily scalable to network-published variables. Use shared variables when you can statically configure a communication mechanism.

LabVIEW Real-Time Course Manual

3-88

ni.com

Lesson 3

Real-Time Architecture: Design

Notes

National Instruments Corporation

3-89

LabVIEW Real-Time Course Manual

Lesson 3

Real-Time Architecture: Design

Notes

LabVIEW Real-Time Course Manual

3-90

ni.com

Lesson 4 Timing Applications and Acquiring Data

Lesson 4 Timing Applications and Acquiring Data

Topics A. Timing Control Loops B. Software Timing C. Hardware Timing D. Event Response

Introduction
In this lesson, you develop the time-critical portion of a target program. This typically involves control parameters, hardware input and output, and timing. This lesson focuses on software and hardware methods of timing a control loop.

National Instruments Corporation

4-1

LabVIEW Real-Time Course Manual

Lesson 4 Timing Applications and Acquiring Data

Timing Control Loops


Provide sleep to allow time for lower priority threads to execute Reduce application jitter Use software or hardware methods to time control loops
Software jitter is typically greater than hardware jitter Software jitter can be around 15 s, which is sufficient for many applications Hardware timing is not available on [c]FP systems

A. Timing Control Loops


Because of the preemptive nature of the RTOS on RT Series devices, a time-critical application thread can monopolize the processor on the device. A thread might use all processor resources and not allow lower priority threads in the application to execute. The time-critical task must periodically yield processor resources to the lower-priority tasks so they can execute. By properly separating the time-critical task from lower priority tasks, you can reduce application jitter. You can use software methods or hardware methods to time control loops. Before discussing timing and sleep, here are some differences between software and hardware control. Software control is less deterministic than hardware control because code execution time usually varies more than a timebase governed by a hardware oscillator. An example of a hardware oscillator is the 20 MHz timebase on most Multifunction DAQ devices. Depending on the timebase and accuracy of the oscillator, hardware jitter ranges from one to a few hundred nanoseconds. In contrast, software jitter within the real-time OS is around 15 s.

LabVIEW Real-Time Course Manual

4-2

ni.com

Lesson 4 Timing Applications and Acquiring Data

Timing Control Loops


Software Timing (all real-time platforms)
Timing tied to the operating system millisecond clock Loop timing achieved with wait functions Wait functions masks software jitter within loop but introduces a minor amount of its own jitter

Hardware Timing (not available on [c]FP)


Timing tied to the microsecond processor clock or an external clock Clock is independent from OS timing Hardware jitter depends on accuracy of the clock

You can use software methods or hardware methods to time control loops. The software method is available for all RT platforms. The hardware method is available only for controllers that use a Pentium 3 or 4, or for platforms that can utilize an external clock. For the platforms used in this course, PXI can time control loops using the hardware or the software method, and Compact FieldPoint can use only the software method. You can use software timing on any RT platform, because software timing accesses the operating system clock that is available on all platforms. You can use hardware timing only on some platforms. One method of hardware timing accesses the processor clock, which can only be used on Pentium 3 or 4 processors. Compact FieldPoint and FieldPoint modules do not use Pentium 3 or 4 processors. The second method of hardware timing accesses an externally provided clock, such as the clock on a Multifunction DAQ board. Compact FieldPoint and FieldPoint modules cannot access external clocks for timing.

National Instruments Corporation

4-3

LabVIEW Real-Time Course Manual

Lesson 4 Timing Applications and Acquiring Data

Software Timing
Three standard methods of accomplishing software timing: Insert Wait function in loop Insert Wait Until Next Multiple function in loop Replace looping mechanism with a timed loop
Looping mechanism

Configure

Acquire, Control, and Output

Close

Real-Time Module Control Architecture

B. Software Timing
LabVIEW provides three software timing methods. The first two methods are LabVIEW wait functions that you can insert in your code to add sleep time. The third method is a timed loop and is chosen for its other benefits. All three methods have a millisecond resolution when used for software timing.

LabVIEW Real-Time Course Manual

4-4

ni.com

Lesson 4 Timing Applications and Acquiring Data

Software TimingWait

Causes VI to sleep for specified time Do not use in parallel with time-critical code Code execution time can vary, therefore total loop execution time varies
Code execution Wait (ms) execution Code execution

OS ms timer value = 112

OS ms timer value = 122

Wait Function
The Wait function causes a VI to sleep for the specified amount of time. For example, if the operating system millisecond timer value is 112 ms when the Wait function executes, and the Count (mSec) input equals 10, then the function returns when the millisecond timer value equals 122 ms. Avoid using this VI in parallel with anything in a time-critical priority. If the Wait function executes first, the whole thread sleeps until the Wait finishes, and the code in parallel does not execute until the Wait function finishes. The resulting loop period is the code execution time plus the Count (mSec) time.

National Instruments Corporation

4-5

LabVIEW Real-Time Course Manual

Lesson 4 Timing Applications and Acquiring Data

Software TimingWait Until Next Multiple

Thread sleeps until the operating system millisecond timer equals a multiple of the Count (mSec) input First loop iteration is indeterminate
Code execution Wait execution Code execution Wait execution

OS ms timer value = 30

OS ms timer value = 42

OS ms timer value = 100

OS ms timer value = 109

OS ms timer value = 200

Wait Until Next Multiple Function


The Wait Until Next Multiple function causes a thread to sleep until the operating system millisecond timer value equals a multiple of the Count (mSec) input. For example, if the Wait Until Next Multiple function executes with a Count (mSec) input of 100 ms and the operating system millisecond timer value is 112 ms, the VI sleeps until the millisecond timer value equals 200 ms because 200 ms is the first multiple of 100 ms after the Wait Until Next Multiple function executes. Use the Wait Until Next Multiple function to synchronize a loop with the operating system millisecond timer value multiple. A loop has a period of Count (mSec) if the Wait Until Next Multiple function executes in parallel with other code in the same loop. However, the loop does not have the period of Count (mSec) if the code takes longer to execute than the Count (mSec). However, avoid placing the Wait Until Next Multiple function in parallel with other code because doing so can cause incorrect timing of a control system. Because of the dataflow properties of LabVIEW programming, the Wait Until Next Multiple function can execute before, after, or between the execution of the analog input and output. The behavior of the loop differs depending on when the Wait Until Next Multiple function executes. Instead, use a sequence structure to control when the Wait Until Next Multiple function executes, as shown above. In the figure above, the code may take a variable amount of time to finish executing, but by calling Wait Until Next Multiple function afterwards, you enforce a loop frequency of 10 Hz (1/100 ms). The maximum loop rate that can be achieved using this method is 1 kHz with a wait multiple of 1 ms.

LabVIEW Real-Time Course Manual

4-6

ni.com

Lesson 4 Timing Applications and Acquiring Data

Software TimingWait Until Next Multiple

Add a Wait before the loop to initialize the timer Even first iteration of loop time is determinate with this method
Wait execution Code execution Wait execution Code execution Wait execution

13

100

112

200

209

300

Because Wait Until Next Multiple only accepts integers, loop rates are limited to only a few frequencies: 1000, 500, ~333, 250, 200, ~167 Hz, and so on. In the slide above, the 100 ms timer is initialized by calling the Wait Until Next Multiple function immediately before the While Loop begins. Otherwise, the loop time for the first iteration would be indeterminate. In the While Loop, the Wait Until Next Multiple function is enclosed in a sequence structure to assure that the delay is added after the code has finished. In this way, the order of execution is guaranteed. Before deciding on a millisecond multiple, you must ensure that the code in your loop can execute faster than the wait multiple. If your code takes slightly longer than the ms multiple, then your loop actually waits 2 ms multiples, because code was running when the first ms multiple arrived. In this case, the wait until ms multiple is not aware that the first ms multiple occurred and waits until a second ms multiple occurs before returning. In addition to controlling loop rates, the Wait Until Next Multiple function forces timecritical VIs to sleep until the wait is finished. When a VI sleeps, it relinquishes the CPU, allowing other VIs or threads to execute. Sleep time is required in time-critical VIs, because the user interface and other background processes need CPU time to survive.

National Instruments Corporation

4-7

LabVIEW Real-Time Course Manual

Lesson 4 Timing Applications and Acquiring Data

Software TimingWait Until Next Multiple

TWC (worst case execution time) < T (millisecond multiple + jitter)


SW timing, T = 5 ms +/- inherent jitter Code execution time, Te Worst case software jitter, Tj Worst case time, Twc (t)

The Wait Until Next Multiple function masks software jitter within the loop. The function has some inherent jitter, which is acceptable for many real-time applications. In this example, the Wait Until Next Multiple function synchronizes with each 5 ms tick of the OS clock, allowing the loop to achieve 200 Hz software-timed analog input. The timeline illustrates the 5 ms wait multiple at T, the actual time required to execute the code at Te, worst case jitter at Tj, and worst case time at TWC. As long as the worst case time is smaller than the wait multiple, the actual loop period equals the wait multiple, plus or minus the jitter incurred by the function itself.

LabVIEW Real-Time Course Manual

4-8

ni.com

Lesson 4 Timing Applications and Acquiring Data

Software TimingTimed Loop


Use instead of a For or While Loop when appropriate Choose the ms timer on the timed loop to use software timing Use the Timed Loop to develop VIs with the following:
Multi-rate timing capabilities Feedback on loop execution Timing characteristics that change dynamically

LabVIEW Timed Loop (Windows and ETS Only)


A Timed Loop executes an iteration of the loop at the period you specify. Use the Timed Loop when you want to develop VIs with multi-rate timing capabilities, feedback on loop execution, or timing characteristics that change dynamically. Because the Timed Loop automatically imposes sleep as needed to achieve the loop rate you specify, there is no need to use a Wait or Wait Until Next Multiple function to add sleep time in the loop. Refer to Lesson 8, Advanced Topics, to learn more about when and how to use Timed Loops.

National Instruments Corporation

4-9

LabVIEW Real-Time Course Manual

Lesson 4 Timing Applications and Acquiring Data

Hardware TimingNot Available on [c] FieldPoint


Four standard methods of accomplishing hardware timing exist
Insert Wait function with s resolution in loop Insert Wait Until Next Multiple function with s resolution in loop Replace loop with a Timed Loop linked to s clock or external clock Use DAQmx VIs to connect to external clock
Looping mechanism

Configure

Acquire, Control, and Output

Close

Real-Time Module Control Architecture

C. Hardware Timing
LabVIEW provides four hardware timing methods. The first three methods are similar to software timing methods, but access a microsecond clock on the processor rather than the millisecond operating system clock. These three methods are the Wait function, the Wait Until Next Multiple function, and the Timed Loop. The fourth method involves using DAQmx functions to connect to an external clock, such as the clock on a Multifunction DAQ device. You can use an external clock with the DAQmx VIs to time data acquisition or as an input on the Timed Loop.

LabVIEW Real-Time Course Manual

4-10

ni.com

Lesson 4 Timing Applications and Acquiring Data

Hardware Timings Timing Functions


Choose s timing for the Wait function, Wait Until Next Multiple function, and Timed Loop to achieve greater loop rate resolution Enables loop rates of 1 MHz, 500 KHz, ~333KHz, 250 KHz, 200 KHz, ~167 KHz, and so on Worst case code execution time must still be less than T Use same programming architecture as with software timing

Microsecond Timing Functions


If you are targeted to an RT target that allows microsecond timing, you can use the microsecond clock for the wait functions. If you are not targeted to an acceptable target, you can still select microsecond timing, but the program uses the millisecond operating system clock instead. Using the microsecond clock allows for more loop rate options: With a ms (millisecond) clock, loop rates are 1/X ms = 1KHz, 500 Hz, ~333 Hz, 250 Hz, and so on With a s (microsecond) clock, loop rates are 1/X s = 1 MHz, 500 KHz, ~333KHz, 250 KHz, and so on

National Instruments Corporation

4-11

LabVIEW Real-Time Course Manual

Lesson 4 Timing Applications and Acquiring Data

Hardware TimingTimed Loop

Choose the s timer Or connect an external clock

Timed Loops using a Hardware Clock


When you configure a Timed Loop, you can choose the MHz clock (s timer), if you are targeted to an appropriate target. You also can choose to connect an external clock to a terminal. You can access the configuration window by double-clicking the Timed Loop.

LabVIEW Real-Time Course Manual

4-12

ni.com

Lesson 4 Timing Applications and Acquiring Data

Hardware TimingDAQmx

Demo: NI Example Finder


Hardware Input and OutputDAQmxControlGeneral PID Control-Single Channel.vi

Accessing an External Clock with DAQmx


You can use NI data acquisition hardware and NI-DAQmx to achieve a sleep resolution much finer than 1 kHz. Hardware timing uses the DAQ device internal clock or an external clock to control when a Read VI or a Write VI executes within a loop. With hardware timing, the loop rate matches the rate programmed into the Sample Clock VI. You must choose the Hardware Timed Signal Point sample mode input. Overwrite errors can occur, however, when the requested scan rate is too fast relative to the code execution time. In other words, if the CPU is not powerful enough to execute the code within the loop at least as fast as the scan rate, the FIFO eventually overflows with new, unread data.

National Instruments Corporation

4-13

LabVIEW Real-Time Course Manual

Lesson 4 Timing Applications and Acquiring Data

Exercise 4-1 Software and Hardware Sleep


Time to complete: 10 min.

OBJECTIVE

Using pre-existing code, implement software or hardware timing to the code.

LabVIEW Real-Time Course Manual

4-14

ni.com

Lesson 4 Timing Applications and Acquiring Data

Event ResponseMonitoring for Events


Use the point-by-point VIs to monitor for the following events: Triggering datalogging Triggering an alarm Performing a calculation

D. Event Response
With real-time event response, you can respond to a single event within a given amount of time. However, to respond to an event, the VI must know that the event has happened. Some common events include detecting a peak in a measurement or detecting when a threshold has been reached. You can use the Point-by-Point Signal Analysis VIs to watch for these types of events.

National Instruments Corporation

4-15

LabVIEW Real-Time Course Manual

Lesson 4 Timing Applications and Acquiring Data

Event ResponseDigital Change Detection


Common event response application Must have a digital I/O device that supports change detection

(NI-DAQmx only) Another common event response application involves watching for a digital line change, which is useful when watching for an alarm trigger. The slide above uses the DAQmx digital change functionality with the Timed Loop. Notice that the digital line is connected to the clock terminal of the Timed Loop. When the digital change happens or a timeout occurs, the timed loop wakes up and processes the code in the loop.

LabVIEW Real-Time Course Manual

4-16

ni.com

Lesson 4 Timing Applications and Acquiring Data

Exercise 4-2 Time-Critical VI


Time to complete: 60 min.

OBJECTIVE

To create the time-critical portion of the project.

National Instruments Corporation

4-17

LabVIEW Real-Time Course Manual

Lesson 4 Timing Applications and Acquiring Data

SummaryQuiz
Which clock provides finer resolutionthe processor clock or the operating system clock? What are the benefits of timing a control loop?

LabVIEW Real-Time Course Manual

4-18

ni.com

Lesson 4

Timing Applications and Acquiring Data

Exercise 4-1A cFP Software Sleep


Objective: To use pre-existing code, to implement software timing to the code. In this exercise, you implement software timing for an existing piece of code. The purpose of the existing VI is to turn the heater on and off on the temperature chamber within a set number of seconds. 1. Open the Real-Time Exercises project from the C:Exercises\ LabVIEW Real Time directory. You created this project in exercise 2-2. 2. Add the cFP-Sleep.vi from the C:\Exercises\LabVIEW Real-Time directory to your RT target in the Project Explorer. 3. Double-click the CFP-Sleep VI to open it.

Front Panel
1. Modify the front panel of the VI to include a numeric control with U32 representation for the wait time, as shown in Figure 4-1.

Figure 4-1. FieldPoint Sleep Front Panel

Block Diagram
1. Modify the block diagram of the VI as shown in Figure 4-2. a. Place a Flat Sequence structure to control the order of operations for the software timing. b. Place a Wait Express VI inside the Sequence structure. Use the Wait function you prefer; Figure 4-2 uses the Wait function from the Real-Time palette. For the Real-Time wait function, select mSec for the counter units. Leave the size of the internal counter at 32-bit. c. Wire the Wait Time (ms) control to the Wait function.

National Instruments Corporation

4-19

LabVIEW Real-Time Course Manual

Lesson 4

Timing Applications and Acquiring Data

Figure 4-2. FieldPoint Sleep Block Diagram

2. Save the VI.

Run the VI
1. Return to the front panel. 2. Select the Heater channel on the temperature chamber in the FieldPoint IO Point In control. 3. Set the Wait Time (ms) to a value that allows you to visually inspect whether the Wait function is executing. For example, a value such as 500 ms would turn the heater on and off every 0.5 seconds. 4. Run the VI. 5. Close the VI when you are finished.

End of Exercise 4-1A

LabVIEW Real-Time Course Manual

4-20

ni.com

Lesson 4

Timing Applications and Acquiring Data

Exercise 4-1B PXI - Hardware Sleep


Objective: Given pre-existing code, implement hardware timing to the code. In this exercise, you implement hardware timing for an existing piece of code. The purpose of the existing VI is to turn the heater on and off in the temperature chamber within a set number of seconds. 1. Open the Real-Time Exercises project from the C:\Exercises\ LabVIEW Real-Time directory. You created this project in exercise 2-2. 2. Add the PXI - Sleep.vi from the C:\Exercises\LabVIEW Real-Time directory to your RT target in the Project Explorer. 3. Double-click the PXI - Sleep VI to open it.

Front Panel
4. Modify the front panel of the VI as shown in Figure 4-3. a. Place a DAQmx Physical Channel control on the front panel, and change the label of the control to Sleep Channel. b. Place a Numeric control with double-precision representation on the front panel, and change the label to Rate (Hz).

Figure 4-3. PXI Sleep Front Panel

Block Diagram
1. Modify the block diagram of the VI, as shown in Figure 4-4, to use the analog input sample clock to time the While Loop. In this exercise, add a task for an analog input channel. This task does not use the data acquired; the task only times the While Loop. a. Place a DAQmx Create Virtual Channel VI on the block diagram.
National Instruments Corporation

Use the Operating tool to select the Analog InputVoltage instance for the DAQmx Create Channel VI. Wire the Sleep Channel control to the physical channels input.
4-21 LabVIEW Real-Time Course Manual

Lesson 4

Timing Applications and Acquiring Data

b. Place a DAQmx Timing VI on the block diagram. Select the Sample Clock instance for the Timing VI. Right-click the Sample Mode input and select Create Constant to create an enumerated constant. Select Hardware Timed Single Point on the enumerated constant. Wire the Rate (Hz) control to the rate input. Wire the error cluster and the task from the DAQmx Create Channel VI to the DAQmx Timing VI. Wire the error cluster and the task from the DAQmx Timing VI to the DAQmx Start Task VI.

c. Place a DAQmx Start Task VI on the block diagram.

d. Place a DAQmx Read VI on the block diagram. Notice that you do not access the data read by the DAQmx Read VI. You only use the DAQmx Read VI to control the timing of the loop. Select the AnalogSingle ChannelSingle SampleDBL instance for the Read VI. Wire the error cluster and the task from the DAQmx Start Task VI to the DAQmx Read VI. Wire the error cluster and the task from the DAQmx Read VI to the DAQmx Stop Task VI. Wire the error cluster and the task from the DAQmx Stop Task VI to the DAQmx Clear Task VI.

e. Place a DAQmx Stop Task VI on the block diagram.

f. Place a DAQmx Clear Task VI on the block diagram.

g. Merge the error clusters from the control task existing code with the error clusters from the added timing code.

LabVIEW Real-Time Course Manual

4-22

ni.com

Lesson 4

Timing Applications and Acquiring Data

Figure 4-4. PXI Sleep Block Diagram

2. Save the VI.

Run the VI
1. Select counter 0 of the DAQ device in the Counter(s) control by choosing Dev1/ctr0 from the drop-down menu. 2. Select analog input 0 of the DAQ device in the Sleep Channel control by choosing Dev1/ai0 from the drop-down menu. 3. Set the Rate (Hz) control to a value that allows you to visually inspect that the Wait VI is functioning. Remember that this value is in terms of Hertz. For example, a value such as 2 Hz would turn the heater on and off every 0.5 seconds. 4. Run the VI. 5. Close the VI and the project when you are finished.

End of Exercise 4-1B

National Instruments Corporation

4-23

LabVIEW Real-Time Course Manual

Lesson 4

Timing Applications and Acquiring Data

Exercise 4-2A cFP-Time-Critical


Objective: Create the time-critical portion of the course project. In this exercise, you build the time-critical portion of your course project. You may wish to refer to the flowchart from Exercise 3-3 as you complete each step. This exercise is divided into three main sections: 1. Step 1: Configure 2. Step 2: Create Time-Critical Loop 3. Step 3: Stop Loop and Clear Resources

Step 1: Configure
The first block on the flowchart consists of configuring the temperature and the PWM outputs. Because you have previously setup your configuration, no other hardware configuration is necessary. 1. Open C:\Exercises\LabVIEW Real-Time\Project Files\ cFP Real-Time Project.lvproj. This project contains a target and a number of modules, subVIs and variables for implementing the project. 2. Right-click the RT target in the Project Explorer and select Properties. 3. Enter the IP address of your target in the IP Address/DNS Name field and click OK. 4. Add C:\Exercises\LabVIEW Real-Time\Project Files\ cFP - TCL Project.vi to the Fieldpoint target in the Project Explorer. 5. Double-click the cFP-TCL Project.vi to open it. This VI contains the basic framework you need and follows the TCL (time-critical loop) flowchart. This VI has already been set to time-critical. 6. Confirm that the correct input values are selected for the Thermocouple Channel, Lamp Channel, and Fan Channel constants. 7. Drag two copies of the Global VI from the Project subVIsVariables folder of the Project Explorer to the block diagram, outside the loop in the configuration section. 8. Select Setpoint Profile and PID Gains as the data items for the two global variables. These two pieces of data are accessed only at the beginning of the program, so they can be passed to the TCL through any inter-threaded communication method. 9. On the block diagram place a Wait Until Next ms Multiple function to initialize the software timing.
LabVIEW Real-Time Course Manual 4-24 ni.com

Lesson 4

Timing Applications and Acquiring Data

10. Place the software timing function inside a Sequence structure to control when it executes. 11. Convert the loop rate into milliseconds for input into the software timing function. a. Place an Reciprocal function after the loop rate constant to convert Hz to seconds. b. Place a Multiply function on the output of the Reciprocal function to multiply seconds by 1000 for conversion to milliseconds. c. Place a To Unsigned Long Integer function to convert the output of the multiply function to an unsigned 32-bit integer. Converting the output to the correct representation needed for the timing function reduces the number of memory buffers needed while running the time-critical loop. d. Wire the functions together and input to the timing function. If you need assistance completing these steps, refer to Figure 4-5.
Note

Remember to periodically save your work throughout this exercise.

Step 2: Create Time-Critical Loop


The next step on the flowchart consists of creating the time-critical loop. The time-critical loop must complete the following steps: 1. Read temperature 2. Get timestamp 3. Determine PID output 4. Read disturbance 5. Output fan PWM 6. Output lamp PWM 7. Write data to FIFOs 8. Read stop You must complete one additional step to set up software timing for the time-critical loop.

National Instruments Corporation

4-25

LabVIEW Real-Time Course Manual

Lesson 4

Timing Applications and Acquiring Data

Complete each of these steps in sequence, using the error cluster to impose the order of operations on each step. You must impose operation order to ensure that there are no parallel processes in the time-critical loop. 1. Read the temperature from the thermocouple connected to the cFP-TC-120. a. Place the FP Read (Polymorphic) VI inside the loop, next to the Thermocouple Channel control on the block diagram. b. Connect the Thermocouple Channel constant to the FieldPoint IO Point In input on the FP Read (Polymorphic) VI. c. Place a Numeric constant with a representation of DBL (double-precision, floating-point) on the block diagram and connect it to the type input on the FP Read (Polymorphic) VI. This instructs the VI of the data type of the value output. The numeric constant is available on the Numeric palette. After placing the numeric constant on the block diagram, right-click and select RepresentationDBL to set the data type.
Note

2. Get the time stamp after reading the temperature. a. Place the Get Date/Time in Seconds function on the block diagram after the FP Read (Polymorphic) VI. b. Use a To Double Precision Float function to convert the output to a double-precision, floating-point numeric. c. Impose data flow on the time stamp function. Because there is no error input to the Get Data/Time in Seconds function, you must impose data flow in another manner. One method is to surround the function with a Sequence structure frame and wire the error cluster through the frame, starting from the error output on the FP Read (Polymorphic) VI. An example of this method is shown in Figure 4-5. 3. Determine PID Outputs. a. Place the PID Setpoint Profile VI on the block diagram. b. Place the PID VI next to the PID Setpoint Profile VI. c. Impose data flow on the PID functions by encasing them in a Sequence structure and passing the error cluster through the structure. d. Connect the Loop Rate constant to the dt input of PID Setpoint Profile function and connect the dt terminals of the two PID functions. e. Determine when to initialize the PID Setpoint Profile VI.

LabVIEW Real-Time Course Manual

4-26

ni.com

Lesson 4

Timing Applications and Acquiring Data

The VI should be initialized on the first interation of the loop only. This is true when the interation terminal is equal to zero. Therefore, place an Equal to Zero? function after the interation terminal and pass the output to the reinitialize? input of the PID Setpoint Profile VI. f. Wire the Setpoint Profile global variable to the setpoint profile input of the PID Setpoint Profile VI. g. Wire the PID Gains global variable to the PID gains input of the PID VI. h. Wire the current temperature value from the Fieldpoint Read VI to the process variable input of the PID VI. i. Wire the PID output range control to the PID VI. Refer to Figure 4-5 if you need assistance wiring the inputs.

Figure 4-5. Determine PID Outputs

4. Read the disturbance Boolean with a functional global variable. You can use a functional global variable here, because the only the most recent data is of interest. Also, if the variable is already being accessed by another VI, it can be skipped, and programmed to use the last known value. a. Drag the FGV Disturbance VI from the Project subVIsVariables folder of the Project Explorer to the block diagram. b. Create a constant on the mode input of the FGV and select Read. c. Skip the FGV if busy by right-clicking the FGV and selecting Skip Subroutine Call if Busy.

National Instruments Corporation

4-27

LabVIEW Real-Time Course Manual

Lesson 4

Timing Applications and Acquiring Data

d. Pass the latest data out of the FGV. If the FGV is skipped, then you need a method to remember the previous value. You can use a Select function on the Skipped? output and use a Feedback Node or shift register to pass previous data to the correct input of the Select function. An example of this method is shown in Figure 4-6. Remember to initialize the Feedback Node or shift register. The Feedback Node or shift register places an initialization terminal on the border of the While Loop. Wiring a FALSE Boolean to this terminal gives the Feedback Node a starting value. e. Pass the error cluster to the FGV to impose data flow. If you need assistance completing the steps necessary to read the Disturbance Boolean, refer to Figure 4-6.

Figure 4-6. Read Disturbance Boolean

5. If the Disturbance Boolean is TRUE, output full power to the fan. a. Place a Select function on the block diagram and use it to output 0 if the Boolean is FALSE, and 100 if the Boolean is TRUE. b. Place a FP Write (Polymorphic) VI on the block diagram, after the Select function. c. Wire the output of the Select function to the Values input on the FP Write (Polymorphic) VI. d. Wire the Fan Channel constant and the error cluster to the FP Write (Polymorphic) VI.

LabVIEW Real-Time Course Manual

4-28

ni.com

Lesson 4

Timing Applications and Acquiring Data

Refer to Figure 4-7 for assistance with wiring.

Figure 4-7. Write Fan Output

6. Output the correct power, determined by the PID functions, to the lamp. a. Place a FP Write (Polymorphic) VI on the block diagram after the FP Write (Polymorphic) VI that was used for the fan. b. Connect output on the PID VI to the Values input on the FP Write (Polymorphic) VI. c. Wire the Lamp Channel constant and the error cluster to the FP Write (Polymorphic) VI.

National Instruments Corporation

4-29

LabVIEW Real-Time Course Manual

Lesson 4

Timing Applications and Acquiring Data

Refer to Figure 4-8 for assistance with wiring.

Figure 4-8. Write Lamp Output Figure 4-9. Output PID-Determined Value to Lamp

7. Create the shared-variable FIFOs for inter-thread communication. A library of shared-variables is provided for you. a. Under your RT Target in the Project Explorer browse to Project subVIsVariablesProject Variables.lvlib. b. Double-click one of the variables in the library to open the configuration dialog for the variable and observe the configuration. Each of the variables is a single-process, shared-variable with the RT FIFO option enabled. Use these variables to transfer data between the time-critical and normal priority loops. Network-published shared-variables allow you to transfer data from your target to your host. However, for the project, use TCP/IP to transfer data from the normal priority loop to the host. c. Drag each shared-variable from the Project Explorer to your block diagram. d. Right-click each shared-variable and select Change to write. 8. Use the shared-variable FIFOs to transfer data to the normal priority loop. a. Wire the PID setpoint from the PID Setpoint Profile VI to the Setpoint shared variable.

LabVIEW Real-Time Course Manual

4-30

ni.com

Lesson 4

Timing Applications and Acquiring Data

b. Wire the value output from the FP Read VI to the Actual shared variable. The value is the current temperature. c. Wire the double-precision timestamp from the Get Timestamp sequence frame to the Timestamp shared variable. d. Wire the PID output from the PID VI to the Lamp shared variable. e. Wire the Boolean output indicating whether the fan is on or off from the select statement controlling the disturbance to the Fan shared variable f. Wire the error clusters through the shared variables. Figure 4-10 provides assistance wiring the shared variables. The wire labels indicate the source of each wire. 9. Read the stop value with a functional global variable. You can use a functional global variable here, because only the most recent data is of interest. Also, if the variable is already being accessed by another VI, it can be skipped, and programmed to use the last known value. a. Drag the FGV Stop VI from the Project subVIsVariables folder of the Project Explorer to the block diagram. b. Create a constant on the mode input of the FGV and select Read. c. Skip the FGV if busy by right-clicking the FGV and selecting Skip Subroutine Call if Busy. 10. Setup software timing for the loop. a. Place a Wait Until Next ms Multiple function on the block diagram. b. Wire the loop time in milliseconds to the input of the timing function chosen. This is the same wire connected to the input of the timing function that is initialized outside of the While Loop. c. Impose dataflow on the Wait function by placing it in a Sequence structure and passing the error cluster through the structure, as shown in Figure 4-10. You have now completed the time-critical loop of the time-critical subVI, except for the stop conditions. Figure 4-10 shows an example of a completed time-critical loop. Refer to Figure 4-10 to confirm that you have correctly completed each step. In the next step, configure the stop conditions for the loop.

National Instruments Corporation

4-31

LabVIEW Real-Time Course Manual

Lesson 4

Timing Applications and Acquiring Data

Figure 4-10. Write data to FIFOs and read Stop Boolean from FIFO

Step 3: Stop Loop and Clear Resources


Stop the loop and clear the resources as shown in the last step of the time-critical flowchart. 1. Set the stop conditions for the time-critical loop. The stop conditions are to stop on Profile Complete, on stop received from host, or on an error. a. Place a Compound Arithmetic function next to the stop terminal. b. Right-click the Compound Arithmetic function and select Change ModeOR to apply OR logic to the stop conditions. c. Resize the Compound Arithmetic function to create three inputsone for each stop condition. d. Wire the correct stop conditions to each input on the Compound Arithmetic function. Profile Complete is an output available on the PID Setpoint Profile VI. Stop received from host is determined by the Stop shared variable. Stop on an error is determined by reading the status element of the error cluster. Use an Unbundle By Name function to choose the status element, and pass this value to the last input on the Compound Arithmetic function.

e. Connect the output of the Compound Arithmetic function to the Stop terminal of the While Loop. The Stop terminal is set to Stop if True (default). 2. Clear the resources for each of the three channels used. Set the outputs to a value of zero, otherwise the hardware continues to output the last value written to the hardware. a. Place an FP Write (Polymorphic) VI for each of the two outputs.

LabVIEW Real-Time Course Manual

4-32

ni.com

Lesson 4

Timing Applications and Acquiring Data

b. Connect an output channel task to each FP Write (Polymorphic) VI. c. Create a double-precision numeric constant and enter a value of 0 in the constant. d. Wire the constant to the values input on both FP Write (Polymorphic) VIs. This writes a value of zero to the output. e. Pass the error cluster to each of the FP Write (Polymorphic) VIs. f. Connect the error out output of the last FP Write (Polymorphic) VI executed to the error out indicator. You have now completed step 3 of the time-critical subVI. Refer to Figure 4-11 for assistance with the stop conditions or with clearing the resources.

Figure 4-11. Set TCL Stop conditions and clear cFP resources

3. If you completed each step correctly, a solid run arrow appears on the toolbar. If the run arrow is broken, use debugging techniques that you are familiar with to check for problems. If you cannot solve the issues in the time allotted for this exercise, you may also debug this exercise in Lesson 6, Verifying Your Application. 4. Compare the flowchart you created in Exercise 3-3 with your completed block diagram. Do they match? Are you accomplishing the tasks as designed? 5. Wire the error cluster throughout the VI and notice how it controls the order of operations. 6. Save and close the cFP - TCL Project VI.

End of Exercise 4-2A


National Instruments Corporation 4-33 LabVIEW Real-Time Course Manual

Lesson 4

Timing Applications and Acquiring Data

Exercise 4-2B PXI-Time-Critical


Objective: Create the time-critical portion of the course project. In this exercise, you build the time-critical portion of your course project. You may wish to refer to the flowchart from Exercise 3-3 as you complete each step. This exercise is divided into the following sections: 1. Step 1: Configure 2. Step 2: Create Time-Critical Loop 3. Step 3: Stop Loop and Clear Resources

Step 1: Configure
The first block on the flowchart consists of configuring the data acquisition. You must create and configure three tasks: temperature input, fan output, and lamp output. 1. Open C:\Exercises\LabVIEW Real-Time\Project Files\PXI Real Time Project.lvproj. This project contains a target and a number of modules, subVIs and variables for implementing the project. 2. Right-click the RT target in the Project Explorer and select Properties. 3. Enter the IP address of your target in the IP Address/DNS Name field and click OK. 4. Add the PXI-TCL Project VI from the C:\Exercises\LabVIEW Real-Time\Project Files directory to the RT target in your project. This VI contains the basic framework you need and follows the TCL (time-critical loop) flowchart. This VI has already been set to time-critical. If you need further assistance with completing the configuration section of the block diagram throughout the individual steps, refer to Figure 4-12, which shows a completed version of the configuration section of the block diagram.
Tip

5. Open the PXI-TCL Project VI. 6. Place a three of the DAQmx Create Virtual Channel VI next to the Temp Physical Channel, Fan Physical Channel and Lamp Physical Channel controls on the block diagram. This VI creates the task for the inputs and outputs. a. Choose the correct task types for each type of input and output. The temperature is read as an analog input thermocouple temperature, and the fan and lamp is output as a counter output pulse generation frequency.

LabVIEW Real-Time Course Manual

4-34

ni.com

Lesson 4

Timing Applications and Acquiring Data

b. Connect the controls to the appropriate inputs of each DAQmx Create Virtual Channel VI. 7. Place a DAQmx Timing VI next to each task created. Because you are using hardware timing in the project, this VI selects the hardware clock for each task. You use the onboard clock for all three tasks. a. Choose the Sample Clock timing type on each DAQmx Timing VI. b. Create a constant on the sample mode input of each DAQmx Timing VI and select the Hardware Timed Single Point option on the enumerated constant that appears. c. Connect the Loop Rate control to each DAQmx Timing VI. d. Create a constant on the source input of the DAQmx Timing VI for each counter output task. You do not need to create a constant of the source input of the DAQmx Timing VI attached to the input, because the default selection is correct. e. Select Dev1/ai/sample clock for each source constant. 8. Place a DAQmx Start Task VI next to each DAQmx Timing VI. This function sends the configuration information to the data acquisition board to prepare for efficient running. 9. Place a Merge Errors VI before or after the DAQmx Start Task VI for the temperature task. Before entering the time-critical loop, the errors must be merged. Having only one error wire allows you to control the order of operation of tasks within the loop, imposing data flow. 10. Wire the errors to be merged to the inputs on the Merge Errors VI. 11. Save this VI as PXI - TCL Project.vi to C:\Exercises\ LabVIEW Real-Time\Project Files. Remember to periodically save your work throughout this exercise. You have now completed the configuration portion of the time-critical subVI. Figure 4-12 shows an example of a completed configuration section. Refer to this figure to confirm that you have correctly completed each step.

National Instruments Corporation

4-35

LabVIEW Real-Time Course Manual

Lesson 4

Timing Applications and Acquiring Data

Figure 4-12. PXI - TCL Project VI: Configuration

Step 2: Create Time-Critical Loop


The next step on the flowchart consists of creating the time-critical loop. The time-critical loop completes the following steps: 1. Read temperature. 2. Get timestamp. 3. Determine PID output. 4. Read disturbance. 5. Output fan PWM. 6. Output lamp PWM. 7. Write data to FIFOs 8. Read stop.

LabVIEW Real-Time Course Manual

4-36

ni.com

Lesson 4

Timing Applications and Acquiring Data

Complete each of these steps in sequence, using the error cluster to impose the order of operations on each step. You must impose operation order to ensure that there are no parallel processes in the time-critical loop. 1. Read the temperature from the thermocouple attached to the data acquisition board. a. Place the DAQmx Read VI inside the loop, next to the DAQmx Start Task VI for the temperature task. b. Choose a read type of AnalogSingle ChannelSingle Sample DBL. This instructs the VI to return only one double-precision, floating-point numeric temperature read from the device for each clock cycle. c. Wire the task in and error in inputs of the DAQmx Read VI. Because the error cluster is wired first to this function when it enters the time critical loop, this function is the first to execute. 2. Get the time stamp after reading the temperature. a. Place the Get Date/Time in Seconds function on the block diagram, after the DAQmx Read VI. b. Place the To Double Precision Float function on the block diagram, to convert the output to a double-precision, floating-point numeric control. c. Place a Flat Sequence structure on the block diagram, to impose data flow on the timestamp function. Because there is no error input to the Get Data/Time in Seconds function, you must impose data flow in another manner. An appropriate method is to surround the function with a Sequence structure frame, and wire the error cluster through the frame. This restricts the execution of the Sequence structure until it receives data along the error cluster wire. An example of this method is shown in Figure 4-13.

National Instruments Corporation

4-37

LabVIEW Real-Time Course Manual

Lesson 4

Timing Applications and Acquiring Data

Figure 4-13. Sequence Structure Used to Impose Data Flow

3. Determine PID Outputs. A global variable for the setpoint profile and a global variable for the PID gains has already been placed outside the loop in the configuration section. These two pieces of data are accessed only at the beginning of the program, so they can be passed to the TCL through any inter-thread communication method. Global variables were chosen for simplicity. a. Place the PID Setpoint Profile VI on the block diagram. b. Place the PID VI on the block diagram. c. Impose data flow on the PID functions by surrounding them in a Sequence structure and passing the error cluster through the structure. d. Wire the necessary inputs to the PID functions. Refer to Figure 4-14 for assistance wiring the inputs.

LabVIEW Real-Time Course Manual

4-38

ni.com

Lesson 4

Timing Applications and Acquiring Data

Figure 4-14. Determine PID Outputs

4. Read the Apply Disturbance control with a functional global variable. You can use a functional global variable here, because the only the most recent data is of interest. Also, if the variable is already being accessed by another VI, it can be skipped, and programmed to use the last known value. a. Drag the FGV Disturbance VI from the Project subVIsVariables folder of the Project Explorer to the block diagram. b. Create a constant on the mode input of the FGV Disturbance VI and select Read. c. Skip the FGV if busy by right-clicking the FGV Disturbance VI and selecting Skip Subroutine Call if Busy. d. Pass the latest data out of the FGV Disturbance VI. If the FGV is skipped, then you need a method to remember the previous value. One method is to use a Select function on the Skipped? output and use a Feedback Node or shift register to pass previous data to the correct input of the Select function. An example of this method is shown in Figure 4-15.

National Instruments Corporation

4-39

LabVIEW Real-Time Course Manual

Lesson 4

Timing Applications and Acquiring Data

Remember to initialize the Feedback Node or shift register. The Feedback Node or shift register places an initialization terminal on the border of the While Loop. Wiring a FALSE Boolean to this terminal gives the Feedback Node a starting value.
Note If you wire the Select output to the Select input, a Feedback Node automatically appears.

e. Pass the error cluster to the FGV Disturbance VI to impose data flow. Refer to Figure 4-15 if you need assistance completing the steps necessary to read the Apply Disturbance control.

Figure 4-15. Read Disturbance Boolean

5. If the Apply Disturbance control is TRUE, output full power to the fan. a. Place a Select function and use it to output .0001 if the Boolean is FALSE, and .9999 if the Boolean is TRUE. These are the minimum and maximum duty cycle values that can be output. b. Place a DAQmx Write VI on the block diagram after the Select function. c. Select the CounterSingle ChannelSingle SampleFrequency type for the DAQmx Write VI. d. Wire the appropriate inputs to the DAQmxWrite VI.

LabVIEW Real-Time Course Manual

4-40

ni.com

Lesson 4

Timing Applications and Acquiring Data

These inputs include the fan task, the frequency, the duty cycle (output of the Select function) and the error cluster. Refer to Figure 4-16 for assistance with wiring.

Figure 4-16. Write Fan Output

6. Output the correct power, determined by the PID functions, to the lamp. a. Convert the output of the PID VI to a duty cycle for the lamp PWM. The PID VI has been set up to output a value from 0100. When this value is written to the log file, this can be read as a percentage of available power. However, the DAQmx Write VI needs the output as a duty cycle between .0001.9999. One method of accomplishing this is to pass the output through the In Range and Coerce function then divide the result by 100. The limits used on the In Range and Coerce function are .1 and 99.99 Refer to Figure 4-17 for an example of this method. b. Place a DAQmx Write VI on the block diagram after the conversion.

National Instruments Corporation

4-41

LabVIEW Real-Time Course Manual

Lesson 4

Timing Applications and Acquiring Data

c. Select the CounterSingle ChannelSingle SampleFrequency type for the DAQmx Write VI. d. Wire the appropriate inputs to the DAQmxWrite VI. These inputs include the lamp task, the frequency, the duty cycle (output of the conversion) and the error cluster. Refer to Figure 4-17 for assistance with wiring.

Figure 4-17. Output PID-Determined Value to Lamp

7. Create the shared-variable FIFOs for inter-thread communication. A library of shared-variables is provided for you. a. Under your RT Target in the Project Explorer browse to Project subVIsVariablesProject Variables.lvlib. b. Double-click one of the variables in the library to open the configuration dialog for the variable and observe the configuration. Each of the variables is a single-process shared variable with the RT FIFO option enabled. Use these variables to transfer data between the time-critical and normal priority loops. Network-published shared variables allow you to transfer data from your target to your host. However, for the project, use TCP/IP to transfer data from the normal priority loop to the host.

LabVIEW Real-Time Course Manual

4-42

ni.com

Lesson 4

Timing Applications and Acquiring Data

c. Drag each shared variable from the Project Explorer to your block diagram. d. Right-click each shared variable and select Change to write. 8. Use the shared-variable FIFOs to transfer data to the normal priority loop. a. Wire the PID setpoint from the PID Setpoint Profile VI to the Setpoint shared variable. b. Wire the data output from the DAQmx Read VI to the Actual shared variable. The data is the current temperature. c. Wire the double-precision timestamp from the Get Timestamp sequence frame to the Timestamp shared variable. d. Wire the PID output from the PID VI to the Lamp shared variable. e. Wire the Boolean output indicating whether the fan is on or off from the select statement controlling the disturbance to the Fan shared variable. f. Wire the error clusters through the shared variables. Figure 4-18 provides assistance wiring the shared variables. The wire labels indicate the source of each wire. 9. Read the stop value with a functional global variable. You can use a functional global variable here, because the only the most recent data is of interest. Also, if the variable is already being accessed by another VI, it can be skipped, and programmed to use the last known value. a. Drag the FGV Stop VI from the Project subVIsVariables folder of the Project Explorer to the block diagram. b. Create a constant on the mode input of the FGV Disturbance VI and select Read. c. Skip the FGV Disturbance VI if busy by right-clicking the FGV Disturbance VI and selecting Skip Subroutine Call if Busy. You have now completed the operations required in the time-critical loop of the time-critical subVI. Figure 4-18 shows an example of a completed time-critical loop, except for the stop conditions. Refer to this figure to confirm that you have correctly completed each step. You set up the stop conditions for the loop in the next step.

National Instruments Corporation

4-43

LabVIEW Real-Time Course Manual

Lesson 4

Timing Applications and Acquiring Data

Figure 4-18. Write Data to FIFOs and Read Stop Boolean from FIFO

Step 3: Stop Loop and Clear Resources


Stop the loop and clear the resources as shown in the last step of the time-critical flowchart. 1. Set the stop conditions for the time-critical loop. The stop conditions are to stop on Profile Complete, on stop received from host, or on an error. a. Place a Compound Arithmetic function next to the stop terminal. b. Right-click the Compound Arithmetic function and select Change ModeOR to apply OR logic to the stop conditions. c. Resize the Compound Arithmetic function to create three inputsone for each stop condition. d. Wire the correct stop conditions to each input on the Compound Arithmetic function. Profile Complete is an output available on the PID Setpoint Profile VI. Stop received from host is determined by the Stop shared variable.

LabVIEW Real-Time Course Manual

4-44

ni.com

Lesson 4

Timing Applications and Acquiring Data

Stop on an error is determined by reading the status element of the error cluster. Use an Unbundle By Name function to choose the status element, and pass this Boolean value to the first input on the Compound Arithmetic function.

e. Connect the output of the Compound Arithmetic function to the Stop terminal of the While Loop. Ensure the Stop terminal is set to Stop if True. 2. Clear the DAQ resources for each of the three tasks created. a. Replace the While Loop tunnels for the three DAQ references and the error tunnels with shift registers. Ensure that both the left and the right tunnels are replaced.
Note Shift registers are not necessary for the error wires and references in this particular VI because the loop is guaranteed to run at least once and automatically stops on error. However, using the shift registers is good programming practice because some loops may run zero times or continue after an error.

b. Place a DAQmx Clear Task VI for each of the three tasks on the block diagram. c. Connect a task to each of the DAQmx Clear Task VIs. d. Pass the error cluster to each of the DAQmx Clear Task VIs. e. Connect the error out output of the last DAQmxClear Task VI executed to the error out indicator. You have now completed step 3 of the time-critical subVI. Refer to Figure 4-19 for assistance with the stop conditions or with clearing the DAQmx tasks.

National Instruments Corporation

4-45

LabVIEW Real-Time Course Manual

Lesson 4

Timing Applications and Acquiring Data

Figure 4-19. Set TCL Stop Conditions and Clear DAQ resources

3. If you have correctly completed each step, a solid run arrow appears on the toolbar. If the run arrow is broken, use debugging techniques that you are familiar with to check for problems. If you cannot solve the issues in the time allotted for this exercise, you also can debug this exercise in Lesson 6, Verifying Your Application. 4. Compare the flowchart you created in Exercise 3-3 with your completed block diagram. Do they match? Are you accomplishing the tasks as designed? 5. Save and close the PXI - TCL Project VI.

End of Exercise 4-2B

LabVIEW Real-Time Course Manual

4-46

ni.com

Lesson 4

Timing Applications and Acquiring Data

Notes

National Instruments Corporation

4-47

LabVIEW Real-Time Course Manual

Lesson 4

Timing Applications and Acquiring Data

Notes

LabVIEW Real-Time Course Manual

4-48

ni.com

Lesson 5 Communication

Lesson 5 Communication

Topics A. Front Panel Communication B. Network Communication Methods C. Communication Programming D. LabVIEW Real-Time Wizards

Introduction
The RT Engine on the RT target does not provide a user interface for applications. You can use one of two communication protocols, front panel communication or network communication, to provide a user interface on the host computer for RT target VIs. In this lesson, you will develop the normal priority portion of the target program, along with the host program.

National Instruments Corporation

5-1

LabVIEW Real-Time Course Manual

Lesson 5 Communication

Front Panel Communication

Targeted

A. Front Panel Communication


With front panel communication, LabVIEW and the RT Engine execute different parts of the same VI, as shown in the slide above. LabVIEW on the host computer displays the front panel of the VI while the RT Engine executes the block diagram. A user interface thread handles the communication between LabVIEW and the RT Engine. Use front panel communication between LabVIEW on the host computer and the RT Engine to control and test VIs running on an RT target. After downloading and running the VIs, keep LabVIEW on the host computer open to display and interact with the front panel of the VI. You also can use front panel communication to debug VIs while they run on the RT target. You can use LabVIEW debugging toolssuch as probes, execution highlighting, breakpoints, and single steppingto locate errors on the block diagram code. Refer to Lesson 6, Verifying Your Application, for information about debugging applications. Front panel communication is a good communication method to use during development, because front panel communication is a quick method for monitoring and interfacing with VIs running on an RT target. However, front panel communication is not deterministic and can affect the determinism of a time-critical VI. Use network communication methods to increase the efficiency of the communication between a host computer and VIs running on the RT target.

LabVIEW Real-Time Course Manual

5-2

ni.com

Lesson 5 Communication

Network Communication

B. Network Communication
With network communication, a host VI runs on the host computer and communicates with the VI running on the RT target using specific network communication methods such as networkpublished, shared variables, TCP, VI Server, and in the case of non-networked RT Series plug-in devices, shared memory reads and writes. You might use network communication for the following reasons: To run another VI on the host computer. To control the data exchanged between the host computer and the RT target. You can customize the communication code to specify which front panel objects get updated and when. You also can control which components are visible on the front panel, because some controls and indicators might be more important than others. To control timing and sequencing of the data transfer. To perform additional data processing or logging. In the figure above, the RT target VI is similar to the VI shown in the Front Panel Communication section, which runs on the RT target using front panel communication to update the front panel controls and indicators. However, the RT target VI in the figure above uses RT FIFO VIs to pass data to a communication VI. The communication VI then communicates with the host computer VI using network communication methods to update controls and indicators.

National Instruments Corporation

5-3

LabVIEW Real-Time Course Manual

Lesson 5 Communication

Network Communication Methods


Protocol TCP UDP Shared Variable Programming Speed Architecture Caveats Difficulty Good Good Best Better Client/Server String data Broadcast or Unreliable, Client/Server String data Publisher/ NI protocol, Good Subscriber LabVIEW 8+ Best Poor Client/Server LabVIEW only

VI Server Better

The network communication methods most commonly used with LabVIEW RT include TCP, UDP, shared variables, and VI Server. Other methods, mostly used in legacy systems include DataSocket and Logos. TCPProtocol most commonly used for large systems. Provides a good mixture of speed and reliability. Data must be formatted as strings. UDPFastest network protocol. Includes little error checking and can loose packets. Robust systems must implement their own error checking. Data must be formatted as strings. Shared VariablesEasiest protocol to implement. Shared variables can be used deterministically directly from a time-critical loop, because they implement a normal-priority communication loop automatically. Only host programs using LabVIEW and other NI products can access shared variables that are only available on LabVIEW 8.0 or later. VI ServerYou can use VI Server to run VIs and/or access and set the value of controls and indicators. VI Server communication is not recommended for transferring large amounts of data.

Architectures
Client-ServerA dedicated connection is created between a client and a server. BroadcastApplication broadcasts data onto a network, any listeners can receive the data. Typically a one-way conduit. Publisher/SubscriberA server or program publishes data items. Subscribers subscribe to data items. Each subscriber can read and/or write to the data item.

LabVIEW Real-Time Course Manual

5-4

ni.com

Lesson 5 Communication

TCP Communication
TCPTransmission Control Protocol Industry standard protocol for network communication Non-deterministicDo not use inside a time-critical VI LabVIEW TCP functions:

Demo: NI Example Finder Toolkits and ModulesReal-TimeNetwork Communication TCP Communication

TCP
TCP is an industry-standard protocol for communicating over networks. VIs running on the host computer can communicate with RT target VIs using the LabVIEW TCP functions. However, TCP is non-deterministic, and using TCP communication inside a time-critical VI might cause the loop cycle time to vary from the desired time. The LabVIEW Real-Time Module extends the capabilities of the existing TCP functions to enable communication with networked RT Series devices and to allow communication across shared memory with RT Series plug-in devices. (RTX) Use RTRTX::0 as the address of an RT target when attempting to open a TCP connection with the target using the LabVIEW TCP functions.

National Instruments Corporation

5-5

LabVIEW Real-Time Course Manual

Lesson 5 Communication

UDP Communication
UDPUser Datagram Protocol Not connection-basedLittle overhead; cannot verify receipt of data Non-deterministicDo not use inside a time-critical VI LabVIEW UDP functions:

UDP
UDP is a network transmission protocol for transferring data between two locations on a network. UDP is not a connection-based protocol, so the transmitting and receiving computers do not establish a network connection. Because there is no network connection, there is little overhead when transmitting data. However, UDP is non-deterministic, and using UDP communication inside a time-critical VI might cause the loop cycle time to vary from the desired time. When using UDP to send data, the receiving computer must have a read port open before the transmitting computer sends the data. Use the UDP Open function to open a write port and specify the IP address and port of the receiving computer. The data transfer occurs in byte streams of varying lengths called datagrams. Datagrams arrive at the listening port and the receiving computer buffers and then reads the data. You can transfer data bidirectionally with UDP. With bidirectional data transfers, both computers specify a read and write port and transmit data back and forth using the specified ports. You can use bidirectional UDP data transfers to send and receive data from the network communication VI on the RT target. UDP has the ability to perform fast data transmissions deterministically. However, UDP cannot guarantee that all datagrams arrive at the receiving computer. Because UDP is not connection based, you cannot verify the arrival of datagrams. You must ensure that network congestion does not affect the transmission of datagrams. Also, you must read data stored in the data buffer of the receiving computer fast enough to prevent overflow and loss of data. (RTX) You must use RTRTX::0 as the address of the RT target when attempting to write data to the target using the LabVIEW UDP functions.
LabVIEW Real-Time Course Manual 5-6 ni.com

Lesson 5 Communication

Shared Variable Communication


Network-published, shared variables can communicate with host From time critical loopwith RT FIFOs From normal priority loopwithout RT FIFOs

There are two ways to use network-published, shared variable s to transfer data from a target to the host. Network-published, shared variable s with the RT FIFO option enabled automatically generate an invisible communication loop. A variable configured in this manner transfers data from the time-critical loop to the communication loop using an RT FIFO and transfer data from the communication loop to the host by using PSP, a protocol created using UDP. If the only function of the normal priority loop in your application is to transfer data to the host, using networkpublished, shared variable s removes the need to program a second loop and saves you effort. Network-published shared variables without the RT FIFO option allow you to transfer data from a normal priority loop to the host using PSP. If your application requires a normal priority loop for reasons other than communication, such as data logging, then you can transfer the data to the normal priority loop using an RT FIFO or single-process shared variable FIFO and then transfer data from the normal priority loop to the host using a network-published, shared variable .

National Instruments Corporation

5-7

LabVIEW Real-Time Course Manual

Lesson 5 Communication

VI Server Communication
Monitor and control VIs on an RT target Can only invoke VIs in memory on the RT target Non-deterministicdo not use inside a time-critical VI LabVIEW VI Server functions:

Demo: NI Example Finder Toolkits and ModulesReal-TimeNetwork CommunicationVI Server

VI Server
Use the VI Server to monitor and control VIs on an RT target. Using VI Server technology, a LabVIEW VI can invoke RT target VIs remotely. The LabVIEW VI can pass parameter values to and from the RT target VIs, creating a distributed application. A host VI can invoke only VIs in memory on the RT target. The host VI cannot dynamically download LabVIEW VIs to the RT target for use with the VI Server. One advantage to communicating using the VI Server is that the VI Server allows you to access the functionality of TCP while working within the framework of LabVIEW. However, the VI Server is non-deterministic and using VI Server communication inside a time-critical VI adds jitter to the application. (RTX) You must use RTRTX::0 as the computer name of the RT target when attempting to open an application reference using the VI Server.

LabVIEW Real-Time Course Manual

5-8

ni.com

Lesson 5 Communication

Communication ProgrammingTCP and UDP


Developing a Data Protocol TCP and UDP are very efficient communication mechanisms, but transfer only string data Robust systems typically require communication for multiple data items with different data types Define a protocol to package your data and information about the data, known as metadata

National Instruments Corporation

5-9

LabVIEW Real-Time Course Manual

Lesson 5 Communication

Communication ProgrammingTCP and UDP


Transferring Metadata
Examples of metadata include data size, data item name, and data type For efficient communication
store static meta data such as item names and types on both the host and target transfer only an index or reference to the metadata

Example packet: Refer to the Simple TCP/IP Messaging Protocol for more information. Browse to ni.com/info and enter rdstcp.

LabVIEW Real-Time Course Manual

5-10

ni.com

Lesson 5 Communication

Communication ProgrammingShared Variable Avoiding Overflow


Enable buffering on networkpublished, shared variables if your host needs to receive all data points Network-published, shared variable buffers are separate from shared variable FIFO buffers and use additional memory

If your host application needs to receive all of the data transferred, enable buffering on your network-published, shared variable s to avoid loosing data points.

National Instruments Corporation

5-11

LabVIEW Real-Time Course Manual

Lesson 5 Communication

Communication ProgrammingShared Variable


Avoiding Underflow
Check timestamps on the host to avoid reading data twice Or use an event structure to process value change event notification (requires LabVIEW DSC Module)

If your host application must read each value only once, check the timestamp on each reading and compare it to the timestamp of the last reading to ensure that you do not read the same value twice. You also can avoid underflow by using processing value changes using the event structure. Shared variable value change notifications are available with the LabVIEW Datalogging and Supervisory Control (DSC) Module.

LabVIEW Real-Time Course Manual

5-12

ni.com

Lesson 5 Communication

Location for Network-Published Variables


Network-published, shared variables can be located on either the host or the target. Both locations have advantages:
Variables on Target Delta filtering can reduce updates and network traffic for non-buffered shared variable write operations Less chance of engine being unavailable due to crash or user intervention Variables on Host Less memory and processor use on RT target LabVIEW DSC features available Other computers reading the data do not use resources on target

You can choose to host network published shared variables on either your host or your target. The following are advantages of hosting on a target: Non-buffered shared variables use a technique known as delta-filtering to reduce updates. When the value written to a variable is the same as the last value transferred, a variable does not generate an update event and therefore causes less network traffic. This only works if the variable is hosted on the machine that is writing the variable. RT targets are more stable than most computers, tend to be on consistently, and have no user interface to interfere with. Therefore, there is less chance that the network variable engine will be unavailable if it is hosted on the target. The shared variable engine and each shared variable require memory and processor resources on the computer hosting the variable. You must host shared variables on a host computer in order to use LabVIEW DSC features on the variables. Examples of LabVIEW DSC features include database logging, alarms, events, security settings, and control over the initial variable value. If more than one host or computer needs to read the value of the shared variable, hosting the variable on the host reduces the resource drain on the target.

Advantages of hosting on a host:

National Instruments Corporation

5-13

LabVIEW Real-Time Course Manual

Lesson 5 Communication

Scope of Network-Published Shared Variables


Network-published, shared variables are deployed and published when a VI that references a variable runs All variables in a library are deployed at the same time Network-published, shared variables are never automatically undeployed Deployed network-published, shared variables remain on a system even after rebooting

When a VI that references a network-published, shared variable is run, all variables in the library containing the variable are deployed and published. You should consider how to group variables into libraries to avoid deploying unnecessary variables. Network-published, shared variables are never automatically undeployed, even after a system reboot. They remain on the system, ready provide or receive data.

LabVIEW Real-Time Course Manual

5-14

ni.com

Lesson 5 Communication

Undeploying Shared Variables


Undeploy variables Programmatically, using LabVIEW DSC API Programmatically, using VI Server Manually, using the Project Explorer Manually, using the Variable Manager

There are many ways to remove shared variables from a system if they are no longer in use. 1. Programmatically undeploy variables using the VIs in the LabVIEW DSC module. 2. Programmatically undeploy variables by using the LibraryUndeploy Library method of the Application VI Server class. 3. Manually undeploy a library by right-clicking the library in the Project Explorer and selecting Undeploy. 4. Manually undeploy a library by using the Variable Manager. Start the Variable Manager by selecting ToolsShared VariableVariable Manager.

National Instruments Corporation

5-15

LabVIEW Real-Time Course Manual

Lesson 5 Communication

LabVIEW Real-Time Wizards


Communication Wizard Converts existing VIs to real-time systems Divides a VI into user interface (host) and processing (target) VIs Choose a communication protocol

LabVIEW Real-Time contains two wizards that can help you create a communication mechanism. Communication Wizard Converts existing VIs to real-time systems. The Communication Wizard divides a single VI into a user interface and a time critical loop and implements a network communication mechanism to communicate between them. You can choose the following options for the network communication mechanism: Shared VariablesCreates a project, a time critical VI, and a host VI. Uses networkpublished, shared variables with RT FIFOs to transfer data between the time critical loop and the host. TCPCreates a time critical VI, a normal priority VI and a host VI. Uses RT FIFOs to transfer data from the time critical to the normal priority loop and uses TCP to transfer data to the host. UDPCreates a time critical VI, a normal priority VI and a host VI. Uses RT FIFOs to transfer data from the time critical to the normal priority loop and uses UDP to transfer data to the host. LogosThis protocol is provided mainly for legacy purposes. Use shared variables rather than the Logos protocol.

LabVIEW Real-Time Course Manual

5-16

ni.com

Lesson 5 Communication

LabVIEW Real-Time Wizards (Cont.)


Project Wizard Creates a framework for developing a new system Uses shared variables for communication Choose an architecture for the project

Project Wizard Creates a framework for developing a new system. The Project Wizard creates a new project and host and target VIs from scratch. Projects created from the Project Wizard use shared variables to transfer data. You can choose from a variety of architecture combinations for your program: Continuous Communication ArchitectureGenerates a VI on the target to continually transfer data using a network-published, shared variable with RT FIFO enabled. You can choose to create a single time-critical loop or create a time-critical and normal-priority loop. Both create a single target VI using timed loops. You can choose to create a host VI, or configure the system for remote panels. State Machine ArchitectureGenerates a host and target VI that synchronize to transfer configuration data from the host to the target before executing an action on the target and returning the results. This architecture is very similar to the architecture used in the project of the course.

National Instruments Corporation

5-17

LabVIEW Real-Time Course Manual

Lesson 5 Communication

Exercise 5-1 RT Communication Wizard


Time to complete: 20 min.

The project uses TCP communication. When completing this exercise, choose a communication method that you are interested in other than TCP. A secondary choice for PXI users is DataSocket; many FieldPoint applications use Logos.

OBJECTIVE

Use the RT Project Wizard and RT Communication Wizard to automatically generate code.

LabVIEW Real-Time Course Manual

5-18

ni.com

Lesson 5 Communication

Exercise 5-2 Implement Normal Priority


Time to complete: 1 hour 30 min.

The RT Communication Wizard is not used in the exercise.

OBJECTIVE

Create the target program that includes the normal priority loop and calls the time-critical VI.

National Instruments Corporation

5-19

LabVIEW Real-Time Course Manual

Lesson 5 Communication

Exercise 5-3 Host Program


Time to complete: 10 min.

Review the completed host VI for the project and compare to the provided flow chart. Optional: Instructions are provided to build the entire host program as a self-study exercise in Exercise 5-4.

Instructor Note
Instructions are provided to build the host program in Exercise 5-4. If the students need further practice and time remains in the course, have the students build the host program as listed in Exercise 5-4 and skip Exercise 5-3. Otherwise, students should complete only Exercise 5-3. Exercise 5-4 takes approximately 1 hour to complete.

OBJECTIVE

LabVIEW Real-Time Course Manual

5-20

ni.com

Lesson 5 Communication

SummaryMatching Quiz
1. TCP 2. UDP 3. Networkpublished, shared variables 4. VI Server A. Fast, lossy communication protocol with minimal error checking B. Control VIs directly on an RT target C. Commonly used protocol, fast and lossless. D. Can transfer data directly from a time-critical loop

Refer to the Network Communication section of this lesson for more information and review on each communication method. Refer to the LabVIEW Help for more information on using these communication methods in LabVIEW.

National Instruments Corporation

5-21

LabVIEW Real-Time Course Manual

Lesson 5 Communication

SummaryDiscussion Questions
Why would you need to create a normal priority loop rather than using network-published, shared variables with RT FIFOs? Why would you use network communication rather than front panel communication?

Network-published, shared variable s allow you to transfer data without creating a normal priority loop. However, you cannot alter the communication loop that the variable generates, so if you need a normal priority loop for other tasks such as data logging, you must create it normally. You also need a normal priority loop if you want to use a network communication protocol other than PSP. For example, if you want to use TCP for increased speed, or to communicate with a host application written in another programming environment, you must manually create a normal priority loop. There are many reasons for choosing network communication over front panel communication. One reason is that front panel communication is not deterministic and can affect the determinism of a time-critical VI. Use network communication methods to increase the efficiency of the communication between a host computer and VIs running on the RT target.

LabVIEW Real-Time Course Manual

5-22

ni.com

Lesson 5

Communication

Exercise 5-1
Objective:

Using RT Wizards

Use the Real-Time Project Wizard and Real-Time Communication Wizard to automatically generate code. In this exercise, you explore how the wizards provided by LabVIEW RT can reduce the amount of code you need to develop for an RT project.

Part A: RT Project Wizard


The Real-Time Project Wizard creates a framework for you when starting a new project. The wizard allows you to select your project type and options and then generates a new project file and code accordingly. 1. Select ToolsReal-Time ModuleProject Wizard to open the Real-Time Project Wizard. 2. Select Continuous communication architecture from the Project type pull-down menu. 3. Check the Application includes deterministic components checkbox. 4. Enter Project Wizard for the Project name. 5. Browse to C:\Exercises\LabVIEW Real-Time as the Project folder and select Current Folder. 6. Click Next. 7. Select the Two loops option. 8. Check the Include user interface checkbox. 9. Select the Host VI option. 10. Click Next. 11. Select the Networked option. 12. Click the Browse button. 13. In the Add Targets and Devices dialog box, select Existing device on remote subnet. 14. Select FieldPoint<Module>, where <Module> is the Fieldpoint Network Module that you are using. OR 15. Select Real-Time PXI from the list of target types if you are using PXI. 16. Enter the IP Address for the Real-Time hardware in the IP address field. 17. Click OK. 18. Click Next. 19. Check the Open VIs when finished checkbox. 20. Click Finish.

National Instruments Corporation

5-23

LabVIEW Real-Time Course Manual

Lesson 5

Communication

21. Open the target - multi rate variables VI and observe the block diagram. This VI is the target VI for the program. The VI provides two timed While Loops, one for time-critical code and one for normal priority code. Network-published shared variables communicate between the loops and back to the target. Network-published shared variables automatically create a communication thread, so no communication code is needed in the normal-priority loop. You can replace the data subVI with code to acquire or generate data. By default, the data is a sine wave. 22. Run the target - multi rate variables VI. 23. Open the host VI and observe the front panel and block diagram. The host VI reads the network-published shared variables and displays data on the front panel. 24. Run the host VI. The target VI generates data and transfers it to the host. If time allows, experiment with different configurations for the shared variables.

Part B: RT Communication Wizard


The Real-Time Communication Wizard helps you convert an existing VI to a time-critical VI running under LabVIEW RT. The Real-Time Communication Wizard automatically splits your VI into time critical and UI portions and generates communication and host code based upon options that you select. 1. Open Communication Wizard.vi in the C:\Exercises\LabVIEW Real-Time directory. 2. Observe the front panel and block diagram of the VI. Notice that the VI is a normal VI, which contains no code for performing communication between the target and host. The RT Communication Wizard can generate a host VI and communication loop for this VI, and modify the VI so that it runs as a time-critical loop on the RT target. 3. Close all open VIs and return to the LabVIEW Getting Started screen. 4. Select ToolsReal-Time ModuleCommunication Wizard to open the Real-Time Communication Wizard. 5. Click the Browse button next to the Time-critical VI checkbox and navigate to Communication Wizard.vi in the C:\Exercises\LabVIEW Real-Time directory. 6. Enter the name or IP address of the target in the Name of RT target box. 7. Select Shared Variables as the Front panel communication method.

LabVIEW Real-Time Course Manual

5-24

ni.com

Lesson 5

Communication

Note You can repeat the exercise with other communication methods to observe the different communication mechanisms.

8. Select RT Target as the Shared Variable Destination. You can deploy the shared variables on either the host or the target. Both possibilities have advantages. In Part A of this exercise, you observed a VI with variables running on the host. In this part of the exercise, deploy the variables to the target and observe that the variables function correctly in either location.
Tip

9. Click Next. 10. Select all available controls and indicators. 11. Click Next. 12. Leave the default filenames for the VIs that the Real-Time Communication Wizard generates. 13. Click Finish. LabVIEW generates a project and a library of variables. It also divides your original VI into a host VI, which contains your original front panel, and a time-critical VI, which contains your original block diagram code. Both VIs use shared variables to communicate with each other. The Real-Time Communication Wizard only creates a project for you if you choose shared variables as the communication mechanism. If you choose another communication mechanism, create a project normally and add the generated files to the project.
Note

14. Open the TCL_Communication Wizard VI from the Project Explorer and observe the block diagram of the VI. 15. Run the TCL_Communication Wizard VI. 16. Open the Host_Communication Wizard VI from the Project Explorer and observe the front panel and block diagram of the VI. 17. Run the Host_Communication Wizard VI. You should be able to see data that is transferred from the time-critical loop on the target. When generating code automatically, shared variables with long names such as the ones in this example may overlap other code. Move or resize the code to clean your block diagrams up. You also can wire the error clusters of the shared variables to control execution order and eliminate the need for the Sequence structure in the host VI.
Tip

National Instruments Corporation

5-25

LabVIEW Real-Time Course Manual

Lesson 5

Communication

18. After you are finished experimenting with the VIs, click the Stop Time Critical VI button on the host, then click the Stop button on the host, and close both VIs. 19. Close all VIs.

End of Exercise 5-1

LabVIEW Real-Time Course Manual

5-26

ni.com

Lesson 5

Communication

Exercise 5-2
Objective:

Target Program

Create the target program, which includes the normal priority loop and calls the time-critical subVI. In this exercise you create the target program for the project. This includes programming the normal priority tasks and using the time-critical subVI created in Exercise 4-2. This exercise has the following sections: Architecture, Initialization State, Configuration State, Running State, and Stop State.

Architecture
The target program has four distinct states: Initialization, Configuration, Run, and Stop. This fact immediately suggests a state machine architecture for the program. Use a simple state machine with a type-defined enumerated type control as the architecture for the target program. You could also use a queued message handler state machine. 1. Open <target-type> Real Time Project.lvproj, where <target-type> is cFP or PXI, from the C:\Exercises\LabVIEW Real-Time\ Project Files directory. 2. Select FileNew to open the New dialog box. 3. Ensure that the Add to project checkbox is checked and click OK. 4. Select VIFrom TemplateFrameworksDesign PatternsStandard State Machine. 5. Select FileSave. 6. Click Yes when prompted to save the new, unsaved files. 7. Save the type definition as State Enum.ctl in the C:\Exercises\ LabVIEW Real-Time\Project Files directory. 8. Save the state machine VI as <target-type> - NPL Project.vi in the C:\Exercises\LabVIEW Real-Time\Project Files directory, where <target-type> is cFP or PXI. 9. Close the VI. 10. Drag the <target type> - NPL Project VI from the My Computer section of the Project Explorer to the RT Target. 11. Double-click the <target type> - NPL Project VI to open it. 12. Modify the block diagram of the VI as shown in Figure 5-1. The modifications include removing the timing function, stop conditions, and documentation.

National Instruments Corporation

5-27

LabVIEW Real-Time Course Manual

Lesson 5

Communication

13. Update the type-defined enumerated type constant to include all of the necessary states. a. Right-click the Beginning State enumerated type constant and select Open Type Def to modify the type definition. b. Right-click the States enumerated type control and select Edit Items. c. Add Configure and Running to the available states. d. Save the type definition. e. Close the type definition. After the type definition has been updated, all other copies of that type definition are also updated. For example, use the Select tool on a different instance of the type definition to confirm that the Configure and Running options are available. 14. Add cases to the Case structure for each of the added states as shown in Figure 5-1. a. Right-click the Case Selector label and select Add Case After to add the Configure state. b. Repeat Step a to add the Running state.

Figure 5-1. State Machine Template Modifications

LabVIEW Real-Time Course Manual

5-28

ni.com

Lesson 5

Communication

You have completed the basic architecture for the target program. Now, you can begin developing the code from the design at any state. Many programmers find it easiest to begin in the Running state and add the other states to support the Running state afterwards. This allows you to discover what you must provide to the Running state as you program, reducing your debugging time. 15. Before starting the Running state portion of this exercise, explore the subVIs provided to you for this application. These VIs are located in the Project subVIs folder of your project. The following module subVIs are provided: the FIFO Module, the File I/O Module, and the TCP Module. These modules perform the major tasks you need to accomplish. Each is a multi-functional subVI that you control by passing enumerated commands to the operation input. The FIFO SubVIs Module has Configure, Read, and Clear operations. This module reads the shared-variable FIFOs from the time-critical loop and formats the data for transfer to the File and TCP modules. The File SubVIs Module has Create, Write, and Close operations. This module logs the data into an ASCII file on the target. The TCP SubVIs Module has First Connection to Host, Get Config from Host, Close Connection, Reconnect to Host, and Data Transfer operations. This module transfers data from the target to the host for display. Also, the Variables folder contains a global variable and two functional global variables for sharing non-deterministic data between the time-critical and normal priority loops. 16. Save the VI.

Running State
In this section, build the Running state for the target program. Figure 5-2 shows the flowchart for this section; refer to this flowchart as necessary. This flowchart was created in Exercise 3-3.

National Instruments Corporation

5-29

LabVIEW Real-Time Course Manual

Lesson 5

Communication

Run TCL SubVI

Get Data from TCL

Transfer Data to and from Host and Log to File

Transfer Distrubance and Stop to TCL

TCL Stopped?

No

Error?

No

Yes Yes

Yes Yes Close Resources

FIFO Empty?

Close Log File

Unrecoverable Error?

No Read FIFO Data, Log, and Transfer to Host

Figure 5-2. Target Run State Flowchart

1. Drag <target-type> - TCL Project VI, from the Project Explorer to the Running case of the NPL Project VI case structure, where <target-type> is cFP or PXI. Refer to 5-3 for the placement of the VI. After you have performed the appropriate initialization and configuration you call the time-critical loop to start the control and data acquisition. 2. Double-click the <target-type> - TCL Project VI. Notice that the TCL Run block on the flowchart has no connections to any other portion of the flowchart. This indicates that there is no data dependency between the time critical portion of the VI and the normal priority portion of the VI. 3. Create an indicator on the Stopped output of the <target-type> TCL cFP Project VI. Rename the indicator TCL Stopped to make it more descriptive. 4. Place a While Loop inside the Running case, but not enclosing the TCL call, to contain the normal priority tasks involved in the Running state. The first block on the flowchart is Get Data from TCL. Notice that there is a returning arrow to this block. Therefore, this process should be placed inside the While Loop created in step 4. 5. Drag a FIFO Module VI from the Project Explorer to the normal priority loop.

LabVIEW Real-Time Course Manual

5-30

ni.com

Lesson 5

Communication

6. Select the Read operation on the FIFO Module VI by right-clicking the Operation input and selecting CreateConstant. Use the Operating tool to set the value of the enumerated constant to Read. The next block on the flowchart is Transfer Data to and from Host and Log to File. The data is transferred to the host through TCP. If you lose the TCP connection, the program should continue running and accomplish all non-TCP processes without error. One way to assure this is to make the TCP task and the log task into parallel processes. 7. Drag a TCP Module VI from the Project Explorer, with the Data Transfer operation on the block diagram. This subVI writes the current FIFO data to the host and reads the Disturbance and Stop Booleans from the host. 8. Place a File Module VI, with the Write operation on the block diagram after the FIFO Module VI. 9. Place a Merge Errors VI on the block diagram to merge the error clusters from the File Module VI and the TCP Module VI. Create constants for the File Module VI and the TCP Module VI. 10. Wire the File Module VI and the TCP Module VI as shown in Figure 5-3.

Figure 5-3. Merge Errors from Parallel Process Note

Figure 5-3 and the subsequent figures in this section show the TCL VI for the PXI target. The TCL for cFP targets has a slightly different icon. In Figure 5-2, the next block on the flowchart is Transfer Disturbance and Stop to TCL. This data is received from the host through TCP, so if the TCP

National Instruments Corporation

5-31

LabVIEW Real-Time Course Manual

Lesson 5

Communication

connection has been lost, this block must be skipped. Because the error cluster contains the TCP error, the subVI should not execute if it receives an error. 11. Place a Write FGVs VI on the block diagram after the Merge Errors VI. This VI is a functional global variable that has already been created for you. a. Drag the Write FGVs VI from the Project Explorer. b. Wire the error cluster from the Merge Errors VI to the Write FGVs VI. The functional global variable is designed to skip if it receives an error.

Figure 5-4. Write FGVs in the Running State

c. Pass the disturbance and stop data to the time critical loop from the TCP Module VI to the Write FGVs VI as shown in Figure 5-4. If the TCP connection has been lost, it must be reconnected without interfering with the FIFO read and data log. Therefore, use a separate While Loop to check the connection and reconnect if the connection has been lost. This server loop design appears in Figure 5-5. 12. Add a TCP server loop to the Running state. a. Add space to increase the height of the state machine. b. Place a While Loop in the Running state. c. Place a TCP Module VI on the block diagram in the new While Loop. d. Right-click the Operation input of the TCP Module VI and select the Reconnect to Host.

LabVIEW Real-Time Course Manual

5-32

ni.com

Lesson 5

Communication

e. Create a constant on the TCP Port input. Move the constant outside the state machine, because this value only needs to be read once. Although you use the default value 1080, creating a constant makes it easier to modify the port if needed for debugging. f. Add a software wait to create sleep time for the server loop by using the Wait Until Next ms Multiple VI. g. Create a constant of 100 ms for the Wait Until Next ms Multiple VI. This software sleep does not affect the loop rate of the TCL tasks. The software sleep only affects the rate at which the server loop checks for reconnection.

Figure 5-5. TCP Server Loop

The next set of blocks on the flowchart in Figure 5-2 refer to the stop conditions for the loop. These blocks show that the TCP Client and Log loop should stop if the time-critical subVI has stopped and the FIFOs are empty, or an error has occurred. The following is the logic equation:
[TCL Stopped AND FIFOs empty] OR error occurred

13. Create a local variable of the TCL Stopped indicator to read this value in the TCP Client and Log loop. 14. Right-click the local variable and select Change to Read. 15. Place an And function after the local variable.

National Instruments Corporation

5-33

LabVIEW Real-Time Course Manual

Lesson 5

Communication

16. Determine whether all the FIFOs have been read. a. Place an Equal to Zero? function on the block diagram before the And function. b. Wire the Elements Read output of the FIFO Module to the Equal to Zero? function. When Elements Read is equal to zero, the FIFOs are empty. 17. Wire the inputs of the And function. a. Wire the TCL Stopped local variable to one input of the And function. b. Wire the Equal to Zero? output to the other input of the And function. 18. Place an Or function on the block diagram after the And function. 19. Wire the And function output to one of the Or inputs. 20. Wire the status Boolean value of the error cluster to the other Or input. a. Place an Unbundle by Name on the block diagram after the Write FGVs VI. b. Wire the error output of the Write FGVs VI to the Unbundle by Name function. The status Boolean should populate the Unbundle by Name function as the default selection. c. Wire the output of the Unbundle by Name function to the input of the Or function. d. Wire the output of the Or function to the Stop loop control. The block diagram code just created mirrors the logic equation:
[TCL Stopped AND FIFOs empty] OR error occurred

Confirm correct completion by referring to Figure 5-6. 21. Add software sleep to the TCP client and log loop. This software sleep does not affect the loop rate of the TCL tasks; it only affects the rate at which the data displays to the user and writes to file. a. Place a Wait function on the block diagram in the While Loop. b. Create a constant on the input of the timing function, and set the constant to 100. You can adjust this sleep time or use a different timing function if you prefer.

LabVIEW Real-Time Course Manual

5-34

ni.com

Lesson 5

Communication

Figure 5-6. Stop Conditions for TCP Client and Log loop

One problem not taken into consideration is how to remove TCP errors so that these errors do not cause the While Loop to stop. Currently, any error causes the While Loop to stop. Many ways exist to solve this problem. The following steps illustrate one possible method. 22. Enclose the contents of the TCP Client and Log Loop in another While Loop, as shown in Figure 5-7. 23. Place a TCP Module VI on the block diagram in the new While Loop, as the next task along the error cluster. 24. Select the Close Connection operation on the TCP Module VI. This operation closes the connection if it is still open and erases any connection errors. 25. Check the Loop conditions using the same logic as the interior loop. Refer to Figure 5-7 for assistance. Set the Stop conditions for the server loop. The server loop should stop when the client loop stops. 26. Create an indicator on the stop conditions configured in step 25. a. Right-click the wire between the Or function and the Stop terminal and select CreateIndicator from the shortcut menu. b. Rename the indicator to Running Complete.

National Instruments Corporation

5-35

LabVIEW Real-Time Course Manual

Lesson 5

Communication

27. Create a local variable from the Running Complete indicator. 28. Place the Running Complete indicator in the server loop to stop the server loop as shown in Figure 5-7.

Figure 5-7. Stop the TCP Server Loop

The only block remaining on the flowchart for the Running state is Close Log File. The log file should only close if stop conditions have been met. Therefore, the log file should close outside the normal priority loops. 29. Place a File Module VI on the block diagram as the next task along the error cluster, outside the While Loops. You may need to expand the width of the state machine to create room for the function. 30. Right-click the Operation input and select the Close operation on the File Module VI. Determine the next state for the state machine to go to when the Running state has completed. If the state has completed because the TCL subVI completed, the state machine should progress to the Configuration state, as shown in the Normal Priority flowchart. However, if an unrecoverable error (in this case, a non-TCP error) has occurred, the state machine should progress to the Stop state to close the resources and end the target program. An unrecoverable error is the only reason the target program ends.

LabVIEW Real-Time Course Manual

5-36

ni.com

Lesson 5

Communication

31. Merge the errors from the time-critical subVI and the File Module VI to determine whether an unrecoverable error has occurred. You need to determine if an unrecoverable error has occurred in every state, so complete the error check on the error cluster outside the Case structure. a. Place a Merge Error VI on the block diagram after the File Module VI. b. Wire the error outputs from both VIs to the Merge Error VI. c. Place an Unbundle by Name function on the block diagram after the Merge Error VI outside the Case structure to access the status Boolean on the error output. d. Place a Select function on the block diagram on the input side of the State Enum shift register. e. Use the status Boolean value from the Unbundle by Name function as the input to the Select function. f. If an error has occurred, go to the Stop case.
Tip Use the State Enum type definition to create an enumerated constant to select the next case. The easiest way to accomplish this is to copy and paste an enumerated constant that is already referenced to the type definition.

g. If an error has not occurred, go to the Configure case. Refer to Figure 5-8 for assistance in completing this step. 32. Pass a FALSE constant from the Running state to the loop condition terminal for the state machine. a. Place a FALSE constant inside the Case structure. b. Wire the FALSE constant to the loop condition terminal of the exterior While loop.
Note

The state machine only stops from the Close state. 33. Pass the error cluster to other states in the state machine. a. Wire the error cluster from the Merge Errors VI to the border of the While Loop. b. Right-click the tunnel that appears and select Replace with Shift Register. A shift register also appears on the opposite side of the While Loop. c. Wire the error input shift register to the error input on the FIFO Module VI with the Read operation. d. Wire the input error shift register to the error input on the time-critical subVI as well.

National Instruments Corporation

5-37

LabVIEW Real-Time Course Manual

Lesson 5

Communication

Figure 5-8. Set up the error shift register

You have completed the Running state of the state machine.

Stop State
If the target program reaches the Stop state, then an unrecoverable error has occurred. The Stop state is responsible for closing and releasing any resources. Potential resources in this program include a File resource, FIFO resources, and a TCP connection. The File resource and the TCP connection has been closed already in the Running state. The only resources remaining are the FIFO Resources. 1. Switch to the Stop case on the state machine. 2. Place an instance of FIFO Module VI on the block diagram in the Stop case. 3. Select the Clear operation to clear the FIFO resources. 4. Pass the error cluster through the case as shown in Figure 5-9. 5. Wire a TRUE constant to the state machine stop terminal. A Stop value of the State Enum enumerated constant has already been connected to the tunnel that controls the next state. This was built into the state machine template. Because you end the While Loop in this state, the value wired into the next state tunnel will be ignored.

LabVIEW Real-Time Course Manual

5-38

ni.com

Lesson 5

Communication

Figure 5-9. Stop State

You have completed the Stop case.

Initialize State
An initialization state opens resources and initializes any controls or indicators used, including local and global variables. In this program, the Initialize state runs only once. If any items need to be initialized more than once, such as each time a temperature profile runs, then the initialization should be placed in the Configure state. The Configure state runs each time a new profile is downloaded to the target. A simple way to determine which resources need to be opened only once is to determine which resources are closed only once. For example, in the Stop state, the only resources closed are the FIFO resources. 1. Switch to the Initialize case on the state machine. 2. Create the RT FIFOs used throughout the target program, as shown in Figure 5-10. a. Place an instance of the FIFO Module VI on the block diagram in the Initialize case. b. Select the Configure operation on the FIFO Module VI. c. Wire the error output from the FIFO Module VI to the error shift register. 3. Change the Next State enumerated constant to Configure.

National Instruments Corporation

5-39

LabVIEW Real-Time Course Manual

Lesson 5

Communication

4. Create a FALSE constant for the state machine Loop Condition terminal. 5. Refer to Figure 5-10 to confirm that you have correctly completed the Initialize state.

Figure 5-10. Initialize State

6. Save the VI. You have completed the Initialize state of the state machine. You reinitialize the local and global variables in the Configure state, because they must be reinitialized for each temperature profile.

Configure State
In this section, build the Configure state for the target program. From the previous section, you know that you need to initialize the local variables in the Configure state. Before beginning the tasks outlined in the flowchart, initialize the necessary items. 1. Switch to the Configure case of the state machine. 2. Set the stop indicators used in the Running state to FALSE. a. Place two local variables in the Configure case. b. Click the first variable and select TCL Stopped. c. Click the second variable and select Running Complete.

LabVIEW Real-Time Course Manual

5-40

ni.com

Lesson 5

Communication

d. Confirm that each local variable is set to Write. e. Create a FALSE Constant for both local variables. f. Encase this code in a Flat Sequence Structure. This allows you to easily impose data flow on this code in the future. g. Refer to Figure 5-11 for assistance in completing this step.

Figure 5-11. Initialize Local Variables

Refer to Figure 5-12, as necessary, for the flowchart for this section. This flowchart was created in Exercise 3-3.

National Instruments Corporation

5-41

LabVIEW Real-Time Course Manual

Lesson 5

Communication

Connected to Host? Yes

No

Connect to Host

Listen for Data

No

Data Received?

Yes

Open Log File

Figure 5-12. Configure Flow Chart

Notice that the top portion of the flowchart repeats, depending on whether it receives the data. You use a While Loop in LabVIEW to implement this repetitive behavior. The configure portion of the flowchart starts at the Connect to Host block. Refer to Figure 5-13 for more information on programming the block diagram. 3. Place a While Loop on the block diagram in the Configure case. 4. Implement the Connect to Host block of the flowchart. a. Place a TCP Module VI on the block diagram in the While Loop. b. Select the First Connection to Host operation on the TCP Module VI. c. Wire the error cluster shift register to the error in input of the TCP Module VI. d. Wire the TCP port constant to the TCP port input of the TCP Module VI. Wire through the local variable Sequence structure; this ensures that the local variables execute before the While Loop.

LabVIEW Real-Time Course Manual

5-42

ni.com

Lesson 5

Communication

5. Implement the Listen For Data block of the flowchart. a. Place a TCP Module VI on the block diagram in the While Loop. b. Select the Get Config from Host operation on the TCP Module VI. c. Wire the error cluster from the output of the previous TCP Module VI to the input of this TCP Module VI. If data are sent, you must convert the data to the correct type. The data to convert includes the PID gains, the setpoint profile, and the log file name. 6. Convert the data output of the TCP Module. Within the TCP Module VI, the retrieved data has already been converted from a binary string to an array of binary strings. Refer to Figure 5-13 for assistance with completing this step. a. Place an Index Array function on the block diagram on the Config data output of the TCP Module VI. b. Resize of the Index Array function to include two additional input/output pairs. Each output of the Index Array function is a string containing one of the three pieces of retrieved data. c. Place an Unflatten From String function on the block diagram after each output of the Index Array function. This function coverts the binary string input into a type that you specify. d. Place instances of the PID Gains and Setpoint Profile global variables on the block diagram. Both variables are located in the Global VI in the Variables folder.
Tip To place an instance of an existing global variable, drag the variable file from the Project Explorer and then right-click and select Select Item to choose the specific global value.

e. Right-click each global variable and select CreateConstant. You can rearrange the constants inside each cluster and hide index displays on arrays to reduce the block diagram size of the constants.
Tip

f. Place a String constant on the block diagram. g. Wire as shown in Figure 5-13. Use the constants from the global variable and string constant as the type inputs of the Unflatten From String function.

National Instruments Corporation

5-43

LabVIEW Real-Time Course Manual

Lesson 5

Communication

Figure 5-13. Unflatten TCP Data

Refer to Figure 5-16 for wiring information. 7. Implement the Data Received? and Connected to Host? checks of the flowchart. If data was not sent over TCP, the TCP Module outputs an error. If data was sent, no error occurs. Use this information to determine the stop behavior for the While Loop and to disconnect and reconnect the host. A more efficient way to implement the Connected to Host? check is to check the connection status and only reconnect if necessary. However, in this particular VI you do not have access to the TCP reference for the connection.
Tip

a. Place a Case structure on the block diagram after the TCP Module VIs. b. Place a Merge Errors VI on the block diagram. c. Wire the error wires from each Unflatten From String function to the Merge Errors VI. d. Wire the error cluster from the Merge Errors VI to the case selector input of the Case structure. e. Place a True Constant in the No Error case of the Case structure and wire the constant through a tunnel to the stop condition of the While Loop.

LabVIEW Real-Time Course Manual

5-44

ni.com

Lesson 5

Communication

If no error occurred then the data was retrieved and decoded successfully, so you should exit the While Loop. f. Pass the error through the No Error case, as shown in Figure 5-14.

Figure 5-14. No Connection Error - Data Received

g. Place a TCP Module VI on the block diagram in the Error case. h. Select the Close Connection operation on the TCP Module VI. This operation closes the TCP connection if it has not already ended and erases any connection errors that may have occurred. i. Place a FALSE Constant in the Error case. Wire the constant to the stop tunnel. If an error occurred, then re-establish the connection and try again. j. Pass the new error through the case, as shown in Figure 5-15.

Figure 5-15. Connection Error - Disconnect TCP

8. Implement the Open Log File block of the flowchart. The log file should be opened only after data has been received, therefore open the file outside the While Loop. a. Place a File Module VI on the block diagram outside the While Loop, but inside the Configure case. b. Select the Create operation on the File Module VI. c. Wire as shown in Figure 5-16.

National Instruments Corporation

5-45

LabVIEW Real-Time Course Manual

Lesson 5

Communication

9. Determine the next case to execute. a. Place a FALSE constant on the block diagram and wire to the state machine loop condition. b. Place an instance of the State Enum enumerated constant on the block diagram and select the Running state. c. Wire as shown in Figure 5-16.

Figure 5-16. Determine Next State After Configure

10. Save the VI. You have completed the Configure state and the entire state machine. In the next exercise you build the host program, which allows you to test your entire project. Now examine your program to be sure you understand the operation and that each step has been completed. You should see a solid Run button implying that there are no errors.

End of Exercise 5-2

LabVIEW Real-Time Course Manual

5-46

ni.com

Lesson 5

Communication

Exercise 5-3
Objective:

Completed Project Host VI


If you want, skip this exercise and complete Exercise 5-4 instead. In Exercise 5-4, rather than opening a completed host VI, you complete the host VI by adding the programming necessary to implement the flowchart steps specified in Exercise 3-3. In this exercise, the host VI has already been completed for you. 1. Add the Completed Project Host.vi in the C:\Exercises\ LabVIEW Real-Time\Project Files directory to the My Computer target of your project. The host VI does not run on the RT target. It runs on the host computer to provide a user interface. The My Computer target represents the host computer in your project. 2. Right-click the My Computer target and select NewFolder. Name the folder Project subVIs. 3. Double-click the Completed Project Host VI to open it. 4. The front panel is shown in Figure 5-19. Review the front panel. You may want to change the chart properties and the setpoint profile values.

Review the completed host VI for the project and compare to the provided flowchart.

Figure 5-17. Host User Interface

5. Enter the IP address of your target in the RT target control. 6. Right-click the RT target control and select Data OperationsMake Current Value Default.

National Instruments Corporation

5-47

LabVIEW Real-Time Course Manual

Lesson 5

Communication

7. If you have changed the values of any other controls, set the new value to default, as in the previous step, to hold the control values. 8. Open the block diagram. 9. Compare the block diagram to the flowchart you created in Exercise 3-3. A copy of the flowchart is included in Figure 5-18.

Initialize

No Target Running? Yes No Idle Start Button Pressed? Yes Send Configuration Data to Target

Read and Write Data from Target No Host Stop Pressed or Error? Yes No Data Request Complete? Yes Clean Up Resources

Figure 5-18. Host Flowchart

10. Open and run the <target-type> - NPL Project VI. 11. Run the Completed Project Host VI. 12. If your target VI did not have any errors, you can use the host VI to try communicating with the target. If the VI does not work, debug the VI in Lesson 6, Verifying Your Application. 13. If you are not completing Exercise 5-4, save this VI as Project Host.vi in the C:\Exercises\LabVIEW Real-Time\Project Files directory. Replace the existing file when requested. 14. Stop and close both VIs when you are finished.

End of Exercise 5-3

LabVIEW Real-Time Course Manual

5-48

ni.com

Lesson 5

Communication

Exercise 5-4
Objective:

Project Host VI (Optional)


The user interface for the host VI has already been completed for you. Add the programming necessary to implement the flowchart steps specified in Exercise 3-3. This exercise includes the following segments: Architecture, Check Target State, Idle State, Configuration State, Running State. 1. Add the Project Host.vi in the C:\Exercises\LabVIEW Real-Time\Project Files directory to the My Computer target of your project. The host VI does not run on the RT target. It runs on the host computer to provide a user interface. The My Computer target represents the host computer in your project. 2. Right-click the My Computer target and select NewFolder. Name the folder Project subVIs. 3. Double-click the Project Host VI to open it. 4. The user interface has already been created for you and is shown in Figure 5-19.

Create the host VI for the project from the provided flowchart.

Figure 5-19. Host User Interface

5. Review the user interface. You may want to change the chart axis ranges and the Setpoint Profile values. 6. Enter the IP address of your target in the RT target control. 7. Open the block diagram.

National Instruments Corporation

5-49

LabVIEW Real-Time Course Manual

Lesson 5

Communication

8. Review the host flowchart, as shown in Figure 5-20, to prepare for creating the host VI.

Initialize

No Target Running? Yes No Idle Start Button Pressed? Yes Send Configuration Data to Target

Read and Write Data from Target No Host Stop Pressed or Error? Yes No Data Request Complete? Yes Clean Up Resources

Figure 5-20. Host Flowchart

Architecture
The host program has three distinct states as stated in the Requirements Document: Idle, Configuration, and Running. Use a simple state machine with a type-defined enumerated control as the architecture for the target program. Unlike the previous exercise, build the architecture from scratch. 1. Temporarily move all controls and indicators to one area of the block diagram for easy access in the future. 2. Place a While Loop on the block diagram. Do not enclose the controls and indicators in the While Loop. 3. Place a Case structure on the block diagram inside the While Loop to create the state machine. 4. Create a constant to initialize the state machine. The Control State indicator is a type-defined enumerated indicator of the states of the state machine. a. Right-click the Control State indicator and select CreateConstant. b. Set the value of the constant to Idle.

LabVIEW Real-Time Course Manual

5-50

ni.com

Lesson 5

Communication

c. Wire the constant to the case selector of the Case structure. d. Add any missing states to the state machine by right-clicking the case selector and selecting Add Case for Every Value. Your state machine should contain three states: Idle, Configuration, and Running. e. Replace the While Loop tunnel for the state with a shift register, as shown in Figure 5-21.

Figure 5-21. State Machine for the Host Program

You have now completed the architecture design for the state machine.

Idle State
In the Idle state, implement the Idle block of the flowchart. The flowchart shows that the program does not progress until the Start button has been clicked. 1. Read the Start button to determine whether is has been clicked. a. Move the Start control into the Idle case of the state machine. b. Place a Select function on the block diagram to determine the next state based on the value of the Start button. c. Place two copies of the state enumerated control in the idle state. d. If the Start button is FALSE, that is, it has not been clicked, return to the Idle state.

National Instruments Corporation

5-51

LabVIEW Real-Time Course Manual

Lesson 5

Communication

e. If the Start button is TRUE, that is, it has been pressed, go to the Configuration state. f. Complete the wiring as shown in Figure 5-22. 2. Display the next state of the state machine on the Control State indicator. a. Move the Control State indicator in the While Loop to the right of the Case structure. b. Wire the state data to the indicator. 3. Add software timing to the While Loop to provide processor time. a. Place a Wait Until Next ms Multiple function on the block diagram in the While Loop, to the right of the Case structure. b. Create a constant on the input of the timing function and enter a value of 100 to give a 100 ms software wait time.

Figure 5-22. Idle State for the Host Program

You have now completed the Idle state of the host program.

Configuration State
The next block on the flowchart is Send Configuration Data to Target. This block describes the total operation of the Configuration state. Once the user has clicked the start button, the current PID Gains, Setpoint Profile, and Log File Name are sent to the target.

LabVIEW Real-Time Course Manual

5-52

ni.com

Lesson 5

Communication

For assistance in completing the Configuration state, refer to Figure 5-23. 1. Open the Configuration case of the state machine. 2. Connect to the target through TCP. A Host TCP Module VI has been provided to you. It is very similar to the TCP Module VI used in the target program. Open this VI and familiarize yourself with its functions. a. Place a Host TCP Module VI on the block diagram in the Configuration case. b. Select the Connect to Target operation on the Host TCP Module VI. c. Wire the TCP Port and TCP timeout (ms) constants to the appropriate inputs of the Host TCP Module VI. Leave the constants outside the state machine, because the values do not change while the program is running. d. Wire the RT target control to the address input of the Host TCP Module VI. e. Leave this control outside the state machine as well. A Boolean flag is sent through TCP from the target to the host when the TCP connection is made. The flag is TRUE if the target is waiting for configuration data, and FALSE if the target is currently running a configuration data set. You will use this data before the state machine to complete the Target Running? check on the flowchart. In the Configuration state, the data is irrelevant, but must be read to remove it from the data queue. 3. Read the Boolean flag to remove it from the TCP data queue. a. Place another Host TCP Module VI on the block diagram next to the existing Host TCP Module VI. b. Select the Read Boolean Flag operation on the Host TCP Module VI. c. Wire the TCP timeout (ms) constant to the appropriate input of the Host TCP Module VI. d. Wire the error out from the previous VI to the error in of this VI. 4. Prepare the configuration data for TCP transfer to the target. This data must be converted to a binary string. a. Move the PID Gains, Setpoint Profile, and Log File Name controls inside the Configuration state. b. Place a Flatten to String function on the block diagram after each control. c. Place a Build Array function on the block diagram to combine these three binary strings into a binary string array.

National Instruments Corporation

5-53

LabVIEW Real-Time Course Manual

Lesson 5

Communication

d. Resize the Build Array function to add two additional inputs. e. Wire the data string output of each Flatten to String function to an input of the Build Array function. The order of the array has already been determined in the target program. You must match the order of the array. The first item is the PID Gains, the second item is the Setpoint Profile, and the third item is the Log File Name. 5. Pass the configuration data to the target. a. Place another Host TCP Module VI on the block diagram next to the last Host TCP Module VI. b. Select the Write operation on the Host TCP Module VI. c. Wire the TCP timeout (ms) constant to the appropriate input of the Host TCP Module VI. d. Wire the error out from the previous VI to the error in of this VI. e. Wire the output of the Build Array function to the Data In input on the Host TCP Module VI with the Write operation. 6. Execute the Running state of the state machine after completion of the Configuration case. a. Place an instance of the state enumerated constant on the block diagram in the Configuration case. b. Select the Running option on the enumerated constant. c. Wire to the next state output of the Case structure. 7. Pass the error cluster to other states through a shift register. You have completed the Configuration case. Refer to Figure 5-23 to verify completion of the Configuration state.

LabVIEW Real-Time Course Manual

5-54

ni.com

Lesson 5

Communication

Figure 5-23. Configuration State for the Host Program

Running State
The next block on the flowchart is Read and Write Data from Target. This state continues until you press the Stop Host button, the target program completes its Running State, or an error occurs. 1. Switch to the Running case of the state machine. 2. Move the Disturbance and Stop RT controls into the Running case. 3. Format the data into a binary string array, with the Disturbance data listed first in the array. a. Place two Type Cast functions on the block diagram into the Running case. b. Wire the Booleans to the input of a Type Cast function. The Type Cast functions convert to binary string as the default operation, so there is no need to wire a type to the function. c. Place a Build Array function on the block diagram in the Running case after the Type Cast functions. d. Resize the Build Array function to include a second input. e. Wire the binary string conversion of the Disturbance Boolean to the first input and the binary string conversion of the Stop RT Boolean to the second input of the build array.

National Instruments Corporation

5-55

LabVIEW Real-Time Course Manual

Lesson 5

Communication

4. Write the Disturbance and Emergency Stop Booleans to the target. a. Place a TCP Host Module VI on the block diagram in the Running state after the Build Array. b. Select the Write operation on the TCP Host Module VI. c. Wire the output of the Build Array function to the data in input of the TCP Host Module VI. d. Wire the error cluster to the error in on the TCP Host Module VI. 5. Read the TCP data from the target. a. Place a TCP Host Module VI on the block diagram in the Running state after the TCP Host Module VI placed in step 4. b. Select the Read operation on the TCP Host Module VI. c. Wire the error cluster. 6. Convert the TCP data to display on the front panel. The TCP data is a binary string array, which may contain more than one set of data. Refer to Figure 5-24 for assistance with completing this step. a. Place an Index Array function on the block diagram after the TCP Host Module VI. Use this function to read the individual string elements of the array. b. Wire the Data Out output of the TCP Host Module VI to the array input of the Index Array function. c. Resize the Index Array function so that it has five index inputs and five element outputs, to match the five expected pieces of TCP data. d. Place five Unflatten From String functions on the block diagram; one after each element output of the Index Array function. The data is currently a binary string. Each string must be converted to an array of ASCII strings. e. Wire the element outputs of the Index Array function to the binary string input of an Unflatten From String function. f. Wire a string array to the type input of each Unflatten From String function. g. Place a For Loop on the block diagram after the Unflatten From String functions. Use the For Loop to step through the array data. If you use the index array input on a For Loop, the For Loop reads one element of the array for each iteration of the loop. It ends as soon as the array is empty. h. Wire the value output of each Unflatten From String function to the While Loop.

LabVIEW Real-Time Course Manual

5-56

ni.com

Lesson 5

Communication

i. Right-click each input tunnel on the For Loop and select Enable Indexing. j. Move the Disturbance, Temp Chart, Current Timestamp, and Lamp Power indicators into the While Loop, in the order listed. k. Place five Type Cast functions inside the For Loop. l. Wire each input tunnel to an x input on each Type Cast function. m. Wire a Boolean constant to the type input of the first Type Cast function. The first data in the binary string array is a Boolean indicating whether the disturbance (fan) is on or off. n. Wire a Numeric constant of double representation to the type input of each of the remaining Type Cast functions. The remaining elements of the binary string array are the setpoint, actual temperature, timestamp and lamp power, which are all double-precision, floating-point numerics.
Tip Right-click the Numeric constant and select RepresentationDouble Precision to change the representation type.

o. Wire the first indexed tunnel to the Disturbance indicator. p. Place a Bundle function on the block diagram after the second indexed tunnel. q. Wire the second indexed tunnel to the first input on the Bundle function and wire the third indexed tunnel to the second input on the Bundle function. The Bundle function combines the setpoint and actual temperature values into one wire to wire to the temperature chart. Each element of the Bundle function is a plot on the chart. r. Wire the output of the Bundle function to the Temp Chart indicator. s. Place a Format Date/Time String function on the block diagram after the fourth indexed tunnel. t. Wire the fourth index tunnel to the time stamp input of the Format Date/Time String function. u. Wire the date/time string output of the Format Date/Time String function to the Current Timestamp indicator. v. Wire the fifth index tunnel to the Lamp Power indicator.

National Instruments Corporation

5-57

LabVIEW Real-Time Course Manual

Lesson 5

Communication

Figure 5-24. Convert TCP Data for Display

7. Determine the next state after the Running state. When the target has finished sending data, the state machine returns to the Idle state to wait for the next set profile. If the target has not finished sending data, the state machine returns to the Running state to retrieve the next set of TCP data. Check whether the target has finished sending data by watching for an error 66 to occur. An error 66 (Connection Closed error) occurs when the TCP connection has been closed by the target. a. Place an Unbundle by Name function on the block diagram after the TCP Host Module VI set to the Read operation. b. Wire the error out output from the TCP Host Module VI to the Unbundle by Name function. Use the Unbundle by Name function to determine whether an error has occurred. The status element displays by default. c. Use the Operating tool to select the Code element on the Unbundle by Name function. d. Place a Case structure on the block diagram after the Unbundle by Name function. e. Wire the Unbundle by Name function output to the case selector on the Case structure. f. Go to the 1 case and use the Typing tool to change 1 to 66. g. Place an instance of the State Enum on the block diagram in each case.

LabVIEW Real-Time Course Manual

5-58

ni.com

Lesson 5

Communication

h. Wire the 0 case as shown in Figure 5-25.

Figure 5-25. Connection Zero Case

i. Place a TCP Host Module VI in the 66 case. j. Select the Close Connection operation on the TCP Host Module VI. k. Wire the 66 case as shown in Figure 5-26.

Figure 5-26. Connection 66 Case

8. Implement the stop conditions to complete the state machine. The state machine ends when the user clicks the Stop Host button, or when a unrecoverable error has occurred. The Stop Host Boolean and error check should be checked in every state, therefore, implement the stop conditions outside the Case structure. Refer to Figure for assistance with completing this step. a. Move the Stop Host Boolean into the state machine While Loop next to the loop condition terminal. b. Place an Unbundle by Name function on the block diagram in the same location. c. Wire the error cluster to the Unbundle by Name function. Use the Unbundle by Name function to determine whether an error has occurred. The status element is available by default. d. Place an Or function on the block diagram next to the loop condition terminal.

National Instruments Corporation

5-59

LabVIEW Real-Time Course Manual

Lesson 5

Communication

e. Wire the Stop Host Boolean to one input of the Or function. f. Wire the Unbundle by Name function output to the other input of the Or function. g. Wire the output of the Or function to the loop condition terminal. At this point, the state machine should be complete. However, notice that the error cluster output from the Case structure is missing a connection in one case. Because you created the error cluster shift register in the Configuration state, the errors in the Idle state were never wired. h. Return to the Idle case and wire the error cluster through the case. You have completed the state machine.

Figure 5-27. Completed Host State Machine

Check Target State


When the host program is first started, check to see if the target program is currently running a profile or if it is waiting for configuration data. The framework for this check has already been designed. The target program sends a Boolean flag whenever it connects to the host. If it is the first connection, the flag is TRUE. If it is not the first connection, the flag is FALSE. Therefore, if the flag is TRUE, the target is waiting for configuration data. If the flag is FALSE, the target is currently running a profile. Use this information to determine where the Host program should start. Place this programming to the left of the state machine.

LabVIEW Real-Time Course Manual

5-60

ni.com

Lesson 5

Communication

1. Wire to the target program through TCP. a. Select the TCP Port, RT target, and TCP timeout ms constants/controls, and move them to the left on the block diagram. Leave enough room between the constants and controls and the state machine to place a few VIs. b. Place a Host TCP Module VI on the block diagram next to the constant/controls. c. Select the Connect to Target operation on the Host TCP Module VI. d. Disconnect the TCP Port constant and RT target control. e. Wire the constants and controls to the appropriate inputs of the Host TCP Module VI. The TCP port value and RT target address are held in a shift register inside the Host TCP Module VI as the TCP Refnum. Therefore, this data only needs to be passed to instances of the Host TCP Module VI that are using the Connect to Target operation. 2. Read the Boolean flag from the TCP data. a. Place a Host TCP Module VI on the block diagram next to the Host TCP Module VI set to Connect to Target operation. b. Select the Read Boolean Flag operation on the Host TCP Module VI. c. Wire the error output from the previous Host TCP Module VI to the error input of this Host TCP Module VI. 3. Determine in which state to begin the host program. a. Place a Case structure on the block diagram next to the Host TCP Module VI set to the Read Boolean Flag operation. b. Wire the value output of the Host Module VI to the case selector of the Case structure. c. Switch to the TRUE case of the Case structure. d. Move the Idle enumerated constant on the state machine input to the TRUE case of the Case structure. If the Boolean flag is TRUE, the target is waiting for configuration data and the host program should begin in the Idle state. e. Reconnect the enumerated constant to the state machine state input. f. Place a Host TCP Module VI on the block diagram in the TRUE case of the Case structure. g. Select the Close Connection operation on the Host TCP Module VI. h. Wire the error cluster from the VI before the Case structure to the Host TCP Module VI input inside the Case structure.

National Instruments Corporation

5-61

LabVIEW Real-Time Course Manual

Lesson 5

Communication

i. Wire the error output from the Host TCP Module VI inside the Case structure to the error cluster shift register on the state machine.

Figure 5-28. Boolean Flag Is True

j. Switch to the FALSE case of the Case structure. k. Place an instance of the State Enum on the block diagram in the FALSE case. l. Select Running on the enumerated constant. If the Boolean flag is FALSE, the target is currently running a profile and the host program should begin in the Running state. m. Wire the error cluster through the Case structure to the error cluster shift register on the state machine.

Figure 5-29. Boolean Flag Is False

LabVIEW Real-Time Course Manual

5-62

ni.com

Lesson 5

Communication

4. Wire the TCP Timeout constant to the timeout input of every Host TCP Module VI used in the host program. 5. The Tab control is not used on the block diagram of this VI. You can place the control anywhere. Unused controls and indicators are generally placed within the initialization structure. In this case, the initialization structure is the Sequence structure. 6. Place a Simple Error Handler VI to handle errors after the state machine has completed.

Figure 5-30. Completed Host Program

You have completed the host program. 7. Compare the final program to the host flowchart. 8. Save and close the VI. If you have do not have any errors in the host or target VIs, you can run the VI. If you do have errors, you debug the programs in the next lesson.

End of Exercise 5-4

National Instruments Corporation

5-63

LabVIEW Real-Time Course Manual

Lesson 5

Communication

Notes

LabVIEW Real-Time Course Manual

5-64

ni.com

Lesson 6 Verifying Your Application

Lesson 6 Verifying Your Application

Topics A. Verifying Correct Application Behavior B. Verifying Correct Timing Behavior C. Verifying Memory Usage D. Execution Trace Toolkit

Introduction
Building deterministic LabVIEW applications requires programming techniques different from typical LabVIEW programming. Deterministic applications have two levels of debuggingapplication behavior and timing behavior. In this lesson, you learn how to debug an RT application and how to monitor the timing behavior and the memory usage.

National Instruments Corporation

6-1

LabVIEW Real-Time Course Manual

Lesson 6 Verifying Your Application

Verifying Correct Application Behavior


Debugging in LabVIEW Real-Time Module VI is identical to debugging a normal LabVIEW VI All standard debugging techniques are available while targeting the RT system, aside from the Call Chain Ring Select Allow debugging in VI Properties

A. Verifying Correct Application Behavior


When verifying your application, you must ensure that the application behaves as expected. Use the LabVIEW debugging tools, such as execution highlighting and single-stepping, while the host computer is connected to an RT target to step through LabVIEW code. Note You must place a checkmark in the Allow debugging checkbox of the Execution page of the VI Properties dialog box to use the LabVIEW debugging tools to debug a VI. The only feature not supported by the LabVIEW Real-Time Module is the Call Chain ring, which appears in the toolbar of a subVI block diagram window while single-stepping. Note Do not use the LabVIEW debugging tools to debug execution timing, because all debugging tools affect the timing of an application. The next few pages review standard LabVIEW debugging techniques. Refer to Debugging Techniques in the LabVIEW Help to learn more about debugging in LabVIEW.

LabVIEW Real-Time Course Manual

6-2

ni.com

Lesson 6 Verifying Your Application

Standard Debugging Techniques


Finding Errors
Click Broken Run A window showing the error appears

Error Handling
Debug and manage errors in VIs

Execution Highlighting
Click Execution Highlighting Data flow is animated using bubbles Values are displayed on wires

When your VI is not executable, a broken arrow appears in the Run button on the toolbar. To list errors and warnings, click the broken arrow. Click the error message to locate the bad object on the block diagram. Use error handling to debug and manage errors in VIs. The LabVIEW error handler VIs return error codes when an error occurs in a VI. Error codes reveal the specific problem the VI encountered. When you configure an RT target, LabVIEW automatically copies the error code files used by the error handler VIs to the target. You can use custom error codes with VIs that run on an RT target. Create error files using the Error Code File Editor by selecting ToolsAdvancedEdit Error Codes. If you use custom errors with LabVIEW, you must rename the files to use a .err extension and then place the error files in the c:\ni-rt\system\user.lib\errors directory or the c:\ni-rt\ system\errors directory on the RT target. Use the FTP client in MAX or any other FTP client to transfer the error file to the networked device. Refer to the LabVIEW Help for information about defining custom error codes. Execution highlighting animates the diagram and traces the flow of the data, allowing you to view intermediate values. To implement execution highlighting, click the light bulb in the toolbar.

National Instruments Corporation

6-3

LabVIEW Real-Time Course Manual

Lesson 6 Verifying Your Application

Standard Debugging Techniques


Probe
Right-click a wire and select Probe, which shows data as it flows through the wire segment Select Retain Wire Values before running to probe wires that have already executed

Breakpoint
Right-click a wire and select Set Breakpoint, which pauses execution at the breakpoint

Conditional Probe
Combination of a breakpoint and a probe Right-click a wire and select Custom Probe

A probe helps view values passing through a wire segment. Click a wire with the Probe tool or right-click the wire to set a probe. A breakpoint sets a pause at a location on the diagram. Click wires or objects with the Breakpoint tool or right-click a wire to set breakpoints. A conditional probe is a probe on which conditions can be set for when to break at the probe. For example, you may want a breakpoint to occur only when the value in the wire drops below zero. A conditional probe can accomplish this task.

LabVIEW Real-Time Course Manual

6-4

ni.com

Lesson 6 Verifying Your Application

Standard Debugging Techniques


Step Into, Over, and Out Buttons for Single Stepping
Click Step Into, to enable single stepping. Once Single Stepping has begun, the button steps into nodes Click Step Over, to enable single stepping or to step over nodes Click Step Out, to step out of nodes

Single stepping allows you to execute the diagram node by node. You can access single stepping from the diagram toolbar by using the step functions found on the diagram toolbar. Use Step Into/Step Over to begin single stepping. Step IntoSteps into a node. If there is a subVI, it then brings up the subVI diagram and enable single stepping through it. Step OverExecutes nodes, but visually does not single step through nodes. Step OutSteps out of nodes, if the diagram has completed execution; click Step Out to terminate single stepping mode.

National Instruments Corporation

6-5

LabVIEW Real-Time Course Manual

Lesson 6 Verifying Your Application

Exercise 6-1 Debug Exercise VI


Time to complete: 15 min.

OBJECTIVE

To use the debugging tools to verify the behavior of the project.

LabVIEW Real-Time Course Manual

6-6

ni.com

Lesson 6 Verifying Your Application

Verifying Correct Timing Behavior


Software Benchmarking Profile Performance and Memory tool Timing functions such as the Tick Count function and NI Time Stamp VIs Hardware Benchmarking Software driver functionality Oscilloscope

B. Verifying Correct Timing Behavior


Timing is crucial in a deterministic application. Use one of the following methods to verify the timing of an application: Profile Performance and Memory tool Timing functions Software driver functionality Oscilloscope

National Instruments Corporation

6-7

LabVIEW Real-Time Course Manual

Lesson 6 Verifying Your Application

Profile Performance and Memory Tool


Select ToolsProfilePerformance and Memory Analyze how an application uses execution time and memory Identify specific subVIs that need to be optimized Perform time profiling separate from memory profiling

Using the Profile Window to Benchmark an Application


The Profile Performance and Memory window is a tool for statistically analyzing how an application uses execution time and memory. The Profile Performance and Memory window displays information that can identify the specific VIs or parts of VIs you need to optimize. For example, if you notice that a particular subVI takes a long time to execute, you can improve the performance of that VI. The Profile Performance and Memory window displays the performance information for all VIs in memory in an interactive tabular format. From the Profile Performance and Memory window, you can select the type of information to gather and sort the information by category. You also can monitor subVI performance within different VIs. Select ToolsProfilePerformance and Memory to display the Profile Performance and Memory window. If you are profiling the memory usage, you must place a checkmark in the Profile Memory Usage checkbox, before starting a profiling session. Collecting information about VI memory use adds a significant amount of overhead to VI execution, which affects the accuracy of any timing statistics gathered during the profiling session. Therefore, perform memory profiling separate from time profiling to return an accurate profile. Many of the options in the Profile window become available only after you begin a profiling session. During a profiling session, you can take a snapshot of the available data and save it to an ASCII spreadsheet file. The timing measurements accumulate each time you run a VI

LabVIEW Real-Time Course Manual

6-8

ni.com

Lesson 6 Verifying Your Application

Benchmarking an Operation
Record time at A start of operation

Perform operation

BA=

Operation Benchmark

Record time at end of operation

B A and B precision?

Benchmarking an Operation
Benchmarking an operation involves measuring the time at the start of the operation, performing the operation, and measuring the time at the end of the operation. Usually, you repeat this procedure many times to get an average operation benchmark. The precision of this method depends on the precision of the time stamp. Generally, time is measured using the millisecond clock on the processor, the counter on the DAQ board, or the microsecond clock on the target processor. The speed of the clock determines the precision of the timestamp.

National Instruments Corporation

6-9

LabVIEW Real-Time Course Manual

Lesson 6 Verifying Your Application

Tick Count (ms) FunctionGood


Measures the time it takes to perform N iterations of a specified operation using the millisecond timer

Demo: NI Example Finder FundamentalsLoops and StructuresTiming Template (data dep)

Using the Tick Count (ms) Function


Use the Tick Count (ms) function to measure the time it takes to perform N iterations of a specified operation. This method is as precise as the clock used for the Tick Count function. When using this method, you must account for the possibility of counter rollover. Refer to the Timing Template (data dep) VI located in the NI Example Finder for an example using the Tick Count (ms) function to benchmark code. To use the example, place the code to be benchmarked within the For Loop (for example, build an array) to measure the timing statistics. This VI first gets the current number of milliseconds since power-up from Tick Count (ms). The For Loop does not execute until it receives data from Initial Tick Count (ms). The sequence does not execute until it receives the Initial Tick Count (ms) from the For Loop; and For Loop does not release the Initial Tick Count (ms) until the loop has finished executing. Therefore, the For Loop is dependent on Initial Tick Count (ms), and the sequence is dependent on the For Loop that is dependent on the LabVIEW event inside.

LabVIEW Real-Time Course Manual

6-10

ni.com

Lesson 6 Verifying Your Application

Time Stamp VIsBest

Demo: NI Example Finder Toolkits and ModulesReal-TimeBenchmarkingBenchmark Project

Using the NI Time Stamp VIs


The NI Timestamp VIs, located in the Real-Time Utilities palette, read the Time Stamp Counter register from the processor of RT targets for every loop iteration. Refer to the NI Timestamp Code Timer VI located in the NI Example Finder for an example using the NI Timestamp VIs to benchmark code. The NI Timestamp Code Timer VI example uses an assembly-level call to obtain precise timestamps from RT targets. The example obtains several consecutive 64-bit timestamps, which are stored in an array and used later to produce a histogram of execution time. This VI can selfcalibrate by subtracting out the overhead of calling the NI Get Timestamp VI from the array of timing data.

National Instruments Corporation

6-11

LabVIEW Real-Time Course Manual

Lesson 6 Verifying Your Application

Hardware Benchmarking
Software Drivers (NI-DAQmx)Use software driver feedback, such as DAQmx errors to confirm whether the application is keeping real time Use an oscilloscope to precisely measure the overall system jitter

Hardware Benchmarking
Using Software Drivers
Sometimes you can use software drivers to make sure that the application is capable of keeping up with the desired loop rate. For example, you can check for errors after a DAQmx Wait for Next Sample Clock VI to determine whether a control loop is keeping real time.

Using an Oscilloscope
The Tick Count (ms) function and the NI Timestamp VIs allow you to examine the relative timing of sections of LabVIEW VIs and to measure the software jitter in the VIs. Sometimes you might need to measure the jitter of the whole system at the hardware level, especially when you use hardware timing and the software jitter is masked out at the system level. Use external tools such as an oscilloscope to study the relationship between input and output signals and to measure loop rates and jitter levels.

LabVIEW Real-Time Course Manual

6-12

ni.com

Lesson 6 Verifying Your Application

Exercise 6-2 Verify Timing Behavior


Time to complete: 25 min.

OBJECTIVE

Use the available tools to determine and to verify timing behavior of the project.

National Instruments Corporation

6-13

LabVIEW Real-Time Course Manual

Lesson 6 Verifying Your Application

Verifying Memory Usage


Profile Performance and Memory window RT Engine Info tool Show Buffer Allocations tool Real-Time System Manager

C. Verifying Memory Usage


You can verify memory usage with the Profile Performance and Memory window, as explained in the previous section. However, you also can verify and determine memory usage with the RT Engine Info tool, the Show Buffer Allocations tool, and the Real-Time System Manager.

LabVIEW Real-Time Course Manual

6-14

ni.com

Lesson 6 Verifying Your Application

Real-Time Engine Info


View and track the memory usage of an embedded application

Real-Time Engine Info


The Real-Time Engine Info tool displays the current RT target address, the total memory on the target, and the free memory available. You can use this tool to periodically view the status of the RT target.

National Instruments Corporation

6-15

LabVIEW Real-Time Course Manual

Lesson 6 Verifying Your Application

Show Buffer Allocations


Shows specific areas on the block diagram where LabVIEW allocates memory Use this information to edit the VI and reduce the amount of memory needed
Black squares indicate where a buffer is created

Show Buffer Allocations Window


Select ToolsProfileShow Buffer Allocations to display this window. Use this window to identify where LabVIEW allocates memory on the block diagram. Place a checkmark next to the data types you want to see buffers for and click Refresh. Notice that black squares appear on the block diagram to indicate where LabVIEW creates buffers to hold the data on the block diagram. After you know where LabVIEW creates buffers, you might be able to optimize the performance of the VI by editing it to reduce the amount of memory LabVIEW requires to run the VI. However, verify the memory use of your application using other methods as well, because the Show Buffer Allocations window can be misleading. For example, although a buffer is shown being allocated in a loop, it may only be allocated the first iteration or may be allocated every iteration.

LabVIEW Real-Time Course Manual

6-16

ni.com

Lesson 6 Verifying Your Application

Real-Time System Manager (RTSM)


View system memory and CPU usage Includes logging at configured ranges CPU usages of different priority levels View VI Status Running, Idle, Stopped Start/stop embedded VIs without a front panel connection

Real-Time System Manager


The Real-Time System Manager displays details about VIs running on an RT target and provides a dynamic display of the performance of the target. You also can stop VIs and start idle VIs using the Real-Time System Manager. Select ToolsReal-Time ModuleSystem Manager to open the Real-Time System Manager. The Real-Time System Manager is installed by default when you install LabVIEW Real-Time. It is available only with ETS.

National Instruments Corporation

6-17

LabVIEW Real-Time Course Manual

Lesson 6 Verifying Your Application

Real-Time System Manager (RTSM)


RTSM Interface Running on Host RTSM Embedded VI Running on Target

Sends status messages at the configured update rate

RTSM Hidden Status VI

The RTSM is an interface that runs on the host and reports the RT system usage. The data that gets displayed in the interface comes from a VI that is running in the background on the target. The VI only starts whenever you launch the RTSM interface that reports system information back to the host at the update rate that you specify. If the target has no available CPU resources to run this hidden RTSM VI, then the target does not report back any information.

LabVIEW Real-Time Course Manual

6-18

ni.com

Lesson 6 Verifying Your Application

Configuring the RTSM


1. Select Properties for the RT target in the Project Explorer 2. Configure VI Server to use TCP/IP 3. Add the host IP address to the TCP/IP Access list

Configuring the Real-Time System Manager


To configure the RTSM for use, you must first configure the VI Server. The hidden VI on the target communicates with the RTSM interface on the host using VI Server. First, select ToolsRT Target: [X.X.X.X] Options. Then, configure VI Server to use TCP/IP on the VI Server: Configuration tab. Last, add the host IP address to the TCP/IP Access list on the VI Server: TCP/IP Access tab.

National Instruments Corporation

6-19

LabVIEW Real-Time Course Manual

Lesson 6 Verifying Your Application

Configuring the RTSM


Update Interval How often the RTSM checks for information If target is too busy to provide this information, then no information is reported

After you configure the VI Server, open the RTSM interface by selecting ToolsReal-Time ModuleSystem Manager. Configure how often the hidden VI on the target returns data to the RTSM interface on the host by modifying the Update Interval.

LabVIEW Real-Time Course Manual

6-20

ni.com

Lesson 6 Verifying Your Application

Configuring the RTSMLogging


Saves system data when any property is out of its configured range Allows user to let the utility run for long periods of time without having to constantly monitor it Data can be saved to disk

Configure the Real-Time System Manager when the system information should be logged and saved for viewing purposes later. This is very important for monitoring system history. Therefore, if an RT system has problems, you can return to this log to see what the system properties were around that time.

National Instruments Corporation

6-21

LabVIEW Real-Time Course Manual

Lesson 6 Verifying Your Application

RTSMMemory and CPU Usage


Determine if memory leaks occur over time Shows how much time a timecritical loop is leaving for other loops to run
Different colors represent different priorities
Red = Time Critical Yellow = High White = Normal Blue = Low

[c]FP shows 100% CPU usage

Using the Real-Time System Manager


The first chart in the slide above displays the total system memory usage of the target. If the memory usage continuously increases, then the application has a memory leak that needs to be resolved. The second chart in the slide above displays the total CPU usage of the system. It also breaks this up into how much is being used by different priority levels. This lets you distinguish how much CPU time is actually available for your time-critical task. With FieldPoint and Compact FieldPoint systems, the CPU Usage chart always shows 100% CPU Usage. The FP Manager uses the available processor power to run background tasks.

LabVIEW Real-Time Course Manual

6-22

ni.com

Lesson 6 Verifying Your Application

Exercise 6-3 Verify Memory Usage


Time to complete: 15 min.

OBJECTIVE

To use the available tools to measure the memory usage of the project.

National Instruments Corporation

6-23

LabVIEW Real-Time Course Manual

Lesson 6 Verifying Your Application

LabVIEW Execution Trace Toolkit (ETS only)


Display timing and event data of VI and thread events Highlights: Thread swaps Mutexes Memory allocation

D. LabVIEW Execution Trace Toolkit


The LabVIEW Execution Trace Toolkit is a set of real-time event and execution tracing tools that allows you to capture and display the timing and event data of VI and thread events for LabVIEW Real-Time Module applications in Windows. With minimal modifications to your embedded code, these tools graphically display multithreaded code execution while highlighting thread swaps, mutexes, and memory allocation. Using this information, you can optimize the real-time code for faster control loops and more deterministic performance. Note The toolkit requires Windows 2000/XP on the host machine and ETS on the target machine.

LabVIEW Real-Time Course Manual

6-24

ni.com

Lesson 6 Verifying Your Application

How Does it Work?


VI Running on Target Trace Tool Interface Running on Host

While VI is executing, all pre-configured events are logged to a memory buffer

When execution completes, all VI and thread events are sent to the trace tool for viewing

Special instrumentation VIs are placed in the application running on the RT target. These VIs control with the tracing begins and ends. After the trace has ended, it sends information back to the Trace tool user interface running on the host.

National Instruments Corporation

6-25

LabVIEW Real-Time Course Manual

Lesson 6 Verifying Your Application

Instrumentation VIs

Start Trace
Disable trace logging if currently enabled Clears the trace log buffer Sets real-time flags and subsystem flags Enables trace logging

Stop Trace and Send


Disable trace logging Gets timestamp frequency Enumerates all log entries in the trace log Compresses the trace log Sends the log in 8 KB chunks using TCP/IP to Execution Trace Tool user interface running on the host

The Instrumentation VIs include the Start Trace, Stop Trace and Send, Stop Trace and Save, Load Trace and Send and Log User Events. Refer to the LabVIEW Help, available by selecting HelpVI, Function, & How-To Help, for more information about using these VIs.

LabVIEW Real-Time Course Manual

6-26

ni.com

Lesson 6 Verifying Your Application

Instrumentation VI Example
The following is a typical implementation example:
1. Start tracing before any code executes 2. End tracing after code completes and send to host

Start Trace

Stop Trace

National Instruments Corporation

6-27

LabVIEW Real-Time Course Manual

Lesson 6 Verifying Your Application

Trace Logging Buffer


Each change on the trace is an event that has occurred and been logged There is a limited amount of memory that can buffer these events on the target If this buffer is full, the buffer overwrites the oldest data
Configure Buffer

Only a limited amount of memory exists to hold the tracing data. You can configure the memory through the buffer size input on the Start Trace VI. If this buffer is filled, then it acts as a FIFO, keeping only the newest data and overwriting the oldest. Note After using the Start Trace VI to set the buffer size, changing the buffer size requires a rebooting the target.

LabVIEW Real-Time Course Manual

6-28

ni.com

Lesson 6 Verifying Your Application

Viewing a Trace
Thread View
Shows when each thread is active Execution of each individual LabVIEW and ETS thread Colors represent priority levels Flag detailed events

VI View
Shows each VI in memory and when it executes Colors match the thread view Lists each instance of VIs in memorylists reentrant VIs more than once

Demo: NI Example Finder Toolkits and ModulesExecution Trace ToolExecution Systems

Two ways exist to view the execution of the RT system. The Thread view shows when each thread is active. The Thread view also shows any flags that you may have configured. The VI view lists each VI in memory and shows exactly when it executed.

Thread View
Shows all of the threads that are running on the system. This includes things outside of LabVIEW, such as ETS timing and communication threads. The LabVIEW threads are listed as LabVIEW threads, are color coordinated to match the VI priorities in the VI view, and show their LabVIEW execution system. The thread view also allows viewing of more detailed events as shown on the next page.

VI View
Two VIs can overlap in the VI view but cannot execute at exactly the same time. The reason that this occurs is that one VI preempts the other; meaning that one VI has a higher priority, so it stops the lower priority VI so that it can instantly use the processor. This switch happens so quickly that the lower priority VI cannot log that it is stopping. Therefore, the TraceTool GUI shows that it continues to run. At this point, you can look at the thread VI to determine which thread is active, and hence which VI is active. After this higher priority task is finished, it returns back to the original VI, finishes, and then logs that it has stop, as shown in the TraceTool GUI.

National Instruments Corporation

6-29

LabVIEW Real-Time Course Manual

Lesson 6 Verifying Your Application

Thread View: Flags


More detailed events are shown as colored flags Memory Mutex Sleep Waiting Custom flags (for example, timed loops)

Often you want to see other events occur besides a VI starting and stopping. These events may include accessing the memory manager (a shared resource), sleep, iterations of a timed loop, and so on.

LabVIEW Real-Time Course Manual

6-30

ni.com

Lesson 6 Verifying Your Application

Exercise 6-4 Execution Trace


Time to complete: 15 min.

OBJECTIVE

To use the LabVIEW Execution Trace Tool to verify overall behavior of the project.
* Must have the Execution Trace Tool to complete this exercise.

National Instruments Corporation

6-31

LabVIEW Real-Time Course Manual

Lesson 6 Verifying Your Application

SummaryMatch the Tool to the Test


1. Real-Time System Manager 2. Performance and Memory Profiler 3. Execution Trace Tool 4. Probes 5. Real-Time Engine Info 6. Time-Stamp VIs A. Application Behavior B. Timing Behavior C. Memory Usage

LabVIEW Real-Time Course Manual

6-32

ni.com

Lesson 6

Verifying Your Application

Exercise 6-1
Objective:

Debug Exercise

To use the debugging tools built into LabVIEW to verify the functionality of an application. In this exercise you use the debugging tools in LabVIEW to verify the functionality of the application. In this exercise, notice that the debugging capabilities in LabVIEW Real-Time perform the same way as they do in LabVIEW. 1. Open the target application <target type> - NPL Project.vi from your Project Explorer window. 2. Select FileVI Properties and select the Execution category. 3. Verify that Allow Debugging is enabled. 4. Close the VI Properties dialog box. 5. Switch to the block diagram of the target application. 6. If the Run arrow is broken, click it to display a list of errors in the VI. You can double-click an error listing in the Error window to have LabVIEW take you to the location of the error on the block diagram. Solve each error listed before moving on to the next step.

Execution Highlighting
7. Turn execution highlighting on by clicking the Execution Highlighting button on the toolbar. 8. Run the VI. Notice that you can watch the flow of data as the application runs. 9. Turn execution highlighting off while you keep the application running on the target.

Probe
10. Right-click any wire on the block diagram and select Probe. Notice how you can see the data that is on a wire with a Probe. Try adding multiple Probes on different wire types to your block diagram. A probe does not display a value until the execution of the block diagram reaches the probed wire. You cannot probe the value of a wire after execution has passed the wire unless you enable the Retain Wire Values option before running the VI.
Note

National Instruments Corporation

6-33

LabVIEW Real-Time Course Manual

Lesson 6

Verifying Your Application

Breakpoints
11. Right-click a wire inside the While Loop and select Set Breakpoint. Execution pauses at the breakpoint when data flows through that wire segment. 12. Now that the application is paused, use the Step Into, Step Over, and Step Out debugging tools. Try to understand how you can use these debugging tools can be used when verifying the functionality of your application. 13. Right-click the breakpoint and select Clear Breakpoint. 14. Click the Continue button to continue execution after you are satisfied with the operation of the debugging tools.

Conditional Probes
15. Right-click an error wire and select Custom ProbeConditional Error Probe. 16. Select the Condition tab and check the Error checkbox. Execution breaks at this wire if it contains an error. 17. Close the conditional probe. 18. Try creating conditional probes on wires with different data types and notice how the conditional probe adapts to the data type by providing information that is relevant to the data type. 19. Use the tools mentioned in the previous steps to debug your application if it is not currently working. Debug both the target application and the host application. 20. Stop and save the VIs when you are finished.

End of Exercise 6-1

LabVIEW Real-Time Course Manual

6-34

ni.com

Lesson 6

Verifying Your Application

Exercise 6-2
Objective:

Verify Timing Behavior


In this exercise you use the tools in LabVIEW to verify the code performance. Before beginning this exercise, refer to the Requirements Document to determine the required loop cycle time for your application. 1. Open <target type> - Benchmark.lvproj. This project will help you to benchmark the amount of time required to execute the code in your time critical loop. 2. Open <target type> - Benchmark.vi from the Project Explorer. This VI has been created using the Benchmark Project example from the LabVIEW Example Finder. The <target type> - Benchmark TCL.vi subVI in the Benchmark TCL frame is a variation of the TCL VI you created earlier in the course. 3. Right-click the RT target in the Project Explorer and select Properties. 4. Enter the IP address of your target in the IP Address/DNS Name textbox and click OK. 5. Open the <target type> - Benchmark TCL.vi by double clicking it on the block diagram or in the Project Explorer and observe the block diagram of the VI. This VI is very similar to the TCL VI you created for the project. The While Loop has been replaced with a For Loop in order to run the loop a specified number of times for benchmarking, and the stop logic is no longer used. An additional function to gather the timing information for each execution of the loop has been added. The sleep code for the loop has also been removed in order to benchmark the duration of the time-critical code without sleep time. The sleep code for cFP was a Wait until next ms Multiple function and the sleep code for PXI was a sample clock on the DAQmx task. 6. Close the <target type> - Benchmark TCL.vi when you are finished examining it. 7. Run the <target type> - Benchmark.vi. 8. Analyze the timing data, to ensure that the mean time plus the maximum jitter is less than the total loop period specified in the project requirements. For the program to have reliability and determinism, the mean time also must be less than the execution time to allow normal priority code to execute. The histogram and standard deviation should indicate a fairly consistent execution time.

To use the provided tools to benchmark the VI timing behavior.

End of Exercise 6-2

National Instruments Corporation

6-35

LabVIEW Real-Time Course Manual

Lesson 6

Verifying Your Application

Exercise 6-3
Objective:

Verify Memory Usage


In this exercise you use the tools in LabVIEW to measure the memory usage on the RT target.

To measure the memory usage.

Enable VI Server
In this exercise you use the Real-Time System Manager, but you must verify that VI Server is configured to allow the Real-Time System Manager to run. 1. Right-click the RT target in the Project Explorer and select Properties. 2. Select the VI Server: Configuration category and select the TCP/IP checkbox. 3. Select the VI Server: Machine Access tab and add * to the Machine Access List. 4. Click OK to exit the Real-Time Properties dialog box. 5. Right-click the RT target and select Deploy to load the configuration changes to the target.

Measure Memory Usage


1. Right-click the RT target and select UtilitiesTarget Information. This dialog box displays the amount of used and free memory of the target. 2. Open the target application <target type> - NPL Project.vi from the Project Explorer if it is not already open. 3. Right-click the <target type> - NPL Project.vi in the Project Explorer and select Deploy. 4. Right-click the RT target and select UtilitiesTarget Information again. Notice the amount of memory used by the VI. 5. Select ToolsReal-Time ModuleSystem Manager. 6. Select your target from the Machine Name/IP Address drop-down menu. 7. Click Start Monitoring. It takes some time for the Real-Time System Manager to negotiate communications with the Real-Time hardware. 8. Select each tab in the Real-Time System Manager and observe the capabilities of the manager. 9. Select the VIs tab and check the Track VI States checkbox.

LabVIEW Real-Time Course Manual

6-36

ni.com

Lesson 6

Verifying Your Application

10. Select the NPL VI. 11. Press Start VI to start the application on the Real-Time hardware. 12. Select the Resources tab and observe the memory and CPU usage. 13. Open and run the Completed Project Host.vi from the Project Explorer. 14. While observing the Resources tab in the Real-Time System Manager, use the host application to communicate to the Real-Time hardware and execute a control profile. What happened to the memory and CPU usage? 15. Stop and close the host application. 16. Stop the target application from the Real-Time System Manager. 17. Close the Real-Time System Manager. 18. Close the <target type> - NPL Project.vi. 19. Right-click the RT target and select UtilitiesTarget Information again. Notice that closing the VI removed it from memory on the target.

End of Exercise 6-3

National Instruments Corporation

6-37

LabVIEW Real-Time Course Manual

Lesson 6

Verifying Your Application

Exercise 6-4
Objective:

Execution Trace
In this exercise, you will modify the NPL Project VI to record trace information for the running state of the VI. 1. Open the target application <target type> - NPL Project.vi from the Project Explorer. 2. Select FileSave As and select the Open additional copy and Add copy to project options. 3. Click Continue and save the file as <target type> - Trace NPL Project.vi in the C:\Exercises\LabVIEW Real-Time\ Project Files directory. 4. Close the original, unmodified NPL Project VI. Do not save any changes. 5. Open the block diagram of the new VI. 6. Open the Configure state of the state machine. 7. Place a TraceTool Start Trace VI after the File I/O Module VI that is responsible for creating the new file. Refer to Figure 6-1 for assistance with wiring this step.

To use the Execution Trace Toolkit to verify overall behavior of the VI.

LabVIEW Real-Time Course Manual

6-38

ni.com

Lesson 6

Verifying Your Application

Figure 6-1. Start Trace in the Configuration State

8. Open the Running state of the state machine. 9. Place a TraceTool Stop Trace And Send VI after the File I/O Module VI that is responsible for closing the file. 10. Create a constant on the Trace Host Network Address input and enter the IP address of the host computer. When the trace has completed, the trace information is sent to the Execution Trace Tool running at this IP address.

National Instruments Corporation

6-39

LabVIEW Real-Time Course Manual

Lesson 6

Verifying Your Application

Refer to Figure 6-2 for assistance with wiring this step.

Figure 6-2. Stop Trace in the Running State

11. Save the VI. 12. Run the VI. 13. Open the LabVIEW Execution Trace Tool, available in the Tools menu of LabVIEW. 14. Open Project Host.vi from the Project Explorer. 15. Run the VI. 16. Click the Start button to begin a profile. 17. After the profile has completed, click the Stop User Interface button to stop the host program 18. The LabVIEW Execution Trace Tool dialog box shows the data sent from the target computer. Review this data. 19. Stop and close the target program.

End of Exercise 6-4

LabVIEW Real-Time Course Manual

6-40

ni.com

Lesson 6

Verifying Your Application

Self Review
Quiz
1. In which portion of an application using the real-time architecture described in this course, do you set your loop cycle time? a. Host VI b. Normal Priority Loop c. Time-Critical Loop d. Target VI 2. Which item does not affect the accuracy of a benchmark? a. Timing method used to acquire benchmark b. Execution speed of code being benchmarked c. Jitter inherent in the benchmark function d. Correct use of benchmark

Job Aid
Use the following table to choose the debugging methods that best suit your needs Incorrect Application Behavior X X X X X X X X X X X X

Debugging Method Probes Breakpoints Execution Highlighting Real-Time System Manager Real-Time Engine Info VI Profiler Benchmarking Execution Trace Tool Oscilloscope

Loop Cycle Time Memory Usage Incorrect High

National Instruments Corporation

6-41

LabVIEW Real-Time Course Manual

Lesson 6

Verifying Your Application

Notes

LabVIEW Real-Time Course Manual

6-42

ni.com

Lesson 7 Deploying Your Application

Lesson 7 Deploying Your Application

Topics A. Introduction to Deployment B. Creating a Build Specification C. Communication with Deployed Application

Introduction
After developing a LabVIEW Real-Time Module application, you often want to deploy the application so that it becomes the primary application for the controller. In this lesson, you will learn how to create an executable from an application, embed the executable on the target, launch the executable, and communicate with the executable.

National Instruments Corporation

7-1

LabVIEW Real-Time Course Manual

Lesson 7 Deploying Your Application

Introduction to Deployment
Creating a stand-alone application (executable) of a LabVIEW Real-Time Module application using the LabVIEW Application Builder Benefits of deploying your RT Application:
Embed executable in permanent memory on the target Launch executable automatically when target is booted

A. Introduction to Deployment
After you have completed the development work on a project, you may wish to deploy the project. Use the LabVIEW Application Builder, included with the LabVIEW RealTime Module Professional Development System, to create stand-alone LabVIEW Real-Time Module applications. You can embed a stand-alone application on an RT target and launch the application automatically when you boot the target.

LabVIEW Real-Time Course Manual

7-2

ni.com

Lesson 7 Deploying Your Application

Preparing Your Application for Deployment


Review the code for unsupported functions Functions that modify front panel objects Functions that use technologies specific to other operating systems

Preparing Your Application for Deployment


Before deploying your application, you must prepare the application for deployment. This involves reviewing the code for any unsupported functions. Some of the LabVIEW features that are unavailable when you target a specific RT target include functions that modify front panel object and functions specific to other operating systems, such as ActiveX. Note If you attempt to download and run a VI that has unsupported functionality on an RT target, the VI still executes. However, the unsupported functions do not work and return standard LabVIEW error codes.

National Instruments Corporation

7-3

LabVIEW Real-Time Course Manual

Lesson 7 Deploying Your Application

Do Not Modify Front Panel Objects


Front panel property nodes and control references Dialog VIs VI Server front panel functions

Modifying Front Panel Objects of RT Target VIs


When a VI or stand-alone application runs on an RT target and there is no front panel connection with LabVIEW on the host computer, you cannot execute VIs that modify a front panel. For example, you cannot change or read the properties of front panel objects with property nodes, because no front panel exists. You must establish a front panel connection with the RT target or open a remote front panel connection to read any front panel properties or for any front panel property node changes to reflect on the front panel objects. Refer to Lesson 5, Communication, for more information about front panel connections. The following features do not work on an RT target with no front panel connection: Front panel property nodes and control references Dialog VIs VI Server front panel functions

LabVIEW Real-Time Course Manual

7-4

ni.com

Lesson 7 Deploying Your Application

Do Not Use OS-Specific Technologies


ActiveX VIs .NET VIs VIs that use NI-IVI drivers Windows Registry Access VIs TestStand VIs (ActiveX-based) Report Generation Toolkit VIs Call Library Nodes that access an operating system API other than Pharlap Graphics and Sound VIs Database Connectivity Toolset XML DOM Parser and G Web Server for CGI Support

Using OS-Specific Technologies in RT Target VIs


VIs on the RT target cannot use VIs that leverage Windows-only technology. The following features do not work on an RT target: ActiveX VIs .NET VIs VIs that use NI-IVI drivers Windows Registry Access VIs TestStand VIs (ActiveX-based) Report Generation Toolkit VIs Call Library Nodes that access an operating system API other than Pharlap Graphics and Sound VIs Database Connectivity Toolset XML DOM Parser and G Web Server for CGI Support

National Instruments Corporation

7-5

LabVIEW Real-Time Course Manual

Lesson 7 Deploying Your Application

Creating a Build Specification

B. Creating a Build Specification


An RT build specification saves stand-alone applications on the host computer or embeds applications on an RT target. You create a build specification through the RT target in the Project Explorer. You can launch a built application from the project explorer or outside of LabVIEW. Refer to the Launching Applications Automatically Using Command Line Arguments section of this lesson for information about automatically launching stand-alone applications using command line arguments.

LabVIEW Real-Time Course Manual

7-6

ni.com

Lesson 7 Deploying Your Application

Configuring SettingsApplication Information

Set names and destinations

Configuring Settings
The Application Information category contains the Build specification name, Executable filename, and Target destination directory for both the target and host.

National Instruments Corporation

7-7

LabVIEW Real-Time Course Manual

Lesson 7 Deploying Your Application

Configuring SettingsSource Files

Set startup VI(s) and include dynamically referenced files

The Source Files category allows you to set startup VIs and include additional VIs or support files. You do not need to specifically include VIs called as subVIs from the Startup VIs unless the subVIs are called dynamically. The Destinations and Source File Settings categories allow you to control where files are created and to set the visual properties of each VI. Both of these categories are rarely used when building RT applications.

LabVIEW Real-Time Course Manual

7-8

ni.com

Lesson 7 Deploying Your Application

Configuring SettingsAdvanced

Enable or disable debugging

The Advanced category allows you to enable debugging in the executable, disconnect polymorphic VIs and typedefs before deploying, and use an alias file. Enabling debugging in an executable allows you to connect to the executable and debug it as it runs. However, debugging requires additional resources on the target.

National Instruments Corporation

7-9

LabVIEW Real-Time Course Manual

Lesson 7 Deploying Your Application

Configuring SettingsPreview

Preview files and destinations

The Preview category shows you the destination of the files to be created when you deploy the build.

LabVIEW Real-Time Course Manual

7-10

ni.com

Lesson 7 Deploying Your Application

Automatic Start on Target

Selecting the Set as Startup option configures the target to run the VI automatically when the target is powered on or rebooted. This allows you to create headless systems that start automatically without any interaction from the host or the development environment. You can select Unset as Startup to disable automatic startup. Connecting to the target from any project other than the one containing the startup VI also disables automatic startup.

National Instruments Corporation

7-11

LabVIEW Real-Time Course Manual

Lesson 7 Deploying Your Application

Deploying the Build Specification

Select Build to build the application and Deploy to download the executable to the target. In most cases, selecting Deploy also builds the application.

LabVIEW Real-Time Course Manual

7-12

ni.com

Lesson 7 Deploying Your Application

Removing Executables
1. 2. Connect to the module Remove executable Note: Compact FieldPoint usersplace the module in safe mode first

Removing Executables from the Target


At some point, you may want to remove an executable you stored on your RT Target. The easiest way to do this is to use FTP to the module and delete the file. You can use FTP using any FTP client software including Internet Explorer. After you access the Target, you can see all of the files stored on the target. Compact FieldPointAt this point, if you try to remove the file, you get a message that you do not have permission. You must set the Compact FieldPoint in safe mode before you can remove files from the flash. To put the module in safe mode, flip the dip switch labeled safe mode and power cycle the module. You must power cycle because this switch, along with the Disable VI and Reset switches, is only read on power-up. If you have the VI set to launch on boot up, you also must flip the Disable VI switch. After the module comes back online, you can delete the startup.exe file. The file is located in NI-RT\Startup.

National Instruments Corporation

7-13

LabVIEW Real-Time Course Manual

Lesson 7 Deploying Your Application

Exercise 7-1 Deploy Project


Time to complete: 5 min.

OBJECTIVE

To prepare the project for deployment and create an executable.

LabVIEW Real-Time Course Manual

7-14

ni.com

Lesson 7 Deploying Your Application

Communicating with Deployed Applications


You cannot open a front panel connection to a stand-alone application running on an RT Target Use remote panels to connect to the application Create communication VIs to communicate with the time-critical VI as shown in Lesson 5, Communication Debug the executable using normal debugging functions

C. Communication with Deployed Applications


You cannot open a front panel connection to a stand-alone application running on an RT target. Use a remote panel connection to connect to the application or use the RT Communication Wizard to create communication VIs to show the front panel of a time-critical VI on the host computer as described in Lesson 5, Communication. You also can debug a deployed executable using standard debugging functions.

National Instruments Corporation

7-15

LabVIEW Real-Time Course Manual

Lesson 7 Deploying Your Application

Remote Front Panels


What is a remote front panel? Active view of the executing VI in a Web browser VI interface is embedded in an HTML page Control of the VI takes place through the Web browser How does it work? Remote front panel uses the Web server on the RT Engine RT Engine updates page

Use remote front panels to view or remotely control an RT target VI from a remote LabVIEW client or Web browser. Only one user may control a VI at any specific time, but several users at different locations can view the VI front panel simultaneously. You do not need LabVIEW to see the running VI on the RT Engine. After setting up the RT Engine, you can connect to the RT Engine using an ordinary Web browser and use the RT Engine to view and control the running VI.

LabVIEW Real-Time Course Manual

7-16

ni.com

Lesson 7 Deploying Your Application

Remote Front Panels (cont.)


How is this different from RT development? Cannot edit or debug the VI Cannot view the block diagram Why is it useful? LabVIEW Development System is not required on the client computer to control and view the executing VI Can be controlled from other computers Can connect with more than one client if the Remote Front Panel License is set to allow more than one connection

When you open a front panel remotely from a client, the Web server sends the front panel to the client, but the block diagram and all the subVIs remain on the server computer. You can interact with the front panel in the same way as if the VI were running on the client, except that the block diagram executes on the server. This is how remote front panels differ from a VI in the development state targeted to the RT Engine.

National Instruments Corporation

7-17

LabVIEW Real-Time Course Manual

Lesson 7 Deploying Your Application

Developing Remote Panels


Consider the following when creating a remote front panel from a VI: To reduce network traffic, display only what is necessary To reduce network traffic and preserve target resources, limit the number of connections The number of connections is limited by the number of deployment licenses purchased Number of connections also may be limited by the memory resources

When creating a remote front panel, there are several factors to consider. As with any VI, the fewer indicators on the front panel, the faster the user interface can be updated. This concept is important when using remote front panels, because all of the updated indicator values must be transmitted to the remote client. Therefore, limit the front panel displays to show only the necessary information. Another consideration is security settings on the remote front panel. Limit the access to the remote front panel, so that unwanted connections do not occur. You can limit the number of connections by purchasing the required number of licenses. Memory resources on the controller also limit the number of connections. After you purchase additional remote front panel Licenses from NI, they need to be transferred to the real-time target. To do this, you must download the Remote Panel License Transfer Utility for LabVIEW Real-Time Targets from ni.com/support. This utility allows the transfer of the license file from the host PC to the RT target.

LabVIEW Real-Time Course Manual

7-18

ni.com

Lesson 7 Deploying Your Application

Creating a Remote Panel


After the RT Development System has created and debugged the VI, complete the following steps:
Enable Web Server Set IP Access Permissions Select VIs to be visible Use Web Publishing Tool to create the HTML Page Embed the HTML in the WWW directory

You can create Remote Panels using the Real-Time Module development environment. After you create and test a VI using the RT Development System, there are only a few steps to configure and create the remote front panel, as shown in the slide.

National Instruments Corporation

7-19

LabVIEW Real-Time Course Manual

Lesson 7 Deploying Your Application

1. Enable Web Server


a. Select Properties for the RT target in the Project Explorer Select the Web Server: Configuration category Enable the Web Server Use default values for other options (recommended)

b. c. d.

Next, you must enable the Web server on the RT target to allow remote front panel control of a VI running on the target or to view the front panel of a VI running on the target remotely using a Web browser. Complete the following steps to enable the Web server on the RT target and add VIs to the Web Server Visible VIs list. 1. Select Properties, for the RT target in the Project Explorer, and select the Web Server: Configuration category. 2. Select the Enable Web Server checkbox to enable the Web Server. 3. Enter the directory that you want to use as the Web Server root directory in the Root Directory text box or use the default. Note The Root Directory is the directory that the Web server looks for the HTML page to display. The HTTP Port is set to 80. Most internet browsers use port 80 as the default port for viewing HTML pages. Changing this may make it more difficult to browse to the remote panel. However, another common Web server port is 8080. The Timeout represents the the number of seconds that the Web server waits while reading a request before the Web server times out. The timeout is set to 60 seconds as the default. The Use Log File Option allows the controller to record the network communications to a log file.

LabVIEW Real-Time Course Manual

7-20

ni.com

Lesson 7 Deploying Your Application

2. Set IP Access Permissions


a. Select the Web Server: Browser Access category and add IP addresses Choose to allow viewing and controlling, just viewing, or deny access to specific IP addresses

b.

You next must set the Browser Access options for the Web Server. You can choose the permission level for each IP Address. Complete the following steps: 1. Select the Web Server: Browser Access category. 2. Add the IP address that you wish to specify in your browser access list. 3. Choose the permission level for each IP address, then click Add. LabVIEW reads the Browser and TCP/IP Access List from the top down. The permission for a later entry in the list overrides previous permissions. You can click and drag an entry in the list to change the order. For example, if you need to deny access to all clients except a designated few, first deny access to all IP addresses, then add individual addresses to allow access.

National Instruments Corporation

7-21

LabVIEW Real-Time Course Manual

Lesson 7 Deploying Your Application

3. Set Visible VIs


a. Select the Web Server: Visible VIs category and add VIs to allow users to access Download the VIs to the RT target, if you have not already done so

b.

You must add a VI to the Web Server Visible VIs list to allow users to access or view a VI remotely. Complete the following steps: 1. Select the Web Server: Visible VIs category 2. Add to the Visible VIs list the VIs that you want to publish on the Web. 3. Click the OK button to close the RT Target Options dialog box. By default, the front panel images of all VIs are visible. Refer to the Web Server & Configuration Options topic of the LabVIEW Help for more information about denying access to specific VIs.

LabVIEW Real-Time Course Manual

7-22

ni.com

Lesson 7 Deploying Your Application

5. Create the HTML Page


a. b. c. d. Open the VI Select ToolsWeb Publishing Tool Follow Wizard Save the HTML file to disk

To create an HTML page for the remote front panel, complete the following steps: 1. Save the VI. 2. Download the VI to the RT Engine. 3. Select ToolsWeb Publishing Tool to open the Web Publishing Tool. 4. Select an open VI in the VI Name field or select Browse from the VI Name drop-down menu and navigate to a VI. 5. Choose a Viewing Mode. 6. Choose Next. 7. Enter text in the Document Title, Text 1, and Text 2 text boxes. 8. Choose Next. 9. Click Save to Disk to save a HTML document as index.htm and save it in the C: directory on the computer. Notice that the HTML document is saved to the host computer. The HTML page is placed manually on the RT target.

National Instruments Corporation

7-23

LabVIEW Real-Time Course Manual

Lesson 7 Deploying Your Application

6. Embed the HTML Page


Use FTP to send the file to the target.
ftp://[IP Address of the target]/NI-RT/SYSTEM/WWW

For the Web server on the RT target to display the newly created HTML page, place it in the root directory of the Web server on the target. If the defaults were used when enabling the Web server, the root directory is C:\ni-rt\system\www. An easy way to send the HTML file to this directory is by using an FTP connection. If you open a Windows or Internet Explorer window, you can enter ftp://[IP Address of the target]/NI-RT/SYSTEM/WWW. You can copy and paste files into the folder just as you would with files on your local computer. Note There is already an index.htm file placed in C:\ni-rt\system\www by LabVIEW RT when installing the software. Replace this with the index.htm you just created.

LabVIEW Real-Time Course Manual

7-24

ni.com

Lesson 7 Deploying Your Application

View the Remote Panel


Open a Web browser. Enter http://[IP address
of target]

Page displays automatically. Add /name.html if name is not


index.html

You can view the remote front panel by typing the IP address into a Web browser. If the HTML page was named index.htm, then it displays automatically when the IP address is entered. If the HTML page has a name other than index.htm, you have to type http://[IP Address of the target]/[name].html.

National Instruments Corporation

7-25

LabVIEW Real-Time Course Manual

Lesson 7 Deploying Your Application

Controlling the Remote Panel VI


Right-click the panel and select Request Control of VI.
Allows the Client to interact with the executing VI through the remote front panel

Only one client can control the VI at a time


Should release control when done Options can be set a timeout time that a client can be in control of a VI Other clients wanting to connect are placed into a queue Security options can be set on which computers can control the VI

Controlling the Remote Panel


After the client has browsed to the Web page, the user must be able to view the current status of that VI. In order to change values of controls and interact with the remote front panel, the user must gain control over the VI. Right-click anywhere on the page itself. A shortcut appears with an option to Request Control of VI. A dialog box appears to inform the user that control has been granted. Similar messages appear on clients that previously had control indicating that a user has requested control. Only one user (client) may have control at any given time. Several options, which are configured for the Web server, can limit the amount of time a client can have control or even grant/deny access to specific IP addresses. You can set Web options by selecting ToolsOptionsWeb Server: Visible VIs or Web Server: Browser Access.

LabVIEW Real-Time Course Manual

7-26

ni.com

Lesson 7 Deploying Your Application

Remote Front Panel Licenses


Allow multiple Web clients to access the embedded program By default, an RT Target has one connection licenseyou can purchase additional licenses Number of concurrent client connections is limited by memory resources as well

To access a remote front panel, a license must be present on the target controller to allow this connection. By default, a target controller has one remote front panel license. However, there must be enough licenses on the target controller to support the number of clients that potentially could connect to it. When you exceed the number of clients allowed by your license, an error message appears, and the connection to the target controller is denied. Target controllers are limited in the number of clients that can connect to the remote front panel. Because updating each remote front panel consumes processor time and memory on the target controller, this limit on the client connections increases the resources for the executing VI. As mentioned earlier, the memory resources of the controller also limit the number of connections.

National Instruments Corporation

7-27

LabVIEW Real-Time Course Manual

Lesson 7 Deploying Your Application

Debugging Executables
1. 2. 3. 4. 5. Enable the debugging option when you build the executable. Select OperateDebug Application or Shared Library. Enter the IP Address of the target and click Refresh. Select the application to debug and click Connect. Debug the application normally.

You can debug deployed executables as long as you enable the debugging option when you build the executable. Notice that debuggable applications use more memory and processor resources than non-debuggable applications. To debug a stand-alone executable, perform the following steps: 1. Enable the debugging option when you build the executable. 2. Select OperateDebug Application or Shared Library. 3. Enter the IP Address of the target and click Refresh. 4. Select the application to debug and click Connect. 5. Debug the application normally.

LabVIEW Real-Time Course Manual

7-28

ni.com

Lesson 7 Deploying Your Application

Exercise 7-2 Remote Panels


Time to complete: 40 min.

OBJECTIVE

To communicate with a deployed application, similar to the course project, using remote panels.

National Instruments Corporation

7-29

LabVIEW Real-Time Course Manual

Lesson 7 Deploying Your Application

SummaryDiscussion
What is the difference between the development state of a VI (front panel communication) and using Remote Panels to communicate with the deployed application? What are some of the benefits of using remote front panels to communicate with a deployed application? What are the benefits of creating a VI to communicate with the deployed application (for example, the real-time architecture taught in this course)?

When you open a front panel remotely from a client, the Web server sends the front panel to the client, but the block diagram and all the subVIs remain on the server computer. You can interact with the front panel in the same way as if the VI were running on the client, except the block diagram executes on the server. This is where remote front panels are different from a VI in development state targeted to the RT Engine. In other words, you cannot edit or debug the VI when using remote front panels. You also cannot view the block diagram.

LabVIEW Real-Time Course Manual

7-30

ni.com

Lesson 7

Deploying Your Application

Exercise 7-1
Objective:

Deploying an Application
1. Review the target VIs of the project that you created to ensure that it does not use any unsupported functions. For example, you can remove any Error Handler VIs used for debugging. 2. Close all VIs before building an application. You cannot build an application from a VI that is in memory. 3. Right-click Build Specifications under the RT Target in the Project Explorer and select NewReal-Time Application. 4. Enter Temperature Chamber Controller in the Build specification name textbox. 5. Select the Source Files category. 6. Select the <target type>- NPL Project VI and click the right arrow to add it to the Startup VIs list.

To deploy the project for development and create an executable.

Figure 7-1. FieldPoint Remote Front Panel

National Instruments Corporation

7-31

LabVIEW Real-Time Course Manual

Lesson 7

Deploying Your Application

7. Observe the settings in the other categories but do not make any changes. 8. Click the OK button. 9. Right-click the Temperature Chamber Controller build specification in the Project Explorer and select Set as startup. Once the application has been deployed, the RT target starts the application each time it is turned on. You can disable the VI from starting automatically by right-clicking the build specification or by deploying any other RT project to the target. 10. Right-click the Temperature Chamber Controller build specification in the Project Explorer and select Build. 11. Right-click the Temperature Chamber Controller build specification in the Project Explorer and select Deploy. 12. Right-click the RT Target in the Project Explorer and select Utilities Reboot. Rebooting takes approximately 30 seconds. After rebooting the hardware, the application that you built launches. 13. Open the Host VI of the project and verify that the built application is running correctly on the Real-Time Series hardware. 14. Right-click the RT target in the Project Explorer and select Connect. You should receive a conflict resolution dialog box that informs you that the NPL VI will close if you continue. 15. Click OK. 16. Right-click the Temperature Chamber Controller build specification and choose Unset at startup. 17. Right-click the Temperature Chamber Controller build specification and select Deploy to disable the automatic startup of the application.

End of Exercise 7-1

LabVIEW Real-Time Course Manual

7-32

ni.com

Lesson 7

Deploying Your Application

Exercise 7-2A cFP - Remote Panels


Objective: Given a target application, use Remote Panels to view and control the application. In this exercise, modify the time-critical loop of the application so that it runs self-contained without the need of the host application or the normal priority loop. After you modify the time-critical loop, you can control the application using remote panels. 1. Open cFP - TCL Project.vi from the cFP Real-Time Project.lvproj. 2. Select FileSave As and select Open additional copy. Save the file as cFP - Remote Panels TCL.vi in the C:\Exercises\LabVIEW Real Time directory. 3. Close the original TCL VI and any other open VIs.

Front Panel
1. Delete all controls and indicators on the front panel of the VI, except for the PID output range control. 2. Open Project Host.vi from the Project Explorer. 3. Copy the following controls and indicators from Project Host VI and paste them into the cFP - Remote Panels TCL.vi front panel: Tab control containing the Setpoint Profile and the PID Gains controls Emergency Stop button Apply Disturbance button Temperature Chamber chart Lamp Power graduated bar Current timestamp string Disturbance Boolean indicator

Close the Project Host VI after copying the controls and indicators. Do not save changes. The completed front panel for cFP - Remote Panels TCL.vi should resemble Figure 7-2.

National Instruments Corporation

7-33

LabVIEW Real-Time Course Manual

Lesson 7

Deploying Your Application

Figure 7-2. FieldPoint Remote Front Panel

Block Diagram
1. Modify the block diagram of cFP - Remote Panels TCL VI to operate as a self-contained application. a. Remove the code that sends data through shared variable FIFOs. b. Wire the temperature and setpoint data items to a Bundle function located on the FunctionsCluster palette as shown in Figure 7-3. Notice that the setpoint is wired as the first element in the Bundle function, setpoint because the Temperature chart that you copied from the host VI is expecting the setpoint to be the first item charted. c. Wire the output of the Bundle function to the Temperature chart. d. Place the Format Date/Time String function on the block diagram. e. Wire the Timestamp to the input of Format Date/Time String function. f. Wire the output of the Format Date/Time String function to the Current Timestamp indicator. g. Remove the functional global variables for the disturbance and stop condition. h. Remove the Select function and Feedback node that were connected to the Disturbance functional global variable. i. Wire the Apply Disturbance control to the existing Select function, so that when the Boolean is TRUE, a 100 is passed to the FieldPoint Write VI, and when the Boolean is FALSE, a 0 is passed to the FieldPoint Write VI. j. Wire the PID output to the Lamp Power indicator.

LabVIEW Real-Time Course Manual

7-34

ni.com

Lesson 7

Deploying Your Application

k. Wire the Emergency Stop control to the Or function which can cause the While Loop to stop executing when the user clicks the Stop button.

Figure 7-3. FieldPoint Remote Block Diagram

l. Replace the Setpoint Profile and PID Gains global variables with the appropriate controls as shown in Figure 7-4. m. Because the error clusters were removed, wire a channel constant through the Case structure to control order of execution. n. Confirm that your code matches Figure 7-3 and Figure 7-4 then press the <Ctrl-B> keys to remove any remaining broken wires.

National Instruments Corporation

7-35

LabVIEW Real-Time Course Manual

Lesson 7

Deploying Your Application

Figure 7-4. FieldPoint Remote Block Diagram Initialization Code

The time-critical loop can now run as a self-contained application, which is required in order to use Remote Panels. 2. Save the VI.

Web Publishing Tool


1. Select ToolsWeb Publishing Tool to open the Web Publishing Tool dialog box. 2. Select the VI you just modified from the VI name drop-down menu. 3. Select Embedded for the Viewing Mode. 4. Click the Next button. 5. Enter a Document Title, Header, and Footer. 6. Enter C:\Exercises\LabVIEW Real Time as the Directory to save the web page. 7. Enter cFP - Remote Panels TCL as the Filename. 8. Click Save to Disk. 9. When prompted with a message that the file is not in the Web Server root directory, click OK. You move the file to the RT target next. 10. Open Internet Explorer and enter ftp://[IP Address of RT target]/NI-RT/SYSTEM/WWW in the address field.

LabVIEW Real-Time Course Manual

7-36

ni.com

Lesson 7

Deploying Your Application

11. Copy cFP - Remote Panels TCL.htm in the C:\Exercises\ LabVIEW Real-Time directory to the target by dragging it into Internet Explorer. 12. Right-click the RT Project in the Project Explorer and select Properties. 13. Click the Enable Web Server box in the Web Server:Configuration category. 14. Click OK. 15. Right-click the RT Project in the Project Explorer and select Deploy to apply the configuration changes. 16. Right-click the cFP - Remote Panels TCL VI in the Project Explorer and select Deploy. 17. Access the RT target through Remote Panels. a. In Internet Explorer, enter http://[IP Address of RT target]/cFP - Remote Panels TCL.html. b. The Web page containing the Remote Front Panel should appear. c. Right-click the panel and select Request Control of VI. d. Run the VI
Note If your VI does not display properly on the Web page, make sure your Internet settings are set to refresh on every visit to the page. For Internet Explorer select Tools Internet OptionsTemporary Internet FilesSettingsEvery Visit to the Page.

End of Exercise 7-2A

National Instruments Corporation

7-37

LabVIEW Real-Time Course Manual

Lesson 7

Deploying Your Application

Exercise 7-2B PXI - Remote Panels


Objective: Given a target application, use Remote Panels to view and control the application. In this exercise, you modify the time-critical loop of the application so that it runs self-contained without the need of the host application or the normal priority loop. After you modify the time-critical loop, you can control the application using Remote Panels. 1. Open PXI - TCL Project.vi from the PXI Real-Time Project.lvproj. 2. Select FileSave As and select Open additional copy. Save the file as PXI - Remote Panels TCL.vi in the C:\Exercises\LabVIEW Real Time directory. 3. Close the original TCL VI and any other open VIs.

Front Panel
1. Delete all controls and indicators on the front panel of the VI, except for the Channel Parameters, Timing and Triggering Parameters, and PID output range. 2. Open Project Host.vi from the Project Explorer. 3. Copy the following controls and indicators from the Project Host VI and paste them into the PXI - Remote Panels TCL.vi front panel: Tab control containing Setpoint Profile, and PID Gains Emergency Stop button Apply Disturbance button Temperature Chamber chart Lamp Power graduated bar Current Timestamp string Disturbance Boolean indicator

Close the Project Host VI after copying the controls and indicators. Do not save changes. The completed front panel for PXI - Remote Panels TCL VI should resemble Figure 7-5.

LabVIEW Real-Time Course Manual

7-38

ni.com

Lesson 7

Deploying Your Application

Figure 7-5. PXI Remote Front Panel

Block Diagram
1. Modify the block diagram of PXI - Remote Panels TCL VI to operate as a self-contained application. a. Remove the code that sends data through the shared variable FIFOs. b. Wire the temperature and setpoint data items to a Bundle function as shown in Figure 7-6. Notice that the setpoint is wired as the first element in the Bundle function because the Temperature chart that you copied from the host VI is expecting the setpoint to be the first item charted.

Figure 7-6. PXI Remote Block Diagram

National Instruments Corporation

7-39

LabVIEW Real-Time Course Manual

Lesson 7

Deploying Your Application

c. Wire the output of the Bundle function to the Temperature chart. d. Place the Format Date/Time String function on the block diagram. e. Wire the Timestamp to the input of Format Date/Time String function. f. Wire the output of the Format Date/Time String function to the Current Timestamp indicator. g. Remove the functional global variables for the disturbance and stop condition. h. Remove the Select function and Feedback node that were connected to the Disturbance functional global variable. i. Wire the Apply Disturbance control to the existing Select function, so that when the Boolean value is TRUE, a .999 is passed to the counter frequency, and when the Boolean value is FALSE, a 0.001 is passed to the counter frequency. j. Wire the Apply Disturbance control to the Disturbance indicator. k. Wire the PID output to the Lamp Power indicator. l. Wire the Emergency Stop button to the Or function, which causes the While Loop to stop executing when the user clicks the stop button. m. Replace the Setpoint Profile and PID Gains global variables with the appropriate controls as shown in Figure 7-7. n. Confirm that your code matches Figure 7-6 and Figure 7-7 then press the <Ctrl-B> keys to remove any remaining broken wires.

LabVIEW Real-Time Course Manual

7-40

ni.com

Lesson 7

Deploying Your Application

Figure 7-7. PXI Remote Block Diagram Initialization Code

The time-critical loop now can run as a self-contained application that you can use with Remote Panels. 2. Save the VI.

Web Publishing Tool


1. Select ToolsWeb Publishing Tool to open the Web Publishing Tool dialog box. 2. Select the VI you just modified from the VI name drop-down menu. 3. Select Embedded for the Viewing Mode. 4. Click the Next button. 5. Enter a Document Title, Header, and Footer. 6. Enter C:\Exercises\LabVIEW Real Time as the Directory to save the web page. 7. Enter PXI - Remote Panels TCL as the Filename. 8. Click Save to Disk.

National Instruments Corporation

7-41

LabVIEW Real-Time Course Manual

Lesson 7

Deploying Your Application

9. When prompted with a message that the file is not in the Web Server root directory, click OK. You move the file to the RT target next. 10. Open Internet Explorer and enter ftp://[IP Address of RT target]/NI-RT/SYSTEM/WWW in the address field. 11. Copy PXI - Remote Panels TCL.htm in the C:/Exercises/ LabVIEW Real Time directory to the target by dragging it into Internet Explorer. 12. Right-click the RT Project in the Project Explorer and select Properties. 13. Click the Enable Web Server box in the Web Server:Configuration category. 14. Click OK. 15. Right-click the RT Project in the Project Explorer and select Deploy to apply the configuration changes. 16. Right-click the PXI - Remote Panels TCL VI in the Project Explorer and select Deploy. 17. Access the RT target through Remote Panels. a. In Internet Explorer, enter http://[IP Address of RT
target]/PXI - Remote Panels TCL.html.

b. The Web page containing the Remote Front Panel should appear. c. Right-click the panel, and select Request Control of VI. d. Run the VI
Note If you VI does not display properly on the Web page, make sure your Internet settings are set to refresh on every visit to the page. For Internet Explorer select Tools Internet OptionsTemporary Internet FilesSettingsEvery Visit to the Page.

End of Exercise 7-2B

LabVIEW Real-Time Course Manual

7-42

ni.com

Lesson 7

Deploying Your Application

Notes

National Instruments Corporation

7-43

LabVIEW Real-Time Course Manual

Lesson 7

Deploying Your Application

Notes

LabVIEW Real-Time Course Manual

7-44

ni.com

Lesson 8 Advanced Topics

Lesson 8 Advanced Topics

Topics A. Multi-Rate Applications Using Timed Loops B. [c]FP Isolation C. Integrating [c]FP into SCADA Systems

Introduction
There are a few topics not used in the course project that may be useful to you in the course of your real-world application. These topics are included in this lesson. Your instructor may skip some sections of this lesson dependent on the needs of the class. For example, section B and C apply only to [c]FP users. These sections discuss further issues with [c]FP, such as utilizing the isolation features on the modules and integrating into SCADA systems. You also can learn about using timed loops to implement multirate, multi-priority applications.

National Instruments Corporation

8-1

LabVIEW Real-Time Course Manual

Lesson 8 Advanced Topics

Timed LoopMulti-Rate Applications


Execute multiple tasks at different rates and dynamic rates Execute multiple tasks at different priorities2 billion priority levels available Implement up to 128 timed loops Higher priority timed loops preempt lower priority timed loops

A. Timed Loops
A Timed Loop executes an iteration of the loop at the period you specify and at the priority level you specify. Use the Timed Loop when you want to develop VIs with multi-rate timing capabilities, feedback on loop execution, or timing characteristics that change dynamically. Use the VIs and functions on the Timed Loop and the DAQmx palettes with the Timed Loop to develop VIs that control timing sources. You can use the Timed Loop on Windows 2000/XP, PharLap ETS, and LabVIEW Real-Time Module on Mac OS 10.x targeted to a supported real-time device. Refer to the <labview>\examples\general\timedloop.llb for examples of using the Timed Loop.

LabVIEW Real-Time Course Manual

8-2

ni.com

Lesson 8 Advanced Topics

Timed LoopProject Modification Example


Priority Level Emergency shutdown: Implement as a hardware 1000 switch, and use digital change detection on a timed loop Apply disturbance: Implement as a hardware switch, and use digital change detection on a timed loop 200

Read temperature and apply control: Use a timed loop 800 Send data to host over TCP: Use a timed loop Do not use any time-critical loops. 100

Timed Loop Application Example


As an example, consider modifying the course project to use timed loops. One of the problems that you may have noticed is that the Emergency Stop button and the Disturbance button is not read if there is a loss of the TCP connection. In a real-world example, this is a serious problem: that Emergency Stop button must be read immediately. Therefore, the Emergency Stop button should be implemented as a hardware switch that someone could press or flip in case of an emergency. The digital line is then read in the target program, removing TCP from consideration. For safety reasons, emergency shut-down procedures should always have the highest priority. In the example shown above, the emergency shutdown is implemented as hardware switch and digital change detection can be used on the timed loop, if your hardware supports it. Here, a priority level of 1000 is used. The actual number used is not important, just the relation to the other priority levels used. Notice that the priority level of 1000 is the highest used, and 199 levels remain between it and the next priority level. This allows room for future expansion of the program.

National Instruments Corporation

8-3

LabVIEW Real-Time Course Manual

Lesson 8 Advanced Topics

Timed LoopMulti-Rate Applications

Output Node Right Data Node Input Node

Left Data Node

Timed Loop Options


The Timed Loop includes the Input, Left Data, Right Data, and Output nodes, as shown in the slide above. You can set configuration options of the Timed Loop by wiring values to the inputs of the Input Node, or you can use the Loop Configuration dialog box to enter values for the options. By default, the inputs of the Input Node appear as icons with the values you specified in the Loop Configuration dialog box. Refer to the Timed Loop Configuration section for more information about configuring a Timed Loop. The Left Data Node of the Timed Loop provides timing and status information about the previous loop iteration, such as if the iteration executed late, the time the iteration actually started executing, and when the iteration should have executed. You can wire data from the Left Data Node to the Right Data Node to configure future iterations of the Timed Loop. You can resize the Left Data and Right Data nodes. Refer to the Changing Timed Loop Input Node Values Dynamically section for more information on using the Left Data and Right Data nodes. The Output Node returns information from the final iteration of the while loop, including whether the final iteration completed on time, and any errors that occurred during loop execution.

LabVIEW Real-Time Course Manual

8-4

ni.com

Lesson 8 Advanced Topics

Timed LoopConfiguration

Timed Loop Configuration


Use the Configure Timed Loop dialog box to configure how the Timed Loop executes. Double-click the Input Node or right-click the Input Node and select Configure Input Node from the shortcut menu to display the Configure Timed Loop dialog box. You can use this dialog box to specify a timing source, period, offset timing, and other options. When you wire a value to an input node terminal, the corresponding field in the Configure Timed Loop dialog box becomes disabled. After the loop begins, you can use the Right Data Node to dynamically adjust the period, offset, priorities, and mode values for the Timed Loop. The updates take effect the next iteration of the loop. Refer to the Changing Timed Loop Input Node Values Dynamically section for more information about dynamically adjusting the Timed Loop values.

National Instruments Corporation

8-5

LabVIEW Real-Time Course Manual

Lesson 8 Advanced Topics

Timed LoopTiming Source


Default: 1 kHz clock of the operating system
Maximum execution: once every 1 ms Only timing source available for [c]FP

Hardware clocks
Events such as digital change detection Hardware clock on a DAQ device 1 MHz clock available on some real-time hardware

Use the Source type listbox in the Loop Configuration dialog box to select a timing source or use the Create Timing Source VI to programmatically select a timing source

Selecting Timing Sources


A timing source determines when a Timed Loop executes a loop iteration. By default, the Timed Loop uses the 1 kHz clock of the operating system as the timing source and can execute only once every 1 ms because that is the fastest speed at which the operating system timing source operates. If the system does not include a supported hardware device, the 1 kHz clock is the only timing source available. If the system does include a supported hardware device, you can select from other timing sources, such as the 1 s in CPU cycles available on some real-time hardware; or events, such as the rising edge of a DAQ counter input or output; or the end-of-scan interrupt of a DAQ device. A 1 MHz clock is available on controllers that use a Pentium 3 or 4 processor. Use the Source type listbox in the Loop Configuration dialog box to select a timing source or use the Create Timing Source VI to programmatically select a timing source.

LabVIEW Real-Time Course Manual

8-6

ni.com

Lesson 8 Advanced Topics

Timed LoopPeriod and Offset


PeriodLength of time between loop executions OffsetLength of time the Timed Loop waits to execute Timing source determines the time unit of the period and the offset

Setting the Period and the Offset


The period is the length of time between loop executions. The offset is the length of time the Timed Loop waits to execute the iterations. The timing source determines the time unit of the period and the offset. If the timing source is a 1 kHz clock, the unit of time for the period and the offset is in milliseconds. If the timing source is a 1 MHz clock on a LabVIEW Real-Time Module target with a Pentium processor, the unit of time for the period and the offset is in microseconds. The time the first timing source starts determines the start time of the offset.

National Instruments Corporation

8-7

LabVIEW Real-Time Course Manual

Lesson 8 Advanced Topics

Timed LoopSetting Priorities


Use to write applications with multiple tasks that can preempt each other within the same VI Higher priority valuehigher priority relative to other Timed Loops on the block diagram. No effect on other programs or code All Timed Loops execute below time-critical priority but above high priority in relation to ordinary VIs.

Setting Priorities
Each Timed Loop on the block diagram creates and runs in its own execution system that contains a single thread, so no parallel tasks can occur. The priority of a Timed Loop specifies when the loop executes on the block diagram relative to other Timed Loops. Use the priority setting of a Timed Loop to write applications with multiple tasks that can preempt each other in the same VI. The higher the value you enter in Priority of the Timed Loop, the higher the priority the Timed Loop has relative to other Timed Loops on the block diagram. The value you enter in the Priority input must be a positive integer between 1 and 2,147,480,000. If two Timed Loops have the same priority, the first Timed Loop that executes completes its execution before the other Timed Loop starts its execution. Timed Loops execute at a priority below the time-critical priority of any VI but above high priority, which means that Timed Loops execute in the data flow of a block diagram ahead of any VI not configured to run at a time-critical priority.

LabVIEW Real-Time Course Manual

8-8

ni.com

Lesson 8 Advanced Topics

Timed LoopNaming Timed Loops


Unique identifier for each Timed Loop Use the name provided by LabVIEW or use a custom name. Refer to the loop programmatically using this name.

Naming Timed Loops


By default, LabVIEW automatically uniquely identifies each Timed Loop you place on the block diagram with a name, which appears in the Loop name text box of the Loop Configuration dialog box. You can rename the Timed Loop by entering a name in this text box. You can use the unique name of the Timed Loop with the VIs on the Timed Loop palette to programmatically stop the Timed Loop and to synchronize a group of Timed Loops to use the same start time. If a reentrant VI includes a Timed Loop and you use two or more instances of that reentrant VI as subVIs on a block diagram, you must programmatically change the name of the Timed Loop for each instance of the reentrant VI. Ensure that the reentrant VI that includes the Timed Loop has an input terminal on the connector pane connected to a string control wired to the Loop name input of the Timed Loop on the block diagram. On the block diagram where two or more instances of the reentrant VI are used as a subVI, wire unique string values to the Loop name input on the reentrant subVI to uniquely identify each Timed Loop within each instance of the reentrant subVI. For example, the following block diagram includes two instances of the same reentrant VI as subVIs. The Loop name string constants wired to the instances of the subVIs pass two different names to the Timed Loop in the block diagram of the reentrant VI each time the block diagram executes. If the Timed Loops were not programmatically renamed, LabVIEW would return an error. Refer to the Suggestions for Using Execution Systems and Priorities top in the LabVIEW Help for more information about using reentrant VIs.

National Instruments Corporation

8-9

LabVIEW Real-Time Course Manual

Lesson 8 Advanced Topics

Timed LoopModes
Determines how to handle late iterations: The LabVIEW Timed Loop Scheduler can align the execution with the original established schedule The LabVIEW Timed Loop Scheduler can define a new schedule that starts at the current time Can process the missed iterations Can skip any missed iterations

Timed Loop Modes


Occasionally, an iteration of a Timed Loop might execute later than the time you specified. The mode of the Timed Loop determines how the loop handles any late executions. Use the options in the Action to take on late iterations section of the Configure Timed Loop dialog box or the Mode input of the Input Node to specify the mode a Timed Loop uses to handle the late execution of a Timed Loop iteration. You can handle the late execution of a Timed Loop in the following ways: The LabVIEW Timed Loop Scheduler can align the execution with the original established schedule. The LabVIEW Timed Loop Scheduler can define a new schedule that starts at the current time. The Timed Loop can process the missed iterations. The Timed Loop can skip any missed iterations. For example, if you set a Timed Loop with a period of 100 ms and an offset of 30 ms, you expect the first loop iteration to execute 30 ms after the first timing source starts running and in multiples of 100 ms after that at 130 ms, 230 ms, 330 ms, and so on. However, the first execution of the Timed Loop might occur after 240 ms have elapsed. Because other Timed Loops or hardware devices might already be running at the schedule you specified, you might want to align the late Timed Loop with the already running global schedule, which means the Timed Loop should align itself as quickly as possible with the schedule you specified. In this case, the next Timed Loop iteration

LabVIEW Real-Time Course Manual

8-10

ni.com

Lesson 8 Advanced Topics

would run at 330 ms and continue to run in multiples of 100 at 430 ms, 530 ms, and so on. If aligning the Timed Loop with other Timed Loops or other hardware devices is not important, the Timed Loop can run immediately and use the current time as its actual offset. In this case, the subsequent loop iterations would run at 240 ms, 340 ms, 440 ms, and so on. If the Timed Loop is late, it might miss data other Timed Loops or hardware devices generate. For example, if the Timed Loop missed two iterations and some of the data from the current period, a buffer could hold the data from the missed iterations. You might want the Timed Loop to process the missed data before it aligns with the schedule you specified. However, a Timed Loop that processes the missed iterations causes jitter, which is the amount of time that a loop cycle time varies from the time you specified. If you do not want to process the missed data, the Timed Loop can ignore older data in the buffer the loop iterations missed and process only the latest data, such as the data available at the next period and the subsequent iterations.

National Instruments Corporation

8-11

LabVIEW Real-Time Course Manual

Lesson 8 Advanced Topics

Timed LoopChanging Dynamically


Runs 1 second longer each time the loop iterates until the loop has executed six times

Changing Timed Loop Input Node Values Dynamically


Use the Left Data Node to acquire information about the execution of the Timed Loop, such as if the timing source executed late or if the offset or period values changed. You can wire the values the Left Data Node returns to the Right Data Node or to nodes in the subdiagram within the Timed Loop. Use the Right Data Node to dynamically change the input values of the Timed Loop on the next loop iteration. The Timed Loop in the above figure runs 1 second (1,000 ms) longer each time the loop iterates until the loop has executed six times. If you dynamically change the offset of the Timed Loop by wiring a value to the Offset input terminal of the Right Data Node, you also must specify a mode with the Mode input terminal of the Right Data Node. To set the mode, right-click the Mode input terminal of the Right Data Node and select CreateConstant or CreateControl from the shortcut menu to create an enumerated constant or control you can use to select a mode.

LabVIEW Real-Time Course Manual

8-12

ni.com

Lesson 8 Advanced Topics

Timed LoopAborting Execution


Use the Stop Timed Loop VI to abort execution programmatically In this example, when Abort? is pressed, the High Timed Loop is stopped.

Aborting a Timed Loop Execution


Use the Stop Timed Loop VI to abort the execution of a Timed Loop programmatically. Specify the name of the Timed Loop you want to abort by wiring that name in a string constant or control to the name input of the Stop Timed Loop VI. For example, in the following block diagram, the Low Timed Loop includes the Stop Timed Loop VI. The High Timed Loop runs and displays the number of iterations it has completed. If the user clicks the Abort Time-Critical Loop button on the front panel, the Wakeup reason output of the Left Data Node returns a value of Aborted, a dialog box appears, and when the user clicks OK in the dialog box, the VI stops running.

National Instruments Corporation

8-13

LabVIEW Real-Time Course Manual

Lesson 8 Advanced Topics

Timed LoopSynchronizing Timed Loops

Synchronizing Timed Loops


Use the Synchronize Timed Structure Starts VI to ensure all the Timed Loops on a block diagram use the same start time and the same timing source. For example, you might have two Timed Loops and you want to ensure that they execute on the same schedule relative to each other. You might want the first Timed Loop to execute first and generate data, then have the second Timed Loop process that data when the Timed Loop execution finishes. To ensure that both Timed Loops use the same start time as the basis for their execution, you create a Timed Loop group by wiring a name for the group to the synchronization group name input and wiring an array of Timed Loop names to the loop names input. The Synchronize Timed Loop Starts VI in the slide creates a synchronization group name and synchronizes Timed Loops A and B to use the same start time.

LabVIEW Real-Time Course Manual

8-14

ni.com

Lesson 8 Advanced Topics

Exercise 8-1 Timed Loops


Time to complete: 30 min.

OBJECTIVE

Create an application that uses multiple, dynamic rates and multiple priorities.

National Instruments Corporation

8-15

LabVIEW Real-Time Course Manual

Lesson 8 Advanced Topics

FieldPoint Isolation
FieldPoint Modules and Backplane are isolated Each module is isolated from other modules Optical isolation between I/O connectors and backplane Up to 2300 V isolation between modules Safety isolation up to 250 Vrms Proper wiring required so that isolation is not defeated

B. [c]FieldPoint Isolation
With proper design, each of the modules in a Fieldpoint system are isolated from each other. There is optical isolation between the I/O connectors and the Fieldpoint backplane. The isolation rating of 2300 V is the maximum voltage differential that can occur between the terminals on the terminal base and the common on the backplane of the module without causing damage to the circuitry. The backplane and the network module share a common ground. This isolation rating is for a transient voltage and cannot be maintained over time. Safety isolation of 250 Vrms is also known as working voltage. The safety isolation is the maximum voltage differential that can be sustained between the terminals on the terminal base and the ground on the backplane of the bank, while still allowing accurate measurements and safe working conditions for human operators. If this limit is exceeded, the accuracy of inputs and outputs can not be guaranteed. These isolation ratings are between the backplane and terminals. For most modules there is no channel to channel isolation, which means that the voltage potential that can exist between to terminals on a module is significantly less. Consult the operating instructions for the specific I/O module for more information.

LabVIEW Real-Time Course Manual

8-16

ni.com

Lesson 8 Advanced Topics

Wiring for Isolation


Modules designed to provide isolation
Cascading power by jumping V and C terminals on modules defeats isolation For each module that requires power provide a separate power supply

Each terminal base provides a V (voltage supply) and C (common). The voltage supply and common are used for power and referencing of the I/O signals. They are not referenced to the common or power supply of the Fieldpoint control circuitry (network module and backplane). Most output modules require external power to work, while most other modules do not require external power. One common technique to provide power to multiple output modules is to connect the V and C terminals from terminal base to terminal base. This allows a single power supply to power the network module and backplane and to provide power to the individual modules. Although this is convenient, it defeats the isolation and the protection of the system. Therefore the best option is to use one power supply for the network module and one power supply for each output module.

National Instruments Corporation

8-17

LabVIEW Real-Time Course Manual

Lesson 8 Advanced Topics

Implementing the [c]FP-20xx in SCADA Systems


Use MAX to Configure the OPC Server
OPC Clients (Lookout, LV DSC, DataSocket, Third Party) Publish Data VIStore Memory Values, Scaled Data, System Parameters Acquire/Control Current Process Values Remotely

Use [c]FP-20xx Module to Store/Display Data


Reliable Acquisition Transfer Files to SCADA PCs through TCP-IP Based Protocols LabVIEW WebServer Can Display Data to HTML

C. Integrating [c]FP into SCADA Systems


You can use a variety of methods to integrate [c]FP-20xx Modules in a large Supervisory Control and Data Acquisition (SCADA) system.

Use MAX and Configure the OPC Server


The FieldPoint hardware can communicate through OPC, an industry-standard protocol. When you use MAX to configure an IAK file, you are actually configuring data items on the FieldPoint OPC server so any OPC Client computer with proper access can connect to the FieldPoint data items. Each channel in the IAK will be available as an OPC item. The OPC server resides on the same computer as the MAX Software and runs as NT service that is launched automatically when the first OPC Client tries to connect.

LOGOS
If you are using National Instruments Software products, you also can connect to the FieldPoint OPC Server through DataSocket, LabVIEW DSC, and Lookout. However, because the Client and Server in this case are both products of National Instruments, you can bypass the OPC Protocol altogether and use Logos. Logos allows you to communicate directly with the FieldPoint module. You would want to use this protocol instead of the OPC server when relying on a designated computer with the FieldPoint OPC Server is not desirable. However, for most users, OPC is sufficient because the FieldPoint OPC Server resides on the same computer as the OPC client.

LabVIEW Real-Time Course Manual

8-18

ni.com

Lesson 8 Advanced Topics

Publish Data VIs


You can use the Publish Data VIs to post scaled data or other control parameters to the memory of the [c]FP-20xx module. These data items appear as channels under the [c]FP-20xx modules device in MAX. They can be written to and read from just like any other I/O data item except it is not directly linked to a particular hardware input or output. The Publish Data VI can be useful to publish calculated values, such as values that have been scaled. It also can be used to allow clients to control the flow of the program. Channels can be created to represent a set point or state of the program (for example, automatic or manual control). The Publish Data VI can be found on the FieldPoint RT palette.

Remote Access
Even while an embedded application is running on your [c]FP-20xx module, you can still access the data items (Published Memory Values and I/O Data Items) from MAX, LabVIEW DSC Program, DataSocket, or an OPC Client. However, note that any communication to the [c]FP-20xx module requires processing time and enough sleep or delay must be introduced in your RT loop to avoid starvation.

Use FP-20xx Module to Store Data


The CompactFLASH memory on your [c]FP-20xx module can be used to store data in files much like a hard drive. This can be a reliable way to acquire critical data because you can save directly to the [c]FP-20xx without depending upon network connections. You can periodically retrieve the data files remotely through a TCP-IP protocol such as FTP, DataSocket, or VI-Server. You could even use the Web Server built into LabVIEW to post data to HTML pages. The HTML pages can be read from the FP-20xx itself so remote users can view the current or historical values of the process variables in a Web browser.

National Instruments Corporation

8-19

LabVIEW Real-Time Course Manual

Lesson 8 Advanced Topics

Typical SCADA System with [c]FP-20xx Module


OPC Client
10 Base-T or 100 Base-T

FP OPC/ Time Server LV DSC Server

RT Loop

Firewall

LV DSC Client

Intranet

Internet

Web Client

Typical SCADA System with FP-20xx Module


In this system, a [c]FP-20xx is running a time-critical operation. MAX has been set up on the local intranet and is posting some critical control parameters through OPC to a Legacy system OPC Client. This computer also is providing a Time Server for the [c]FP-20xx modules time stamping. LabVIEW DSC has been implemented to datalog the control parameters from the RT Loop as well as several hundred process variables from diverse equipment including [c]FP-20xx and other legacy PLCs, RTUs, and so on. This data can be viewed from several key locations at LV DSC Client computers. The users can use powerful graphical displays to view historical and current process parameters. Also, some important data is being exported to the Web directly from the [c]FP-20xx directly using the LabVIEW Web Server and anyone with a Web browser and security access is able to log in from anywhere in the world and view the live data.

LabVIEW Real-Time Course Manual

8-20

ni.com

Lesson 8 Advanced Topics

Summary
What are some of the benefits of using Timed Loops? Are Timed Loops a method of software or hardware timing? Should you use a time-critical thread with Timed Loops?

National Instruments Corporation

8-21

LabVIEW Real-Time Course Manual

Lesson 8

Advanced Topics

Exercise 8-1A cFP - Timed Loops


Objective: Create an application that uses multiple rates, multiple priorities, and dynamic rates. Create an application that dynamically changes the blinking rate of a lamp and turns on a fan if the temperature exceeds a specified maximum. Blinking the lamp at the correct rate is a higher priority than controlling the fan. 1. Open the Real-Time Exercises project from the C:\Exercises\ LabVIEW Real Time directory. 2. Add a blank VI to your cFP target in the Project Explorer. 3. Save the new VI as cFP - Timed Loops.vi in the C:\Exercises\ LabVIEW Real-Time directory. 4. Place a Numeric Control on the front panel of the blank VI. 5. Label the Numeric Control Max Temp. The fan turns on when the measured temperature is above the Max Temp.

Lamp Timed Loop


1. Place a Timed Loop from the StructuresTimed Loops palette on the block diagram, to handle the lamp control. 2. Double-click the Input Node of the Timed Loop and configure the Timed Loop with the following options: Period: 5000 ms Priority: 1000 Loop Name: Lamp All other options can be left at default

3. Place a FP Write VI in the Timed Loop. a. Right-click the FieldPoint IO Point In input and select Create Control. b. Name the control Lamp Channel and place it outside the loop. c. Set the duty cycle of the lamp to 100 when the loop iteration is even, and 0 when the loop iteration is odd. This logic turns the lamp on for even iterations and off for odd iterations. One example of this logic is shown in Figure on the block diagram. 4. Use the left and right input terminals to reduce the period by 250 ms each loop iteration. Notice that the loop period begins at 5 seconds, as shown during the Timed Loop configuration you completed in Step on the block diagram.

LabVIEW Real-Time Course Manual

8-22

ni.com

Lesson 8

Advanced Topics

5. End the loop when the period is less than or equal to 250 ms.

Figure 8-1. Completed Lamp Timed Loop

Temperature and Fan Timed Loop


1. Place a Timed Loop on the block diagram to handle the temperature and fan control. Double-click the Input Node of the Timed Loop and configure the Timed Loop with the following options: Period: 1000 ms Priority: 500 Loop Name: Fan All other options can be left at default.

2. Place a FP Read VI in the Timed Loop. a. Right-click the FieldPoint IO Point In input and select Create Control. b. Name the control Temperature Channel and place it outside the loop. c. Wire a double-precision, floating-point numeric constant to the Type input. 3. Place a FP Write VI in the Timed Loop. a. Right-click the FieldPoint IO Point In input and select Create Control. b. Name the control Fan Channel and place it outside the loop. c. If the temperature is less than the Max Temp control, set the fan duty cycle to 0; if is equal to or greater than the Max Temp control, set the fan duty cycle to 100.

National Instruments Corporation

8-23

LabVIEW Real-Time Course Manual

Lesson 8

Advanced Topics

One example of this logic is shown in Figure 8-2 on the block diagram.

Figure 8-2. Completed Fan Timed Loop

Stop the Application


Use the Stop Timed Loop VI to stop the Fan Timed Loop after the Lamp Timed Loop has completed. 1. Place a Stop Timed Loop VI on the block diagram to the right of the Lamp Timed Loop. 2. Connect the error out output from the Lamp Timed Loop to the error in input of the Stop Timed Loop VI to control the order of execution. 3. Create a constant on the Name input of the Stop Timed Loop VI and enter the value of Fan. 4. This VI stops the Fan Timed Loop. 5. Place a Clear Specific Error VI from the C:\Exercises\LabVIEW Real Time directory after the error output of the temperature and fan Timed Loop.

LabVIEW Real-Time Course Manual

8-24

ni.com

Lesson 8

Advanced Topics

6. Wire a numeric constant with a value of -816 to the Clear Specific Error VI. When aborted, the timed loop generates error -816. Because the abort is an expected behavior, you can ignore this error. 7. Place an instance of the FP Write VI to the right of each Timed Loop. 8. Write a value of 0 to each FP Write VI to set the lamp and fan power levels back to 0. 9. Place a Merge Errors VI on the block diagram and use it to merge the error cluster outputs from the three DAQmx Clear VIs. 10. Place a Simple Error Handler VI on the block diagram and use it to display errors from the output of the Merge Errors VI. An example of the completed application is shown in Figure 8-3 on the block diagram.

Figure 8-3. Completed Timed Loop Application

National Instruments Corporation

8-25

LabVIEW Real-Time Course Manual

Lesson 8

Advanced Topics

Run the Application


1. Save the VI. 2. Set up the channels for the lamp, fan, and temperature on the front panel of the VI. 3. Enter a Max Temp value of 30 C. This temperature ensures that you see the fan operating if your chamber is starting from room temperature. Experiment with other Max Temp values as necessary. 4. Run the VI. 5. Close the VI when you are finished.

End of Exercise 8-1A

LabVIEW Real-Time Course Manual

8-26

ni.com

Lesson 8

Advanced Topics

Exercise 8-1B PXI - Timed Loops


Objective: Create an application that uses multiple rates, multiple priorities, and dynamic rates. Create an application that dynamically changes the blinking rate of a lamp and turns on a fan if the temperature exceeds a specified maximum. Blinking the lamp at the correct rate is a higher priority than controlling the fan. 1. Open the Real-Time Exercises project from the C:\Exercises\ LabVIEW Real-Time directory. You created this project in Exercise on the block diagram. 2. Add the PXI - Timed Loops.vi from the C:\Exercises\ LabVIEW Real-Time directory to your RT target in the Project Explorer. 3. Double-click the Timed Loops VI to open it. A portion of the program has been built for you. It already contains the task information for the lamp, fan, and thermocouple.

Lamp Timed Loop


4. Place a Timed Loop on the block diagram to handle the lamp control. 5. Double-click the Input Node of the Timed Loop and configure the Timed Loop with the following options: Period: 5000 ms Priority: 1000 Loop Name: Lamp All other options can be left at default.

6. Collapse the terminals on the Input Node of the Timed Loop so that only a single terminal is visible. 7. Left-click the remaining terminal and select Error. 8. Wire the error wire from the DAQmx Start Task VI to the error terminal of the Timed Loop. 9. Place a DAQmx Write VI on the block diagram in the timed loop. 10. Select the CounterSingle ChannelSingle SampleFrequency instance from the polymorphic VI selector of the DAQmx Write VI. 11. Connect the task input to the DAQmx Write VI. 12. Connect the Error output from the left loop terminal to the DAQmx Write VI. You can drag the terminal down to simplify wiring. 13. Wire the PWM Frequency control to the frequency input of the DAQmx Write VI.

National Instruments Corporation

8-27

LabVIEW Real-Time Course Manual

Lesson 8

Advanced Topics

14. Set the duty cycle of the lamp to 0.999 when the loop iteration is even, and 0.001 when the loop iteration is odd. This logic turns the lamp on for even iterations and off for odd iterations. One example of this logic is shown in Figure on the block diagram. 15. Use the left and right input terminals to reduce the period by 250 ms each loop iteration. Remember that the loop period begins at 5 seconds, as described in the Timed Loop configuration Step 5. 16. End the loop when the period is less than or equal to 250 ms.

Figure 8-4. Completed Lamp Timed Loop

Temperature and Fan Timed Loop


1. Place a Timed Loop on the block diagram to handle the temperature and fan control. 2. Double-click the Timed Loop border to open the Configure Timed Loop dialog box and configure the Timed Loop with the following options: Period: 1000 ms Priority: 500 Loop Name: Fan All other options can be left at default.

LabVIEW Real-Time Course Manual

8-28

ni.com

Lesson 8

Advanced Topics

3. Collapse the input terminals of the Timed Loop so that only a single terminal is visible. 4. Click the remaining terminal and select Error. 5. Wire the error output from the DAQmx Start Task VI to the error input of the Timed Loop. 6. Place a DAQmx Write VI in the Timed Loop next to the fan task. 7. Select the CounterSingle ChannelSingle SampleFrequency instance from the polymorphic VI selector of the DAQmx Write VI. 8. Connect the task input to the DAQmx Write VI. 9. Expand the left data node of the Timed Loop to display two items. 10. Click and select Error for one data item and Wakeup Reason for the other. 11. Connect the Error from the left loop terminal to the DAQmx Write VI. You can drag the terminal down to simplify wiring. 12. Wire the PWM Freq control to the frequency input of the DAQmx Write VI. 13. Place a DAQmx Read VI in the Timed Loop next to the temperature task. 14. Select the AnalogSingle ChannelSingle SampleDBL instance from the polymorphic VI selector of the DAQmx Read VI. 15. Connect the task input and error input to the DAQmx Read VI. 16. If the temperature is less than the Max Temp indicator, set the fan duty cycle to 0.001; if the temperature is equal to or greater than the Max Temp indicator, set the duty cycle to 0.9999. An example of this logic is shown in Figure 8-5 on the block diagram.

National Instruments Corporation

8-29

LabVIEW Real-Time Course Manual

Lesson 8

Advanced Topics

Figure 8-5. Completed Fan Timed Loop

Stop the Application


Use the Stop Timed Loop VI to stop the Fan Timed Loop after the Lamp Timed Loop has completed. 1. Place a Stop Timed Structure VI on the block diagram to the right of the Lamp Timed Loop. 2. Wire the error out output from the Timed Loop to the error in input of the Stop Timed Loop VI. 3. Create a constant on the Name input of the Stop Timed Loop VI and enter the value of Fan. 4. Stop the loop when the wakeup reason is anything but Normal. See the logic in Figure on the block diagram. When the lamp loop completes and calls the Stop Timed Structure VI, the temperature and fan loop executes immediately and the wakeup reason is Aborted. By stopping the loop with any wakeup reason but Normal, you handle the abort and any potential errors. 5. Place a Clear Specific Error VI from the C:\Exercises\LabVIEW Real Time directory after the error output of the temperature and fan Timed Loop.
LabVIEW Real-Time Course Manual 8-30 ni.com

Lesson 8

Advanced Topics

6. Wire a Numeric constant with a value of -816 to the Clear Specific Error VI. When aborted, the timed loop generates error -816. Because the abort is an expected behavior, you can ignore this error. 7. Place a DAQmx Clear Task VI to the right of the timed loops for each DAQmx task. 8. Wire the DAQmx Clear VIs. 9. Place a Merge Errors VI on the block diagram to merge the error cluster outputs from the three DAQmx Clear VIs. 10. Place a Simple Error Handler VI and use it to display errors from the output of the Merge Errors VI. An example of the completed application is shown in Figure 8-6 on the block diagram.

National Instruments Corporation

8-31

LabVIEW Real-Time Course Manual

Lesson 8

Advanced Topics

Figure 8-6. Completed Timed Loop Application

Run the Application


1. Save the VI. 2. Set up the channels for the lamp, fan, and temperature on the front panel of the VI: Lamp: SCC1Mod19/ctr0 Temperature: SCC1Mod1/ai0 Fan: SCC1Mod20/ctr0

3. Enter the Max Temp of 30 C. This temperature should ensure that you see the fan come on and off, if your chamber is starting from room temperature. Experiment with other Max Temps as necessary. 4. Run the VI. 5. Close the VI when you are finished.

End of Exercise 8-1B


LabVIEW Real-Time Course Manual 8-32 ni.com

Lesson 8

Advanced Topics

Notes

National Instruments Corporation

8-33

LabVIEW Real-Time Course Manual

Lesson 8

Advanced Topics

Notes

LabVIEW Real-Time Course Manual

8-34

ni.com

Course Project Resources

This appendix contains the following resources for use in completing the course project.

Topics
A. Course Project Specification Document B. Course Project Requirements Document C. Course Project Flowcharts

National Instruments Corporation

A-1

LabVIEW Real-Time Course Manual

Appendix A

Course Project Resources

A. Course Project Specification Document


Overview
A temperature chamber provides a two stage temperature ramp for the incubation of cells. This program controls the temperature chamber. The temperature in the chamber is achieved through the control of a lamp and a fan. The fan also simulates disturbance to the temperature chamber. Temperature ranges are confined from room temperature to 75 C.

User Interface
The user interface allows the user to select a range of temperatures and times. Each temperature is held for the time specified by the user in the order entered. A graph shows actual temperature versus time and setpoint versus time. The user can start the test from the user interface, abort the test, and apply disturbance to the temperature chamber.

Data Logged
The header for the data file includes the user interface inputs and beginning time stamp for the control profile. Data logged includes temperature, time stamp, setpoint, lamp power, and whether disturbance was applied. All data are logged every time the temperature is read.

Specifications
The temperature should be measured, recorded, and used to calculate output to the lamp. Also, an output should be applied within a set response rate (loop cycle). Two different labs are using this system. One needs the response rate at 10 Hz with a maximum of 1 Hz deviation, and the second needs the response rate at 100 Hz with a maximum of 0.5 Hz deviation. The system should start automatically on power up. External systems should be able to view and utilize current data through a UDP connection at user specified addresses. System must respond to the Abort command within one cycle.

LabVIEW Real-Time Course Manual

A-2

ni.com

Appendix A

Course Project Resources

B. Course Project Requirements Document


Overview
A temperature chamber provides a temperature ramp for the incubation of cells. This program controls a temperature chamber. The temperature ramp in the chamber is achieved through the control of a lamp. A fan simulates disturbance to the temperature chamber. The entire control setup is shown in Figure A-1.

Temperature Chamber Thermocouple I/O

Target Control Communicate Log TCP/IP

Host Set control setpoint profile View temp GUI: Start, Abort and Disturbance

Figure A-1. Overview of Control Setup

Target temperature ranges are confined from room temperature to 75 C. The user inputs a range of temperatures and hold times. The sum of the hold times never exceeds 15 minutes. For example, a setpoint profile of:
[0 s, 25 C], [10 s, 30 C], [20 s, 30 C]

means to start at 25 C, ramp up to 30 C in 10 seconds, and hold at 30 C for another 10 seconds. The control algorithm used for the system is PID. The system has already been modeled as a first-order system and the PID values determined. Use the following PID values: P: 15 I: 0.5 D: 0.01

There are two separate implementations of this system. One lab needs a response rate of 10 Hz with a maximum jitter of 1 Hz. This lab is implemented using a Compact FieldPoint system. The second lab needs a response rate of 100 Hz with a maximum jitter of 0.5 Hz. This lab is implemented using a PXI system.

Implementation #1 Hardware:

National Instruments Corporation

[c]FP-2000 or 2010 network module [c]FP-PWM-520 module and TB-1 [c]FP-TC-120 module and TB-3
A-3 LabVIEW Real-Time Course Manual

Appendix A

Course Project Resources

Temperature chamber: 12 volt lamp, J-type thermocouple, and a 12 volt fan to simulate disturbance

Implementation #2 Hardware:
PXI chassis PXI controller (recommended: PXI-8186 or PXI-8176) PXI-6040E DAQ device; counter outputs are used for pulse width modulation (PWM) to control the fan and lamp, analog input reads the temperature Signal conditioning circuit Temperature chamber: 12 volt lamp, J-type thermocouple, and 12 volt fan

Host Program
The user interface is implemented on a Windows XP computer. The user interface communicates with a data acquisition and control program running on a real-time operating system on the target hardware. The user interface allows the user to set the temperature ramp characteristics. The temperature ramp characteristics include the setpoint profile and the PID values. Although the PID values have already been determined, the user should be able to adjust these values from the user interface. Figure A-2 shows an example user interface with the default values set. Once the user has set the temperature ramp characteristics and PID values, clicking the Start button sends the data to the target program and instructs the target program to begin the temperature ramp. You can click the Disturbance button at any time during a test. In case of emergency, an Emergency Stop button is provided to stop the hardware. The target program must respond to the Emergency Stop and Disturbance buttons as soon as possible. The user can also provide a name for the log file on the target, and the IP address of the target hardware. Information displayed to the user includes the current power output to the lamp as a percentage of maximum power, an LED indicating whether the disturbance (fan) is on or off, the timestamp of last value read, and a chart displaying the actual temperature and current target setpoint. The user interface also displays the current state of the system, which includes Idle, Configuration, and Run. The Idle state designation implies that no temperature ramp is currently running, or that there is no TCP connection to the system.

LabVIEW Real-Time Course Manual

A-4

ni.com

Appendix A

Course Project Resources

The Configuration state designation implies that the control profile and PID gains are being sent to the target system. The Run state designation immediately follows the Configuration state and implies that the system is currently running a temperature ramp. If the Host has lost TCP connection to the system and reconnects while the system is in the midst of a ramp, the host displays to the user that the system is currently in the Run state and continues displaying the current data.

Figure A-2. Example User Interface

The following list summarizes the major host program tasks: Transfer PID values and setpoint profile on start command Send emergency stop command through TCP as needed Send disturbance command through TCP as needed Receive and chart TCP data from target

Target Program
When idle, the target program waits for configuration data and the start command from the host. When received, the program configures the system. After you configure the system, the program begins the temperature ramp. The program must monitor continually for the emergency stop command and the disturbance command during the temperature ramp, and implement as soon as possible. After the temperature ramp is completed or terminated, the program waits for the next set of configuration data from the host. Figure A-3 shows a high level flowchart of the expected behavior of the target program. It illustrates the expected four states of the target program: Initialize, Configuration, Run, and Close.

National Instruments Corporation

A-5

LabVIEW Real-Time Course Manual

Appendix A

Course Project Resources

Initialize Resource, Variables, etc.

Get Configuration Data from Host

Run TCL and NPL Loops

Unrecoverable Error? No

Yes

Close Resources

No

Config Request Complete? Yes

Figure A-3. High-Level Flowchart of the Target Program

During the Run state, this program retrieves the temperature from a thermocouple and a time stamp specifying when the temperature was read. The data retrieved determines whether to increase, hold, or decrease the temperature by using PID control to determine output levels for the lamp. Disturbance to the system is simulated by turning on the fan. A disturbance selection sends full power to the fan until the disturbance is deselected. This program also logs the retrieved data on the target. This data must be accurately time-stamped. The system must log the data in a tab-delimited ASCII file. Data is logged for every temperature read. Logging of data must not affect the system determinism in any form. Table A-1 shows an example of the expected log file.
Table A-1. Log File

Setpoint (C) Temp (C) 28 28 25.00 26.01

Time Stamp Lamp Power 36:00:00 36:00:01 80% 75%

Disturbance (T/F) F F

Setpoint, temperature, time stamp, lamp power, and disturbance are sent to the host program at each cycle through TCP using port 1080 for the user interface.

LabVIEW Real-Time Course Manual

A-6

ni.com

Appendix A

Course Project Resources

The following list summarizes the major target program tasks: Monitor for configuration data and start command Implement configuration data when received Control temperature chamber as specified Monitor for emergency stop and disturbance commands Implement emergency stop and disturbance commands Transfer data to host through TCP Log data to file

National Instruments Corporation

A-7

LabVIEW Real-Time Course Manual

Appendix A

Course Project Resources

C. Course Project Flowcharts


The flowcharts shown in this section are used throughout the course as a basis for the course project.

Host Flowchart

Initialize

No Target Running? Yes No Idle Start Button Pressed? Yes Send Configuration Data to Target

Read and Write Data from Target No Host Stop Pressed or Error? Yes No Data Request Complete? Yes Clean Up Resources

Figure A-4. Project Host Flowchart

LabVIEW Real-Time Course Manual

A-8

ni.com

Appendix A

Course Project Resources

Time-Critical Priority Loop Flowchart

Configure Hardware

Read Temperature

Get Timestamp

Determine PID Output

Read Disturbance

Write Lamp and Fan Output

Write Time Critical Loop Data to Real-Time FIFO

Read Emergency Stop

No

Profile Complete or Stop? Yes Close Open References

Figure A-5. Time-Critical Priority Loop Flowchart

National Instruments Corporation

A-9

LabVIEW Real-Time Course Manual

Appendix A

Course Project Resources

Normal Priority Loop Flowchart

Initialize

Connected to Host? Yes

No

Connect to Host

Listen for Data No Data Received? Yes

Open Log File

Configuration

Run TCL SubVI

Get Data from TCL

Transfer Data to and from Host and Log to File

Transfer Disturbance and Stop to TCL

TCL Stopped? Yes

No

Error?

No

No Yes Unrecoverable Error? Yes

FIFO Empty?

Close Log File

Yes Read FIFO Data, Log, and Transfer to Host

Run

Close Resources

Figure A-6. Normal Priority Loop Flowchart

LabVIEW Real-Time Course Manual

A-10

ni.com

Additional Information about LabVIEW Real-Time

This appendix contains the following sections of useful information for LabVIEW Real-Time:

Topics
A. Implementing Redundancy in Your System B. Using LabWindows/CVI DLLs in LabVIEW Real-Time

National Instruments Corporation

B-1

LabVIEW Real-Time Course Manual

Appendix B

Additional Information about LabVIEW Real-Time

A. Implementing Redundancy in Your System


When designing for a critical application, a system that incorporates redundancy is a good idea. For complete redundancy, two complete control systems are created. Only one of them is active while the other one is in a wait state. The second system simply monitors the first one. Typically a heartbeat is created by the primary system. As long as the heartbeat is changing, the primary system is in control. If the heartbeat stops, the secondary system takes over. Depending on the process, the back up system can take over control when the heart beat fails or it may require some information about the state. For example, consider a process that controls the water level in a tank. The system monitors the water level and if it is below a certain level a pump is turned on. In this scenario, the back up system does not need to know anything about the state of the system. It can simply measure the water level and then determine if the pump should be on or off. Other systems may go through stages or have varying setpoints. If that is the case, then the primary system should continually be passing that information to the backup system. That way when the primary controller fails, the back up system will have recent information. Figure B-1 demonstrates a typical redundant system. When the system starts, the primary system is in control and the secondary or backup system monitors the primary process. Data about state and setpoints pass from the primary system to the secondary system.

LabVIEW Real-Time Course Manual

B-2

ni.com

Appendix B

Additional Information about LabVIEW Real-Time

Primary System Data In Control 1

Secondary System

Monitoring/ Sleeping

Unknown Failure

3 Data Recovering In Control

Figure B-1. Redundant Systems

1. The primary system fails and enters an unknown state. 2. The secondary system does not receive the heart beat and becomes active. It takes control of the process using the latest information about the state. 3. The primary system is restored. Before it becomes active it should request state information from the secondary unit (if necessary). 4. The primary system takes control and sends a signal to the secondary controller to let it know that it has to taken control. The signal could be a restored heartbeat. 5. The secondary system receives the signal or heartbeat and returns to its sleep mode. The primary system is now back in control of the process and the secondary system is back to monitoring the primary controller.

National Instruments Corporation

B-3

LabVIEW Real-Time Course Manual

Appendix B

Additional Information about LabVIEW Real-Time

B. Using LabWindows/CVI DLLs in LabVIEW Real-Time


LabWindows/CVI extends the functionality of LabVIEW Real-Time in two ways. First, it allows the use of ANSI C code on LabVIEW Real-Time (RT) targets. Second, LabWindows/CVI offers programmatic access to the shared memory of National Instruments RT Plug-In devices, enabling you to use the LabWindows/CVI environment to develop host applications for these devices.

Benefits of Using LabWindows/CVI DLLs in Real-Time


LabWindows/CVI can compile code into a LabVIEW Real-Time compatible DLL that can be called and executed by the LabVIEW Real-Time environment. This feature reduces development time for real-time applications in three ways: Engineers and scientists with large amounts of existing ANSI C code greatly reduce their development time for their LabVIEW Real-Time applications through code reuse. Engineers and scientists can develop portions of their LabVIEW Real-Time applications in ANSI C. Engineers and scientists can take advantage of the LabWindows/CVI development environment to create LabVIEW Real-Time VISA drivers for non-NI PXI/PCI hardware. In doing this, third party hardware can be incorporated into LabVIEW Real-Time applications.

LabWindows/CVI Functions Supported by LabVIEW Real-Time


LabVIEW Real-Time hardware devices include an embedded real-time operating system. The real-time operating system is different than traditional operating systems, such as Windows, and supports a slightly different set of functions. When creating a DLL in LabWindows/CVI, you can specify its use for LabVIEW Real-Time. When this is done, the LabWindows/CVI compiler automatically verifies that all of the function calls made from that DLL will be supported by the real-time operating system. To make this specification, select the LabVIEW Real-Time Only option as the run-time support in the Target Settings dialog box. For further instructions, refer to the Using LabWindows/CVI with LabVIEW Real-Time tutorial available by browsing to ni.com/info and entering rdul38. The following LabWindows/CVI libraries are supported for use with the LabVIEW Real-Time Support Engine: Analysis or Advanced Analysis Library ANSI C Library

LabVIEW Real-Time Course Manual

B-4

ni.com

Appendix B

Additional Information about LabVIEW Real-Time


Note

Formatting and I/O Library TCP Support Library Utility Library

Not all of the functions in the preceding libraries are supported. For a complete list of these exported functions, enter cvi_lvrt.dll in the index tab of the NI LabWindows/CVI Help. In addition to the libraries listed previously you also can link the following libraries into the project:
Note

GPIB Library VXI Library VISA Library IVI Library Traditional Data Acquisition Library NI-CAN Most of the functions in the instrsup.dll

For a more detailed list of what functions and libraries are supported, refer to the Target Settings for DLLs section of the NI LabWindows/CVI Help.

TCP Library Support


LabWindows/CVI 8.0 includes TCP Library function support for LabVIEW Real-Time application development. This feature allows DLLs on RT targets to share data directly with nodes on the network, eliminating the need to return to the LabVIEW code to pass data to another node. This can be done through the new Process TCP Events function. TCP function calls, such as TCP write or TCP read, trigger events when they are completed. In previous versions of LabWindows/CVI these events were captured by messaging, which is not supported under real-time operating systems. The Process TCP Events function uses polling to capture TCP events. This feature is useful in any application that needs to publish data as it is received. For example, you may have a DLL that contains a function with multiple data acquisition loops and you would like to publish the data as you acquire it. However, because DLLs pass data back to the calling application only when the function has finished executing, you would need to be able to send the data from within the DLL. Without TCP polling functions, the only way to send the data across the network as you received it would be to implement a loop in LabVIEW and call a function in the LabWindows/CVI DLL that acquired data only a

National Instruments Corporation

B-5

LabVIEW Real-Time Course Manual

Appendix B

Additional Information about LabVIEW Real-Time

single time. After you did that, each time the data was acquired, the function would end and the data would be passed back to the LabVIEW Real-Time application. After the data was back in LabVIEW, you could use the LabVIEW TCP functions to publish the data. However this requires the DLL to be called, loaded, and unloaded each time the LabVIEW loop executes. It also undermines performance. With the added functionality of the TCP function calls, the data can be sent from within the DLL in each loop, allowing the DLL to be called only once, and therefore saving time and memory. The RTServer shipping example located in the CVI70\samples\TCP directory uses the Process TCP Events function to capture TCP events with Polling.
Note

LabWindows/CVI Host Applications for LabVIEW RT targets


You also can use LabWindows/CVI as a host application for LabVIEW RT targets. This functionality allows you to use LabWindows/CVI applications for communication with and control of RT targets. This communication can be achieved through TCP function calls and the programmatic access to the shared memory of National Instruments RT Plug-In devices. A practical example of this would be an RT target that acquires data and sends it to a host LabWindows/CVI application that then analyzes and displays it. You can pass information between programs running on the RT Series DAQ device and the host LabWindows/CVI application through reading and writing data to the shared memory. The functions that provide access to the shared memory are located in the cvirtsup.fp instrument driver. When using these functions, notice the C code is not actually downloaded to the device itself, only the shared memory is accessed. For an example of this type of communication, refer to the lvrtsamp.prj in the CVI70\ samples\cvirtsup directory. When using TCP, remember that the LabVIEW Real-Time Module uses Big Endian notation. If the program that you are sending the data to uses Little Endian notation, you must convert the data before displaying it. You can use the Swap Bytes and Swap Words functions to convert the data in LabVIEW.
Note

LabVIEW Real-Time Course Manual

B-6

ni.com

Instructors Notes

This appendix contains information that the instructor needs to properly set up and teach this course.

A. Course Setup
1. Confirm that all host computers are setup for static IP addresses. Course instructions are simplified if all computers use the same IP address. Do not use DHCP in this course; classrooms do not have enough IP addresses allocated. 2. Run the Test Station VI on the host computer. 3. Place the following equipment at each station: One PXI chassis One [c]FP system One temperature chamber One cross-over cable (grey) One SC-2345 box One thermocouple cable One six-pin cable One PS-3 power supply Three power cables

The student connects the hardware in the configuration exercise. You do not need to connect/test this equipment.

B. Course Shut-Down
Access each target computer and delete any executables installed by the students. These computers are not re-ghosted for each class, so you must complete this step after each course.

National Instruments Corporation

C-1

LabVIEW Real-Time Course Manual

Appendix D Real-Time Systems

Appendix D Real-Time Systems


Real-Time Event ResponseRespond to a single event within a given amount of time. Real-Time ControlRepeatedly perform a user-defined task with a specified time interval separating the tasks. Real-Time Signal ProcessingDeterministic time intervals between repetitive events.

Control Theory Introduction


The simplest real-time system is event response. With real-time event response, you can respond to a single event within a given amount of time. The real-time system guarantees some maximum response time to the single event. The event can be either periodic or random. An example of a real-time event response application is a safety monitoring system. If a physical plant enters a dangerous state, the real-time system must respond to the danger event within a guaranteed amount of time. Latency is used to describe the time it takes to respond to an event. Latency is similar to the determinism in real-time control applications. With real-time event response, you are guaranteed a worst case latency. With real-time control, you can continually monitor and simulate a physical system. Real-time control applications repeatedly perform a user-defined task with a specified time interval separating them. There are many real-time control systems in the world around you such as the cruise control in your car or the thermostat controlling the temperature in your home. Real-time signal processing has many of the same characteristics as real-time control. It requires deterministic time intervals between repetitive events. But instead of calculating a response, it performs signal processing on the acquired data. An example of such a system is calculating the frequency of a signal. The example deterministically acquires a collection of values that represents a waveform and then performs a power spectrum on that data in a loop. All of these systems require precise timing. The following explores real-time control in more detail.

National Instruments Corporation

D-1

LabVIEW Real-Time Course Manual

Appendix D Real-Time Systems

Control TerminologyFurnace Example


Terms: Process variable (PV) Setpoint (SP) Controller output Plant Examples: Temperature Desired temperature Heater voltage Temperature chamber

Real-Time Control
The following are some basic terms that are common to all control systems: Process variableProcess parameter that is to be controlled SetpointDesired value for the process variable Controller outputValue output to an actuator in the system PlantDynamic process in which the process variable is affected by the controller output Note The temperature chamber example is used to illustrate control ideas throughout this course.

LabVIEW Real-Time Course Manual

D-2

ni.com

Appendix D Real-Time Systems

Typical Performance Requirements

Percent Overshoot

Rise Time

Settling Time Steady-State Error

Control Performance Requirements


The control design process begins by defining the performance requirements. Control system performance is often measured by applying a step function as the set point command variable, and then measuring the response of the process variable. Commonly, the response is quantified by measuring defined waveform characteristics. Rise Time is the amount of time the system takes to go from 10% to 90% of the steady-state, or final, value. Percent Overshoot is the amount that the process variable overshoots the final value, expressed as a percentage of the final value. Settling Time is the time required for the process variable to settle to within a certain percentage (commonly 5%) of the final value. Steady-State Error is the final difference between the process variable and setpoint. Notice that the exact definition of these quantities varies in industry and academia. After using one or all of these quantities to define the performance requirements for a control system, it is useful to define the worst case conditions in which the control system is expected to meet these design requirements. Often, there is a disturbance in the system that effects the process variable or the measurement of the process variable. For example, in a temperature chamber the disturbance might be a fan that blows cool air into the chamber and disturbs the temperature. It is important to design a control system that performs satisfactorily during worst case conditions. The measure of how well the control system can overcome the effects of disturbances is referred to as the disturbance rejection of the control system.
D-3

National Instruments Corporation

LabVIEW Real-Time Course Manual

Appendix D Real-Time Systems

Some systems exhibit an undesirable behavior called deadtime. Deadtime is a delay between when a process variable changes and when that change can be observed. For instance, if a temperature sensor is placed far away from a cold water fluid inlet valve, it does not measure a change in temperature immediately if the valve is opened or closed. A system (plant) or output actuator that is slow to respond to the Compensator command, for example, a valve that is slow to open or close, can also cause deadtime. After the performance requirements have been specified, examine the system (plant) and select an appropriate control scheme. In most applications, a Proportional-IntegralDerivative (PID) Compensator provides satisfactory results. However, you must understand some of the alternatives to basic PID control and when they are appropriate. In some cases, the response of the system (plant) to a given control output may change over time or in relation to some variable. A nonlinear system is a system in which the control parameters that produce a desired response at one operating point might not produce a satisfactory response at another operating point. For instance, a chamber partially filled with fluid exhibits a much faster response to heater output when nearly empty than it does when nearly full of fluid. This example is a situation in which basic PID control is not appropriate. The measure of how well the control system tolerates disturbances and nonlinearities is referred to as the robustness of the control system.

LabVIEW Real-Time Course Manual

D-4

ni.com

Appendix D Real-Time Systems

Control Systems
Open Loop Control System
Set Point Actuator Output
Heater Voltage

Plant (Furnace)

Temperature

Closed Loop Control System


Set Point
Desired Temp

Error

Compensator PV (Temp)

Actuator Output

Heater Voltage

Plant (Furnace)

Sensor Feedback

The slide above illustrates two types of control systems: open loop and closed loop. An open loop control system outputs a specific value and assumes the desired response happened. An example of an open loop control system is shown in the slide above. A closed loop control system outputs a specific value, then checks the response. The next output depends on the response measured. For this reason, closed loop control systems are also called feedback systems. An example of a closed loop control system is shown above. The Real-Time Module provides tools for two different types of closed loop compensators (control algorithms): PID control and fuzzy logic control. Some advanced control mechanisms available include continuous linear VIs, discrete linear VIs and nonlinear VIs. You can learn more about these functions in the PID Control Toolset User Manual.

National Instruments Corporation

D-5

LabVIEW Real-Time Course Manual

Appendix D Real-Time Systems

PID ControlProportional, Integral, Derivative


Compensator
Proportional

Desired Temp (setpoint)

Kc
Kc fdt Ti

Heater Voltage

Error

Integral

Derivative

KcTd

df dt

Actual Temp (process variable)

Purpose: drive error between setpoint and process variable to zero

PID Control
The slide above shows a compensator containing the classic PID algorithm. The error is the difference between the process variable (temperature) and the set point (desired temperature). The controller uses the proportional gain, Kc, the integral time constant, Ti, and the derivative time constant, Td, to determine an output (heater voltage), which drives the error to zero. The gain, Kc, is applied directly to the error signal, the gain Kc / Ti is applied to the integral of the error signal, and the gain Kc*Td is applied to the derivative of the error signal. The results of these three operations are added together to form the controller output. This is the where the term PID is derived from. At this point, you must not fully understand the algorithm. Instead, look at each of the terms and see how they affect the response of the system.

LabVIEW Real-Time Course Manual

D-6

ni.com

Appendix D Real-Time Systems

PID GainsP
SP PV

Only proportional gain applied to the error signal

Proportional gain Kc
The Sledgehammerquickly drive to set point Provides immediate controller response to set point change, but process variable (PV) may not settle exactly on set point (SP) using proportional control alone

The proportional gain is equivalent to the controller gain Kc, the parameter that is tuned first. This parameter provides the muscle of the PID algorithm. A sudden change in set point causes a sudden change in error, which in turn causes a sudden change in controller output. The above figure shows the classical step response of a system with a PID controller. The x-axis represents time and the y-axis represents set point and process variable. The step response is the performance of the system when the set point is suddenly changed from zero to some finite value. Thus, the top line represents the set point value, and the lower curve represents the process variable response from rest. As we can see from this figure, the gain constant is used to adjust the performance of the controller. We can see how fast the PID controller acts to drive the process variable to the set point value. With only the proportional part of the PID controller active, we have an error from the set point value at steady state. Some amount of error is necessary for the controller to have a non-zero output since controller output = Kc * error. Steady state is the point at which the process variable no longer changes or oscillates uniformly.

National Instruments Corporation

D-7

LabVIEW Real-Time Course Manual

Appendix D Real-Time Systems

PID GainsPI
SP PV

Proportional gain Kc Integral gain Kc/Ti

Proportional and Integral gain applied to the error signal

Fine tuning Integrates the error over time to overcome the steady-state error such that PV = SP. However, integral action may cause overshoot, oscillation, and/or instability problems.

The next parameter tuned is the integrator. This integrates the steady-state error between the set point and process variable to allow for a steady-state value at the set point. The slide above shows how adding both proportional and integral control to your system permits you to adjust for initial response time and drive the process variable to the set point. However, too much integral action can lead to excessive oscillation as shown. Integral control also helps with disturbance rejection. This is the ability of the system to reject the effect of external disturbances.

LabVIEW Real-Time Course Manual

D-8

ni.com

Appendix D Real-Time Systems

PID GainsPID
SP PV

Proportional gain Kc Integral gain Kc/Ti Derivative gain Kc*Td

Proportional, Integral and Derivative gain applied to the error signal

Damping Used to pull back on PI control to prevent overshoot and oscillation and to add stability

The last portion of the controller to be tuned is the derivative gain. This portion of the controller is thought of as damping, which controls initial overshoot and oscillations of the system process variable. As shown in the slide above, when all three parts of the PID controller are active, we can control response time, minimize steady-state error, and control oscillation and overshoot. The three gains must be adjusted at the same time to find the optimum PID controller. These adjustments are generally referred to as controller tuning. Because each plant (process) that is controlled is different, the gain values that produce the best control are different for each system. Thus, you must tune gains for each system in which a PID controller is used. Although there are analytical methods for tuning PID gains, the most common technique used is trial-and-error. Since this is often very time consuming, autotuning techniques that automate the tuning process are very desirable. The PID Control Toolset includes an autotuning algorithm to automatically improve the performance of the PID controller. The algorithm requires that the PID controller is operating on the system with a stable set of P, PI, or PID gains defined. Then, the algorithm automatically tests the control system to determine new control parameters that improve the performance of the controller with respect to parameters, such as rise time and overshoot.

National Instruments Corporation

D-9

LabVIEW Real-Time Course Manual

Appendix D Real-Time Systems

Effect of PID Parameters

Increase proportional gain, Kc Faster system May make system unstable Decrease integral time, Ti Disturbance rejection Reduced steady state errors Increases overshoot Increase derivative time, Td Decreased overshoot Higher gain with stability Sensitive to noise

LabVIEW Real-Time Course Manual

D-10

ni.com

Appendix D Real-Time Systems

Autotuning PID Procedure


After you have made an educated guess on the PID parameters and achieved stable control, autotuning can further refine the parameters. Procedure: 1. Create your control application and determine PID parameters that produce stable control of the system. 2. Run the autotuning procedure from the host computer and record the calculated PID parameters.

PID Autotuning
You must obtain a minimum level of stable (non-oscillatory) control before you can begin the autotuning process. You must run the PID Autotuning VI on the host computer, and you cannot run it embedded. After the PID gains have been obtained, you can replace the PID Autotuning.VI with PID.VI or PID Advanced.VI, which are suitable for embedded execution. Refer to the PID Control Toolkit User Manual for more information about autotuning.

National Instruments Corporation

D-11

LabVIEW Real-Time Course Manual

Appendix D Real-Time Systems

Fuzzy Logic Control


Set Point Values Fuzzy Controller Multiple Inputs, IF THEN Rules Actuator Output

Measured Values

Used for the following: Non-linear or complex systems Systems with multiple inputs and/or outputs

Fuzzy Logic Control


Many systems are nonlinear and therefore difficult or impossible to model mathematically, which is required for the design of most traditional control algorithms. In addition, many processes that might or might not be modeled mathematically are too complex or nonlinear to be controlled with traditional strategies. However, if an expert can describe a control strategy qualitatively, fuzzy logic can be used to define a controller that emulates the heuristic rule-ofthumb strategies of the expert. Therefore, fuzzy logic can be used to control a process that a human can control manually with expertise gained from experience. For example: IF the temperature is hot, THEN turn the fan on to full power. Also, fuzzy logic often is used in systems that have multiple inputs. For example, if you wanted to control both the temperature and the pressure in the temperature chamber, you might choose to use fuzzy logic.

LabVIEW Real-Time Course Manual

D-12

ni.com

Appendix D Real-Time Systems

Control Techniques Comparison


Autotuning? PID PID Advanced with Gain Scheduling PID with Disturbance Decoupling Fuzzy Logic Disturbance Rejection? Good Better Best Best Nonlinear Systems?

Control Techniques Comparison


The above chart can help you to choose the appropriate control technique for your system. During the course project, you use PID control. PIDThe Proportional-Integral-Derivative (PID) algorithm is the most common control algorithm used in industry. AutotuningPID control supports autotuning, or automatically testing the process under control to determine the controller parameters that provide the best performance. In LabVIEW, the PID Autotuning VI includes an autotuning wizard that guides you through the process. The PID Autotuning VI is not supported in the Real-Time Module. PID AdvancedThe PID Advanced VI offers features that can benefit systems that require increased disturbance response or increased error response. The beta input allows you to make the PID algorithm more sensitive to disturbances and less sensitive to the set point command. This results in a stronger response to disturbances, but has the side-effect that it may make the system less sensitive to the set point command. Similarly, the linearity input allows you to increase the response of the PID algorithm in a parabolic manner when the error signal becomes large. The PID Advanced VI also offers manual control, which allows you to manipulate the actuator output manually, which is useful for testing purposes. Gain SchedulingIn the case of PID control, gain scheduling is a way to improve the robustness of the control system. In a fluid chamber example, a PID compensator using gain scheduling could adjust its parameters based on the fluid level to meet the design requirements regardless of the fluid level. More specifically, it would slow its response

National Instruments Corporation

D-13

LabVIEW Real-Time Course Manual

Appendix D Real-Time Systems

when the fluid level is low by using a smaller Proportional Gain and speed its response when fluid level is high by using a larger Proportional Gain. PID with Disturbance DecouplingDisturbance decoupling is a variation on basic PID control that helps for systems that have a slow response to disturbances. If the disturbance can be measured, then the compensator output can be adjusted immediately to respond. For instance, if a fan introduces cold air into a temperature chamber, the heater output can be increased immediately rather than first waiting for the temperature to drop. This approach is not always necessary since increasing the proportional gain on a traditional PID compensator also improves disturbance rejection, and does not require that the disturbance be measured. Fuzzy LogicFuzzy logic is a method of rule-based decision making that emulates the rule-of-thumb thought process that human beings use. Most traditional control algorithms require a mathematical model, but many physical systems are difficult or impossible to model mathematically. In addition, many processes are either nonlinear or too complex for you to control with traditional strategies. However, if an expert can qualitatively describe a control strategy, you can use fuzzy logic to define a controller that emulates the rule-of-thumb strategies of the expert. Therefore, you can use fuzzy logic to control a process that a person manually controls with knowledge she gains from experience. For instance, if the temperature is extremely hot, then turn on the cooling fan to its high setting. Fuzzy logic is frequently used in conjunction with other control techniques.

LabVIEW Real-Time Course Manual

D-14

ni.com

Appendix D Real-Time Systems

Project Closed Loop Control System


LabVIEW Front Panel Input PID Control Toolset Error
20 C

cFP-PWM-520 or PXI-DAQ 6040E Heater Voltage

Disturbance: Cold Air

Desired Temp
120 C

Compensator

Output
62%

Temp Chamber

100 C

Measured Temp
cFP-TC-120 or PXI-DAQ 6040E

Thermocouple Sensor

NI LabVIEW Real-Time Hardware

The slide above illustrates the control system used in the course project. Because the temperature chamber is a first-order system with one process variable, PID control is a good choice. The boxed area in the slide represents the parts of the control system that are accomplished within NI LabVIEW Real-Time hardware. In the Compact FieldPoint implementation, the Desired Temp is read from the LabVIEW front panel. The thermocouple sensor connects directly to a thermocouple input module such as the FP-TC-120, which is configured to return temperature readings in degrees Celsius. The LabVIEW PID Control Toolset is used to implement the PID Compensator, and a FP-PWM-520 module is used to control the heater output. The FP-PWM-520 module can control up to 1 A of current at 30 VDC and acts by switching on and off DC power supply voltage with a programmable duty cycle and frequency. This type of output is called pulse width modulation (PWM). For example, at 100% duty cycle, the heater is always on, while at 50% duty cycle it is on only half the time. The I/O read, PID calculation, and I/O write operations are placed within a LabVIEW While Loop and repeated continuously at a fixed rate.

National Instruments Corporation

D-15

LabVIEW Real-Time Course Manual

Appendix D Real-Time Systems

Control Parameters for Course Project


Temperature chamber for course project has already been modeled as a first-order system. PID values are determined as follows: P: 15 I: 0.5 D: 0.01

No exercises exist in this course to practice system modeling, as this is more detail than this course can cover. Instead, the control parameters for the course project have been provided to you.

LabVIEW Real-Time Course Manual

D-16

ni.com

Appendix D Real-Time Systems

Summary
Increase proportional gain, Kc
Faster system May make system unstable

Decrease integral time, Ti


Disturbance rejection Reduced steady state errors Increases overshoot

Increase derivative time, Td


Decreased overshoot Higher gain with stability Sensitive to noise

National Instruments Corporation

D-17

LabVIEW Real-Time Course Manual

Additional Information and Resources

This appendix contains additional information about National Instruments technical support options and LabVIEW Real-Time resources.

National Instruments Technical Support Options


Visit the following sections of the National Instruments Web site at ni.com for technical support and professional services. SupportOnline technical support resources at ni.com/support include the following: Self-Help ResourcesFor immediate answers and solutions, visit the award-winning National Instruments Web site for software drivers and updates, a searchable KnowledgeBase, product manuals, step-by-step troubleshooting wizards, thousands of example programs, tutorials, application notes, instrument drivers, and so on. Free Technical SupportAll registered users receive free Basic Service, which includes access to hundreds of Application Engineers worldwide in the NI Developer Exchange at ni.com/exchange. National Instruments Application Engineers make sure every question receives an answer.

System IntegrationIf you have time constraints, limited in-house technical resources, or other project challenges, National Instruments Alliance Program members can help. The NI Alliance Program joins system integrators, consultants, and hardware vendors to provide comprehensive service and expertise to customers. The program ensures qualified, specialized assistance for application and system development. To learn more, call your local NI office or visit ni.com/alliance.

If you searched ni.com and could not find the answers you need, contact your local office or NI corporate headquarters. Phone numbers for our worldwide offices are listed at the front of this manual. You also can visit the Worldwide Offices section of ni.com/niglobal to access the branch office Web sites, which provide up-to-date contact information, support phone numbers, email addresses, and current events.

National Instruments Corporation

E-1

LabVIEW Real-Time Course Manual

Appendix E

Additional Information and Resources

Other National Instruments Training Courses


National Instruments offers several training courses for LabVIEW users. These courses continue the training you received here and expand it to other areas. Visit ni.com/training to purchase course materials or sign up for instructor-led, hands-on courses at locations around the world.

National Instruments Certification


Earning an NI certification acknowledges your expertise in working with NI products and technologies. The measurement and automation industry, your employer, clients, and peers recognize your NI certification credential as a symbol of the skills and knowledge you have gained through experience. areas. Visit ni.com/training for more information about the NI certification program.

LabVIEW Resources
This section describes how you can receive more information regarding LabVIEW.

LabVIEW Publications
The following publications offer more information about LabVIEW.

LabVIEW Technical Resource (LTR) Newsletter


Subscribe to LabVIEW Technical Resource to discover tips and techniques for developing LabVIEW applications. This quarterly publication offers detailed technical information for novice users and advanced users. In addition, every issue contains a disk of LabVIEW VIs and utilities that implement methods covered in that issue. To order the LabVIEW Technical Resource, contact LTR publishing at (214) 706-0587 or visit www.ltrpub.com.

LabVIEW Books
Many books have been written about LabVIEW programming and applications. The National Instruments Web site contains a list of all the LabVIEW books and links to places to purchase these books.

info-labview Listserve
info-labview is an email group of users from around the world who discuss LabVIEW issues. The list members can answer questions about building LabVIEW systems for particular applications, where to get instrument drivers or help with a device, and problems that appear.

LabVIEW Real-Time Course Manual

E-2

ni.com

Appendix E

Additional Information and Resources

To subscribe to info-labview, send email to:


info-labview-on@labview.nhmfl.gov

To subscribe to the digest version of info-labview, send email to:


info-labview-digest@labview.nhmfl.gov

To unsubscribe to info-labview, send email to:


info-labview-off@labview.nhmfl.gov

To post a message to subscribers, send email to:


info-labview@labview.nhmfl.gov

To send other administrative messages to the info-labview list manager, send email to:
info-labview-owner@nhmfl.gov

You might also want to search previous email messages at:


www.searchVIEW.net

The info-labview web page is available at:


www.info-labview.org

National Instruments Corporation

E-3

LabVIEW Real-Time Course Manual

Course Evaluation
Course _______________________________________________________________________________________ Location _____________________________________________________________________________________ Instructor _________________________________________ Date ____________________________________

Student Information (optional)


Name ________________________________________________________________________________________ Company _________________________________________ Phone ___________________________________

Instructor
Please evaluate the instructor by checking the appropriate circle. Instructors ability to communicate course concepts Instructors knowledge of the subject matter Instructors presentation skills Instructors sensitivity to class needs Instructors preparation for the class
Unsatisfactory Poor Satisfactory Good Excellent

Course
Training facility quality Training equipment quality Was the hardware set up correctly? The course length was Yes No Too much Just right Not enough Yes No Sometimes Yes No Too long Just right Too short

The detail of topics covered in the course was The course material was clear and easy to follow. Did the course cover material as advertised?

I had the skills or knowledge I needed to attend this course. Yes No If no, how could you have been better prepared for the course? ____________________________________________________________________ _____________________________________________________________________________________________ What were the strong points of the course? __________________________________________________________ _____________________________________________________________________________________________ What topics would you add to the course? ___________________________________________________________ _____________________________________________________________________________________________ What part(s) of the course need to be condensed or removed? ____________________________________________ _____________________________________________________________________________________________ What needs to be added to the course to make it better? ________________________________________________ _____________________________________________________________________________________________ How did you benefit from taking this course? ________________________________________________________ _____________________________________________________________________________________________ Are there others at your company who have training needs? Please list. ____________________________________ _____________________________________________________________________________________________ _____________________________________________________________________________________________ Do you have other training needs that we could assist you with? _________________________________________ _____________________________________________________________________________________________ How did you hear about this course? NI Web site NI Sales Representative Mailing Co-worker Other _____________________________________________________________________________________

You might also like