engg4420 ‐‐ chapter 3 lecture 1

92
CHAPTER 3 ‐‐ LabVIEW REALTIME APPLICATION DEVELOPMENT REFERENCES: [1] NI, RealTime LabVIEW. [2] R. Bishop, LabVIEW 2009. LabVIEW LabVIEW is a major player in the area of testing and measurements, industrial automation, and data analysis Engineers and scientists in research, development, production, test, and service industries as diverse as automotive, semiconductor, aerospace, electronics, chemical, telecommunications, and pharmaceutical have used and continue to use LabVIEW to support their work. LabVIEW programs are called Virtual Instruments, or VIs for short. LabVIEW uses a graphical programming language, known as the G programming language. LabVIEW uses a terminology familiar to scientists and engineers. ENGG4420 ‐‐ CHAPTER 3 ‐‐ LECTURE 1 October3110 5:12 PM CHAPTER 3 By Radu Muresan University of Guelph Page 1

Upload: others

Post on 11-May-2022

3 views

Category:

Documents


0 download

TRANSCRIPT

Page 1: ENGG4420 ‐‐ CHAPTER 3 LECTURE 1

CHAPTER 3 ‐‐ LabVIEW REAL‐TIME APPLICATION DEVELOPMENTREFERENCES: [1] NI, Real‐Time LabVIEW.[2] R. Bishop, LabVIEW 2009.

LabVIEWLabVIEW is a major player in the area of testing and measurements, industrial automation, and data analysis

Engineers and scientists in research, development, production, test, and service industries as diverse as automotive, semiconductor, aerospace, electronics, chemical, telecommunications, and pharmaceutical have used and continue to use LabVIEW to support their work. 

LabVIEW programs are called Virtual Instruments, or VIs for short.

LabVIEW uses a graphical programming language, known as the G programming language.

LabVIEW uses a terminology familiar to scientists and engineers.

ENGG4420 ‐‐ CHAPTER 3 ‐‐ LECTURE 1October‐31‐105:12 PM

CHAPTER 3 By Radu Muresan University of Guelph Page 1

Page 2: ENGG4420 ‐‐ CHAPTER 3 LECTURE 1

WHAT ARE VIRTUAL INSTRUMENTS?A VI and its components are analogous to main programs and subroutines from text programming languages such as C and Fortran.

An interactive user interface know as the front panel○Source code – represented in graphical form on the block diagram. The block diagram consists of executable icons (called nodes) connected (or wired) together

VIs have:•

The art of successful programming in G is an exercise in modular programming – divide a task into a series of simpler subtasks (subVIs)

The subVIs are similar to subroutines. The subVIs are then assembled on a top‐level block diagram to form the complete program. Modularity means that you can execute each subVI independently, thus making debugging and verification easier. Furthermore, if your subVIs are general purpose programs, you can use them in other programs.

The front panel is the interactive user interface of a VI. The front panel contains knobs, push buttons, graphs, and many other controls (the term control is interchangeable with inputs) and indicators ( or outputs).

The block diagram is the source code for the VI. The icons of a block diagram represent lower‐level VIs, built‐in functions, and program control structures. These icons are wired together to allow the data flow.

The icons and connectors specify the pathways for data to flow into and out of VIs. All VIs have an icon and a connector.

VIs (and subVIs) have three main parts: 1) the front panel, 2) the block diagram, and 3) the icon/connector. 

CHAPTER 3 By Radu Muresan University of Guelph Page 2

Page 3: ENGG4420 ‐‐ CHAPTER 3 LECTURE 1

DATA FLOW PROGRAMMINGThe principle that governs VI execution is know as data flow ‐‐ Data flow programming is characteristic to execution of G programs and is not to be confused with a linear execution of lines of code.

The executable elements of a VI execute only when they have received all required input data.

In a situation where one code segment must execute before another, and there is no type dependency between functions, you must use a Sequence structure to force the order of execution.

LEARN LabVIEW PROGRAMMIN BY:Use Getting Started with LabVIEW document•Use the book: LabView 2009 by Robert H. Bishop.•

CHAPTER 3 By Radu Muresan University of Guelph Page 3

Page 4: ENGG4420 ‐‐ CHAPTER 3 LECTURE 1

NEED OF A WELL TESTED AND DEBUGGED RTOS

Simplify the coding process for complex applications;

Help in building a product fast;○Aid in building robust and bug free software by testing and simulation before locating the codes into hardware.

Readily available RTOS:•

Common options available for selecting an RTOS: 1) Own RTOS for small scale embedded system; 2)Linux based RTOS functions: Red Hat, eCOS or RT Linux; 3) uC/OS‐II: freeware for noncommercial use; 4) VxWorks; 5) PSoS; 6) Nucleus; 7) QNX, Window CE, Palm OS, Pocket PC; 8) VRTX; 9) OS‐9.

BASIC FUNCTIONS EXPECTED FROM KERNEL OF AN RTOSKernel (Scheduler).•Error handling functions.•Service and system clock functions.•Device driver, network stack send and receiver functions.•Time and delay functions.•Initiate and start functions.•Task state switching functions.•ISR functions.•Memory functions ‐‐ Create; query; get; put•IPC(Inter‐Process Communication) functions ‐‐ Signal exception handling functions; semaphore; queue; mailbox; pipes; sockets.

CHAPTER 3 By Radu Muresan University of Guelph Page 4

Page 5: ENGG4420 ‐‐ CHAPTER 3 LECTURE 1

LabVIEW RUNNING IN WINDOWS OPERATING SYSTEMSLabVIEW applications running in Windows are not guaranteed to run in real‐time, because Windows is not a real‐time OS. Windows cannot ensure that code always finishes within specific time limits. 

Many programs run in the background – screen savers, disk utilities, virus software, and so on

It must service interrupts – keyboard, mouse, Ethernet, etc.○

Processor time is shared between programs and the operating system can preempt high priority Vis. The time your code takes to execute in Windows depends on many factors, such as:

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. 

How can you increase determinism in LabVIEW Windows??•

Nevertheless, increasing determinism does not ensure that code always executes with real‐time behaviour. This is because Windows can preempt your LabVIEW programs, even if you use time‐critical priority. 

With the LabVIEW Real‐Time Module, your program runs in a separate real‐time OS. You do not need to disable programs or write device drivers in order to achieve real‐time performance. A real‐time OS enables users to prioritize tasks so that the most critical task can always take control of the processor when needed.

CHAPTER 3 By Radu Muresan University of Guelph Page 5

Page 6: ENGG4420 ‐‐ CHAPTER 3 LECTURE 1

REAL‐TIME OPERATING SYSTEMSEnsure that high‐priority tasks execute first•Do not require user input from peripherals (keyboard, etc.)

National Instruments designed the LabVIEW Real‐Time Module to execute VIs on two different real‐time OS. 

Venturcom Phar Lap Embedded Tool Suit (ETS) ‐‐provides a real‐time OS 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. 

1)

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.

The LabVIEW Real‐Time Module can execute VIs on hardware targets running the real‐time OS for Venturcom Real‐Time Extension (RTX).

2)

For more information about Phar Lap ETS or RTX, refer to the Venturcom Web site at www.vci.com.

In this Section of the course we will focus on the ETS real‐time platform. 

CHAPTER 3 By Radu Muresan University of Guelph Page 6

Page 7: ENGG4420 ‐‐ CHAPTER 3 LECTURE 1

CHAPTER 3 By Radu Muresan University of Guelph Page 7

Page 8: ENGG4420 ‐‐ CHAPTER 3 LECTURE 1

SELECTING AN OPERATING SYSTEM

If you only must acquire real‐time data, then you might not need a real‐time OS. NI 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.

General Purpose OS ‐‐ used for data acquisition; offline analysis; data presentation.

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 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 OS to guarantee response within a fixed amount of time.

Real‐Time OS used for: closed loop control; time‐critical decisions; extended run time; stand alone operation; increased reliability.

In addition, applications requiring extended run times or stand alone operations are often implemented with real‐time OS.

CHAPTER 3 By Radu Muresan University of Guelph Page 8

Page 9: ENGG4420 ‐‐ CHAPTER 3 LECTURE 1

REAL‐TIME DEVELOPMENT TOOLS

LabVIEWReal-Time

Module

Execution Trace Tool

LabViewReal-Time

Target

RTOS

Microprocessor

I/O Device

CompilerLinker

Debugger

System AnalysisTools

Sof

twar

eH

ardw

are

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.

CHAPTER 3 By Radu Muresan University of Guelph Page 9

Page 10: ENGG4420 ‐‐ CHAPTER 3 LECTURE 1

LabVIEW REAL‐TIME SYSTEM USING ETS

The first system is Window based. On this machine, called host, you develop an application. When you are ready, you can download the application to the target processor. 

The RT Engine has the job of: 1) executing code, 2)controlling any connected I/O, and 3) communicating back to the host machine.

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). 

This figure 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 –

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 such as TCP/IP or VI server.

CHAPTER 3 By Radu Muresan University of Guelph Page 10

Page 11: ENGG4420 ‐‐ CHAPTER 3 LECTURE 1

REAL‐TIME HOST

A real‐time system consists of software and hardware components. 

LabVIEW, the RT Engine, and VIs you build using LabVIEW. 

○The software components include: •

a host computer and an RT target.○The hardware components of a real‐time system include:•

STEPS OF DESIGN:Develop the VIs for the real‐time system on the host ‐‐ the host computer is a computer with LabVIEW and the LabVIEW Real‐Time Module installed. 

1.

Download and run the real‐time VIs on the RT target. 2.The host computer can run VIs that communicate with the VIs running on the RT target.

3.

CHAPTER 3 By Radu Muresan University of Guelph Page 11

Page 12: ENGG4420 ‐‐ CHAPTER 3 LECTURE 1

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.

Real‐Time Series Plug‐in Devices, ○Desktop PCs, ○Real‐Time PXI embedded controllers, ○Real‐Time Compact FieldPoint controllers, and○Compact Vision Controllers.○

You can deploy the LabVIEW Real‐Time Module with a variety of real‐time targets –

CHAPTER 3 By Radu Muresan University of Guelph Page 12

Page 13: ENGG4420 ‐‐ CHAPTER 3 LECTURE 1

REAL‐TIME HARDWARE CONFIGURATIONS

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.

a.

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 host‐target configurations. 

b.

There are two basic configurations for RT targets. •

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.

Desktop PCs can run real‐time applications in either configuration, depending on implementation. 

CHAPTER 3 By Radu Muresan University of Guelph Page 13

Page 14: ENGG4420 ‐‐ CHAPTER 3 LECTURE 1

HOST‐TARGET CONFIGURATION (ETS ONLY)

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 IEEE 1394 cameras

CompactRIO – Embedded system with real‐time controller, reconfigurable FPGA chassis, and industrial I/O modules.

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: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. 

CHAPTER 3 By Radu Muresan University of Guelph Page 14

Page 15: ENGG4420 ‐‐ CHAPTER 3 LECTURE 1

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, etc. 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 system 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.

CHAPTER 3 By Radu Muresan University of Guelph Page 15

Page 16: ENGG4420 ‐‐ CHAPTER 3 LECTURE 1

COMPACT FIELDPOINT [c]FP NETWORK MODULE

Compact FieldPoint (cFP). The cFP‐20xx has many features that enables 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 operatoin 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 of the cFP‐2000, and 64 MB for the cFP‐2010 and cFP‐2020. The cFP‐20202 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.

The serial port allows the cFT‐20xx to connect to existing systems or other serial devices. The Compact FieldPoint I/O modules can be used for industrial environments.

CHAPTER 3 By Radu Muresan University of Guelph Page 16

Page 17: ENGG4420 ‐‐ CHAPTER 3 LECTURE 1

RT‐TARGET ‐ SINGLE BOX CONFIGURATION

A NI PCI‐7041 plug‐in device is a plug‐in device with and embedded processor device and DAQ daughterboard. The processor device contains a microprocessor with a real‐time operating system that runs the RT Engine in 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.

CHAPTER 3 By Radu Muresan University of Guelph Page 17

Page 18: ENGG4420 ‐‐ CHAPTER 3 LECTURE 1

CHAPTER 3 By Radu Muresan University of Guelph Page 18

Page 19: ENGG4420 ‐‐ CHAPTER 3 LECTURE 1

RT TARGET ‐‐ 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 real‐time 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.

CHAPTER 3 By Radu Muresan University of Guelph Page 19

Page 20: ENGG4420 ‐‐ CHAPTER 3 LECTURE 1

CHOOSING THE RIGHT TARGET PLATFORM

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.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 suites industrial applications requiring a small footprint, high‐reliability, distributed, and industrially rated hardware.

The specification 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 values for FieldPoint is 559,188 hours (52 years).

CHAPTER 3 By Radu Muresan University of Guelph Page 20

Page 21: ENGG4420 ‐‐ CHAPTER 3 LECTURE 1

REAL‐TIME ARCHITECTURE DESIGNTarget and host architecture•Multithreading•Sleeping•Improving determinism•Passing data between threads•

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 module, the ability to off‐load processing, and headless black box design, you do not need to change your programming techniques. 

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 threadswithout disrupting determinism. 

However, if your application needs to be deterministic, your application must either guarantee a response to an external event within a given time or meet deadlines cyclically and predictably. 

We will discuss how to design your application to achieve determinism.

ENGG4420 ‐‐ CHAPTER 2 ‐‐ LECTURE 2November‐01‐1012:21 PM

CHAPTER 3 By Radu Muresan University of Guelph Page 21

Page 22: ENGG4420 ‐‐ CHAPTER 3 LECTURE 1

REAL‐TIME TERMINOLOGY FOR LabVIEW REAL‐TIME

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.

Determinism – A characteristic of a system that describes how reliably it can respond to events or perform operations within a given time limit.

Many applications that require a real‐time operating system are cyclical, such as a control application. The time between consecutive cycles, T, is called the loop cycle time (or sample period). 1/T is the loop rate or sample rate.

Loop Cycle Time – The time taken to execute one cycle of a loop.

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.

Jitter – The variation of loop cycle time from the desired loop cycle time.

The term embedded encompasses many application areas, but characterizes a computer system that is typically a component within a larger system. Normally, the 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 systems running on a chip.

○Embedded –•

CHAPTER 3 By Radu Muresan University of Guelph Page 22

Page 23: ENGG4420 ‐‐ CHAPTER 3 LECTURE 1

DEFINITION OF JITTER

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 system scan range within nanoseconds.

General purpose operating systems have high or unbounded maximum jitter that may vary from time to time and is inconsistent.

CHAPTER 3 By Radu Muresan University of Guelph Page 23

Page 24: ENGG4420 ‐‐ CHAPTER 3 LECTURE 1

REAL‐TIME ARCHITECTURE ‐‐ the basic architecture of a well‐designed real‐time program is shown below.

Host Program

UserInterface

DataStorage

DataStorage

Normal PriorityLoop

Time-CriticalLoop

Target Program

Network Communication Inter-Thread Communication

The host program ‐‐ the host program contains the user interface.

a.

And the target program ‐‐ the target program is divided into two parts: 1) the time‐critical loop, and 2) the normal priority loop. 

b.

The overall application program is divided into two parts: 

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.

The loops on the target program 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. 

CHAPTER 3 By Radu Muresan University of Guelph Page 24

Page 25: ENGG4420 ‐‐ CHAPTER 3 LECTURE 1

HOST PROGRAM

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 and other systems

UserInterface

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 from the target program, and any other non‐deterministic task that you may need.

CHAPTER 3 By Radu Muresan University of Guelph Page 25

Page 26: ENGG4420 ‐‐ CHAPTER 3 LECTURE 1

TARGET PROGRAM

Normal PriorityLoop

Time-CriticalLoop

Target Program

Inter-Thread Communication

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.

Higher priority processes preempt lower priority ones

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 ProcessesDeterministic 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.

Multithreading expands the idea of multitasking.•

CHAPTER 3 By Radu Muresan University of Guelph Page 26

Page 27: ENGG4420 ‐‐ CHAPTER 3 LECTURE 1

WHAT IS MULTITHREADING?

Multitasking – Ability of the operating system to quickly switch between tasks giving the appearance of simultaneous execution of those tasks. Windows 95 and later rely on preemptive multitasking, where the OS 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. 

A task is generally an entire application, such as LabVIEW○

Extension of the idea of multitasking•

Subdivide specific operations within an application into individual threads,

Divide processing time among threads,○Enable assigning priorities.○

Multithreading extends the following multitasking capabilities into applications:

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 OS can divide processing time not only among different applications but also among each thread within the application. 

For example, in 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 OS divides processing time on the different threads similar to the way it divides processing time among entire applications in an exclusively multitasking system.

CHAPTER 3 By Radu Muresan University of Guelph Page 27

Page 28: ENGG4420 ‐‐ CHAPTER 3 LECTURE 1

ADVANTAGES OF MULTITHREADING

Example of time critical tasks: control loop; safety monitoring.

Example of non‐critical tasks: communication; data logging.

Differentiates between time‐critical and non‐critical tasks:

Real time performance needs an OS 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 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 was 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 OS, the ability to assign •

CHAPTER 3 By Radu Muresan University of Guelph Page 28

Page 29: ENGG4420 ‐‐ CHAPTER 3 LECTURE 1

levelled priorities is important. 

CHAPTER 3 By Radu Muresan University of Guelph Page 29

Page 30: ENGG4420 ‐‐ CHAPTER 3 LECTURE 1

LabVIEW REAL‐TIME SCHEDULING

LabVIEW Real‐Time Module uses a combination of round‐robin (threads of equal priority receive equal time slices and it might take several turns for a thread to complete) and preemptive scheduling (higher priority thread immediately suspends execution of all lower priority threads).

Thread priority determines the execution of VIs, with higher priority threads preempting lower priority threads

Threads with equal priority use round robin scheduling

Each VI is assigned a priority.•

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.

Enters sleeping state ‐‐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.

Completes the operations.○The normal priority VI then runs until preempted by the time‐critical VI.

The time‐critical priority VI gives processor control to other tasks only when:

CHAPTER 3 By Radu Muresan University of Guelph Page 30

Page 31: ENGG4420 ‐‐ CHAPTER 3 LECTURE 1

SETTING PRIORITY LEVELS

1. Background; 2. Normal; 3. Above normal; 4. High; 5. Time‐critical priority.

The priority levels available in LabVIEW Real‐Time Scheduler include the following in order from the lowest to highest priority:

Set only one VI to 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.

SLEEPINGBecause 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.

CHAPTER 3 By Radu Muresan University of Guelph Page 31

Page 32: ENGG4420 ‐‐ CHAPTER 3 LECTURE 1

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 time‐critical section. Again, one of the two processes may run. If Process A is not put to sleep long enough for both processes 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 higher priority than Process C, it can run before. When the sleep time of Process A is finished, Process A takes the resource back from 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. 

CHAPTER 3 By Radu Muresan University of Guelph Page 32

Page 33: ENGG4420 ‐‐ CHAPTER 3 LECTURE 1

SLEEPING

Software-timed sleep

Use the OS clock to control the rate of a software loop

Hardware-timed sleep

Use hardware or processor clocks to control the rate ofa software loop

The act of suspending the execution of a VI or thread

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 ms 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.3 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.

CHAPTER 3 By Radu Muresan University of Guelph Page 33

Page 34: ENGG4420 ‐‐ CHAPTER 3 LECTURE 1

SLEEPING AND TIME‐CRITICAL PRIORITY

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 loops instead

The following features are unique to the LabVIEW Real‐Time Module:

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 time‐critical 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 Real‐Time, 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.

CHAPTER 3 By Radu Muresan University of Guelph Page 34

Page 35: ENGG4420 ‐‐ CHAPTER 3 LECTURE 1

EXAMPLE ‐‐ CHOOSE PRIORITY LEVEL

DataLogging

UserInterface

Serial

TCPSignal

Analysis

CAN

UDP

BufferedDAQ

When you understand priority levels, you must be able to separate your code into the time‐critical components and the normal priority components. The boxes shown above are different components of a typical program.

ASSIGNMENT: 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.

Target Time Critical: …

Target Normal Priority: …

Host: …

CHAPTER 3 By Radu Muresan University of Guelph Page 35

Page 36: ENGG4420 ‐‐ CHAPTER 3 LECTURE 1

IMPROVING THE DETERMINISM OF THE APPLICATIONChoose 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•

The easiest way to improve the 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.

We have seen that it is suggested to use only one time‐critical loop in one application because when a time‐critical loop goes to sleep, the entire thread goes to sleep. Next we explain programming methods for improving determinism.

ENGG4420 ‐‐ CHAPTER 3 ‐‐ LECTURE 3November‐01‐107:26 PM

CHAPTER 3 By Radu Muresan University of Guelph Page 36

Page 37: ENGG4420 ‐‐ CHAPTER 3 LECTURE 1

SHARED RESOURCESA shared resource in the LabVIEW Real‐Time Module is anything that can only be used by one process at a time

Global variables; real‐time module memory manager; networking code (TCP/IP, UDP, VI server); shared variables; non‐reentrant subVIs; semaphores; file I/O.

○LabVIEW RT shared resources include the following:•

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 variables 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 it is an important skill when programming real‐time applications.

These operations are inherently non‐deterministic. Never use them inside a time‐critical priority loop if you are attempting to achieve real‐time performance.

CHAPTER 3 By Radu Muresan University of Guelph Page 37

Page 38: ENGG4420 ‐‐ CHAPTER 3 LECTURE 1

SHARED RESOURCES

Running WaitingShared

Resource

Process 1 Process 2

Waiting RunningShared

Resource

Process 1 Process 2

Before a process can begin using a shared resource, it must obtaina mutual exclusion (mutex)

After Process 1 finishes, Process 2 proceeds

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 OS cannot allow the time‐critical thread to preempt the normal priority thread, merely because of the mutex around a shared resource.

A mutex is 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.

CHAPTER 3 By Radu Muresan University of Guelph Page 38

Page 39: ENGG4420 ‐‐ CHAPTER 3 LECTURE 1

SHARED RESOURCES ‐ PRIORITIES

Time-Critical Priority waitingPriority inversion: Normal priority VI blocks the higher priority VI with a mutex around the shared resource.

Normal Priority runningPriority ineritance: Normal priority VI inherits higher priority to release mutex.

In this example, 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.

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.

a.

After the protection is removed, the lower priority thread resumes its original lower priority setting and is taken off of the processor.

b.

Now the time‐critical priority thread is free to proceed and use the resource, that is, access the global variable.

c.

The real‐time OS uses a method called priority inheritance to resolve the priority inversion as quickly as possible, by doing the following:

A result of this priority inversion the task jitter in the time‐critical priority thread is increased. However, 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.

CHAPTER 3 By Radu Muresan University of Guelph Page 39

Page 40: ENGG4420 ‐‐ CHAPTER 3 LECTURE 1

SHARED RESOURCES ‐ SubVIs

Configure a subVI for reentrant execution if unrelated parallel processes call the 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.

CHAPTER 3 By Radu Muresan University of Guelph Page 40

Page 41: ENGG4420 ‐‐ CHAPTER 3 LECTURE 1

SHARED RESOURCES ‐MEMORY MANAGEMENT

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 manages memory automatically.

You must control memory allocations to avoid shared resource conflicts with the memory manager.

You statically allocate memory before time‐critical process begins.

The LabVIEW Real‐Time Module has a memory manager that is a shared resource.

The LabVIEW Real‐Time Module has 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. 

The memory manager may already be mutexed by, causing a shared resource conflict.

Even if the memory manager is immediately available, allocating memory is non‐deterministic because there is no upper bound on the execution time of the malloc( ).

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:

CHAPTER 3 By Radu Muresan University of Guelph Page 41

Page 42: ENGG4420 ‐‐ CHAPTER 3 LECTURE 1

PREALLOCATE ARRAYS

Avoid allocating arrays within a time-critical loop

Avoid allocating memory within a time‐critical VI control 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.

If you are using arrays in time‐critical VI control loops, you can reduce jitter by preallocating arrays before entering the loop. 

CHAPTER 3 By Radu Muresan University of Guelph Page 42

Page 43: ENGG4420 ‐‐ CHAPTER 3 LECTURE 1

SHARED RESOURCES ‐‐MEMORY MANAGEMENT

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 perf.,

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.○

Key points about memory management and real‐time•

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.

We don’t discuss all types of shared resource. Avoid semaphores, TCP/IP, UDP, VI Server, and File I/O function 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 GIPB, 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.

CHAPTER 3 By Radu Muresan University of Guelph Page 43

Page 44: ENGG4420 ‐‐ CHAPTER 3 LECTURE 1

AVOID CONTIGUOUS MEMORY CONFLICTS

RTOSRT Engine

RTOSRT Engine

RTOSRT Engine

RTOSRT Engine

ArrayMaker.vi ArrayMaker.vi ArrayMaker.vi

Array 1 Array 2

Array 3

1 2 3 4

Preallocate array space equal to the largest expected array size

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

LabVIEW handles many of the memory details that you normally handle in a conventional, text‐based language. For example, functions that generate data must allocate storage for the data. When the 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 fig. 1. The RT Engine uses available memory for running RT target VIs and storing data. In Fig. 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. If Fig. 3, ArrayMaker.vi creates Array 2. The RTOS creates Array 2 in the reserved memory space that was allocated to 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 Fig 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 Fig. 4, ArrayMaker.vi must create Array 3, larger than the previous arrays, in the available memory. 

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.

CHAPTER 3 By Radu Muresan University of Guelph Page 44

Page 45: ENGG4420 ‐‐ CHAPTER 3 LECTURE 1

AVOID SubVI OVERHEADEach subVI 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.

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 into 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 property. 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.

CHAPTER 3 By Radu Muresan University of Guelph Page 45

Page 46: ENGG4420 ‐‐ CHAPTER 3 LECTURE 1

DISABLE NON‐ESSENTIAL OPTIONSTo 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 check marks 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.

AVOID EXPRESS Vis TO REDUCE JITTERLabVIEW 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 time‐critical 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.

CHAPTER 3 By Radu Muresan University of Guelph Page 46

Page 47: ENGG4420 ‐‐ CHAPTER 3 LECTURE 1

PASSING DATA BETWEEN THREADS

Inter-Thread Communication Methods Good: Global Variables

Better: Functional Global Variables

Best: Real-Time FIFO VIs, Shared-Variable FIFOs

Normal PriorityLoop

Time-CriticalLoop

Inter-ThreadCommunication

Target Program

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

CHAPTER 3 By Radu Muresan University of Guelph Page 47

Page 48: ENGG4420 ‐‐ CHAPTER 3 LECTURE 1

GLOBAL VARIABLES ‐‐ GOOD

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 (<32 bits)

Normal PriorityLoop

Time-CriticalLoop

Global Variables

Target Program

A global variable is a location in the memory that multiple VIs can access. While global variables are easier to program, they are not the ideal method for transferring large amounts of data.

Using a global variable can be a good way to pass data smaller than 32‐bits, such as scalar data, between VIs. However, global variables are a lossy form of communication, meaning the global variable can be overwritten before the data is read. Tasks in a lower priority VI might not have enough processor time to read the data before other tasks in a different VI overwrite the data.

Using global variables in time‐critical priority VIs in LabVIEW Real‐Time can compromise determinism. A global variable is a shared resource. If one piece of code accesses a global variable, no other piece of code can access the global variable until the first piece releases the global variable. When you block the access of a time‐critical VI to a global variable, forcing the time‐critical VI to wait, you introduce jitter to the application and compromise the determinism of the application. 

CHAPTER 3 By Radu Muresan University of Guelph Page 48

Page 49: ENGG4420 ‐‐ CHAPTER 3 LECTURE 1

FUNCTIONAL GLOBAL VARIABLE (FGV) ‐ BETTER

Normal PriorityLoop

Time-CriticalLoop

FunctionalGlobal Variable

Target Program

CHARACTERISTICSCan have several inputs and outputs; can skip if busy; can be lossy.

You can avoid jitter due to resource contention by using a functional global variable, setting it to subroutine priority, and selecting the Skip Subroutine Call if Busy option for it. With a functional global variable (FGV), the time‐critical VI must not access the global if another section of code is already using the global variable. Skipping a subVI helps in time‐critical VIs, because the VI does not wait for the subVI.

If you skip the execution of a subVI, the subVI returns the default value for data type and not the default indicator value. For example, the default data type value for numerics is zero, strings and arrays default to an empty string, and Boolean values default to FALSE. If you want to detect the execution of a functional global variable, wire a TRUE constant to a Boolean output on the functional global variable block diagram. If the Boolean output returns the default value of FALSE, the functional global variable did not execute.

Skip functional global variables in time‐critical VIs but not in lower priority VIs. In lower priority VIs, you can wait to receive non‐default values.

Functional global variables can be a lossy form of communication, if a VI overwrites the shift register data before another VI reads the data.

CHAPTER 3 By Radu Muresan University of Guelph Page 49

Page 50: ENGG4420 ‐‐ CHAPTER 3 LECTURE 1

FUNCTIONAL GLOBAL VARIABLES ‐‐ EXAMPLE

Demo: NI Example FinderToolkits and Modules >> Real-Time >> Multithreaded Communication>> Functional Global Communication

In a FGV, the subVI contains a While Loop with a nested Case structure for read and write access. The above figure shows the read (get data) case and one of the write (set data) cases of the Case structure for a FGV. 

The While Loop contains uninitialized shift registers that store data. A FGV receives an action input parameter that specifies which task the VI performs as shown in this figure by the Operation input parameter. Any subsequent calls to the FGV can access the most recent data. 

FGV expand functionality beyond a simple global variable. For example, you can maintain a history of values in a FGV or you can set a switch to latched until read.

CHAPTER 3 By Radu Muresan University of Guelph Page 50

Page 51: ENGG4420 ‐‐ CHAPTER 3 LECTURE 1

REAL‐TIME FIFO Vis ‐ BEST

Normal PriorityLoop

Time-CriticalLoop

Real-Time FIFO VIs

Target Program

CHARACTERISTICSCan specify buffer size; are lossy if buffer fills up; warn of data loss; use deterministic data transfer.

Use the RT FIFO VIs to transfer data between VIs in an application. An RT FIFO acts like a fixed queue, where the first value you write to the FIFO is the first value that you can read from the FIFO. RT FIFOs and LabVIEW queues both transfer data from one VI to another. However, unlike a LabVIEW queue, an RT FIFO ensure deterministic behavior by imposing a size restriction on the data. You must define the number and size of the RT FIFO elements. Both a reader and writer can access the data in an RT FIFO at the same time, allowing RT FIFOs to work safely from within a time‐critical VI.

Because of the fixed‐size restriction, an RT FIFO can be a lossycommunication method. Writing data to an RT FIFO when the FIFO is full overwrites the oldest element. You must read data stored in an RT FIFO before the FIFO is full to ensure the transfer of every element without losing data. Check the overwrite output of the RTFIFOWrite VI to ensure that you did not overwrite data. If the RT FIFO overwrites data, the overwrite output returns a TRUE value.

A larger FIFO gives the normal priority loop more time to catch up if it falls behind, which can help avoid FIFO overwrites. However, setting a FIFO to be too large wastes memory.

CHAPTER 3 By Radu Muresan University of Guelph Page 51

Page 52: ENGG4420 ‐‐ CHAPTER 3 LECTURE 1

REAL‐TIME FIFO VIs

Create RT FIFOs for sending and fetching data. Control Data FIFO sends the type of waveform we want to generate, the amplitude of the waveform, and the time-critical loop rate. Result Data FIFO receives points of the waveform.

Demo: NI Example FinderToolkits and Modules >> Real-Time >> Communication >> RT FIFO Comm.

Use the RTFIFOCreate VI to create a new FIFO or open a reference to a FIFO that you created in another VI. 

Use the RTFIFORead and RTFIFOWrite VIs to read and write data to the FIFO. 

Refer to the LabVIEW Help, available by selecting Help >> VI, Function, & How‐To Help, for VI reference information about the Real‐Time FIFO VIs and the data types supported by the Real‐Time FIFO VIs.

CHAPTER 3 By Radu Muresan University of Guelph Page 52

Page 53: ENGG4420 ‐‐ CHAPTER 3 LECTURE 1

SHARED VARIABLESShared variables are a multipurpose communication tool you can configure to perform many tasks

Transfer non‐deterministic data between VIs. In this capacity, a shared variable functions much like a global variable. This type of shared variable is called a single‐process, shared variable. 

Transfer non‐deterministic data between a target and a host. This type of shared variable is a network‐published shared variable, usually with the Real‐Time FIFO option enabled.

Transfer non‐deterministic data between hosts or between a host and other computers. Shared variables implement a publisher/subscriber model that allows non‐real‐time computers to communicate across a network. This type of shared variable is called a network‐published shared variable.

Transfer deterministic data between Real‐Time VIs or loops (Real‐Time FIFO). Shared variables can implement a Real‐Time FIFO to transfer data between loops on an RT target. This variable is usually a single‐process shared variable with the Real‐Time FIFO option enabled.

For more information, refer to the Using Time‐Triggered Networks to Communicate Deterministically Over Ethernet with the LabVIEW 8 Real‐Time Module document in the NI Developer Zone. To view the document visit ni.com/info and enter rduttl.

Transfer deterministic data between targets. With a dedicated network connection, shared variables can deterministically transfer data between two or more real‐time targets over a network. This type of variable is called a Time‐Triggered shared variable. 

Shared variable can transfer the following:•

CHAPTER 3 By Radu Muresan University of Guelph Page 53

Page 54: ENGG4420 ‐‐ CHAPTER 3 LECTURE 1

CREATING AND USING SHARED VARIABLES (SV)Right‐click project or library to create a variable•Shared Variable Properties dialog box allows you to configure the type of the shared variable and any other options.

Used much like a local or global variable on the block diagram except: SV have error terminals; SV configured for read can return a timestamp

Items in the project tree represent shared variables. In order to create a shared variable, right click a target or library and select New >> Variable. All variables must exist inside of a library. If you create a new variable outside of a library, LabVIEW automatically creates a library. When you create a shared variable, LabVIEW displays a Shared Variable Properties dialog box that allows you to configure the type of shared variable and any other options such as buffering and Real‐Time FIFO.

To use a shared variable on the block diagram, drag the shared variable from the Project Explorer window to the block diagram. Shared variable references on the block diagram work much like local or global variables. You can right‐click a shared variable and select Change to Read or Change to Write to change the direction of the variable. Unlike local or global variables, shared variables contain additional terminals along with the data. Each shared variable has error in and error out terminals, and shared variables set to read can return the timestamp at which the data was written. To display the timestamp, right‐click the variable and select Show Timestamp.

CHAPTER 3 By Radu Muresan University of Guelph Page 54

Page 55: ENGG4420 ‐‐ CHAPTER 3 LECTURE 1

SHARED VARIABLE REAL‐TIME FIFOs

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

When you enable the Real‐Time FIFO option, LabVIEW uses Real‐Time FIFOs to transfer the data that is written to and read from the shared variable.

You can configure the FIFO to be single or multi‐element and define the size of the FIFO. When you enable the Real‐Time FIFO option, a small icon appears on references to the variable to indicate that it uses Real‐Time FIFOs.

CHAPTER 3 By Radu Muresan University of Guelph Page 55

Page 56: ENGG4420 ‐‐ CHAPTER 3 LECTURE 1

PROGRAMMING TECHNIQUES ‐‐ INITIALIZATION

The FIFO is created the first time a variable is read or written Create and

initialize the FIFO by writing a meaningful value to it before your main loop

Or allow for extra jitter in the first iteration of a loop using variables

Reading the FIFO before a value is written returns error -2222 and a default data value Use the error to check for un-initialized variables

Shared‐variable FIFOs are created the first time a variable is read or written. This results in a slight delay. Therefore, either initialize the variable by reading or writing it before your main loop or allow for a delay in the first iteration of your loop as the FIFO is created.

If you read the value of a shared variable before it has been written to in the program, LabVIEW returns error ‐2222 and the default value for the data type. You can use this error to determine whether the value read is a valid data point, or whether it is the default value. 

Alternately, if you initialize the variable by writing a meaningful value before starting the loop, you can avoid the possibility of reading the variable before it is written.

CHAPTER 3 By Radu Muresan University of Guelph Page 56

Page 57: ENGG4420 ‐‐ CHAPTER 3 LECTURE 1

PROGRAMMING TECHNIQUES ‐‐ IDENTIFYING OVERFLOW AND UNDERFLOW

Multi‐element RT FIFOs have a fixed memory size and a fixed number of elements, which can be configured in the variable properties dialog. Therefore, multi‐element shared variable RT FIFOs introduce the possibility for overflow and underflow errors.

An overflow error occurs when a shared variable reference attempts to write to an RT FIFO that is already full. When an overflow occurs, the shared variable returns error ‐2221 and overwrites the oldest value in the FIFO with the new value. The oldest value is permanently lost.

An underflow error occurs when a shared variable reference attempts to read an empty RT FIFO. When an underflow occurs, the shared variable returns error ‐2220 and returns a default value for the data item. Note that this is different from error ‐2222, which only applies if a variable has never been written to. Also, error ‐2220 applies only to multi‐element FIFOs, whereas error ‐2222 applies to all shared variables. 

CHAPTER 3 By Radu Muresan University of Guelph Page 57

Page 58: ENGG4420 ‐‐ CHAPTER 3 LECTURE 1

PROGRAMMING TECHNIQUES ‐‐MULTIPLE READERS AND WRITERS

Multiple readers and writers block other operations of the same type

Multiple readers of a multi-element FIFO will each remove elements, preventing either reader from getting all of the data

Only a single reader and a single writer can access a shared variable at the same time. If a single variable has multiple readers and writers, the readers and writers alternate in accessing the variable like any other resource. Variable references waiting on another reader or writer are blocked and do not continue block diagram execution.

Because variables can block with multiple readers or writers, you should use caution when using variables in a time‐critical loop. A variable read by a time‐critical loop must not be read by any other loop and a variable written by a time‐critical loop must not be written by any other loop. Failure to follow these rules can cause the time‐critical loop to block and become non‐deterministic. 

Multi‐element FIFOs with multiple readers only return each value in the FIFO once. Therefore, if each reader needs to access all of the values written to the FIFO, use a separate variable for each reader.

CHAPTER 3 By Radu Muresan University of Guelph Page 58

Page 59: ENGG4420 ‐‐ CHAPTER 3 LECTURE 1

LOW‐LEVEL FIFO VIs vs. SHARED VARIABLE FIFOs

Shared Variable FIFO Low-Level FIFO VIs

Configuration Static Dynamic

Performance Write operations must store timestamps

Faster write operations

Programming Easier configuration and general operations

Easier dynamic configuration changes

Features Timestamp available, can be easily changed to other variable types

Compatible with LV 7.x and earlier

Shared variables store the timestamp of each piece of data they receive, this makes write operations slightly slower than the low‐level FIFO VIs.

Shared variable FIFOs can be changed to other shared‐variable types. For example, without any significant changes to the block diagram code, a single‐process shared variable FIFO can be changed into a network‐published shared variable FIFO to communicate with the host.

Shared variables debuted in LabVIEW 8.0. Real‐Time FIFOs are backwards compatible with previous LabVIEW versions.

CHAPTER 3 By Radu Muresan University of Guelph Page 59

Page 60: ENGG4420 ‐‐ CHAPTER 3 LECTURE 1

STATIC vs. DYNAMIC CONFIGURATION

Shared Variable FIFOs are configured statically using dialog boxes Simplify programming and

wiring Conserve block diagram space

Low-level FIFOs are configured dynamically using block diagram code Simplify visually inspecting

block diagram Simplify modifying

configuration while the program is running

Improves control over when the FIFO is created and dstroyed

Shared variables are configured statically. This means that the properties of a shared variable are defined through interactive dialog boxes as you write your program, rather defining them at run‐time as shared variables are defined for dynamically configured entities such as a Real‐Time FIFO.

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

CHAPTER 3 By Radu Muresan University of Guelph Page 60

Page 61: ENGG4420 ‐‐ CHAPTER 3 LECTURE 1

SUMMARY

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

Improve determinism by:•

Good: Global Variables○Better: Functional Global Variables○Best: Real‐Time Module FIFOs or Shared Variable FIFOs

Inter‐thread communication methods:•

CHAPTER 3 By Radu Muresan University of Guelph Page 61

Page 62: ENGG4420 ‐‐ CHAPTER 3 LECTURE 1

TIMING APPLICATIONS AND ACQUIRING DATAIn this section we discuss about the development of time‐critical portion of the target program. This typically involves control parameters, hardware input and output, and timing. 

Timing Control Loops○Software Timing○Hardware Timing○Event Response○

We focus on software and hardware methods of timing a control loop such as:

ENGG4420 ‐‐ CHAPTER 3 ‐‐ LECTURE 4November‐04‐105:28 PM

CHAPTER 3 By Radu Muresan University of Guelph Page 62

Page 63: ENGG4420 ‐‐ CHAPTER 3 LECTURE 1

TIMING CONTROL LOOPSProvide sleep to allow time for lower priority threads to execute

Reduce application jitter•

Software jitter is typically grater than hardware jitter

Software jitter can be around 15 µs, which is sufficient for many applications

Hardware timing is not available of [c]FP (Compact Field Point) systems

Use software or hardware methods to time control loops

Because of the preemptive nature of the RTOS on RT Series devices, a time‐critical application thread can monopolize the processor on the device. A thread might use all processor resources and not allow lower priority threads in the application to execute.

The time‐critical task must periodically yield processor resources to the lower‐priority tasks so they can execute. By properly separating the time‐critical task from lower priority tasks, you can reduce application jitter.

You can use software methods or hardware methods to time control loops. Before discussing timing and sleep, here are some differences between software and hardware control. 

Software control is less deterministic than hardware control because code execution time usually varies more than a timebasegoverned by a hardware oscillator. An example of hardware oscillator is the 20 MHz timebase on most Multifunction DAQ devices. Depending on the timebase and accuracy of the oscillator, hardware jitter ranges from one to a few hundred nanoseconds. In contrast, software jitter within the real‐time OS is around 15 µs.

CHAPTER 3 By Radu Muresan University of Guelph Page 63

Page 64: ENGG4420 ‐‐ CHAPTER 3 LECTURE 1

TIMING CONTROL LOOPS

Timing tied to the operating system millisecond clock.

Loop timing achieved with wait functions.○Wait functions masks software jitter within loop but introduces a minor amount of its own jitter.

Software Timing (all real‐time platforms)•

Timing tied to the microsecond processor clock or an external clock.

Clock is independent from OS timing.○Hardware jitter depends on accuracy of the clock.○

Hardware Timing (not available on [c]FP)•

You can use hardware timing only on some platforms. 

One method of hardware timing is to access the processor clock, which can only be used on Pentium 3 or 4 processors. Compact FieldPoint and FieldPoint modules do not use Pentium 3 or 4 processors. 

The second method of hardware timing is to access an externally provided clock, such as the clock on a Multifunction DAQ board. Compact FieldPoint and FieldPoint mudules cannot access external clocks for timing.

CHAPTER 3 By Radu Muresan University of Guelph Page 64

Page 65: ENGG4420 ‐‐ CHAPTER 3 LECTURE 1

SOFTWARE TIMING

Insert Wait function in loop,○Insert Wait Until Next Multiple function in loop,○Replace looping mechanism with a timed loop.○

Three standard methods of accomplishing software timing:

ConfigureAcquire

Control, andOutput

Close

Looping mechanism

The first two methods are LabVIEW wait functions that you can insert in your code to add sleep time. 

The third method is a timed loop and is chosen for its other benefits. 

LabVIEW provides three software timing methods.•

All three methods have a millisecond resolution when used for software timing.

CHAPTER 3 By Radu Muresan University of Guelph Page 65

Page 66: ENGG4420 ‐‐ CHAPTER 3 LECTURE 1

SOFTWARE TIMING ‐WAIT

Causes VI to sleep for specified time

Do not use in parallel with time-critical code

Code execution time can vary, therefore total loop execution time varies

Code execution Code executionWait (ms) execution

OS ms timervalue = 112

OS ms timervalue = 122

The Wait function cause a VI to sleep for the specified amount of time. For example, if the OS millisecond timer value is 112 ms when the Wait function executes, and the Count (mSec) input equals 10, then the function returns when the millisecond timer value equals 122 ms.

Avoid using this VI in parallel with anything in a time‐critical priority. If the Wait function executes first, the whole thread sleeps until the Wait finishes, and the code in parallel does not execute until the Wait function finishes. 

The resulting loop period equals code execution time plus the Count (mSec) time.

CHAPTER 3 By Radu Muresan University of Guelph Page 66

Page 67: ENGG4420 ‐‐ CHAPTER 3 LECTURE 1

SOFTWARE TIMING ‐‐WAIT UNTIL NEXT MULTIPLE

Thread sleeps until the OS millisecond timer equals a multiple of the Count(mSec) input => Loop period = code execution + count time

First loop iteration is indeterminate

OS ms timer value = 30

OS ms timer value = 42

OS ms timer value = 100

OS ms timer value = 109

OS ms timer value = 200

Code Execution Wait Execution Code Execution Wait Execution

That Wait Until Next Multiple function causes a thread to sleep until the OS millisecond timer value equals a multiple of the Count(mSec) input. For example, if the Wait Until Next Multiple function executes with a Count(mSec) input of 100 ms and the OS millisecond timer value is 112 ms, the VI sleeps until the millisecond timer value equals 200 ms because 200 ms is the first multiple of 100 ms after the Wait Until Next Multiple function executes.

Use the Wait Until Next Multiple function to synchronize a loop with the OS millisecond timer value multiple. A loop has a period of Count(mSec) if the Wait Until Next Multiple function executes in parallel with other code in the same loop. However, the loop does not have the period of Count(mSec) if the code takes longer to execute than the count.

Placing Wait Until Next Multiple function in parallel with other code can cause incorrect timing. Due to the data flow properties of LabVIEW programming the Wait Until Next Multiple function can execute before, after, or between the execution of analog input and output. Instead, use a sequence structure to control when the Wait Until Next Multiple function executes (as shown in this slide). 

In the figure, the code may take a variable amount of time to finish executing, but by calling Wait Until Next Multiple function afterwards, you enforce a loop frequency of 10 Hz (1/100ms). The maximum loop rate that can be achieved using this method is 1 KHz with a wait multiple of 1 ms.

CHAPTER 3 By Radu Muresan University of Guelph Page 67

Page 68: ENGG4420 ‐‐ CHAPTER 3 LECTURE 1

SOFTWARE TIMING ‐‐WAIT UNTIL NEXT MULTIPLE

Add a Wait before the loop to initialize the timer Even first iteration of loop timer is deterministic with this

method

13

Wait Execution Code Execution Wait Execution Code Execution

100 112 200 209

Because Wait Until Next Multiple only accepts integers, loop rates are limited to only a few frequencies: 1000, 500, ~333, 250, 200, ~167 Hz, and so on.

In this figure, the 100 ms timer is initialized by calling the Wait Until Next Multiple function immediately before the While Loop begins. Otherwise, the loop time for the first iteration would be indeterminate. In the While Loop, the Wait Until Next Multiple function is enclosed in a sequence structure to assure that the delay is added after the code has finished. In this way, the order of execution is guaranteed.

Before deciding on a millisecond multiple, you must ensure that the code in your loop can execute faster than the wait multiple. If your code takes slightly longer than the ms multiple, then your loop actually waits 2 times ms multiples, because code was running when the first ms multiple arrived. In this case, the wait until ms multiple is not aware that the first ms multiple occurred and waits until a second ms multiple occurs before returning.

In addition to controlling loop rates, the Wait Until Next Multiple function forces time‐critical VIs to sleep until the wait is finished. When a VI sleeps, it relinquishes the CPU, allowing other VIs or threads to execute. Sleep time is required in time‐critical VIs, because the user interface and other background processes need CPU time to survive.

CHAPTER 3 By Radu Muresan University of Guelph Page 68

Page 69: ENGG4420 ‐‐ CHAPTER 3 LECTURE 1

SOFTWARE TIMING ‐‐WAIT UNTIL NEXT MULTIPLE

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

SW timing, ΔT = 5 ms +/- inherent jitter

Code execution time, Te

Worst case software jitter, Tj

Worst case time, Twc

The Wait Until Next Multiple function masks software jitter within the loop. The function has some inherent jitter, which is acceptable for many real‐time applications. 

In this example, the Wait Until Next Multiple function synchronizes with each 5 ms tick of the OS clock, allowing the loop to achieve 200 Hz software‐timed analog input. 

The timeline illustrates the 5 ms wait multiple at ΔT, the actual time required to execute the code at Te, worst case jitter at Tj, and worst case time at Twc. 

As long as the worst case time is smaller than the wait multiple, the actual loop period equals the wait multiple, plus or minus the jitter incurred by the function itself.

CHAPTER 3 By Radu Muresan University of Guelph Page 69

Page 70: ENGG4420 ‐‐ CHAPTER 3 LECTURE 1

SOFTWARE TIMING ‐‐ TIMED LOOP

Use instead of a For or While Loop when appropriate

Choose the ms timer on the timed loop to use sw timing

Use the Timed loop to develop VIs with the following: Multi-rate timing capabilities; feedback on loop execution; timing

characteristics that change dynamically.

The Timed Loop applies only to Windows and ETS and executes an iteration of the loop at the period you specify. Use the Timed Loop when you want to develop VIs with multi‐rate timing capabilities, feedback on loop execution, or timing characteristics that change dynamically.

Because the Timed Loop automatically imposes sleep asneeded to achieve the loop rate you specify, there is no need to use a Wait or Wait Until Next Multiple function to add sleep time in the loop.

CHAPTER 3 By Radu Muresan University of Guelph Page 70

Page 71: ENGG4420 ‐‐ CHAPTER 3 LECTURE 1

HARDWARE TIMING ‐‐ NOT AVAILABLE ON [c]FieldPoint

Four standard methods of accomplishing hw timing Insert Wait function with µs resolution in loop

Insert Wait Until Next Multiple with µs resolution in loop

Replace loop with Timed Loop linked to µs clock or external clock

Use DAQmx VIs to connect to external clock

ConfigureAcquire

Control, andOutput

Close

Looping mechanism

The first 3 methods are similar to the software timing methods, but access a microsecond clock on the processor rather than the millisecond operating system clock.

The fourth method involves using DAQmx functions to connect to an external clock, such as the clock on a Multifunction DAQ device. 

You can use an external clock with the DAQmx VIs to time data acquisition or as an input to a Timed Loop.

CHAPTER 3 By Radu Muresan University of Guelph Page 71

Page 72: ENGG4420 ‐‐ CHAPTER 3 LECTURE 1

HARDWARE TIMING ‐‐ μs TIMING FUNCTIONS

Choose µs timing for the Wait function, Wait Until Next Multiple function, and Timed Loop to achieve greater loop rate resolution

Enables loop rates of 1 MHz, 500 KHz, ~333KHz, 250 KHz, 200 KHz, ~167 KHz, and so on.

Worst case code execution time must still be less than ΔT

Use same programming architecture as with software timing

If you are targeting to an RT target that allows microsecond timing, you can use the microsecond clock for the wait functions. 

If you are not targeted to an acceptable target, you can still select microsecond timing, but the program uses the millisecond OS clock instead.

With a ms clock, loop rates are 1/X ms = 1KHz, 500 Hz, ~333 Hz, 250 Hz, and so on

With a µs clock, loop rates are 1/X µs = 1 MHz, 500 KHz, ~333 KHz, 250 KHz, and so on

Using the microsecond clock allows for more loop rate options:

CHAPTER 3 By Radu Muresan University of Guelph Page 72

Page 73: ENGG4420 ‐‐ CHAPTER 3 LECTURE 1

HARDWARE TIMING ‐‐ TIMED LOOP

Choosethe µ timer

Or connect an external clock

When you configure a Timed Loop, you can choose the MHz clock (μs timer), if you are targeted to an appropriate target. 

You also can choose to connect an external clock to a terminal. You can access the configuration window by double‐clicking the Timed Loop.

CHAPTER 3 By Radu Muresan University of Guelph Page 73

Page 74: ENGG4420 ‐‐ CHAPTER 3 LECTURE 1

HARDWARE TIMING ‐‐ DAQmx

Demo: NI Example FinderHardware Input and Output >> DAQmx >> Control >> General >> PID Control-Single Channel.vi

You can use NI data acquisition hardware and NI‐DAQmx to achieve a sleep resolution much finer than 1 kHz. Hardware timing uses the DAQ device internal clock or an external clock to control when a Read VI or a Write VI executes within a loop.

With a hardware timing, the loop rate matches the rate programmed into the Sample Clock VI. You must choose the Hardware Timed Signal Point sample mode input.

Overwrite errors can occur, however, when the requested scan rate is too fast relative to the code execution time. In other words, if the CPU is not powerful enough to execute the code within the loop at least as fast as the scan rate, the FIFO eventually overflows with new, unread data.

CHAPTER 3 By Radu Muresan University of Guelph Page 74

Page 75: ENGG4420 ‐‐ CHAPTER 3 LECTURE 1

EVENT RESPONSE ‐‐MONITORING FOR EVENTS

Use the point-by-point VIs to monitor for the events such as: Triggering datalogging

Triggering an alarm

Performing a calculation

With real‐time event response, you can respond to a single event within a given amount of time. However, to respond to an event, the VI must know that the event has happened. 

Some common events include detecting a peak in measurement or detecting when a threshold has been reached. 

You can use the Point‐by‐Point Signal Analysis VIs to watch for these types of events.

CHAPTER 3 By Radu Muresan University of Guelph Page 75

Page 76: ENGG4420 ‐‐ CHAPTER 3 LECTURE 1

EVENT RESPONSE ‐‐ DIGITAL CHANGE DETECTION

Common event response application

Must have a digital I/O device that supports change detection

NI‐DAQmx only. Another common event response application involves watching for a digital line change, which is useful when watching for an alarm trigger. 

The figure above uses the DAQmx digital change functionality with the Timed Loop. 

Notice that the digital line is connected to the clock terminal of the Timed Loop. When the digital change happens or a timeout occurs, the timed loop wakes up and processes the code in the loop.

CHAPTER 3 By Radu Muresan University of Guelph Page 76

Page 77: ENGG4420 ‐‐ CHAPTER 3 LECTURE 1

COMMUNICATION

The RT Engine on the RT target does not provide a user interface for applications. 

You can use one of two communication protocols, front panel communication or network communication, to provide a user interface on the host computer for RT target VIs.

CHAPTER 3 By Radu Muresan University of Guelph Page 77

Page 78: ENGG4420 ‐‐ CHAPTER 3 LECTURE 1

FRONT PANEL COMMUNICATION

With front panel communication, LabVIEW and the RT Engine execute different parts of the same VI, as shown in this figure. LabVIEW on the host computer displays the front panel of the VI while the RT Engine executes the block diagram. A user interface thread handles the communication between LabVIEW and the RT Engine. 

Use front panel communication between LabVIEW on the host computer and the RT Engine to control and test VIs running on an RT target. After downloading and running the VIs, keep LabVIEW on the host computer open to display and interact with the front panel of the VI. 

You can also use front panel communication to debug VIs while they run on the RT target. You can use LabVIEW debugging tools – such as probes, execution highlighting, breakpoints, and single stepping – to locate errors on the block diagram code.

Front panel communication is a good communication method for monitoring and interfacing with VIs running on an RT target. However, front panel communication is not deterministic and can affect the determinism of a time‐critical VI. 

Use network communication methods to increase the efficiency of the communication between a host computer and VIs running on the RT target.

CHAPTER 3 By Radu Muresan University of Guelph Page 78

Page 79: ENGG4420 ‐‐ CHAPTER 3 LECTURE 1

NETWORK COMMUNICATION

CHAPTER 3 By Radu Muresan University of Guelph Page 79

Page 80: ENGG4420 ‐‐ CHAPTER 3 LECTURE 1

NETWORK COMMUNICATION ‐‐

To run another VI on the host computer○To control the data exchanged between the host computer and the RT target. You can customize the communication code to specify which front panel objects get updated and when. You also can control which components are visible on the front panel, because some control and indicators might be more important than others.

To control timing and sequencing of the data transfer.○To perform additional data processing or logging.○

With network communication, a host VI runs on the host computer and communicates with the VI running on the RT target using specific network communication methods such as network‐published, shared variables, TCP, VI Server, and in the case of non‐networked RT Series plug‐in devices, shared memory reads and writes. You might use network communication for the following reasons:

In the diagram, the RT target VI is similar to the VI shown in the Front Panel Communication section, which runs on the RT target using front panel communication to update the front panel controls and indicators. 

However, the RT target VI in the figure above uses RT FIFO VIs to pass data to a communication VI. The communication VI then communicates with the host computer VI using network communication methods to update controls and indicators.

CHAPTER 3 By Radu Muresan University of Guelph Page 80

Page 81: ENGG4420 ‐‐ CHAPTER 3 LECTURE 1

NETWORK COMMUNICATION METHODS

Protocol Programming Difficulty

Speed Architecture Caveats

TCP Good Better Client/Server

StringData

UDP Good Best  Broadcast or Client/Server

Unreliable,String data

SharedVariable

Best Good Publisher/Subscriber

NI protocolLabView 8+

VI Server Better Poor Client/Server

LabVIEWonly

The network communication methods most commonly used with LabVIEW RT include TCP, UDP, shared variables, and VI server. Other methods, mostly used in legacy systems include DataSocket and Logos.

TCP – Protocol most commonly used for large systems. Provides a good mixture of speed and reliability. Data must be formatted as strings.

UDP – Fastest network protocol. Includes little error checking and can loose packets. Robust systems must implement their own error checking. Data must be formatted as strings.

Shared Variables – Easiest protocol to implement. Shared variables can be used deterministically directly from a time‐critical loop, because they implement a normal‐priority communication loop automatically. Only host programs using LabVIEW and other NI products can access shared variables that are only available on LabVIEW 8.0 and later.

VI Server – You can use VI server to run VIs and/or access and set the value of controls and indicators. VI Server communication is not recommended for transferring large amounts of data. 

ARCHITECTURESClient – Server – a dedicated connection is created between a client and a server.•Broadcast – Application broadcasts data onto a network, any listeners can receive the data. Typically a one way conduit.

Publisher/Subscriber – A server or program publishes data items. Subscribers subscribe to data items. Each subscriber can read and/or write to the data item.

CHAPTER 3 By Radu Muresan University of Guelph Page 81

Page 82: ENGG4420 ‐‐ CHAPTER 3 LECTURE 1

END OF CHAPTER 3

CHAPTER 3 By Radu Muresan University of Guelph Page 82

Page 83: ENGG4420 ‐‐ CHAPTER 3 LECTURE 1

SECTIONS COVERED:Components of a DAQ System1.Types of Signals2.Common Transducers and Signal Conditioning3.Signal Grounding and Measurements4.Analog to Digital Conversion Considerations5.DAQ VI Organization6.Choosing your Data Acquisition Device7.

REFERENCE: R. H. Bishop, LabView 2009, Student Edition.

ENGG442g0 ‐‐ CHAPTER 3 ‐‐ REAL‐TIME DATA ACQUISITION (DAQ) WITH LABVIEWOctober‐27‐109:56 AM

CHAPTER 3 By Radu Muresan University of Guelph Page 83

Page 84: ENGG4420 ‐‐ CHAPTER 3 LECTURE 1

A computer‐based data acquisition system consists of sensors and transducers, signal conditioning, the hardware DAQ device, and a computer‐based software suite for acquiring, manipulating, analyzing, storing, and displaying the raw data acquired. 

COMPONENTS OF DAQ SYSTEMOctober‐27‐1010:04 AM

CHAPTER 3 By Radu Muresan University of Guelph Page 84

Page 85: ENGG4420 ‐‐ CHAPTER 3 LECTURE 1

CHAPTER 3 By Radu Muresan University of Guelph Page 85

Page 86: ENGG4420 ‐‐ CHAPTER 3 LECTURE 1

CHAPTER 3 By Radu Muresan University of Guelph Page 86

Page 87: ENGG4420 ‐‐ CHAPTER 3 LECTURE 1

CHAPTER 3 By Radu Muresan University of Guelph Page 87

Page 88: ENGG4420 ‐‐ CHAPTER 3 LECTURE 1

CHAPTER 3 By Radu Muresan University of Guelph Page 88

Page 89: ENGG4420 ‐‐ CHAPTER 3 LECTURE 1

CHAPTER 3 By Radu Muresan University of Guelph Page 89

Page 90: ENGG4420 ‐‐ CHAPTER 3 LECTURE 1

CHAPTER 3 By Radu Muresan University of Guelph Page 90

Page 91: ENGG4420 ‐‐ CHAPTER 3 LECTURE 1

CHAPTER 3 By Radu Muresan University of Guelph Page 91

Page 92: ENGG4420 ‐‐ CHAPTER 3 LECTURE 1

CHAPTER 3 By Radu Muresan University of Guelph Page 92