LabVIEW - Real-Time Application Development Course Manual.pdf
Short Description
Download LabVIEW - Real-Time Application Development Course Manual.pdf...
Description
TM
LabVIEW Real-Time Application Development Course Manual
Course Software Version 8.0 March 2006 Edition Part Number 323843B-01 LabVIEW Real-Time Course Manual Copyright © 2004–2006 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: Help»Patents 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
© National Instruments Corporation
Using RT Wizards ............................................................................5-23 Target Program.................................................................................5-27 Completed Project Host VI ..............................................................5-47 Project Host VI (Optional) ...............................................................5-49
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 Instructor’s 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
v
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
Begin Here
New User
Experienced User
Advanced User
LabVIEW Basics I* LabVIEW Basics II*
LabVIEW Intermediate I* LabVIEW Intermediate II*
LabVIEW Advanced Application Development
Skills learned: • LabVIEW environment navigation • Basic application creation using LabVIEW
Skills learned: • Modular application development • Structured design and development practices • Memory management and VI performance improvement
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:
© National Instruments Corporation
–
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
Student Guide
❑ LabVIEW Real-Time Application Development Course Manual ❑ LabVIEW Real-Time Application Development CD, which contains the following files: Filename
Description
Exercises
a folder containing all files needs to complete the exercises
Solutions
a folder containing the solutions to each exercise
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 Help»Find 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 File»Page Setup»Options 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
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.
monospace
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.
monospace bold
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.
monospace italic
Italic text in this font denotes text that is a placeholder for a word or value that you must supply.
LabVIEW Real-Time Course Manual
x
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 Help»Search 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 • Determinism—A characteristic of a system that describes how reliably it can respond to events or perform operations within a given time limit • Loop Cycle Time—The time taken to execute one cycle of a loop • Jitter—The variation of loop cycle time from the desired loop cycle time • Embedded—Characterizes a computer system that is typically a component within a larger system. Embedded systems usually operate in a headless fashion—that 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
Jitter Range
Loop Iteration
Desired Loop Time
Maximum Jitter
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 background—screen savers, disk utilities, virus software, and so on – It must service interrupts—keyboard, mouse, Ethernet, and so on
• Cannot guarantee determinism—that 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 characteristics—and 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 Software
Linker
LabVIEW Real-Time
Debugger System Analysis Tools
Execution Trace Tool
Hardware
RTOS Microprocessor
LabVIEW Real-Time Target
I/O Device
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
Develop
RT Target
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 systems—the 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
OBJECTIVE
Time to complete: 10 min.
Read and discuss the Project Specification document and determine if real time is necessary for this application.
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.
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 Small footprint, harsh environments
LabVIEW Real-Time
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
RT Compact FieldPoint
Host-Target
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 Target—Host-Target Configuration • Standard desktop computer—Ideal for low cost implementation • NI Real-Time Series PXI Controller—Ideal 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 • CompactRIO—Embedded 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 computer—A standard desktop PC used as a real-time system running LabVIEW Real-Time for ETS Targets. • NI Real-Time Series PXI Controllers—A 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 Modules—A networked device designed for distributed real-time I/O applications. • NI 1450 Series Compact Vision System—A 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 Target—PXI Embedded Controller PXI Backplane
Processor
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 headless—no 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 Target—Single-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 Target—Real-Time Subsystem (RTX only) RT Target and RT Host reside on the same microprocessor RT Target RT Task
RT Host
RT Task
RT Task
Windows Task
RTX Real-Time Kernel
Windows Task
Windows Kernel
Hardware Abstraction Layer (HAL) Microprocessor
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
[c]FP
Loop Speed
Best
Good
Better
Best
Best
I/O Count
High
High
Low
Low
Low
Rugged
Better
Best
—
—
—
Scalability
Best
Better
Good
Better
Better
3rd-party RT HW
Yes
No
No
Yes
Yes
Better
Best
—
Good
—
Distributed
PCI-7041 PC (ETS)
PC (RTX)
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
Summary—Matching 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-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. Determinism—A characteristic of a system that describes how reliably it can respond to events or perform operations within a given time limit. Loop Cycle Time—The time taken to execute one cycle of a loop. Jitter—The variation of loop cycle time from the desired loop cycle time. Embedded—Characterizes a computer system that is typically a component within a larger system. Host—A computer with LabVIEW and the LabVIEW Real-Time Module installed in which you develop the VIs for the real-time system. Target—Real-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 Configuration—Networked 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 Configuration—Network 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 Configuration—Install 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 View»Refresh 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
OBJECTIVE
Time to complete: 40 min.
Configure the Compact FieldPoint or the PXI target systems and the I/O hardware using Measurement and Automation Explorer (MAX).
Instructor Note: If the equipment is not set up before class, this exercise may take longer than the estimated time.
© 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 File»New 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 File»New 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 New»Targets 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 New»Targets 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 Host—front-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 File»Exit – 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 File»Exit 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
OBJECTIVE
Time to complete: 20 min.
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
Summary—Quiz Explain the meaning of the following terms: • Project • Target • Front Panel Communication
Summary Project—A 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. Target—A 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 Communication—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.
© 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 Start»All Programs»National Instruments»Measurement 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 View»Refresh .
© 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 key on the keyboard and select Channel 1 in the Channels list. Tip
-click or -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 System»Data Neighborhood»FieldPoint 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 System»Data Neighborhhod»FieldPoint 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 System»Data Neighborhhod»FieldPoint 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
You can retest the Temp channel to see how the temperature changes with the new Heater and Fan output values.
Note
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 Start»All Programs»National Instruments»Measurement 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 View»Refresh . 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 View»Refresh . 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 Device»NI-DAQmx SCC Connector Block»SC-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 Input»Temperature»Thermocouple. 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 Start»All Programs»National Instruments»LabVIEW 8.0. 2. Create a blank project by selecting File»New Project. 3. Right-click the Project: Untitled Project entry in the Project Explorer and select New»Targets 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», where 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 File»Save 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 -Blinking Light.vi located in the C:\Exercises\LabVIEW Real Time directory where 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
Data Storage
Target Program Network Communication
Normal Priority Loop
Inter-Thread Communication
Time-Critical Loop
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 processes—all 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 – Multitasking—Ability 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 threads—a user interface thread, a data acquisition thread, and an instrument control thread—each 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 non-critical tasks • Communication • Data logging
Some time-critical tasks • Control loop • Safety monitoring
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)
Tasks
Normal Priority
Ambulance
Receptionist
One Mechanic
(Operating System)
(Processor)
Real-Time Multithreading Metaphor • MECHANIC = PROCESSOR—In this example, only one mechanic (Processor) performs the repairs (processing). • RECEPTIONIST = OPERATING SYSTEM—The 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 ONLY—In 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 PRIORITIES—The 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.) • PREEMPTION—If 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 = STARVATION—If 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
Receptionist (Scheduler)
Ambulance
Normal Mechanic (CPU)
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
Receptionist (Scheduler)
Ambulance
Normal Mechanic (CPU)
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 File»VI Properties»Execution. 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
No sleep in time-critical thread
Time Critical Executing
Normal
Waiting
Normal
Sleep added to time-critical thread
Time
Sleeping Executing Waiting
Time Critical Normal Normal
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
No sleep causes starvation
A. Time Critical Executing
B. Above Normal
Waiting
C. Normal
Sleep added—may still starve some threads
Time
Sleeping Executing Waiting
A. Time Critical B. Above Normal C. Normal
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 resource—in 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 VIs—use 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
OBJECTIVE
Time to complete: 10 min.
To adjust the priority levels to understand the effects of priority levels on scheduling a VI
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.
© National Instruments Corporation
3-17
LabVIEW Real-Time Course Manual
Lesson 3 Real-Time Architecture: Design
Class Exercise—Choose Priority Level User Interface Data Logging
TCP
Serial
UDP
Signal Analysis
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
Data Logging
UDP
Buffered DAQ
Buffered DAQ
CAN
Normal Priority VI Separate
TCP
Time-Critical Priority VI
Data Logging
Serial
TCP
UDP
Signal Analysis
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: ― Shared Variables
― Global Variables
― Real-Time Module Memory Manager ― Non-reentrant subVIs ― Single-threaded DLLs
― Semaphores*
― Networking code (TCP/IP, UDP, VI Server) *
― 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
Shared
Process 2
Resource Running
Waiting
After Process 1 finishes, Process 2 can proceed
Process 1
Shared
Process 2
Resource Waiting
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 Resources—Priorities 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 VI inherits higher priority to release mutex
Normal Priority running
In the example above, the shared resource is a global variable, which is shared by two VIs—one 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 Resources—SubVIs
Configure a subVI for reentrant execution if unrelated parallel processes call the same subVI—allows 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 Properties»Execution, 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 Resources—Memory 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 Resources—Memory 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 type—representation, 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 File»VI 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 Variables—Good Target Program Normal Priority Loop
Global Variables
TimeCritical Loop
• Can cause jitter, because they are a shared resource • Lossy—A global variable may be written to many times before being read. • Good for scalar data (
View more...
Comments