0% found this document useful (0 votes)
257 views170 pages

PDF Practical Applications and Solutions Using Labview Software DL

Uploaded by

scrlbd
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
257 views170 pages

PDF Practical Applications and Solutions Using Labview Software DL

Uploaded by

scrlbd
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 170

 

PRACTICAL APPLICATIONS
AND SOLUTIONS USING
LABVIEW™ SOFTWARE

Edited by Silviu Folea


Practical Applications and Solutions Using LabVIEW™ Software
Edited by Silviu Folea

Published by InTech
Janeza Trdine 9, 51000 Rijeka, Croatia

Copyright © 2011 InTech


All chapters are Open Access articles distributed under the Creative Commons
Non Commercial Share Alike Attribution 3.0 license, which permits to copy,
distribute, transmit, and adapt the work in any medium, so long as the original
work is properly cited. After this work has been published by InTech, authors
have the right to republish it, in whole or part, in any publication of which they
are the author, and to make other personal use of the work. Any republication,
referencing or personal use of the work must explicitly identify the original source.

Statements and opinions expressed in the chapters are these of the individual contributors
and not necessarily those of the editors or publisher. No responsibility is accepted
for the accuracy of information contained in the published ar ticles. The publisher
assumes no responsibility for any damage or injury to persons or property arising out
of the use of any materials, instructions, methods or ideas contained in the book.

Publishing Process Manager  Iva Lipovic


Technical Editor Teodora Smiljanic
Cover Designer Jan Hyrat
Image Copyright Sofia, 2010. Used under license from Shutterstock.com

LabVIEW™ is a trademark of National Instruments. This publication is independent of


National Instruments, which is not affiliated with the publisher or the author, and does
not authorize, sponsor, endorse or otherwise approve this publication.

First published July, 2011


Printed in Croatia

A free online edition of this book is available at www.intechopen.com


Additional hard copies can be obtained from [email protected]

Practical Applications and Solutions Using LabVIEW™ Software, Edited by Silviu Folea
p. cm.
ISBN 978-953-307-650-8
free online editions of InTech
Books and Journals can be found at
www.intechopen.com
Contents

Preface IX

Part 1 Virtual Instruments 1

Chapter 1 Virtual Instrument for Online Electrical


Capacitance Tomography 3
Zhaoyan Fan, Robert X. Gao and Jinjiang Wang

Chapter 2 Low-Field NMR/MRI Systems Using LabVIEW


and Advanced Data-Acquisition
Data-Acquisition Techniques 17
Aktham Asfour

Chapter 3 DH V 2.0, A Pocket PC Software to Evaluate Drip


Irrigation Lateral Diameters Fed from the Extreme with
on-line Emitters in Slope Surfaces 41
José Miguel Molina-Martínez, Manuel Jiménez-Buendía and
Antonio Ruiz-Canales

Chapter 4 Application of Virtual Instrumentation


in Nuclear Physics Experiments 57
Jiri Pechousek

Part 2 Hardware in the Loop Simulation 81

Chapter 5 Real-Time Rapid Embedded Power System


Control Prototyping Simulation
Test-Bed Using LabVIEW and RTDS 83
Karen Butler-Purry and Hung-Ming Chou

Chapter 6 The Development of a Hardware-in-the-Loop Simulation


System for Unmanned Aerial Vehicle Autopilot Design
Using LabVIEW 109
Yun-Ping Sun

Chapter 7 Equipment Based on the Hardware in the Loop (HIL) Concept


to Test Automation Equipment Using Plant Simulation 133
Eduardo Moreira, Rodrigo Pantoni and Dennis Brandão
VI Contents

Part 3 eHealth 153

Chapter 8 Sophisticated Biomedical Tissue Measurement Using Image


Analysis and Virtual Instrumentation
Instrumentation 155
Libor Hargaš, Dušan Koniar and Stanislav Štofan

Chapter 9 Instrument Design, Measurement and Analysis of


Cardiovascular
Cardiovascular Dynamics Based on LabVIEW 181
Wei He, Hanguang Xiao, Songnong Li and Delmo Correia

Chapter 10 ECG Ambulatory System for Long Term Monitoring


of Heart Rate Dynamics 201
Agustín Márquez-Espinoza, José G. Mercado-Rojas,
Gabriel Vega-Martínez and Carlos Alvarado-Serrano

Part 4 Test and Fault Diagnosis 227

Chapter 11 Acoustical Measurement and Fan Fault Diagnosis


System Based on LabVIEW 229
Guangzhong Cao

Chapter 12 Condition Monitoring of Zinc Oxide Surge Arresters 253


Novizon, Zulkurnain Abdul-Malek, Nouruddeen Bashir and Aulia

Part 5 Practical Applications


Applications 271

Chapter 13 Remote Instrumentation Laboratory


for Digital Signal Processors Training 273
Sergio Gallardo, Federico J. Barrero and Sergio L. Toral

Chapter 14 Digital Image Processing Using LabView 297


Rubén Posada-Gómez, Oscar Osvaldo Sandoval-González,
Albino Martínez Sibaja, Otniel Portillo-Rodríguez
and Giner Alor-Hernández

Chapter 15 Remote SMS Instrumentation Supervision


and Control Using LabVIEW 317
Rafael C. Figueiredo, Antonio M. O. Ribeiro,
Rangel Arthur and Evandro Conforti

Chapter 16 Lightning Location and Mapping System Using Time


Difference of Arrival (TDoA) Technique 343
Zulkurnain Abdul-Malek, Aulia, Nouruddeen Bashir and Novizon

Chapter 17 Computer-Based Control for Chemical Systems Using


® ®
LabVIEW  in Conjunction with MATLAB 363
Syamsul Rizal Abd Shukor,
Reza Barzin and Abdul Latif Ahmad
Contents VII

Chapter 18 Dynamic Wi-Fi Reconfigurable FPGA Based Platform


for Intelligent Traffic Systems 377
Mihai Hulea, George Dan Moiş and Silviu Folea

Part 6 Programming Techniques 397

Chapter 19 Extending LabVIEW Aptitude for Distributed Controls


and Data Acquisition 399
Luciano Catani

Chapter 20 Graphical Programming Techniques


for Effective, Fast and Responsive Execut 421
Marko Jankovec

Chapter 21 The Importance of a Deep Knowledge of LabVIEW


Environment and Techniques in Order to Develop
Effective Applications 437
Riccardo de Asmundis
Preface

The book consists of 21 chapters which present applications implemented using the
LabVIEW environment, belonging to several distinct fields such as engineering,
chemistry, physics, fault diagnosis and medicine. In the context of the applications
presented in this book, LabVIEW offers major advantages especially due to some
characteristic features. It is a graphical programming language which utilizes
interconnected icons (functions, structures connected by wires), resembling a
flowchart and being more intuitive. Taking into account different objectives, LabVIEW
can be considered an equivalent of an alternative to the classic programming
languages. It is important to mention that the implementation time for a software
application is reduced as compared to the time needed for implementing it by using
other environments.

The built-in libraries and the virtual instruments examples (based on VIs), as well as
the software drivers for almost all the existing data acquisition systems make the
support and the use of devices produced by more than fifty companies, including
industrial instruments, oscilloscopes, multimeters and signal generators possible in
LabVIEW.

The LabVIEW platform is portable, being able to run on multiple devices and
operating systems. Programming in LabVIEW involves the creation of the graphical
code (G) on a PC, where it is afterwards compiled. Tools specific to different targets
such as industrial computers with real time operating systems (PXI), programmable
automation controllers (Compact RIO), PDAs, microcontrollers or field-programmable
gate arrays (FPGAs) are used and after that the compiled code is downloaded to the
target.

Chapter 1 presents a virtual instrument for image capture and display associated with
the electrical capacitance tomography (ECT), a noninvasive measurement method for
visualizing temporal and spatial distributions of materials within an enclosed vessel.
According to the hardware circuitry configuration and the combination of electrodes
for the ECT, the VI is implemented using seven major functional modules: switching
control, data sampling, data normalization, permittivity calculation, mesh generation,
image generation, and image display.
X Preface

Chapter 2  describes a LabVIEW based NMR spectrometer (Nuclear Magnetic


Resonance) working at low field. This spectrometer allows the detection of the NMR
signals of both 1H and 129Xe at 4.5 mT. The aim of this chapter is to present the
advances accomplished by the author in the development of low-field NMR systems.
The flexibility of the system allows its use for a palette of NMR applications without
(or with minor) hardware and software modification.

Chapter 3  introduces a new version of drip irrigation design software (DH V 2.0) for
usage with mobile devices like Smartphones or pocket PCs. It uses LabVIEW PDA as
the programming language. The software allows the users of drip irrigation systems to
evaluate their sensibility to changing conditions (water needs, emitters, spacing, slope,
etc.) for all the diameters of commercial polythene drip lines.

Chapter 4  presents a new method for the design of computer-based measurement


systems that can be seen in the use of up-to-date measurement, control and testing
systems based on reliable devices. The measurement systems built with the help of the
LabVIEW modular instrumentation offer a popular approach to nuclear spectrometers
construction. By replacing the former single-purpose system, units with universal data
acquisition modules, a lower-cost solution that is reliable, fast, and takes high-quality
measurements, is achieved.

Chapter 5 describes a real-time rapid embedded control prototyping simulation and a


simple power system case study implementation. The detailed implementation of an
overcurrent relay for controller-in-the-loop simulation is described, including the
setting and programming of a real-time digital simulator and the programming in
CompactRIO, which includes the FPGA and the real-time processor by using
LabVIEW. A synchronization technique which allows the readers to make the
correction decision on the method to be used based on the application and its
requirements is proposed and also discussed.

Chapter 6 presents a continuing research on the design and verification of an autopilot


system for an unmanned aerial vehicle (UAV) through hardware-in-the-loop (HIL)
simulations. The software development environment used for HIL simulations is
LabVIEW. Different control methods for developing the UAV autopilot system design
are applied and the comparison between the results obtained from HIL simulations is
presented in this chapter.

Chapter 7 proposes a HIL-based system, where a Foundation Fieldbus control system


manages the simulation of a generic plant in an industrial process. The simulation
software is executed on a PC, and it has a didactic purpose for engineering students
learning to control a process similar to the real one. The plant is simulated on a
computer, implemented in LabVIEW and represents a part of the fieldbus network
simulator FBSIMU.

Chapter 8  presents a solution for measuring object beating frequency from a video
sequence using tools of image analysis and spectral analysis. It simplifies the methods
Preface XI

used in present times and reduces the usage of the hardware devices. Using the
LabVIEW environment, the authors created a fully automated application with
interactive inputting of some parameters. Several algorithms were tested on phantoms
with defined frequency. The designed hardware data acquisition system can be used
with or without microscope in applications where the placement of kinematic
parameters sensors is not possible. Intelligent regulation of condenser illumination
through image feature extraction and histogram analysis enables the fully automated
approach to video sequence acquisition.

Chapter 9 describes the design of a product developed by the authors using LabVIEW.
It is named YF/XGYD atherosclerosis detection system. The hardware and software
designs of the arterial elasticity measurement system are detailed. The system can
diagnose the condition of arterial elasticity and the degree of arteriosclerosis.

Chapter 10  proposes a prototype of an ECG telemetry system that fulfills the
requirements of real-time transmission of long term records, low power consumption
and low cost. The software for implementing the acquisition, display and storage of
the 4 signals (3 for ECG leads and one for battery voltage), the detection of the ECG R
wave peak and for processing the R-R intervals based on LabVIEW was developed for
the study of heart rate dynamics.

Chapter 11 presents an intelligent fault diagnosis system, where the noise produced by
a fan is considered to be the diagnosis signal, a non-connect measurement method is
adopted and a non-linear mapping from feature space to defective space using the
wavelet neural network is performed. Modular programming was adopted for the
development of this system, so it is easier to extend and change the characteristics of
the network fault and structure parameters.

Chapter 12  describes a new shifted current method technique for determining ZnO
ageing that was successfully implemented in LabVIEW software and was proven
useful for on-site measurement purposes. The developed program provides
convenience in the system management and a user-friendly interface.

Chapter 13  presents a remote measurement laboratory based on LabVIEW that has
 been designed and implemented. It provides the users with access to remote
measurement instrumentation and a DSP embedded board, delivering different
activities related to digital signal processing and measurement experiments. End-user
Quality of Service has been measured and expressed in terms of satisfaction or
technical terms.

Chapter 14  describes different digital image processing algorithms using LabVIEW.
The chapter presents the image acquisition task and some of the most common
operations that can be locally or globally applied. The statistical information generated
 by the image in a histogram is also discussed. A pattern recognition section shows
how to use an image into a computer vision application through an example of object
XII Preface

detection. All these, along with the use of other functionalities of LabVIEW lead to the
conclusion that this software is an excellent platform for developing robotic projects as
well as vision and image processing applications.

Chapter 15  presents the feasibility of a flexible and low cost monitoring and control
solution using SMS, which can be easily applied and adapted to various applications.
The developed system was applied to a RF signal procedure measurement for saving
time and staff in this process. The tool development and its use in a specific
application outline the LabVIEW versatility.

Chapter 16 introduces a new method for determining the coordinates of any cloud-to-
ground lightning strike within a certain localized region. The system is suitable for
determining distributions of lightning strikes for a small area by measuring the
induced voltages due to lightning strikes in the vicinity of an existing telephone air
line.

Chapter 17  presents a solution using two software development platforms, MATLAB
and LabVIEW, for the proper control of a microreactor-based miniaturized intensified
system. The use of the SIMULINK Interface Toolkit is presented. It enables the user to
transfer measurement data from LabVIEW to the embedded control module in
SIMULINK and also to apply the controller output to the system via LabVIEW.

Chapter 18  proposes a software and hardware platform based on a FPGA board to
which a Wi-Fi communication device has been added in order to make remote
wireless reconfiguration possible. This feature introduces a high level of flexibility
allowing the development of applications which can quickly adapt to changes in
environmental conditions and which can react to unexpected events with high speed.
The capabilities introduced by wireless technology and reconfigurable systems are
important in road traffic control systems, which are characterized by continuous
parameter variation and unexpected event and incident occurrence.

Chapter 19  presents the development of a communication framework for distributed


control and data acquisition systems, optimized for its application to LabVIEW
distributed control, but also open and compatible with other programming languages,
 being based on standard communication protocols and standard data serialization
methods.

Chapter 20  describes some general rules illustrated by examples taken from real life
applications for beginner and advanced developers. The content of this chapter
represents graphical programming techniques for better Virtual Instruments (VI)
performance and rules for a better organization of the LabVIEW code.

Chapter 21 presents a collection of considerations and suggestions, some personal and


others from LabVIEW manuals, in the direction of improving the awareness
concerning what minimum knowledge is necessary for a developer in order to be able
to develop rational, well organized and effective applications.
Preface XIII

I wish to acknowledge the efforts of all the scientists who contributed to editing this
 book and to express my appreciation to the InTech team.

I’d like to dedicate this book to Dr. James Truchard, National Instruments president
and CEO, who invented NI LabVIEW graphical development software together with
 Jeff Kodosky.

Silviu FOLEA
Technical University of Cluj-Napoca
Department of Automation
Romania
Part 1

Virtual Instruments
1

Virtual Instrument for Online Electrical


Capacitance Tomography
Zhaoyan Fan, Robert X. Gao* and Jinjiang Wang
Department of Mechanical Engineering, University of Connecticut,
USA

1. Introduction
Electrical capacitance tomography (ECT) is a technique invented in the 1980’s to determine
material distribution in the interior of an enclosed environment by means of external
capacitance measurements (Huang et al., 1989a, 1992b). In a typical ECT system, 8 to 16
electrodes (Yang, 2010) are symmetrically mounted inside or outside a cylindrical container,
as illustrated in Figure 1. During the period of a scanning  frame, an excitation signal is
applied to one of the electrodes and the remaining electrodes are acting as detector
electrodes. Subsequently, the voltage potential at each of the detector electrodes is
measured, one at a time, by the measurement electronics to determine the inter-electrode
capacitance. Changes in these measured capacitance values indicate the variation of material
distribution within the container, e.g. air bubbles translating within an oil flow. An image of
permittivity distribution directly representing the materials distribution can be retrieved
from the capacitance data through a back-projection algorithm (Isaksen, 1996).While image
resolution associated with the ECT technique is lower than other tomographic techniques
such as CT or optical imaging, it is advantageous in terms of its non-intrusive nature,
portability, robustness, and no exposure to radiation hazard.

Fig. 1. Illustration of major components in an ECT system


As shown in Fig.1, an ECT system generally consists of three major components: 1) An
excitation and measurement circuitry that drives the sensors and conditions the received
signals; 2) A computer-based data acquisition (DAQ) and coordination system, to provide
control logic for the sequential excitations of the electrodes and reconstruct tomographic
 Application of Virtual Instrumentation in Nuclear Physics Experiments 65

By changing the sampling rate, by means of the changes of the width and threshold
parameters for peak validation in WPkD, the non-valid peaks rejection and signal noise
reduction are performed. No pile-up correction/rejection is performed by this function.
WPkD distinguishes the pile-up pulses, but their amplitudes are not corrected. In addition,
few disadvantages of such function for the fast processing were found (Krasilnikov et at.,
2011; Pechousek et al., 2007, 2011), and additional improvements, or new DSP algorithms
were designed.
Another simple DSP module, called “discriminator”, checks whether the analog output
signal is above a predefined threshold or not, and produces a digital output. The threshold
values (voltages) can be adjusted through a front panel.

2.3 Signal analyzer and MCA application


The main part of the presented system is the commercially available digitizer NI PCI-5124,
which uses up to 200 MS s-1 real-time sampling. The digitizer is controlled by instrument
drivers, as mentioned above, and called in the designed software application which
performs all DSP functions. This digitizer was also used in γ-spectroscopy of high rate
events (Yang et al., 2009) and in Mössbauer spectrometer designs (Pechousek et al., 2010).
The 57Co radiation source is used and typical pulses sampled by 200 MS s -1 are displayed.
The signals are acquired from the detectors connected with an amplifier. In Figure 10, the
pulse shapes of three selected detectors are shown. The presented pulse shapes are the
results of an average of one thousand pulses with the same amplitude.

Fig. 10. a) The 14.4 keV pulses acquired from the detectors equipped with YAP:Ce
scintillator (red) and GPC (blue) and 122 keV pulse acquired from the detector equipped
with thick NaI:Tl scintillator (black), and b) the details of the rising parts of these pulses.
In Figure 10 (b), the common ringing in the pulses, mostly originating from the PMTs, is
evident.
The most usual DSP method is the pulse height analysis preformed in MCA, which records
the number of pulses in each pulse bin. In MCA, the channel number corresponds to the
amplitude of a pulse, and the counting histogram is accumulated. Recently, DSP-MCA has
been developed and system performance tested by us (Pechousek et al., 2011) on the nuclear
detectors with very short time pulses (from 40 ns up to few microseconds), and in the range
of low and high energies of X- and γ-rays. The front panel of the main application is shown
in Figure 11, where negative pulses are acquired. The application code is based on the
functions presented in Figures 5 and 9. Blue and red cursors in the MCA window (Figure
11) can be used to extract and analyze the pulses in a selected energy range. These cursors
66 Practical Applications and Solutions Using LabVIEW™ Software

are also used as the discrimination levels for the additional processing included e.g. in
Mössbauer spectrometers.

Fig. 11. Signal and Multichannel analyzer - front panel.

2.3.1 Improvement of MCA with high sampling rate


Four detectors employed for signal analysis and two γ-ray sources are presented in this part.
For each detector, MCA was performed and the main photopeak positions were determined.
In addition to 57Co source, 137Cs (γ-ray, 662 keV) source was also used. The MCA spectra
were measured by means of the detector, amplifier, digitizer, and analyzed by the DSP with
the WPkD.
As a first step, the detector signal was sampled with a low sampling rate (10 MS s-1) for
establishing the standard values. This sampling rate is usable in classic MCA and slow
coincidence systems, but it is still low for a precise MCA spectrum recording. In fast lifetime
measurements, it is necessary to use a maximal sampling rate (time resolution) and,
 Application of Virtual Instrumentation in Nuclear Physics Experiments 67

therefore, the analysis with this sampling rate could be performed for the estimation of the
influence on the MCA spectrum shape (energy resolution). Hence, the second value of the
sampling rate was chosen to be of 200 MS s-1. The MCA energy spectra of X- and γ-radiation
emitted by 57Co and 137Cs sources are shown in Figure 12, where black line belongs to a low
sampling rate and red line to a high sampling rate, respectively.

Fig. 12. 57Co MCA spectra for a) thin NaI:Tl, b) YAP:Ce scintillators, c) GPC, d) thick NaI:Tl
scintillator, and e) 137Cs MCA spectrum for thick NaI:Tl scintillator. Signal is acquired at 10
and 200 MS s-1 sampling rate.
When the detector or source was changed from one to another, the distance was adjusted to
achieve the reasonable counting rates and to minimize the occurrence of pile-up events.
Figure 12 shows the energy resolution improvement for all photopeaks except the GPC
detector, in which case a significant improvement is not evident. Furthermore, in the range
of high energy impulses, another significant improvement is observed due to a better
interleaving of the pulses. The 10 MS s-1 sampling rate is quite underlimited for the YAP:Ce
coupled detector. Generally, the improvement for fast detectors and high energy regions is
the most visible, due to the better recognition of the rising part of a observed pulse.
68 Practical Applications and Solutions Using LabVIEW™ Software

2.4 Time-of-flight and coincidence techniques


In common time-resolved coincidence nuclear systems, two different detectors are used in
order to detect different photon energies emitted from the radioactive source, when a
radioactive decay is studied. Similar methods are used i.e. in the time-resolved fluorescence
system (Moreno et al., 2011) estimating the intrinsic fluorescence decay.
The system published in ref. (Pechousek et al., 2011) is suitable for nuclear coincidence
measurements as the nuclear excited state half-life determination, where two DAQ
channels are necessary. The first channel can detect the start nuclear events and the
second channel the stop events. Both channels are sampled by the highest sampling rate.
When the short-lived excited states are analyzed, time-of-flight (TOF) values has to be
determined with the highest accuracy. The 200 MS s-1  sampling rate is used for precise
MCA and time-resolving measurements and the system is then sensitive to decay
lifetimes from tens of nanoseconds. In Figure 13, a block diagram of the above discussed
system is shown.

Fig. 13. DSP system for time-resolved nuclear spectroscopy.


In time-resolved spectrometry, the TOF value determines when a photon or particle arrives
into the detector. The time accuracy of the measurement system depends on the properties
of the detector and the type of electronics processing the signal. TOF measurement offers the
possibility to perform coincidence and anticoincidence nuclear experiments. There are
several analog timing methods (leading edge timing, crossover timing, constant-fraction
timing, first photoelectron timing) implemented in DSP (Abdel-Aal, 1993; Aspinall et al.,
2009). In one of them, the pulse starting time is interpolated from the samples of the pulse
rise and a digital leading-edge discriminator (LED) determines the TOF value. The TOF then
represents the time at which the pulse crosses the threshold (discrimination level). The LED
is a simply implemented timing method usable mainly when similar pulses shapes in a
signal stream occur. Therefore, the developed DSP system with the TOF-LED technique can
be used with various types of detectors. The description of the LabVIEW LED is given in ref.
 Application of Virtual Instrumentation in Nuclear Physics Experiments 69

(Pechousek et al., 2011). The TOF algorithm development and its application in the
coincidence measurement were carried out. The TOF calculation is depicted in Figure 14.
The code has to distinguish between the maximum value position (from WPkD) and the
beginning of the pulses.

Fig. 14. Practical behavior of the TOF procedure.


As mentioned above, when using a code with the original WPkD function, only the valid
peaks are recognized. However, problems arise for high-rate sampling and therefore, DSP-
TOF improvement is necessary. With a high-rate sampling, the peak location is sometimes
found out of the pulse-maximum position. This error-shift negatively affects time resolving
measurements, and has to be reduced for a precise nuclear coincidence measurement by
modifying the WPkD algorithm with adding the TOF determination. The presented
modified TOF-resolving method is applicable for various detectors and is independent on
the pulse rising time (Pechousek et al., 2011).

2.4.1 Lifetime coincidence measurement


The presented DSP system is typically applied in the coincidence measurement where the
lifetime of the excited nuclear state can be measured by the registration of X- γ, or γ-γ
cascade. In this section, the lifetime coincidence measurement of 57Fe 14.4 keV excited state
is presented. The registrations of two events are acquired with two different detectors
optimized for given energies. In the case of 57Co source, it decays by an electron capture to
the excited state of 57Fe (136 keV) which deexcites thorough the 122 keV and 14.4 keV states
to the ground state. The 14.4 keV excited state has a half-life of 98.3 ns (Dickson & Berry,
1986).
In accordance with Figure 13, the first detector (D1) detects 122 keV γ-photons (thick NaI:Tl)
as start events and the second detector (D2) detects 14.4 keV γ-photons (YAP:Ce or thin
NaI:Tl) as stop events. The coincidence intervals, calculated with TOF code, have been
accumulated into the histogram, and are shown in Figure 15.
70 Practical Applications and Solutions Using LabVIEW™ Software

Each channel of the DSP system was configured individually to detect relevant start and
stop events. The value of the half-life was estimated to be 98.9 ± 0.3 ns.

Fig. 15. Lifetime measurement of the 14.4 keV excited state in 57Co source.

3. Additional DSP methods in nuclear systems performed by VI


Acquiring data from a detector is the most common process in the nuclear systems.
Additionally, various methods are used in other different spectroscopies. For instance, one
method can be the generation of an analog signal (waveform) for controlling a particular
device. Hence, synchronizing such DAQ processes with detector signal digitizing becomes
necessary. This is described in the text below.

3.1 Function generators


Different analog output devices are used. The function generator device with its instrument
drivers delivered will be described. The examples presented below have been established
with the NI 5401 (12-bit, 40 MS s-1 update rate) function generator. This function generator
features also the Real-Time System Integration (RTSI) or PXI trigger bus for routing the
trigger signals in the PCI or PXI system to synchronize other DAQ processes. The NI-FGEN
instrument driver is used in NI 5401 applications and the Soft Front Panel (SFP) can be
employed to interactively generate waveforms with NI the signal generators module, in a
similar way as with stand-alone instruments.
The diagram in Figure 16 shows the general programming flow for applications using NI-
FGEN driver. Details are presented in LabVIEW NI-FGEN Help (National Instruments,
2004, 2009b).
This instrument driver is used in a similar way as the above mentioned NI-SCOPE driver.
After the initialization and configuration processes, the signal generation is started. At the
end of the generation, the abort function is called and the instrument session is closed.
 Application of Virtual Instrumentation in Nuclear Physics Experiments 71

Fig. 16. Data flow for NI-FGEN application.

3.2 Synchronization and triggering techniques implemented via RTSI bus


If an application requires more than two DAQ devices, it is possible to synchronize these
devices on all platforms using digital triggers.
RTSI (Real-Time System Integration) bus is employed to share and exchange timing and
control signals between multiple boards. The RTSI bus cables are short, 34-conductor ribbon
cables equipped with two to five connectors linking together a group of boards. Figure 17
shows an example of an extended five-board cable setup.

Fig. 17. RTSI bus used for synchronization of PCI devices (National Instruments, 2010).
The PXI system uses the PXI trigger bus that includes the RTSI bus and is linked to all slots
in the chassis. Other devices can use the PFI (Programmable Function Interface) digital
triggers on the I/O connector.
Synchronization and triggering are commonly used in more sophisticated measurements,
where one or more DAQ processes relate with other processes. Such a type of combination
is common in applications where one device works as a master (generates signals) and the
other device works as a slave (waits for trigger). In the VI concept, it is easy to build such a
system and the exchange the working mode of these devices.
72 Practical Applications and Solutions Using LabVIEW™ Software

A trigger is a signal that initiates one or more instrument functions. The trigger basic types
are digital, software, or analog, and can be derived from the attributes of a signal being
acquired, such as the level and slope of the signal. Triggers can be internal (software-
generated) or external. External triggers allow synchronizing the hardware operation with
an external circuitry or other devices. There are several types of triggering, and each kind of
triggering uses a different NI-SCOPE or NI-FGEN Configure Trigger function (National
Instruments, 2009b, 2010).
For instance, in the computer-based modular Mössbauer spectrometer (Pechousek et al.,
2010), there are two main parts; the first one is a computer with the NI 5102 digitizer, and
the second, the NI 5401 function generator controlled by VI. Their synchronization is
provided by the RTSI bus or PXI Trigger bus. The function generator generates a velocity
signal on its ARB OUT output. On the SYNC OUT output, a trigger signal is available for
the synchronization of other devices (the routing of this signal is shown in Figure 16). This is
used in the internal RTSI bus and triggers the DAQ process in the digitizer. In the case of
USB devices, it can be generated externally by the digital output signal available in the
multifunction devices.

3.2.1 Triggering with NI-FGEN


When triggering a signal generator, it is possible to select the type of the trigger, trigger
source, and trigger mode. For instance, the function generator works as a master, and except
the periodic analog signal, it generates the digital trigger signal with the same frequency on
the SYNC OUT output. This signal will be routed on the RTSI bus line by the function of
niFgen Export Signal VI   (see Figure 18) to control other devices. This function routes signals
(clocks, triggers, and events) to the specified output terminal, i.e. the RTSI connector.

Fig. 18. Function niFgen Export Signal VI  used to route the trigger signals.
The SYNC OUT signal is normally exported on the SYNC_OUT front panel connector.

3.2.2 Triggering with NI-SCOPE


With NI-SCOPE triggering functions, the trigger can transfer a device from a nonsampling
into a sampling state, then the device starts acquiring data. The function which configures
the digitizer for different types of triggering is niScope Configure Trigger (poly), see Figure 19.

Fig. 19. Function niScope Configure Trigger (poly) used to trigger the digitizer.
78 Practical Applications and Solutions Using LabVIEW™ Software

5. Conclusion
The measurement systems built with LabVIEW modular instrumentation offer a popular
approach to nuclear spectrometers construction. By replacing the former single-purpose
system units with universal data acquisition modules, it is achieved a lower-cost solution
that is reliable, fast, and takes high-quality measurements. The result is a user-friendly
application with high system flexibility.
Performances of the DSP systems were directly determined by spectroscopy application.
The presented methods are simple in realization simultaneously with improvement in
performance for nuclear experiments. Moreover, with VI open approach, it is easy to modify
the configuration of the system in the future.

6. Acknowledgment
This work has been supported by the projects “Advanced Technologies in the Study of
Applied Physics” (CZ.1.07/2.2.00/07.0018) and “Education of Research Workers in the
Regional Centre of Advanced Technologies and Materials” (CZ.1.07/2.3.00/09.0042) in
Operational Program Education for Competitiveness - European Social Fund. Author would
also like to thank to Karolina Siskova for her help with this paper.

7. References
Abdel-Aal, R.E. (1993). Simulation and analysis of nuclear physics instrumentation using the
LabVIEW graphical programming environment. The Arabian Journal for Science and
Engineering, Vol. 18, No. 3, (July 1993), pp. 365-382, ISSN 1319-8025
Ahmed, S.N. (2007). Physics and Engineering of Radiation Detection (first edition), Academic
Pres, ISBN 0-12-045581-1, London, Great Britain
Aspinall, M.D., Joyce, M.J., Mackin, R.O., Jarrah, Z., Boston, A.J., Nolan, P.J., Peyton, A.J. &
Hawkes, N.P. (2009). Sample-interpolation timing: an optimized technique for the
digital measurement of time of flight for γ  rays and neutrons at relatively low
sampling rates.  Measurement Science and Technology, Vol. 20, (November 2008),
015104, 10pp, ISSN 0957-0233
Belli, F., Esposito, B., Marocco, D., Riva, M., Kaschuk, Y., Bonheure, G. &  JET EFDA
contributors (2008). A method for digital processing of pile-up events in organic
scintillators. Nuclear Instruments and Methods in Physics Research A , Vol. 595, (July
2008), pp. 512-519, ISSN 0168-9002
Bettiol, A.A., Udalagama, C. & Watt, F. (2009). A New Data Acquisition System for Nuclear
Microscopy based on a Field Programmable Gate Array Card. Nuclear Instruments
and Methods in Physics Research B, Vol. 267, (June 2009), pp. 2069-2072, ISSN 0168-
583X
Cosulich, E. & Gatti, F. (1992). A digital processor for nuclear spectroscopy with cryogenic
detectors. Nuclear Instruments and Methods A , Vol. 321, (September 1992), pp. 211-
215, ISSN 0168-9002
Dickson, D.P.E. &  Berry, F.J. (1986) Mössbauer spectroscopy. Cambridge: Cambridge
University press, ISBN 978-0521018104
Drndarević, V. (2008). A very low-cost alpha-particle spectrometer.  Measurement Science and
Technology, Vol. 19, (April 2008), 057007, 5pp, ISSN 0957-0233
 Application of Virtual Instrumentation in Nuclear Physics Experiments 79

Drndarevic, V. &  Jevtic, N. (2008). A versatile, PC-based gamma ray monitor. Radiation
Protection Dosimetry, Vol. 129, No. 4, (October 2007), pp. 478-480, ISSN 1742-3406
Ellis, W.H. &  He, Q. (1993). Computer-Based Nuclear Radiation Detection and
Instrumentation Teaching Laboratory System. IEEE Transactions on Nuclear Science ,
Vol. 40, No. 4, (August 1993), pp. 675-679, ISSN 0018-9499
Esposito, B., Riva, M., Marocco D. &  Kaschuck Y. (2007). A Digital Acquisition and
Elaboration System for Nuclear Fast Pulse Detection. Nuclear Instruments and
 Methods in Physics Research A, Vol. 572, (March 2007), pp. 355-357, ISSN 0168-9002
Gilmore, G. (2008). Practical Gamma-ray Spectroscopy  (second eddition), Wiley, ISBN 978-
0470861967,
Gontean, A. & Szabó, R. (2011). LabVIEW Remote Lab, In: LabVIEW - Modeling, Programming
and Simulations, Riccardo de Asmundis, ISBN 978-953-307-521-1, InTech, Rijeka,
Croatia
Green, D.P., Bruce J.B. &  Thomas, J.L. (1996). Sensor Measurement and Experimental
Control in Nuclear Magnetic Resonance Imaging. Review of Scientific Instruments,
Vol. 67, No. 1, (January 1996), pp. 102-107, ISSN 0034-6748
Kholmetskii, A.L., Mashlan, M., Misevich, O.V., Chudakov, V.A., Lopatik, A.R. &  Zak, D.
(1997). Comparison of the productivity of fast detectors for Mössbauer
spectroscopy. Nuclear Instruments and Methods in Physics Research B , Vol. 124, (April
1997), pp. 143-144, ISSN 0168-583X
Kirichenko, A.F., Sarwana, S., Mukhanov O.A., Vernik I.V., Zhang, Y., Kang, J. & Vogt, J.M.
(2001). RSFQ Time Digitizing System. IEEE Transactions on Applied
Superconductivity, Vol. 22, No. 1, (March 2001), pp. 978-981, ISSN 1051-8223
Krasilnikov, V., Marocco, D., Esposito, B., Riva, M. &  Kaschuck, Y. (2011). Fast pulse
detection algorithms for digitized waveforms from scintillators. Computer Physics
Communications, Vol. 182, (October 2010), pp. 735-738, ISSN 0010-4655
Moreno, E., Reyes, P. &  de la Rosa, J.M. (2011). Time-resolved fluorescence spectroscopy
with LabView, In: LabVIEW - Modeling, Programming and Simulations , Riccardo de
Asmundis, ISBN 978-953-307-521-1, InTech, Rijeka, Croatia
National Instruments. (2004). NI-FGEN Instrument Driver Quick Reference, 02.04.2011,
Available from http://www.ni.com/pdf/manuals/371307e.pdf
National Instruments. (2009). NI High-Speed Digitizers Help, 02.04.2011, Available from
http://digital.ni.com/manuals.nsf/websearch/349CC538026ACD5A862576E8004
DB89D?OpenDocument&seen=1
National Instruments. (2009). NI Signal Generators Help, 02.04.2011, Available from
http://digital.ni.com/manuals.nsf/websearch/6F0CB519A713D1E28625762000689
402
National Instruments. (2010). Getting Started with NI-SCOPE, 02.04.2011, Available from
http://zone.ni.com/devzone/cda/tut/p/id/3382
Nelson, M.A., Rooney, B.D., Dinwiddie, D.R. &  Brunson, G.S. (2003). Analysis of digital
timing methods with BaF2 scintillators. Nuclear Instruments and Methods in Physics
Research A, Vol. 579, (June 2003), pp. 247-251, ISSN 0168-9002
Pechousek, J. &  Mashlan, M. (2005). Mössbauer spectrometer in the PXI/CompactPCI
modular system. Czechoslovak Journal of Physics , Vol. 55, No. 7, (July 2005), pp. 853-
863, ISSN 0011-4626
80 Practical Applications and Solutions Using LabVIEW™ Software

Pechousek, J., Mashlan, M., Frydrych, J., Jancik, D. &  Prochazka, R. (2007). Improving
detector signal processing with Pulse Height Analysis in Mössbauer Spectrometers.
Hyperfine Interactions, Vol. 107, (February 2007), pp. 1-8, ISSN 0304-3843
Pechousek, J., Prochazka, R., Mashlan, M., Jancik, D. &  Frydrych, J. (2009). Digital
proportional-integral-derivative controller of a Mössbauer Spectrometer.
 Measurement Science and Technology, Vol. 20, (November 2008), 017001, 4pp, ISSN
0957-0233
Pechousek, J., Jancik, D., Evdokimov, V. & Prochazka, R. (2009). Velocity driving system for
an in-field Mössbauer spectrometer. Nuclear Instruments and Methods in Physics
Research B, Vol. 267, (February 2009), pp. 846-848, ISSN 0168-583X
Pechousek, J., Prochazka, R., Jancik, D., Mashlan, M. &  Frydrych, J. (2010). Universal
LabVIEW-powered Mössbauer spectrometer based on the USB, PCI or PXI devices.
 Journal of Physics: Conference Series, Vol. 217, (May 2010), pp. 012006, ISSN 1742-6588
Pechousek, J., Prochazka, R., Prochazka, V. &  Frydrych, J. (2011). Virtual instrumentation
technique used in the nuclear digital signal processing system design: Energy and
time measurement test. Nuclear Instruments and Methods in Physics Research A , Vol.
637, (February 2011), pp. 200-205, ISSN 0168-9002
Prochazka, R., Tucek, P., Tucek, J., Marek, J., Mashlan, M. & Pechousek, J. (2010). Statistical
analysis And digital processing of the Mössbauer spectra.  Measurement Science and
Technology, Vol. 21, (January 2010), 025107, 7pp, ISSN 0957-0233
Tłaczala, W., Grajner, G. & Zaremba, M. (2008). Virtual Laboratory with Simulated Nuclear
Experiments. IEEE Transactions on Instrumentation and Measurement , Vol. 57, No. 8,
(August 2008), pp. 1766-1770, ISSN 0018-9456
Tłaczala, W. (2005). Virtual instrumentation in physics, In: Handbook of Measuring System
Design, P. Sydeman &  R. Thorn, (Eds.), 695-701, Wiley, ISBN 0-470-02143-8,
Hoboken, NJ, USA
Yan, J., Liu, R., Li, Ch., Jiang, L., Lu, X., Zhu, T., Wang, M., Wen, Z. & Lin, J. (2009). LabVIEW-
based auto timing counts virtual instrument system with ORTEC 974 Counter/Timer.
Nuclear Science and Techniques, Vol. 20, (October 2009), pp. 307-311, ISSN 1001-8042
Yang, H., Wehe, D.K. & Bartels, D.M. (2009). Spectroscopy of high rate events during active
interrogation. Nuclear Instruments and Methods in Physics Research A, Vol. 598,
(October 2008), pp. 779-787, ISSN 0168-9002
Part 2

Hardware in the Loop Simulation


0
5

Real-Time Rapid Embedded Power System


Control Prototyping Simulation Test-Bed Using
LabVIEW and RTDS
Karen Butler-Purry and Hung-Ming Chou
Texas A&M University
United States of America

1. Introduction
When developing new control, protection, and stability methods for power systems, it is
important to study the complex interactions of the system dynamics with the real-time
operation of the new methods. Historically hardware prototypes were developed to study
these interactions. With the recent introduction of the much cheaper rapid hardware and
software prototyping tools, developers are choosing instead to use these tools to study
dynamic interactions during real-time operation. This technology provides a cost effective
option and flexibility in modeling and coding which allows use for versatile applications.
Rapid prototyping technology is being widely used in many application areas for real-time
data analysis and control such as avionics, power, acoustics, mechatronics, and automotive
applications (Keunsoo et al., 2005; Postolache et al., 2006; Spinozzi, 2006; Toscher et al., 2006).
Parallel digital signal processors (DSPs) (French et al., 1998; Lavoie et al., 1995) are also being
used as rapid prototyping technology for real-time simulation and control.
To study real-time dynamic interactions of isolated power systems and control methods, a
test bed is developed that uses rapid prototyping technology. This chapter discusses the
real-time test bed which was developed more generally to study real-time issues, and validate
and verify new designs of centralized and de-centralized control, protection, and wide-area
monitoring methodologies for stand alone power systems, such as naval shipboard power
systems, power transmission and distribution system and microgrids.
The National Instruments Compact RIO (NI CompactRIO, 2011)low cost reconfigurable control
and acquisition system is used to implement the new control and protection methods in the
test bed. The NI CompactRIO embedded system contains the NI reconfigurable technology
and a real-time controller with an embedded (Pentium) floating-point processor. The 8-slot
reconfigurable chassis contains an embedded user-programmable FPGA (field programmable
gate array) chip providing direct access to hot swappable input/output (I/O) modules for
precise control and flexibility in timing, triggering, and synchronization. The I/O modules
contain built-in signal conditioning and isolation. The control and protection methods
are implemented using the LabVIEW RT and FPGA Modules on a Host PC. The code is
downloaded to the cRIO controller and FPGA for execution. LabVIEW Virtual Instruments
(VIs) are used to remotely monitor and control (if desired) the RT Power System and
Controller simulation. National Instruments data acquisition cards and hot swappable input
and output analog and digital modules are used to pass signals between the cRIO controller
84
2 Practical Applications and Solutions Using LabVIEW™ Software
Will-be-set-by-IN-TECH

and the real time power system simulation. The inputs and outputs of the NI I/O modules
were mapped in VIs. Further data acquisition settings for the I/O modules such as the number
of channels, data type, sampling rate, and data buffer length were programmed in VIs.
The power systems are modeled using RSCAD software for a real time digital simulator
(RTDS®) (Real Time Digital Simlator - RTDS, 2011) which is a unique integration of hardware
and software specifically designed to perform electromagnetic transient simulation (EMTP) of 
AC and DC power systems with external hardware in the simulation loop. Based on its unique
architecture, it is equally suitable for simulating large transmission and distribution systems
or tightly coupled power systems such as ship systems, locomotives, airplanes, automobiles,
and micro grids. The RTDS simulator architecture exploits the parallel computation nature
of the mathematical model of large power systems using proprietary parallel processing
hardware. The RSCAD run-time interface of the RTDS is interactive and is used to view
the simulation results and provide user inputs while the simulation is in progress. RTDS
is a modular system consisting of racks that are paralleled. Each rack consists of several
processing cards which can be customized to provide the computational power of a specific
power system problem. These racks can be used to run simultaneous simulations of multiple
smaller systems or large simulations requiring multiple racks. RTDS provides high precision
(16 bit) real-time input/output (I/O) interfaces of both analog and digital signals to interface
with the external instrumentation in the simulation loop.
The implementation of an overcurrent relay protection scheme is discussed in this chapter to
illustrate the operation of the test bed. A two-bus power system which has a generator at one
 bus, a load at the other bus, and a transmission line between them, is simulated on the RTDS.
The overcurrent relay is implemented on the RT processor and FPGA. Measurements of the
current flowing through the cable and the node voltages are measured. Further the results of 
several case studies are discussed.
This book chapter will focus on the concept of real-time rapid embedded control prototyping
simulation and its implementation using LabVIEW. Section two will describe RTDS and cRIO
as well as the proposed methodology for implementation of embedded controller-in-the-loop
simulation. Section three will present the detailed implementation of the overcurrent relay
case study, including the programs in RTDS and in cRIO. Also, a synchronization technique
to synchronize the RTDS with the cRIO in real-time operation will be discussed. In section
four, simulation results will be described. Lastly, the conclusions and some future work will
 be presented.

2. Real-Time Rapid Embedded Power System Control Prototyping Simulation Test


Bed
There are two main components in the Real-Time Embedded Power System Control Rapid
Prototyping Simulation Test Bed. One component uses the National Instruments CompactRIO
(cRIO) Embedded Design Platform that allows users to rapidly build embedded control or
acquisition systems. The other component uses the RTDS real-time digital simulator which
allows real-time simulation of power systems and hardware-in-the-loop (HIL) studies with
controllers, protective relays, and power system components. Figure 1 shows a high-level
system diagram for the Real-Time Embedded Rapid Prototyping Simulation Test Bed which
is used to test new embedded power system control and protection methods. Test power
systems are implemented in the RTDS and new controller designs are implemented in the
cRIO.
Real-Time Rapid Embedded Power System Control
Prototyping Simulation
Real-Time Rapid Embedded Test-Bed
Power System UsingSimulation
Control Prototyping LabVIEWTest-Bedand
Using RTDS
LabVIEW and RTDS 85
3

Fig. 1. System Diagram for the Real-Time Rapid Power System Control Prototyping
Simulation Test Bed
The test bed is designed based on hardware-in-the-loop (HIL) simulation theory.
Hardware-in-the-loop simulation is an approach that is used during the development and
testing of complex real-time embedded controller. HIL simulation provides an effective
platform by adding the complexity of the plant under control to the test platform. The
embedded controller under test interacts with a plant simulation that is a mathematical
representation of all related dynamic systems of the plant. HIL simulation includes electrical
emulation of sensors and actuators which act as the interface between the plant simulation
and the embedded controller under test. The value of each electrically emulated sensor
is controlled by the plant simulation and is read by the embedded controller under test.
Likewise, this embedded controller outputs actuator control signals based on its control
algorithm. Changes in the control signals result in changes to variable values in the plant
simulation.
There are several advantages of HIL (Isermann et al., 1999), including
• Designing and testing of the control hardware and software without the need to operate a
real process.
• Testing of the effects of faults and failures of system.
• Operating and testing of extreme and dangerous operating conditions.
• Reproducible experiments, frequently repeatable.
• Saving of cost and development time.
For example, HIL simulation can be utilized during the validation of flight controllers
(Karpenko & Sepehri, 2006). During the development of flight controllers, their functionality
must be tested. The most realistic way is to put the flight controllers in an actual aircraft.
In this setting, due to safety and cost issues, the extremely dangerous scenarios cannot be
performed, such as engine failure and stalling. However, in HIL simulation, the actual aircraft
can be modeled in a real-time simulator and the flight controllers can directly interact with
the simulation in real-time. During HIL simulation, all possible scenarios can be performed
to test the functionality of the flight controllers without worrying about safety and cost issues.
Therefore, a primary benefit of HIL simulation is that by the time the controllers first operate
Real-Time Rapid Embedded Power System Control
Prototyping Simulation
Real-Time Rapid Embedded Test-Bed
Power System UsingSimulation
Control Prototyping LabVIEWTest-Bedand
Using RTDS
LabVIEW and RTDS 97
15

3.2.1.4 Write RMS value into FIFO (Step A4 in Figure 9)


As mentioned before, the speed of FPGA is much faster than that of RT processor. In this case,
the loop rate of FPGA is 50 us while the loop rate of RT processor is 5 ms. In order to transfer
data (RMS of current value) from FPGA to RT processor without losing data, another FIFO is
used. FPGA will put one current RMS value into the FIFO every 50 us, while the RT processor
will retrieve data from the FIFO every 5 ms. The number of data that the RT processor takes
each time is 100 [= (5ms )/(50us )] .
The function of this FIFO is different from that of FIFO_RMS. FIFO_RMS is used to store one
period of current values to calculate the RMS value of current measurements, while this FIFO
is used as a buffer between the FPGA and the RT processor due to their different execution
speeds. Since there are three RMS values of three-phase current value, three FIFOs are used.
To allocate these FIFOs, go to the "Project Explorer", right click on "FPGA Target", select
"New"-> "FIFO". Then the properties of FIFO are set: "Target-to-Host DMA" is used and
the depth is 255, which is the number of elements of FIFO in FPGA part. ( The number of 
elements of FIFO in RT processor is set in RT program, which will be discussed later in this
 book chapter) DMA is the abbreviation of Direct Memory Access, which transfers data from
the FPGA directly to the memory on the RT processor. A DMA-FIFO consists of two parts, an
FPGA part and RT processor part. LabVIEW uses a DMA engine to connect these two parts.
When the DMA engine runs, it transfers data between the two parts of the FIFO automatically
so they act as one FIFO array. For more information on DMA-FIFO, please refer to Lesson 8,
Section F in (NI, 2004). After the DMA-FIFO is set, the value to be passed into RT processor
can be written into DMA-FIFO by using FIFO Write function.
3.2.1.5 Set up the direction of digital I/O module (Step B1 in Figure 9)
Because the channels in the digital I/O module (NI 9401 or NI 9403) can be set as either input
or output, the input and output channels must be specified.
3.2.1.6 Update the value of digital I/O module (Step B2 in Figure 9)
A while-loop is used to update the value of the digital I/O module. Controllers (DO0, DO1,
DO2, DO3) are connected to the output ports of the digital I/O module while indicators (DI4,
DI5, DI6, DI7) are connected to the input ports of the digital I/O module.
To be able to run this FPGA VI, this VI needs to be compiled into FPGA code. For detailed
information of FPGA compilation, please refer to Lesson 4, Section I in (NI, 2004). To start the
execution of this VI, you can hit the RUN button in the LabVIEW window; however in this
project, the VI in the RT processor controls the execution of this FPGA VI, including start, stop
as well as parameter settings, such as loop rate and scaling factor.

3.2.2 RT processor
There are two functions implemented in RT processor. One function is overcurrent relay logic,
shown on the left side of Figure 12. The other function is user interface and parameter settings
via front panel communication, shown on the right side of Figure 12. The first function is in
the time-critical loop while the second function is in a non-time-critical loop. The reason we
separate the VI into two timed-loops is to prioritize these two different functions.
98
16 Practical Applications and Solutions Using LabVIEW™ Software
Will-be-set-by-IN-TECH

Fig. 12. Flowchart of RT processor VI, , shown in Figure 13


Real-Time Rapid Embedded Power System Control
Prototyping Simulation
Real-Time Rapid Embedded Test-Bed
Power System UsingSimulation
Control Prototyping LabVIEWTest-Bedand
Using RTDS
LabVIEW and RTDS 99
17

(a) Time-critical loop (b) Non-time-critical loop

Fig. 13. VI in the RT processor


100
18 Practical Applications and Solutions Using LabVIEW™ Software
Will-be-set-by-IN-TECH

It is possible to put the above two functions in the same timed-loop. However, since
front-panel communication takes care of the user interface, such as displaying value in the
host-PC screen and sending control value from host-PC to cRIO, it takes time to execute. More
importantly, the time it takes is not deterministic. Therefore, to make the over-current relay
logic deterministic, two timed-loops with different priorities are used. The time-critical loop
with higher priority includes the over-current relay logic while the non-time-critical loop with
lower priority includes user interface and parameter settings. Therefore, the RT processor
resource will be given to the time-critical loop whenever this time-critical loop needs the
resource. Only when time-critical loop doesn’t need the resource, will the non-time-critical
loop use the resource. In this way, the program implemented in the time-critical loop can be
ensured to run deterministically. For more information about the concept of time-critical loop,
please refer to Lesson 3 in (NI, 2009) .
Figure 13 shows the VI implemented in the RT processor. Part(a) is the program that includes
the initialization and the time-critical loop while part(b) includes the non-time-critical loop.
3.2.2.1 Select FPGA program (Step A1 in Figure 12)
Figure 14(a) shows the program that selects the desired FPGA VI to be executed. The selected
file is a FGPA bitfile, which is generated after the FPGA VI is compiled.

Fig. 14. (a)Select FPGA program, (b)set the parameters of FPGA VI

3.2.2.2 Set the parameters of FPGA program (Step A2 in Figure 12)


Some parameters of the FPGA VI, including the loop rate of FPGA and the scaling factor, are
set by the program shown in Figure 14(b). Therefore, users can use the front panel to set these
parameters of FPGA VI.
3.2.2.3 Start the FPGA program (Step A3 in Figure 12)
Figure 15(a) shows the program that starts the FPGA VI execution.

Fig. 15. (a)Run FPGA program, (b)set the FIFO size on target side
Real-Time Rapid Embedded Power System Control
Prototyping Simulation
Real-Time Rapid Embedded Test-Bed
Power System UsingSimulation
Control Prototyping LabVIEWTest-Bedand
Using RTDS
LabVIEW and RTDS 101
19

3.2.2.4 Set the size of DMA-FIFO on target side (Step A4 in Figure 12)
As mentioned, there are two parts of DMA-FIFO. One is in the FPGA and the other is in the
RT processor. The size of DMA-FIFO in the FPGA is set in the FPGA program while the size of 
DMA-FIFO in the RT processor is set by using the function shown in Figure 15(b). If the size
of DMA-FIFO in RT processor side is not specified, then the system will automatically set the
size to be twice the size of the DMA-FIFO in the FPGA. Care must be made when determining
the size of DMA-FIFO. If the size is too small, the DMA-FIFO tends to be full and data cannot
 be written into the DMA-FIFO. If the size is too big, it will waste memory space.
3.2.2.5 Waiting for the rising edge of the triggering signal (Step A5 in Figure 12)
Since the clock rates of RTDS and cRIO are different, there should be some mechanism such
that the program in RTDS and the program in cRIO do not run out of step. In other words,
there needs to be something used to make the two programs proceed together in time.
Using real-time programming concept, the time-critical loop can run in real-time and
deterministically. So why do we need to use triggering signal? Because even if we can run the
program in the RT processor deterministically, say it runs every 5 ms, it is still possible that in
the time frame of RTDS, the program in RT processor runs every 5.001 ms. This is because the
accuracy of clock rate of cRIO and RTDS are not exactly the same. Even though the difference
is very small, in some applications, this difference may accumulate to cause some problems.
Since RTDS is running in real time, the difference will accumulate quickly. Further discussion
of triggering signal will be given in the last part of this section.
Figure 16(a) shows the rising edge detection. If the rising edge of the triggering signal is not
detected, the program will stay in this while loop. When the rising edge of the triggering
signal is detected, the program will leave the while loop and go to the next stage.

Fig. 16. (a)Rising edge detection of triggering signal, (b)output the breaker control signals

3.2.2.6 Output the breaker signal to FPGA (Step A6 in Figure 12)


Figure 16(b) shows that the breaker control signal is output to the digital output channel DO0,
DO1 and DO2. This signal is based on the result of the previous iteration which is 5 ms ago,
the loop rate of RT program.
3.2.2.7 Retrieve RMS data from DMA-FIFO(Step A7 in Figure 12)
Figure 17 shows the program of retrieving data (RMS of current value) from the DMA-FIFO.
Since the execution speed of RT processor is much slower than that of the FPGA (the loop
rate of RT processor is 5 ms while the loop rate of FPGA is 50 us), to prevent this DMA-FIFO
from overflowing, the program in RT processor should retrieve all data in the DMA-FIFO each
time.
102
20 Practical Applications and Solutions Using LabVIEW™ Software
Will-be-set-by-IN-TECH

There are two steps to retrieve all data in the DMA-FIFO. First, the left function block in the
Figure 17(a) gets the number of elements in the DMA-FIFO and passes this number to the
"Number of Elements" of the right function block. The right function block reads "Number of 
Elements" number of data from DMA-FIFO and transfers it to "Data" as an array. Since the
data from DMA-FIFO is an array and only the latest data(N  × RMS2 )is needed, a for-loop
without the N value specified as shown in Figure 17(b) was used.

Fig. 17. (a)Retrieve data block in FIFO, (b)get the last element of data block

3.2.2.8 Implement relay logic (Step A8 in Figure 12)


Figure 18 shows the implementation of the overcurrent relay logic, which updates the breaker
signal. The retrieved N  × RMS2 value is compared with the threshold (pickup) value. Since
the retrieved data is N × RMS2 , the threshold value is also in the same format. In this example,
the threshold current is 0.1 kA, so based on the scaling factor of RTDS, the output voltage is 0.5
V. Since the scaling factor of cRIO is 200 and N is 334., the threshold value is 3,340,000, which
is equal to 334 × (200 × 0.5)2 . If the retrieved N  × RMS2 value is higher than the threshold
value, the breaker signal will be equal to one (open value). Otherwise, the breaker signal will
 be zero (closed value). Note that this breaker signal is updated, but is not output to the digital
output module via FPGA. The new breaker signal is output in the step A6 of next iteration of 
the time-critical loop.

Fig. 18. Comparison with threshold value

3.2.2.9 Implementation in non-time-critical loop (Step B1 in Figure 12)


Below are the tasks for non-time-critical loop:
1. Send the settings of VI from the host PC to the RT processor via front panel communication,
including threshold value, period of time-critical loop, and loop rate of time-critical-loop.
2. Send the results of VI to the host PC, including breaker status, time duration of time-critical
loop, RMS value of current, number of FIFO elements.
3. Convert ( N  × V RMS )2 to actual RMS value of current value.
Real-Time Rapid Embedded Power System Control
Prototyping Simulation
Real-Time Rapid Embedded Test-Bed
Power System UsingSimulation
Control Prototyping LabVIEWTest-Bedand
Using RTDS
LabVIEW and RTDS 103
21

3.2.2.10 Communication between time-critical and non-time critical loops


The signal passing between the time-critical loop and the non-time-critical loop is done via
"Shared Variable". The type of this shared variable is set to be "Single-Process", since these
two timed-loops are in the same single process.
Since the period of these two timed-loops is different, like the situation where there is FPGA
and RT processor, to pass data without loss, FIFO mechanism should be used. Since we just
care about the newest data, then FIFO with "single element" is used. To pass multiple data
lossless, the FIFO with "multi-element" is used and the number of elements of this FIFO is
 based on the loop rate of these two timed loops. These settings are done in the "Properties
Dialog" of shared variables.
3.2.2.11 How to measure the timing of signal (Step T1, T2 in Figure 12)
cRIO and RTDS execute in real time, so it is impossible to store all the simulation results,
making it difficult to debug the program. To check whether the program is executed as
expected, especially the timing of the program, we can take advantage of the digital output
module of the cRIO as well as the RTDS plotting function.
Figure 19 shows one block of program in the RT processor. This block of program
complements the digital output channel DO1 when it is executed. We can place this program
around the place of which we want to check the timing. In this VI, we complement DO2
in the beginning of the time-critical loop and complement DO3 when the rising edge of the
triggering signal is detected.
To measure these timing signals from the digital output module of the cRIO, we can use
oscilloscopes that have limited numbers of channels. Another way is to use RTDS that can
plot signals from its digital input module. In this way, we can overlay these numerous timing
signals in the same plot and check the timing of the RT program. Moreover, it is possible to
store a portion of data points in the plot of RTDS. RTDS greatly facilitates the investigation of 
these timing signals.

Fig. 19. Complement the digital output when executed

3.3 Discussion of synchronization of RTDS and cRIO


The benefit of outputting the breaker control signals at the rising edge of the triggering signal
is that only at the rising edge of the triggering signal can the breaker control signals be output.
The breaker control signal cannot be output at other times.
Even though there are some benefits of implementing this synchronization technique, there
are some disadvantages. Since each iteration of the time-critical loop in RT processor needs to
wait for the rising edge of the triggering signal, it slows down the response of the embedded
controller. This amount of the time delay varies, depending on the phase difference between
the triggering signal and the time-critical loop. It also depends on the frequency of the
triggering signal. If this frequency is low, the time-critical loop will take longer time to wait
104
22 Practical Applications and Solutions Using LabVIEW™ Software
Will-be-set-by-IN-TECH

for the rising edge of triggering signal. However, if the frequency is too high, then EMI issues
will occur. Therefore, the frequency of the triggering signal needs to be selected carefully. In
this case study, 1 kHz is selected.
However, if this small time difference is acceptable and doesn’t cause any problems for the
application, it is not necessary to implement this synchronization technique. This embedded
controller will have quicker response.

4. Case studies
In these case studies, a three-phase ground fault was applied at the end of the transmission
line as shown in Figure 20. When this fault occurs, the value of the phase currents i a (t),  i b (t)
and i c (t), and corresponding RMS values increase. As soon as the RMS value was larger than
the pickup value of the overcurrent relay, the overcurrent relay would open the breaker to
protect the system.

Fig. 20. One-line diagram of system with three-phase ground fault


The loop rate of FPGA was selected to be 50 us, which was the same as the time step in RTDS.
The loop rate of the RT processor was selected to be as fast as possible, while at the same
time permitting the time-critical loop to run deterministically. Therefore, this loop rate would
depend on the computing power of RT processor as well as the complexity of the RT processor
VI. In these case studies, three cases where the period of the RMS calculation window was half 
cycle, one cycle and two cycle, respectively, were compared. For the half cycle, a period is 8.33
ms, for one cycle, a period is 16.66 ms and for two cycle, a period is 33.33 ms. For the half-cycle
and one-cycle case, the loop rate of RT processor was 5 ms while for the two-cycle case, the
loop rate was 10 ms. This was because in the two-cycle case, the amount of data was larger,
requiring more time for RT processor to execute.
The first case study was a modified ride-along mode. The overcurrent relay was implemented
in the RTDS and the cRIO. The purpose of ride-along mode is to compare breaker control
signals from each overcurrent relays program and see if they are equivalent for determining
the accuracy of the implementation.
To ensure that both overcurrent relays observed the same dynamics, the breakers in the
RTDS were always closed even when the fault was applied, which was a modified version
of the ride-along mode shown in Figure 6. This was done because if one of the overcurrent
relays responded first and opened the breaker, the current would decrease, making the
other slower overcurrent relay unable to detect the fault. Therefore the breaker signals from
this slower overcurrent relay remained closed. The comparison between these two breaker
signals would not be right, invalidating the results of ride-along simulation. Therefore, a
modified-ride-along mode was used, where the control signals from RTDS and cRIO were not
used to control the breaker in RTDS. The breakers were always closed in these studies.
Figure 21 shows the response around the time when the fault was applied. Table 5 summarizes
three cases where the window size of RMS calculation were different. The time difference
Real-Time Rapid Embedded Power System Control
Prototyping Simulation
Real-Time Rapid Embedded Test-Bed
Power System UsingSimulation
Control Prototyping LabVIEWTest-Bedand
Using RTDS
LabVIEW and RTDS 105
23

 between the breaker signals from RTDS and cRIO was a little more than the loop rate of the
RT processor. The loop rate was 5 ms for half cycle and one cycle windows while the loop rate
was 10 ms for two cycle window. This was because when the window size of RMS calculation
is two cycles, the number of elements in FIFO_RMS were twice the size of one cycle case,
requiring more time to retrieve the data for cRIO computation. Therefore, the loop rate of RT
processor had to be increased to ensure deterministic operation.
Another observation was that when the RMS calculation window was smaller, the time
difference between fault and breaker signal was smaller since the RMS calculation was more
sensitive if its calculation window was small.

Fig. 21. Response in modified-ride-along mode to a fault scenario


  
  
  
RMS window size
0.5 cycle 1 cycle 2 cycle
  
  
  

Signals   
  
  
  
  

Fault and BRK_RTDS 0.0043 sec 0.0051 sec 0.0053 sec


Falut and BRK_cRIO 0.0104 sec 0.0102 sec 0.0159 sec
BRK_RTDS and BRK_cRIO 0.0060 sec 0.0051 sec 0.0106 sec
Table 5. Time difference among signals for three RMS calculation window in
modified-ride-along mode
The second set of case studies was CIL mode. The overcurrent relay implemented in RTDS
was disabled and the breaker signals from cRIO controlled the breakers implemented in RTDS.
Figure 22 shows the waveform around the time when a three-phase ground fault was applied.
It can be observed that the breaker signals from cRIO successfully opened the breakers after
the fault occurred. The time difference between the fault occurrence and the opening of the
106
24 Practical Applications and Solutions Using LabVIEW™ Software
Will-be-set-by-IN-TECH

 breaker was approximately 10 ms in each phase which was two times the loop rate of RT
processor. Like the first set of case studies, if the window size of RMS calculation was smaller,
it took less time to open the breaker after fault was applied, which is shown in Table 6.

Fig. 22. Response in CIL mode to a fault scenario


  
  
  
RMS window size
  
  
   0.5 cycle 1 cycle 2 cycle
Signals   
  
  
  
  

Fault and BRK 0.01034 sec 0.0111 sec 0.016 sec


Table 6. Time difference among signals for three RMS calculation window in CIL
The results of a timing analysis of the measured signals from the modified-ride-along mode
simulation are shown in Figure 23. Since the breaker signal (BRK_RTDS) from the overcurrent
relay in RTDS is updated when the time-critical loop starts (when DO2 changes its polarity),
the difference between the fault signal and BRK_RTDS is T 1 . The breaker control signal from
the overcurrent relay in cRIO (BRK_cRIO) is updated when there is a rising edge during
the execution of time-critical loop (when DO3 changes its polarity), therefore the difference
 between the fault signal and BRK_cRIO is T 1  +  T 2 . Sometimes it may take an extra loop
iteration for the RMS value to be greater than the pickup value, so the difference maybe
T 1  +  T 2  +  T 3 , where T 3  is close to T RT . Therefore, the time difference between BRK_RTDS
and BRK_cRIO is T 2 +  T 3 .The range of  T 1  is between 0 and  T RT , range of  T 2  is between 0 and
to T tri  and the range of  T 3  is between 0 and T RT , where T RT  is the loop rate of the time-critical
loop in RT processor and T tri  is the period of the triggering signal.
Real-Time Rapid Embedded Power System Control
Prototyping Simulation
Real-Time Rapid Embedded Test-Bed
Power System UsingSimulation
Control Prototyping LabVIEWTest-Bedand
Using RTDS
LabVIEW and RTDS 107
25

Fig. 23. Time analysis of simulation results in Figure 21

5. Conclusions and future work


In this book chapter, the concepts and the implementation of a real-time rapid embedded
power system control prototyping simulation test bed were described. The methodologies
for implementing embedded controller-in-the-loop simulation (CIL) was explained. To
illustrate the functionality of the test bed, the detailed implementation of an overcurrent relay
protection scheme for CIL simulation was described, including the settings and programming
of RTDS, the programming in cRIO, which included the FPGA and RT processor, by using
LabVIEW. Also, a synchronization approach for the RTDS and cRIO was discussed.
Additional studies are ongoing to refine the test bed design, such as studies to investigate the
time delay and data synchronization and its relationship to system performance and stability.
For example, in a power system, to be transient stable, a fault has to be cleared within a specific
amount of time. If the response of the breaker is too late or incorrect, the system will become
unstable.
Further the test bed is being utilized to study new control strategies and their performance.
In power system applications, voltage regulation and load management are used to maintain
the proper operation of power systems. These control strategies can be verified and validated
using the test bed discussed in this chapter. Due to the real-time environment of RTDS and
RT target, it is possible to observe the effectiveness of these control strategies in the real-time
simulation environment.
108
26 Practical Applications and Solutions Using LabVIEW™ Software
Will-be-set-by-IN-TECH

6. Acknowledgment
The authors gratefully acknowledge the contributions of Tania Okotie and the funding
from Office of Naval Research under grants N00014-09-1-0579, N0014-04-1-0404, and
N00014-07-1-0939.

7. References
French, C. D., Finch, J. W. & Acarnley, P. P. (1998). Rapid prototyping of a real time dsp
 based motor drive controller using simulink, Simulation, International Conference on,
pp. 284–291.
Isermann, R., Schaffnit, J. & Sinsel, S. (1999). Hardware-in-the-loop simulation for the design
and testing of engine-control systems,  Control Engineering Practice pp. 643–653.
 J. Duncan Glover, Mulukutla S. Sarma, T. O. (2007).  Power System Analysis and Design , 4 edn,
CL-Engineering.
Karpenko, M. & Sepehri, N. (2006). Hardware-in-the-loop simulator for research on
fault tolerant control of electrohydraulic flight control systems,   American Control
Conference, p. 7.
Keunsoo, H., Seok-Gyu, O., MacCleery, B. & Krishnan, R. (2005). An automated reconfigurable
fpga-based magnetic characterization of switched reluctance machines,   Industrial
Electronics, Proceedings of the IEEE International Symposium on, pp. 839–844.
Lavoie, M., QuÃl’-Do, V., Houle, J. L. & Davidson, J. (1995). Real-time simulation of power
system stability using parallel digital signal processors, Mathematics and Computers in
Simulation pp. 283–292.
Ledin, J. (2001).  Simulation Engineering, CMP Books, Lawrence, USA.
NI (2004).  CompactRIO and LabVIEW Development Fundamentals.
NI (2009).  LabVIEW Real-Time Application Development Course Manual.
NI CompactRIO (2011). Available at:   http://www.ni.com/compactrio/ .
Postolache, O., Dias Pereira, J. M. & Silva Girao, P. (2006). Real-time sensing channel modelling
 based on an fpga and real-time controller, Instrumentation and Measurement Technology
Conference, Proceedings of the IEEE on, pp. 557–562.
Real Time Digital Simlator - RTDS (2011). Available at:   http://www.rtds.com/ .
Spinozzi, J. (2006). A suite of national instruments tools for risk-free control system
development of a hybrid-electric vehicle, American Control Conference, 2006 p. 5.
Toscher, S., Kasper, R. & Reinemann, T. (2006). Implementation of a reconfigurable hard
real-time control system for mechatronic and automotive applications,  Parallel and
Distributed Processing Symposium, IPDPS 20th International p. 4.
6

The Development of a Hardware-in-the-Loop


Simulation System for Unmanned Aerial Vehicle
Autopilot Design Using LabVIEW
Yun-Ping Sun
Department of Mechanical Engineering, Cheng Shiu University,
Taiwan

1. Introduction
This chapter describes a continuing research on design and verification of the autopilot system
for an unmanned aerial vehicle (UAV) through hardware-in-the-loop (HIL) simulation. UAVs
have the characteristics of small volume, light weight, low cost in manufacture, high agility
and high maneuverability without the restriction of human body physical loading. Equipped
with the on-board autopilot system an UAV is capable of performing out-of-sight missions
that inspires scientists and engineers with a lot of innovative applications. Not only in the
military but also in the civil, the applications of UAVs are in full bloom. Apparently one of the
key challenge of UAV research and development is its autopilot system design.
For the purpose of designing an autopilot, the technology of hardware-in-the-loop simulation
plays an important role. The concept of HIL simulation is that a stand-alone personal
computer is used to simulate the behavior of the plant, several data-acquisition devices are
exploited to generate the real signals, and the prototype controller can be tested in real-time
and in the presence of real hardware. HIL simulation presents a new challenge of control
engineering developers as the “correctness” of a real-time model not only depends upon the
numerical computation, but the timelines with which the simulation model interacts with
external control equipment that is the major difference between HIL simulation and numerical
simulation. Due to the useful feature, HIL simulation is applicable to solve many problems in
engineering and sciences effectively (Shetty & Kolk, 1997; Ledin, 2001).
HIL simulation provides an effective technique for design and test of autopilot systems.
Using HIL simulation the hardware and software at subsystem level perform the actual
input/output signals and run at real time so that the test target (e.g. prototype controller) is
working as if in real process. This provides the ability to thoroughly test subsystems under
different working loads and conditions; therefore, engineers can correct and improve their
original designs early in the development process. The advantages of HIL simulation are
reducing the risk in test and shortening the development time. Especially HIL simulation is
suitable for critical or hazardous applications.
(Cosic et al., 1999) used TMS320C40 DSP to set up a HIL simulation platform for a semi-
automatic guided missile system. (Carrijo et al., 2002) applied HIL simulation to test the on-
board computer on a satellite launcher vehicle for motion and attitude control. (Sun et al.,
2006; Sun et al., 2008a; Sun et al., 2009; Sun et al., 2010) developed the HIL simulation system
to evaluate the performance of UAV autopilot that was employed different control laws.
110 Practical Applications and Solutions Using LabVIEW™ Software

Some valuable applications in traffic control (Bullock et al., 2004) and UAV design (Cole et
al., 2006; Salman et al., 2006) using HIL simulation can be found.
The hardware arrangement of HIL simulation includes a personal computer used to
simulate the behavior of an UAV plant, several plug-in data-acquisition (DAQ) devices used
to acquire/generate the specific real input/output signals, and the embedded control
system used to execute the control laws and send control signals to real hardware.
The software development environment for HIL simulation in this work is LabVIEW.
LabVIEW is a graphical programming language widely adopted throughout industry and
academia as a standard for data acquisition and instrument control software. LabVIEW
provides an intuitive graphical programming style to create programs in a pictorial form
called a block diagram that allows users to focus on flow of data within applications and
makes programming easy and efficiency. Additionally, LabVIEW can command plug-in
DAQ devices to acquire or generate analog/digital signals. In combination of LabVIEW and
DAQ devices, a PC-based or embedded control system can communicate with the outside
real world, e.g., take measurements, talk to an instrument, send data to another subsystem.
These features are very helpful in building a HIL simulation system for UAV autopilot
design. As a matter of fact, LabVIEW is not the only software development environment for
HIL simulation, but based on the enumerated advantages it is certainly a nice choice.
In this chapter we are going to apply different control methods to accomplish the design of
UAV autopilot, and compare their results in HIL simulations using LabVIEW. The chapter is
organized as follows. Section 2 describes the dynamic model of an UAV. Section 3 outlines
the HIL simulation system architecture and introduces hardware and software development
environment LabVIEW. Section 4 focuses on stability augmentation system design. Section 5
focuses on autopilot system design including pitch attitude hold mode, velocity hold mode,
roll attitude hold mode and heading angle hold mode. Section 6 concludes this chapter.

2. Dynamics model of an UAV


The MP2000UAV (Fig. 1) is a low-cost and small-volume unmanned aerial vehicle (UAV).
Its physical properties are wingspan 1.75 m, length 1.4 m, wing area 0.5116 m2, wing chord
0.29 m, and weight 3.84 kg. MP2000UAV equipped with a 40 in3, 1 HP, 2 cycle glow engine
and a miniature autopilot is capable to carry out autonomous operations.

Fig. 1. Unmanned aerial vehicle MP2000UAV


The Development of a Hardware-in-the-Loop
Hardware-in-the-Loop Simulation System for
Unmanned Aerial Vehicle Autopilot Design Using LabVIEW 113

X u X w X δ e X δ th Zu Zw Zδ e Zδ th  M u


-6.114 0.789 -0.273 2.936 8.952 -9.220 3.919 143.24 1.275
 M w  M q  M δ e  M δ th Yv Y p Y r  Y δ r  Lv
-1.291 -1.366 -1.699 -64.192 -0.374 -5.113 0.764 -1.264 -2.136
L p Lr  Lδ a Lδ r  N v N  p N r  N δ a N δ r 
-2.656 -5.414 0.967 5.974 0.584 1.250 1.307 -0.191 -4.969
Table 1. Estimation results of dimensional stability derivatives
derivatives
As a result, for the unmanned aerial vehicle MP2000UAV, the longitudinal equations of
motion in state-space form are:

⎡ u ⎤ ⎡ -6.113 0.7889 0 -9.8 ⎤ ⎡ u ⎤ ⎡ -0.273 2 . 9 36 1 ⎤


⎢w ⎥ ⎢ ⎥⎢ ⎥ ⎢ ⎥

⎢ ⎥ = ⎢ 8.952 -9.220 16 0 ⎥ ⎢ w ⎥ ⎢ 3.9191 143.24 ⎥ ⎡ δ e ⎤
  (5)
⎢ q ⎥ ⎢1.2746 -1.290 -1.3656 0 ⎥ ⎢ q ⎥ + ⎢ -1.699 -64.192 ⎥ ⎢⎣δ th ⎥⎦
⎢ ⎥ ⎢ ⎥⎢ ⎥ ⎢ ⎥
⎢⎣ θ ⎥⎦ ⎢⎣ 0 0 1 0 ⎦⎥ ⎢⎣ θ ⎥⎦ ⎢⎣ 0 0 ⎥⎦

and the lateral equations of motion in state-space form are:

⎡ v ⎤ ⎡ −0.373 − 5.113 − 15.236 9.8⎤ ⎡ v⎤ ⎡ 0 − 1.2636⎤


⎢ p ⎥ ⎢ ⎥ ⎢ ⎥ ⎢ ⎥
⎢ ⎥ = ⎢ −2.135 −2.6564 − 5.4143 0 ⎥ ⎢ p⎥ + ⎢ 0.9666 5.9744 ⎥ ⎡δ a ⎤   (6)
⎢ r 
 ⎥ ⎢ 0 .5 8 3 7 1 .2 4 9 7 1.3069 0 ⎥ ⎢ r ⎥ ⎢ − 0.191 − 4.9689⎥ ⎢⎣δ r ⎥⎦
⎢ ⎥ ⎢ ⎥⎢ ⎥ ⎢ ⎥
⎢⎣φ ⎥⎦ ⎣⎢ 0 1 0 0 ⎦⎥ ⎣⎢φ ⎦⎥ ⎣⎢ 0 0 ⎦⎥

where the maximum deflection angles of elevator, aileron, and rudder are ±15°, ±6°,
and ±10°.

3. HIL simulation system


Hardware-in-the-Loop (HIL) simulation is a kind of real-time simulation that the input and
output signals shows the same time dependent values as the real process. It is usually used
in a laboratory environment on the ground to test the prototype controller under different
working loads and conditions conveniently and safely. Compared with numerical
simulation, HIL simulation is more reliable and credible because numerical simulation is
often operated in ideal circumstances, without considering noise, disturbance, and some
practical problems often ignored which might result in fatal failure. HIL simulation has the
advantages of reducing the risk, shortening the developing time, and being well suitable for
critical and hazardous applications.
The concept of HIL simulation is described by Fig. 3. A typical HIL simulation system for
UAV autopilot design is composed of a stand-alone embedded real-time control system, a
personal computer, a servo unit, and a host PC. The hardware arrangement of HIL
simulation system is shown in Fig. 4. The graphical programming language LabVIEW is the
software development environment for data acquisition (DAQ) and instrument control in
performing HIL simulation.
114 Practical Applications and Solutions Using LabVIEW™ Software

3.1 Embedded real-time control system (prototype controller)


The prototype controller is implemented by the National Instruments (NI) PXI real-time
embedded control system which includes:
Real-time Controller NI PXI-8184 RT: It is a stand-alone embedded real-time control
system. This system real-time computes the control output according to the implemented
control law and the error between command signal and feedback signal from sensor.
Multifunction DAQ device NI PXI-6259: It takes the responsibility on (1) acquiring the
analog feedback signal from the plant PC, (2) sending the analog control signal to the plant
PC and the host PC, (3) receiving the digital signal from the host PC to start/stop the PXI
system.

Real-Time Simulation

Plant

Servo

Prototype
Controller

Fig. 3. The concept of HIL simulation

Fig. 4. The hardware layout of a typical HILS system


The Development of a Hardware-in-the-Loop
Hardware-in-the-Loop Simulation System for
Unmanned Aerial Vehicle Autopilot Design Using LabVIEW 115

3.2 Personal computer (Plant)


The personal computer (PC) is used to simulate the dynamics of plant (UAV). The major
specifications are Intel Pentium 4-3.0 GHz CPU and 1 GB SDRAM. The I/O interfaces
include:
Multifunction DAQ device NI PCI-6040E:   It takes the responsibility on (1) acquiring the
analog control signal from the PXI system or from the potentiometer on the servo unit that
represents the control surface angle, (2) receiving the digital signal from the host PC to
start/stop the plant PC.
Multifunction DAQ device NI PCI-6703 : It takes the responsibility on sending the analog
state signal to the PXI system and the host PC.

3.3 Servo unit


Each servo unit contains two sets of servos, Futaba S3001, which is used to actuate the
control surface in UAV to generate the corrective torque in order to keep the desired
attitude. The rotational angle of servo is measured by potentiometer, model no. J50S,
manufactured by Copal Electronics Co., Ltd. in Japan.

3.4 Host PC
The host PC or notebook is used to monitor, synchronously digitally trigger, and display the
virtual aircraft instruments of UAV. The major specifications are Intel Core 2 Duo P8400-
2.26 GHz CPU and 2 GB SDRAM. The I/O interfaces include:
Multifunction DAQ device NI USB-6212 : It takes the responsibility on (1) acquiring the
analog state signal from the plant PC, (2) acquiring the analog control signal from the PXI
system, (3) and sending the digital signal to synchronously trigger the start/stop action of
the plant PC and PXI system.

3.5 Software development environment


environment LabVIEW
To develop a HIL simulation system is not an easy work. The graphical programming
software LabVIEW streamlines the system building with a convenient environment to
integrate hardware and software seamlessly. LabVIEW is a graphical programming
language that has been widely adopted throughout industry and academia as the standard
for data acquisition and instrument control software. While other text-based languages
create lines of codes, LabVIEW provides an intuitive graphical programming style to create
programs in a pictorial form called a block diagram. Graphical programming allows users to
focus on flow of data within the applications that makes programming easy and efficiency.
A LabVIEW program, called virtual instrument (VI), has two main parts: a front panel and a
block diagram. The front panel is the interactive user interface of a VI that the appearance
and operation often imitates actual physical instruments. The block diagram is the VI’s
source code and is the actual executable program. The components of a block diagram are
lower-level VIs, functions, constants, and program execution control structures. In addition,
LabVIEW can command plug-in DAQ devices to acquire or generate analog and digital
signals. You might use DAQ devices and LabVIEW to hook your computer up to the real
world, for example, to take measurements, talk to an instrument, send data to another
computer. It is very convenient to construct HIL simulation systems using LabVIEW. A lot
of valuable books (Larsen, 2011; Travis & Kring, 2007) provide more foundations,
programming skills, and applications for LabVIEW.
116 Practical Applications and Solutions Using LabVIEW™ Software

4. Stability augmentation system


In order to perform missions, the UAV has to be hold on or maneuvered to a specified
cruising speed, altitude, and attitude. A typical feedback system providing desirable
handling qualities for pilot/autopilot commands is called stability augmentation system
(SAS). Especially for an aircraft flying throughout an extended flight envelope, the stability
derivatives in Eq. (3) and (4) are expected to vary significantly. Because of the variation of
stability derivatives, the handling qualities also are going to change. SAS can be designed to
improve the handling qualities over its entire operational envelope (Nelson, 1998; Roskam,
2003; Kayton & Fried, 1969).
The stability augmentation system (SAS) is the inner loop of the flight control system (FCS)
that provides the desirable handling characteristics for pilots. The design parameter in the
SAS is the feedback gain that is determined by applying the root locus technique. The root
locus technique is a simple and powerful tool in classical control theory for determining, by
graphical plot, the detailed information about the stability and performance of a closed-loop
system knowing only the open-loop transfer function. The root locus plot shows the poles of
the closed-loop system in complex plane for every value of the feedback gain. The location
of the closed-loop system poles determine two important quantities, damping ratio and
natural frequency, that are closely related to the time-domain performance specifications
(Cook, 2007; Nise, 2008). According to the linear mathematical models of longitudinal
dynamics for the MP2000UAV, the SAS for pitch attitude control are at first designed by the
root locus technique in MATLAB and then are tested in HIL simulation.

4.1 Design of SAS


The pitch angle, one of the state variables in Eq. (3), is an appropriate output variable for
attitude control. Therefore the pitch angle is used as a feedback in SAS; it can be measured
by vertical gyro or attitude and heading reference system (AHRS).
The negative pitch-attitude-to-elevator
pitch-attitude-to-elevator transfer function from Eq. (2) for the MP2000UAV is:

-θ(s) 1.699(s + 4.7308)(s + 13.7827)


27)
=   (7)
δ e (s) (s +0.0
+0.0106)(s +8.8
+8.854)(s + 3.917 ± j 2.4488)

The open-loop system has two real poles at − 0.0106 , −8.854 , and a pair of stable complex
poles at −3.917 ± j2.4488 . The corresponding damping ratios and natural frequencies are
given in Table 2.

Poles Natural frequency Damping ratio


-0.0106 0.0106 1
-3.917+ j2.4488 4.6195 0.8479
-3.917- j
 j2.4488 4.6195 0.8479
-8.854 8.8540 1
Table 2. The natural frequency and damping ratio for open-loop poles
From the step response as shown in Fig. 5, it is obviously that the settling time is too long,
approximately 300 sec. As a result, the maneuverability is very poor. It is necessary to
design a SAS to enhance the handling quality. The block diagram for pitch-angle to elevator
feedback of SAS is shown in Fig. 6. The elevator deflection is produced in proportion to the
pitch angle and adding it to the pilot’s control input as:
The Development of a Hardware-in-the-Loop
Hardware-in-the-Loop Simulation System for
Unmanned Aerial Vehicle Autopilot Design Using LabVIEW 117

δ e =  δ e_pilot + K θ   (8)

where δ e_pilot  is that part of the elevator deflection created by the pilot. The gain K   is the
design parameter.

Fig. 5. Step response of open-loop system

Fig. 6. The block diagram of SAS for pitch angle control


From classical control theory, the system response is determined by the pole location in
complex plane. The time-domain performance specifications such as peak time, percent
overshoot and settling time are functions of damping ratio and natural frequency of the
dominant poles. The duty of SAS is, therefore, to modify the damping ratio and natural
frequency by adjusting the value of feedback gain K   so that the UAV is easier to control.
Studies have shown that to obtain a desirable transient performance such as a smaller
overshoot and a shorter settling time, the design specifications for damping ratio is
approximately 0.6-0.7 and natural frequency is larger than 2 rad/s.
118 Practical Applications and Solutions Using LabVIEW™ Software

The root locus technique permits the designer to view the trajectories of the close-loop
system poles as the design parameter (feedback gain K ) is varied. It is very convenient to
determine the value of K  in
  in SAS by applying the root locus technique. The root locus plot
constructed by using MATLAB for the pitch-attitude-to-elevator transfer function, Eq. (7), is
shown in Fig. 7.

Fig. 7. Root locus plot for SAS


It is noted that at K  = 3   the damping ratio and natural frequency of the dominant poles
meets the specifications while the damping ratio is 0.6564 and natural frequency is 3.7915.
All the closed-loop system poles and the corresponding damping ratios and natural
frequencies are given in Table 3.

Poles Natural frequency Damping ratio


-2.5306 -2.5306 1
-2.489+ j2.86 3.7915 0.6564
-2.489- j
 j2. 86 3.7915 0.6564
-9.1904 9.1904 1
Table 3. The natural frequency and damping ratio for closed-loop poles
The dc gain (steady-state gain) of closed-loop system is -0.3313. It indicates that at steady
state the ratio of pitch angle to pilot’s control input is approximately one-third:
one-third:

θ(∞ ) 1
»-   (9)
δ e_pilot (∞ ) 3

In Fig. 8 the transient response shows a significant improvement that the settling time is
greatly reduced to 1.2 sec by employing SAS. At this stage, the performance of SAS is verified
by computer simulation that the desired handling quality for pilot command is achieved.
a chieved.
The Development of a Hardware-in-the-Loop
Hardware-in-the-Loop Simulation System for
Unmanned Aerial Vehicle Autopilot Design Using LabVIEW 119

Fig. 8. Step response of closed-loop system

4.2 HIL simulation results


In this section the prototype SAS is realized and implemented by the PXI real-time control
system, and the performance of SAS is examined by HILS experiment in real time and real
signal.

4.2.1 Pilot input on time-table experiment


The pilot control input according to schedule is defined as:

⎧0 , 0 ≤ t < 1

δ e_pilot (t) = ⎨5 , 1 ≤ t < 2   (10)
⎪ 0, t ≥ 2

Fig. 9. The signal flow diagram of HIL simulation


120 Practical Applications and Solutions Using LabVIEW™ Software

The signal flow diagram of HILS system is shown in Fig. 9. The LabVIEW virtual
instruments of the controller, plant, and host PC used to perform HILS experiment are
presented in Figs. 10-14. The sampling rate is 50 Hz.

Fig. 10. The LabVIEW block diagram of controller.

Fig. 11. The LabVIEW block diagram of plant


The Development of a Hardware-in-the-Loop
Hardware-in-the-Loop Simulation System for
Unmanned Aerial Vehicle Autopilot Design Using LabVIEW 121

Fig. 12. The LabVIEW block diagram of host PC

Fig. 13. The LabVIEW front panel of host PC (flight data)


122 Practical Applications and Solutions Using LabVIEW™ Software

Fig. 14. The LabVIEW front panel of host PC (aircraft instruments)

4.2.2 Pilot-in-the-loop experiment


The pilot-in-the-loop (PIL) experiment is developed to test the performance of SAS when the
human pilot joins in the control loop. The pilot’s task is to control UAV pitch attitude to a
desired angle. The pilot looks at the virtual aircraft instruments displayed in the host PC
screen and tries to correct the error between the desired pitch angle and the actual pitch
angle. This process of pilot in control can be expressed as follows: (1) the pilot’s eyes watch
the pitch angle on the screen, (2) the pilot’s brain figures out the magnitude of the error, (3)
the pilot’s brain sends a signal to actuate the hand of pilot, (4) the pilot’s hand manipulates
the control stick to move the elevator, (5) the deflection of elevator changes the pitch angle
of the UAV. The operation of PIL experiment depicted in Fig 15 describes a compensatory
control situation: the pilot tries to maintain the desired pitch attitude by driving the pitch
angle error to zero with the assistance of SAS.

Fig. 15. The operation of pilot-in-the-loop experiment


The Development of a Hardware-in-the-Loop Simulation System for
Unmanned Aerial Vehicle Autopilot Design Using LabVIEW 123

From the HIL simulation results of PIL experiment in Fig. 16-17, pilot control using SAS
demonstrates an excellent handling performance than that without using SAS. The effect of
SAS on improving the handling qualities of UAV is confirmed.

Fig. 16. PIL experiment without SAS

Fig. 17. PIL experiment with SAS


124 Practical Applications and Solutions Using LabVIEW™ Software

5. Autopilot system
The function of stability augmentation system is to improve the flying qualities of an
airplane for pilot manual control. To lower pilot workload, particularly on long-range flights
or out-of-sight flights of UAV, most airplanes or UAVs are equipped with automatic flight
control systems or autopilots. The basic autopilot modes include pitch attitude hold mode,
airspeed hold mode, bank angle (roll attitude) hold mode and heading angle hold mode.
Normally pitch attitude is controlled by the elevator, airspeed is controlled by the engine
throttle, roll attitude is controlled by the aileron, and heading is controlled by the rudder.
Thus there are four feedback loops to achieve four different autopilot modes. Fig. 18 shows
the block diagram of pitch attitude hold mode in HILS experiment.

PXI S stem
PC System

θc e δe θ
PID UAV

Fig. 18. The block diagram of pitch attitude control for autopilot in HILS experiment

5.1 PID controller design


The proportional-integral-derivative (PID) controllers are frequently used in practical
control systems owing to their simple structures and quite clear physical senses. Usually the
PID controller is described by the transfer function:

K i
K PID (s) = K p + + Kd s   (11)
s
where K  p, K i, and K d are gains to be determined to meet design requirements. Specifically,
the PID controller can be expressed by the form in time domain as:

⎛ 1 t de(t) ⎞
u(t) = K p ⎜⎜ e(t) +
⎝ Ti ∫0 e(τ  )d
  τ  + T d
dt ⎟⎠
⎟  (12)

where u  is the controller output, e  is the error between desired and actual output, T i is
integral time, and T d is derivative time. Three important characteristics of PID controller are
described as follows: it provides feedback; it eliminates steady-state error through integral
action; it improves transient response by anticipating the future through derivative action.
In order to meet the design specifications on transient and steady-state response, PID
control is an ideal choice for autopilot design.
The PID controllers are designed by two phases. At first, the coarse PID gains are obtained
according to the well-known Ziegler Nichols tuning rules that provide an acceptable closed-
The Development of a Hardware-in-the-Loop Simulation System for
Unmanned Aerial Vehicle Autopilot Design Using LabVIEW 125

loop response. Next, let the coarse PID gains be the initial guess, the Nonlinear Control System
Toolset in MATLAB/Simulink is applied to optimally determine the fine PID gains to meet
time domain specifications such as rise time, overshoot, settling time, steady state error, and
actuator constrain. The resulting PID gains in four feedback loops of autopilot are listed in
Table 4.

K  p T i T d


Pitch Altitude Loop -11.99 0.001118 0.005657
Velocity Loop 0.07506 0.03649 0.004805
Roll Attitude Loop 0.2571 0.003650 0.01531
Heading Loop -1.9058 0.07574 -0.04379

Table 4. The PID Gains in Four Feedback Control Loops of UAV Autopilot.

5.2 HIL simulation results


In this section the prototype PID controller for each mode of autopilot is implemented by
the PXI real-time control system, and the performance is explored in HIL simulation. The
hardware arrangement of HIL simulation system is shown in Fig. 19. Figs. 20 and 21
represent the LabVIEW front panel and block diagram of UAV plant.

PCI-6602   PCI-6703

Personal Computer 
Plant

SCB-68 SCB-68

Embedded Real- Time Controller 

PXI-8184RT, PXI-6220, PXI-6602

Controller 
Fig. 19. The Hardware Setup of HIL simulation for UAV autopilot
126 Practical Applications and Solutions Using LabVIEW™ Software

Fig. 20. LabVIEW front panel of UAV plant

Fig. 21. LabVIEW block diagram of UAV plant


The Development of a Hardware-in-the-Loop Simulation System for
Unmanned Aerial Vehicle Autopilot Design Using LabVIEW 127

The following LabVIEW front panel and block diagram windows shown in Fig. 22 represent
the prototype PID controller in pitch attitude hold mode of autopilot. It is noticed that the
values of PID gains in front panel are from Table 4 where the integral time T i  and the
derivative time T d are in minute available for LabVIEW PID function.

Fig. 22. LabVIEW front panel and block diagram window of PID controller

1.6
Computer Simulation in CT model
1.4 HIL Real-time Simulation in DT model (T=30ms)

1.2

1
     )
   g
   e
     d
     (
0.8
      θ
0.6

0.4

0.2

0
0 2 4 6 8 10
Time (sec)
Fig. 23. The unit-step response of PID controller in pitch attitude hold mode
Figs. 23-26 show the closed loop unit-step time response of PID controllers in pitch attitude
hold mode, velocity hold mode, bank angle hold mode and heading angle hold mode for
128 Practical Applications and Solutions Using LabVIEW™ Software

UAV autopilot. Apparently, the results of HIL simulation and computer simulation are very
close to each other. Fig. 23 exhibits an underdamped response in pitch control with 4 sec.
settling time, 30% overshoot, and no steady-state error; Fig. 24 also exhibits an
underdamped response (a little increase in damping ratio) in velocity control with 6 sec.
settling time, 35% overshoot, and no steady-state error; Fig. 25 also exhibits an
underdamped response (a bigger time constant) in roll control with over 25 sec. settling
time, 5% overshoot, and still no steady-state error; Fig. 26 exhibits an overdamped response
in heading control with 14 sec. settling time, no overshoot, and no steady-state error. From
the results in HIL simulation, PID controllers demonstrate very good performance.
2
Computer Simulation in CT model
1.8 HIL Real-time Simulation in DT model (T=30ms)

1.6

1.4

1.2
     )
   s
     /
   m 1
     (
   u
0.8

0.6

0.4

0.2

0
0 2 4 6 8 10
Time (sec)
Fig. 24. The unit-step response of PID controller in airspeed hold mode

1.4

Computer Simulation in CT model


1.2 HIL Real-time Simulation in DT model (T=30ms)

     ) 0.8
   g
   e
     d
     (
      φ0.6

0.4

0.2

0
0 10 20 30 40 50
Time (sec)
Fig. 25. The unit-step response of PID controller in bank angle hold mode
The Development of a Hardware-in-the-Loop Simulation System for
Unmanned Aerial Vehicle Autopilot Design Using LabVIEW 129

1.4

ComputerS imulation in CT model


1.2 HIL Real-time Simulation in DT model (T=30ms)

     ) 0.8
   g
   e
     d
     (
    ψ 0.6

0.4

0.2

0
0 10 20 30
Time (sec)

Fig. 26. The unit-step response of PID controller in heading angle hold mode

5.3 HIL simulation system including a servo unit


In this subsection the HIL simulation system with servo unit is taken into consideration. The
servo unit is described in section 3.3. The HIL simulation system with servo unit is
composed of three major parts: a Pentium 4 desktop personal computer (PC) system, a
National Instrument (NI) real-time PXI system, and a servo unit. The hardware arrangement
is shown in Fig. 27.

Plant

PCI-6040
PCI-6703

SCB-68 SCB-68

Servo unit PXI-8184 RT Controller


PXI-6259, PXI-6602

Fig. 27. The hardware arrangement of HIL simulation system with a servo unit
130 Practical Applications and Solutions Using LabVIEW™ Software

After receiving feedback signals by DAQ PXI-6259 from plant (PC system) that represent
UAV actual states, the real-time PXI system carries out the proportional-integral-derivative
(PID) algorithm, computes the control effort (control surface deflection angle and throttle
setting) for UAV flight control, and then generates pulse-width-modulation (PWM) signals
by DAQ PXI-6602 to control a real servo. Each servo unit consists of two Futuba-S3001
servos and two accurate potentiometers. The servo receives PWM signals from PXI system
and rotates to a specific angle. The resulting angle is measured by a potentiometer and fed
back to the plant through DAQ PCI-6040. Finally the PC system computes the dynamical
states of UAV based on the state-space model and outputs these analog signals to the PXI
system by DAQ PCI-6703. As a whole the PC system, PXI system, and servo unit constitute a
real-time closed-loop control system for UAV autopilot HIL simulation.
The HIL simulation results of PID controller for system including servo is denoted by the
solid line in Fig. 28. Apparently the performance becomes a little worse because the real
servo and potentiometer involved in HILS system result in so called unmodelled dynamics
that is not taken into consideration in controller design. This deterioration of controller
performance is revealed by HIL simulation not by numerical simulation. The PID controller
has to be tuned to obtain an acceptable performance. It clearly demonstrates that HIL
simulation is indispensable to controller design and verification.

1.6

Numerical simulation
1.4
HIL simulation without servo
HIL simulation with servo
1.2

1
        )
      g
      e
       d0.8
        (
      θ

0.6

0.4

0.2

0
0 2 4 6 8 10
Time (s)

Fig. 28. The performance of PID controller for HIL simulation system including servo

6. Conclusion
With the growing importance of autonomous vehicles for industry, science, aerospace and
defense applications, engineers are encouraged to use HIL simulation methodology to
shorten development cycle, lower total cost and improve functional performance of the
vehicles. LabVIEW features an easy-to-use graphical programming environment and an
intuitive data flow programming style that makes the work of HIL simulation to be easier
and more efficiency. This chapter not only provides LabVIEW solutions to HIL simulation
The Development of a Hardware-in-the-Loop Simulation System for
Unmanned Aerial Vehicle Autopilot Design Using LabVIEW 131

but also presents a complete analysis, design and HILS verification of UAV stability
augmentation system and autopilot.

7. References
Bullock, D., Johnson, B., Wells, R. B., Kyte, M. & Li, Z. (2004). Hardware-in-the-Loop
Simulation. Transportation Research Part C: Emerging Technologies,   Vol. 12, No. 1,
(February 2004), pp. 73-89, ISSN 0968-090X
Bryson, A. E., Jr. (1994). Control of Spacecraft and Aircraft , Princeton University Press, ISBN 0-
691-08782-2, Princeton, New Jersey, USA
Carrijo, D. S., Oliva, A. P. & W. de Castro Leite Filho (2002). Hardware-in-the-Loop
Simulation development. International Journal of Modeling and Simulation , Vol. 22,
No. 3, pp. 167-175, (July 2002), ISSN 0228-6203
Cole, D. T., Sukkarieh, S. & Goktogan, A. H. (2006). System Development and
Demonstration of a UAV Control Architecture for Information Gathering Missions.
 Journal of Field Robotics , Vol. 26, No. 6-7, (June-July 2006), pp. 417-440, ISSN 1556-
4967
Cook, M. V. (2007). Flight Dynamics Principles (2nd  Ed.), Elsevier, ISBN 978-0-7506-6927-6,
Oxford, UK
Cosic, K., Kopriva, I., Kostic, T., Samic, M. & Volareic, M. (1999), Design and
Implementation of a Hardware-in-the-Loop Simulator for a Semi-Automatic
Guided Missile System . Simulation Practice and Theory, Vol. 7, No. 2, (April 1999),
pp. 107-123, ISSN 1569-190X
Kayton, M. & Fried, W. R. (Editors). (1969). Avionics Navigation Systems, John Wiley & Sons,
ISBN 471-46180-6, New York, USA
Larson, R. W. (2011). LabVIEW for Engineers , Prentice-Hall, ISBN-13 978-0-13-609429-6, New
 Jersey, USA
Ledin, J. (2001). Simulation Engineering, CMP Books, ISBN 157-820-0806, Lawrence, USA
Nelson, R. C. (1998). Flight Stability and Automatic Control (2nd Ed.), McGraw-Hill, ISBN 0-07-
115838-3, Boston, Massachusetts, USA
Nise, N. S. (2008). Control Systems Engineering (5th Ed.), John Wiley & Sons, ISBN 978-0-470-
16997-1, New Jersey, USA
Roskam, J. (2007).  Airplane Flight Dynamics and Automatic Flight Controls, Part I,
DARcorporation, ISBN-13 978-1-884885-17-4, Kansas, USA
Roskam, J. (2003).  Airplane Flight Dynamics and Automatic Flight Controls, Part II,
DARcorporation, ISBN 1-884885-18-7, Kansas, USA
Salman, S. A., Puttige, V. R. & Anavatti, S. G. (2006). Real-Time Validation and Comparison
of Fuzzy Identification and State-Space Identification for a UAV Platform.
Proceedings of the 2006 IEEE International Conference on Control Applications , pp. 2138-
2143, ISBN 0-7803-9797-5, Munich, Germany, October 4-6, 2006
Shetty, D. & Kolk, R. A. (1997). Mechatronics System Design, PWS Publishing Company, ISBN
053-495-2852, Boston, USA
Sun, Y. P., Wu, L. T. & Liang, Y. C. (2006). System Identification of Unmanned Air Vehicle
and Autopilot Verification via Hardware-in-the-Loop Real-time Simulation.
Proceedings of International Forum on Systems and Mechatronics , ISBN 986-688-904-1,
Tainan, Taiwan, December 6-8, 2006
132 Practical Applications and Solutions Using LabVIEW™ Software

Sun, Y. P., Chu, C. Y., & Liang, Y. C. (2008a). Using Virtual Instruments to Develop an
Actuator-Based Hardware-in-the-Loop Test-Bed for Autopilot of Unmanned Aerial
Vehicle. Proceedings of SPIE-Fourth International Symposium on Precision Mechanical
 Measurements, Vol. 7130, Part I, pp. 71301J-1-6, ISBN 9780819473646, Anhui, China,
August 25-29, 2008
Sun, Y. P., Wu, L. T. & Liang, Y. C. (2008b). Stability Derivatives Estimation of Unmanned
Aerial Vehicle. Key Engineering Materials, Vol. 381-382, pp. 137-140, ISSN 1013-9826
Sun, Y. P., Tsai, C. H. & Liang, Y. C. (2009). Fuzzy Logic Control Design and Verification of
Unmanned Aerial Vehicle Autopilot via Hardware-in-the-Loop Simulation.
Proceedings of the 2009 International Symposium on Mechatronic and Biomedical
Engineering and Applications, pp. 156-164, ISBN 978-986-7339-508 , Kaohsiung,
Taiwan, November 5, 2009
Sun, Y. P., Tsai, C. H. & Liang, Y. C. (2010). Design and Implementation of a Stability
Augmentation System for an Unmanned Aerial Vehicle Using Hardware-in-the-
Loop Simulation. Proceedings of the 2010 International Symposium on Mechatronic and
Biomedical Engineering and Applications, pp. 183-193, ISBN 978-986-7339-62-1,
Kaohsiung, Taiwan, November 9, 2010
Travis, J. & Kring, J. (2007). LabVIEW for Everyone: Graphical Programming Made Easy and Fun
(3rd Ed.), Prentice Hall, ISBN 0-13-185672-3, New Jersey, USA
7

Equipment Based on the Hardware in the


Loop (HIL) Concept to Test Automation
Equipment Using Plant Simulation
Eduardo Moreira1, Rodrigo Pantoni1,2 and Dennis Brandão 1
1University of São Paulo,
2Federal Institute of São Paulo,

Brazil

1. Introduction
Considering the difficulties to test a real control system at a learning laboratory, related to
equipment acquisition or physical installation, it is necessary to develop a simulation system
that will act as parts of the real system.
In this scenario, through the use of recent computational resources in hardware and
software, it is possible to explore the concept named Hardware in the Loop (HIL), which
consists on well known technique mostly employed on the development and testing of
electronic, mechanical and mechatronic real equipments by the use a data and signal
interface between the equipments and computational real-time systems.
This work proposes a HIL-based system where a Foundation Fieldbus control system
manages the simulation for a generic plant in an industrial process. The simulation software
is executed in a PC, and its purpose is the didactic use for engineering students to learn to
control a process similar to the real system.
The plant is simulated in a computer, implemented in LabVIEW and part of the fieldbus
network simulator named FBSIMU (Mossin et al., 2008). Foundation Fieldbus physical
devices are configured to operate in a control strategy and interact with the simulated
environment.
Results demonstrate it is a feasible technique that can be extended to more complex and
elaborate control strategies.

2. Works related to hardware in loop for industrial networks


HIL concept is well-known and used in the research area. For this reason, this section cites
the most recent works related to HIL applied to industrial networks.
(Godoy & Porto, 2008) suggest the use of HIL technique to develop Networked Control
Systems (NCS) with CAN (Controller Area Network) networks, presenting the structure for
HIL usage and evaluating the benefits of using this tool to develop NCS with CAN.
Huang & Tan (2010) proposed a HIL simulator that provides an efficient development and
test platform for real-time systems used in assembling lines of automation factories.
134 Practical Applications and Solutions Using LabVIEW™ Software

Fennibay et al. (2010) introduced the HIL technique for hardware and software shared in
embedded systems. This technique reduces the need for developing models for existing
hardware platforms and increases system accuracy and performance.
Li & Jiang (2010) performed a study using a physical system with steam generation together
with HIL simulation, inside a training simulator of an industrial nuclear plant. The purpose
is the study of fieldbus networks for steam systems. Results showed that some existent
delays could be eliminated, according to the authors’ suggestions.
The next chapters describes some important details of the Foundation Fieldbus protocol as
well as its simulator named FBSIMU, which includes a simulation module for the dynamics
of industrial plants, developed over LabVIEW and used in an HIL experiment with a real
fieldbus network.

3. The foundation fieldbus protocol


The term FOUNDATION Fieldbus indicates the protocol specified by the Fieldbus
Foundation. It is a digital, serial, bidirectional, and distributed protocol which
interconnects field devices such as sensors, actuators and controllers. Basically, this
protocol can be classified as a LAN (Local Area Network) for instruments used in process
and industrial automation, with the ability to distribute the control application through
the network.
This protocol is based on the ISO/OSI (International Organization for
Standardization/Open System Interconnection) seven-layer reference model (International
Organization For Standardization, 1994). Although being based on the ISO/OSI model, the
FF does not use the network layer, the transport layer, the section layer, neither the
presentation layer, because it is restricted to local applications. The entire network structure
of the FF concentrates on the physical layer, the data link layer (DLL) and the application
layer. Besides these three implemented layers, the protocol defines an additional layer called
User Application Layer.
The FF Physical Layer, named H1, uses shielded twisted pair cable as a communication
medium. The H1 specifies a 31.25 KBit/s baud rate with Manchester bit codification over a
bus powered channel. The network topology configuration is flexible: it is typically
configured with a trunk and several spurs, attending certain physical and electrical
limitations regarding maximum lengths and number of transmitters.
The DLL carries the transmission control of all messages on the fieldbus and its protocol
grants to the FF network temporal determinism. The communication is based on a master-
slave model with a central communication scheduler (master), named Link Active Scheduler
or LAS. This node performs the medium access control (MAC).
Two types of DLL layer are standardized: Basic and Link Master. A Basic DLL transmitter
does not have LAS capabilities, it operates passively as a communication slave. A Link
Master DLL transmitter, on the other hand, can execute LAS functions and thus, if the active
LAS node fails, become the LAS node.
The FF Data Link Layer supports two transmission policies: one addressed to scheduled
cyclic data and another to sporadic (unscheduled) background data. These two
communication policies share the physical bus but they are respectively segmented in cyclic
time slots or periods. In the scheduled communication period, most process variables
Instrument Design, Measurement and Analysis of Cardiovascular Dynamics Based on LabVIEW 183

host computer include that: real-time displays and records pressure waves of brachial
artery, radial artery and cuff pressure; calculates parameter values through existing
algorithm; saves tester’s information, parameter values and waveforms; evaluates the
artery’s health condition of the object.
The YF/XGYD artery stiffness measuring instrument and the field testing can be seen in Fig. 2.

Fig. 2. The YF/XGYD artery stiffness measuring instrument and the field testing

2.2 Design of software system


2.2.1 The overall block diagram of software system
The software system of YF/XGYD is based on virtual instrument LabVIEW 8.5. It is mainly
used to collect and preprocess data signals, analyze and calculate blood flow parameters,
and store, replay and print test results. The whole block diagram can be seen in Fig. 3.
Through utilizing the powerful function of data acquisition and digital signal processing of
LabVIEW 8.5, we can collect and process these signals of pulse wave and cuff pressure. In
addition, LabVIEW 8.5 has well function of database management and many kinds of tools
and methods. So it can manage many different types of database. Users can utilize data
control to access, add, delete and inquire existing different types of database. And users can
utilize Visual System Manager (VSM) to establish and maintain many different types of
database and generate database application program. Because those well functions of
database management in LabVIEW 8.5, through programming we achieved storage
management of patient file, including: database maintenance, query answering, statistical
analysis and printing.

2.2.2 User interface design of software system


The user interface is very important component in interactive software system. A good user
interface should have the advantages, such as perfect performance, simplified operation,
reliable operation and accurate interpretation of results. Every part of the architecture block
diagram of software system (Fig. 3) corresponds with function module and user interface in
software system, respectively.
184 Practical Applications and Solutions Using LabVIEW™ Software

Fig. 3. The architecture block diagram of software system


1. Main window of the software system
To ensure the security of the software system, users could set a password in the secret code
dialogue window which will be popped out when user starts the system. Only after entering
the correct password, user can enter the main window.
Users could utilize the function menus in the main window to achieve a variety of
processing operations. The window interfaces in the system be generated by menu tool
(Menu Editor) in LabVIEW 8.5 are all standard Windows pull-down menu system. To make
the system easy to operate and make users easy to master, we take into account the
following principles in the design of the menu: in design, organize system menu on the
basis of functions, so users could know clearly structure and function of the system when
they browse the menu; to give a meaningful title to menu against the specified function;
to set hotkeys for these staple menus; to organize menu item according to frequency of
utilization.
The main window and its LabVIEW program code of YF/XGYD can be seen in Fig. 4 and
Fig. 5, respectively. The main window is relatively simple; in addition, in terms of function
set-up, it includes three pull-down menus (the File, the Analysis and the Help) and three
function-buttons (the Fast Test, the Full Parametric Test and the Exit).
Instrument Design, Measurement and Analysis of Cardiovascular Dynamics Based on LabVIEW 185

Fig. 4. Main window of YF/XGYD system

Fig. 5. LabVIEW program code of the main window


2. Test window of the software system
When the YF/XGYD system measures the cardiovascular active state of human, the system
software will carry out data communications and synchronously draw graphics of these
measuring signals. Furthermore, to visually and intuitively describe the process of inflation
and deflation in cuff, the system can utilize progress bar control to dynamically simulate rising
and falling of mercury column in sphygmomanometer when charging and discharging gas in
blood press measurement by the stethoscope. The full parametric test window and its
LabVIEW program code of YF/XGYD can be seen in Fig. 6 and Fig. 7, respectively.
186 Practical Applications and Solutions Using LabVIEW™ Software

The interface (shown in Fig. 6) can be divided into three areas, such as the Function Button
Area, the Test Waveform Display Area, and the Personal Data and Test Results Display
Area.

Fig. 6. The full parametric test window

Fig. 7. A part of LabVIEW program code of the full parametric test window
According to the needs of testing procedure, users could choose the Measuring Button, the
Save Button, the Refresh Button, the Analysis Button, the Reset Button and the Print Button,
respectively. When user clicks the Measuring Button, YF/XGYD system enters testing
Instrument Design, Measurement and Analysis of Cardiovascular Dynamics Based on LabVIEW 187

status. In this state, the host computer begins to communicate with the slave computer; in
the meantime, cuffs are inflated; then the system displays real-time waveform variation
value of three-way signals in the Test Waveform Display Area. These waveforms can be
seen in Fig. 8.

Fig. 8. Graphs of pulse wave and cuff pressure


The roles of function buttons are: the Measuring Button, to begin testing; the Save Button,
to save measuring results, personal data, measuring waveforms, etc.; the Reset Button, to
eject the Input Tester Data Sub Interface and re-input tester basic information (including ID,
name, gender, age, height and weight) in this sub-interface; the Refresh Button, to empty
personal data and measuring waveforms and wait for next test; the Analysis Button, to
enter the Parametric Analysis Interface of Patient who have been tested (the interface and its
LabVIEW program code can be seen in Fig. 9 and Fig. 10, respectively), and to look over
Diastolic initiation wave, Systolic decent wave and other cardiovascular parameters of
patients; the Print Button, to print measuring results.

Fig. 9. Parametric analysis interface


188 Practical Applications and Solutions Using LabVIEW™ Software

Fig. 10. A part of LabVIEW program code of the parametric analysis interface

Fig. 11. Measuring results interface


These test results are displayed in the Personal Data and Test Results Display Area. These
results include personal data, such as ID, name, gender, age, height and weight, and test
results, such as systolic pressure, diastolic pressure, mean pressure, heart rate, pulse wave
velocity [PWV], artery stiffness index [ASI], large artery compliance [C1], and small artery
compliance [C2]. According to measured values of each parameter, the YF/XGYD system
can estimate the cardiovascular status of the object. For example, the system can utilize vivid
Graphic Correlation method to estimate the range of ASI value; waveform envelope shape
Instrument Design, Measurement and Analysis of Cardiovascular Dynamics Based on LabVIEW 189

of pulse wave is divided into five types (A, B, C, D, and E), so the system can synthetically
estimate general situation of artery elasticity. In Fig. 11, we can clearly see a 61-year-old
patient’s test result: systolic pressure is 149mmHg, ASI is 116, and waveform type of pulse
wave is B, and so on. The test result indicates that the patient whose arteries are already
mild stiffness has the tendency of potential artery disease.
In addition, the system software has the Test Waveform Display Area interface. User can
utilize the interface to examine, delete, recover and print patient’s personal data and
waveforms and results of each record. In order to facilitate contrastive analysis, different
parametric results of every test are all displayed on the interface. Fig. 12 showes a patient’s
two test records (ASI is 200 in the first time and 190 in the second time) which reflect that
the patient’s arteries are moderately stiff.

Fig. 12. Test waveform display area interface

2.2.3 Database of software system


1. Establishment of database
The medical signal database with three data tables is created strictly in accordance with the
relational model of database. The tables are: the table of patient’s basic information,
including ID, name, gender, age, height and weight; the table of patient’s basic parameter,
including pulse wave, cuff wave, heart rate, systolic pressure, diastolic pressure, mean
pressure and stroke volume; the table of diagnostic results, to save the corresponding
results in the field of diagnostic results.
2. Operation of database
The operation of database includes data browsing, data query and database editor that adds,
modifies and deletes patient data. Inquiry statistic is a very important function in
management system. The YF/XGYD system utilizes LabVIEW 8.5 well database
management function to achieve the inquiry and statistics of relevant data. It takes a great of
convenience to clinical and scientific researches. The edit function of database can achieve
these operations to add, modify and delete patient records. Choosing the corresponding
190 Practical Applications and Solutions Using LabVIEW™ Software

option in the menu, user can achieve the maintenance of patient records. According to the
actual need, user can choose the print option in the menu to print patient records. It takes a
great of convenience to analysis of patient’s condition.
3. Data management module
Data store can be divided into file store and database store in LabVIEW 8.5. Database store
can overcome the constraints imposed by file store which is proven unfavourable to data
query and management, so the YF/XGYD system utilizes database to store data in the
development of virtual instrument system. This improves running efficiency of the system.
Through Open Database Connectivity (ODBC), LabVIEW communicates with the database.
User needs to name database and install drivers in ODBC. Through third-party software
(LabSQL), software communication interface between LabSQL and LabVIEW database is
created. Users can utilize the interface to log in local or network database and establish,
store, modify and manage this database. Data exchange between application program and
database is achieved by calling the SQL execution module.
4. Data storage module
Users can respectively choose the independent storage and the statistics storage to store
measuring data. Users can look over measuring waveforms, parameters and results of
patient by the independent storage ways or save patient’s measuring results to LabVIEW
tables in the manner of statistical model by the statistics storage ways. At the same time, the
system can create a homonymous Excel electronic spreadsheet. On account of large amount
of waveform data, the method of examining data in Excel is inconvenient. The method of
examining data in LabVIEW table will become necessary means for improving performance
of examining data. And users can look over and compare large categories of waveforms by
this method.
Users can directly call Excel electronic spreadsheet for statistic analysis by SPSS software. A
set of clinical test results after being evaluated and saved is shown in Fig. 13, which is
displayed under the LabVIEW environment. Excel electronic spreadsheet and this LabVIEW
table have same file name and path, but different formats. Users can choose to analyze the
whole measuring data or a certain measuring data or multiple measuring data to contrast
and analyze by statistical method. Users can analyze in term of the repeatability these data
which are gained by repeated measuring the same people. These measuring results of
multiple hospitals can be saved as the same document and displayed synchronously. By and
large, the efficiency of clinical analysis is greatly improved through the improvement of
database.

Fig. 13. A set of clinical test results


Instrument Design, Measurement and Analysis of Cardiovascular Dynamics Based on LabVIEW 191

3. Algorithm, encoding and measurement of arteriosclerosis parameter


Many parameters of artery system can be measured by YF/XGYD system. PWV and ASI are
the two most commonly used parameters among them. We mainly introduced the method
of calculation, the programming of LabVIEW and the process of measurement of the two
parameters.

3.1 Pulse wave velocity (PWV)


3.1.1 Definition of PWV
The systole and diastole of heart lead to the periodic change of blood pressures in whole
arterial system, and the periodic contraction and dilatation of arterial wall, which force the
pulse wave to propagate along blood vessels from heart to whole body(McDonald 1974;
Qiao & Wu 2000). PWV is mainly decided by the arterial physical parameters, such as
arterial wall thickness and Young’s modulus of elasticity. Therefore, PWV can reflect the
changes of these parameters, and judge whether arteriosclerosis or not (Takenaka &
Kobayashi 2004).

3.1.2 Calculation of PWV


In the system, a noninvasive method is used to measure the brachial-radial PWV
(commonly abbreviated as BRPWV) by detecting, collecting and analyzing the pulse signals
at brachial artery and radial artery simultaneously. BRPWV is commonly used for the
degree assessment of human arteriosclerosis (Zhang et al. 2005).
Because pulse wave propagates from heart to peripheral arteries, pulse wave arrive at
brachial artery firstly, then radial artery (McDonald 1974; Qiao & Wu 2000; Mark 2003). We
can measure the time difference Δt of wave arriving at two measure point at brachial and
radial artery, and the distance ΔL of two measuring points, namely the distance of two
pressure sensors in two cuffs. Then we can calculate BRPWV as Eq. 1.

ΔL
PWV  =   (1)
Δt

In order to obtain Δt , the foot of the pulse wave need to be detected, namely the takeoff
point D. Because of the existence of interference factors, the ideal pulse wave is hard to be
obtained, namely the takeoff point D is not the trough location of pulse wave. In Fig. 14,
point A is the trough of pulse wave, and point D is the takeoff point which is needed to
detect. Obviously, the two points are not the same point, so the point D is needed to
calculate using a special algorithm.
The algorithm of detecting the takeoff point D:
Step 1. find the trough A ( x1 , y1 ) and peak B ( x2 , y2 ) of the pulse wave;
Step 2. establish the equation of line AB:

( y1 − y2 ) x + ( x2 − x1 ) y + ( x1 y2 − x2 y1 ) = 0   (2)

Step 3. calculate the distance from a point on the waveform between A and B to the line
AB, and find the maximal distance from a point which is the takeoff point D.
After detecting the takeoff points of the brachial and radial pulse wave, the x coordinate
different value of the two points is the time difference Δt . The schematic figure of
calculating Δt  is showed in Fig. 14.
192 Practical Applications and Solutions Using LabVIEW™ Software

Fig. 14. The schematic figure of calculating Δt

3.1.3 LabVIEW code of calculation of PWV

Fig. 15. LabVIEW graphical code of calculation of PWV


The LabVIEW graphical code of calculating PWV is showed as Fig. 15. There are four
subprograms called by the main program in Fig. 15. The subprogram 1 and 3 are used for
finding the trough and peak of the pulse wave, respectively. The subprogram 2 is used to
establish the equation of the line AB. The takeoff points of the brachial and radial artery and
the time difference are calculated by the subprogram 4 and 5. In order to improve the
accuracy, the subprogram 6 and 7 are used to find several time differences of lower relative
error and calculating the mean of them. The LabVIEW graphical codes of the subprogram 2
and 4 are showed in Fig. 16 and 17.

Fig. 16. The LabVIEW graphical codes of the subprogram 2


Instrument Design, Measurement and Analysis of Cardiovascular Dynamics Based on LabVIEW 193

Fig. 17. The LabVIEW graphical codes of the subprogram 4

3.2 Arterial stiffness factor (ASI)


3.2.1 Definition of ASI
ASI is an important nondimensional parameter which represents the degree of blood-vessel
stiffness (Sunthareswaran 2003; Quan et al. 2006). ASI can indicate arterial wall elasticity,
and serve as an independent predictor of cardiovascular diseases. It is also an important
parameter of YF/XGYD system.

3.2.2 Calculation of ASI


In the system, we use the whole pulse waveform and the pressure curve of cuff to calculate
ASI (Yao et al. 2007). Generally, we find out two peaks at the front and back of the
maximum peak, which are closest approach to 80% of the maximum peak. Then, two cuff
pressures corresponding to the two peaks can be obtained by a subprogram. Finally, ASI is
calculated by multiplying the difference of the two cuff pressures by a special factor.
In the measurement of ASI, the maximum peak P ax  of the whole pulse wave is obtained
firstly, namely the MAP of the pulse wave. Secondly, we need to find out two peaks of pulse
wave whose values are the most approach to P Max *80%   at the front and back of the
maximum peak. The difference of two cuff pressures corresponding to the two peaks
multiplies a special factor to get ASI. The schematic diagram of calculating ASI is showed as
Fig. 18. The equation of calculation is as follows:

 ASI = K * ( P1 − P2 )

Where, K is the correction factor which is relate to the particular case of tester, such as
smoking, sex, age, and health.

Fig. 18. The schematic diagram of calculating ASI


194 Practical Applications and Solutions Using LabVIEW™ Software

In LabVIEW, we use a subprogram VI to realize the calculation of ASI. The graphical code of
the subprogram is showed as Fig. 19.

Fig. 19. The graphical code of calculating ASI

3.2.3 Singular wave processing in actual measurement of ASI


In actual measurement of ASI, the pulse wave signal is greatly influenced by environment
around the tested body (Quan, He et al. 2006; Quan et al. 2006; Yao, He et al. 2007). For
example, the saltation of respiration and the body shaking may product a few singular
waveforms. This kind of interferences will not only influence the data collection, and may
even generate invalid data. In order to remove the influence of singular waveform, we need
to conduct a series of signal processing, such as filtering processing of moving average,
deleting adjacent-wave, high peak and low peak, etc.
1. Deleting adjacent wave processing
In measurement, there are some adjacent waves generated from interference as shown in
Fig. 20. Pulse adjacent wave likely cause the detecting error of the systolic blood pressure
and diastolic blood pressure. So we need to remove these pulse adjacent waves. Through a
lot of waveform analysis, we summarize a method for detecting adjacent wave: if the time
difference of two adjacent peaks is less than 100 sampling points, the two waves
corresponding to the two adjacent peaks are judged to be adjacent wave. Fig. 21 showed the
graphical code of adjacent wave processing.

Fig. 20. Processing adjacent wave


Instrument Design, Measurement and Analysis of Cardiovascular Dynamics Based on LabVIEW 195

Fig. 21. The graphical code of adjacent wave processing


2. Deleting sharp peak processing
In measurement, a vibration of a part of body or other reasons probably cause the
phenomenon of sharp peak in pulse wave as shown in Fig. 22. If the system applies the
singular sharp peak in analysis, the singular wave will be misjudged to be the position of
mean blood pressure. So system must delete these singular sharp peaks.
Through a lot of waveform analysis, we summarize a method for detecting singular sharp
peak: (1) if the value of a certain point A of all pulse peaks surpasses 30 of front and back
point of the point A; (2) if the value of a certain point A of all pulse peaks is more than 30 of
front point, 10 of back point and 30 of back two points of the point A; (3) if the value of a
certain point A of all pulse peaks is more than 30 of back point,10 of front point and 30 of
front two points of the point A; we judge the point A is a singular peak when anyone
condition is right. Fig. 23 shows the graphical code of sharp peak processing.

Fig. 22. Processing sharp peak


ECG Ambulatory System for Long Term Monitoring of Heart Rate Dynamics 209

Fig. 4. A/D block diagram

2.1.3 Radiofrequency module


The device used for transmitter and receiver of the telemetry system is the nRF24L01 of
Nordic Semiconductor. It is a single chip transceiver with an embedded baseband protocol
engine named Enhanced ShockBurst™ (ESB), designed for ultra low power wireless
applications, and for operation in the world wide Industrial-Scientific-Medical (ISM)
frequency band at 2.400 - 2.4835 GHz (Nordic Semiconductor, 2007). ESB enables the
implementation of ultra low power, high performance communication with low cost host
microcontrollers (MCU).
The nRF24L01 is configured and operated through a Serial Peripheral Interface (SPI), in
which the register map is available. The register map contains all configuration registers in
the nRF24L01 and is accessible in all operation modes of the chip. The radio front end uses
GFSK (Gaussian Frequency Shift Keying) modulation, and has user configurable parameters
like frequency channel, output power and air data rate. Its internal voltage regulators ensure
a high Power Supply Rejection Ratio (PSRR) and a wide power supply range.
2.1.3.1 Control of the nRF24L01
The nRF24L01 has a built-in state machine that controls the transitions between the different
operating modes of the chip. The state machine takes input from user defined register
values and internal signals. The nRF24L01 can be configured in four main modes of
operation:
- Power down mode: In this configuration nRF24L01 is disabled with minimal current
consumption.
- Standby modes: Standby-I mode is used to minimize average current consumption
while maintaining short start up times, and part of the crystal oscillator is active. In
standby-II mode extra clock buffers are active compared to standby-I mode and much
more current is used compared to standby-I mode.
210 Practical Applications and Solutions Using LabVIEW™ Software

- Rx mode: In this mode the receiver demodulates the signals from the RF channel,
constantly presenting the demodulated data to the baseband protocol engine, which
constantly searches for a valid packet.
- Tx mode: In this mode the device transmits a data packet previously loaded by the
control stage (MCU).
Transmitter and receiver are programmed with the same RF channel frequency and the
same air data rate to be able to communicate with each other. Then, a RF channel frequency
of 2.4 GHz, a bandwidth of 2 MHz and an air data rate of 2 Mbps were used. This air data
rate provides lower average current consumption and reduced probability of on-air
collisions. The PA control was used to set the output power from the nRF24L01 power
amplifier (PA) to 0 dBm with a DC current consumption of 11.3 mA. In the nRF24L01
receiver the gain in the Low Noise Amplifier (LNA) is controlled by the LNA gain setting,
which it is possible to reduce the current consumption in RX mode with 0.8 mA at the cost
of 1.5 dB reduction in receiver sensitivity.
2.1.3.2 Communication protocol
The embedded baseband protocol engine (ESB) is based on packet communication and
supports various modes from manual operation to advanced autonomous protocol
operation, which it is a desired characteristic in this application. It has internal FIFOs
registers that ensure a smooth data flow between the radio front end and the system’s MCU,
so it reduces system cost by handling all the high-speed link layer operations, and firmware
and required memory in the MCU. The format of the ESB packet contains a preamble field,
address field, packet control field, payload field and a cyclic redundancy check (CRC) field
(Figure 5).

Fig. 5. Format of the Enhanced ShockBurst™ (ESB) packet


- Preamble: The preamble is a bit sequence used to detect 0 and 1 levels in the receiver.
The preamble is one byte long and is either 01010101 or 10101010. If the first bit in the
address is 1 the preamble is automatically set to 10101010 and if the first bit is 0 the
preamble is automatically set to 01010101. This is done to ensure there are enough
transitions in the preamble to stabilize the receiver.
- Address: In this field address for the receiver is defined, and ensures that the correct
packet are detected by the receiver. The address field can be configured to be 3, 4 or, 5
bytes long.
- Packet Control Field: This field consists of 9 bits. The most significant 6 bits are used to
specify the size in bytes of the data field, which can be from 0 to 32 bytes. The 2 bit PID
(Packet Identity) field is used to detect if the received packet is new or retransmitted,
this prevents the MCU receives the package more than once. The PID field is
incremented at the TX side for each new packet received through the SPI. The PID and
CRC fields are used by the PRX device to determine if a packet is retransmitted or new.
The last least significant bit is used for a special feature of the nRF24L01 called auto
acknowledgement.
ECG Ambulatory System for Long Term Monitoring of Heart Rate Dynamics 211

- Data: This field is the user defined content of the packet. It can be 0 to 32 bytes wide and
is transmitted on-air as it is uploaded (unmodified) to the device.
- CRC: This field is used as the error detection mechanism in the packet. It may either
be 1 or 2 bytes and its calculation is based on the contents of the fields of address,
Packet Control Field, and Data. No packet is accepted by ESB if the CRC fails. The
polynomial for 1 byte CRC is X8 + X2 + X + 1. The polynomial for 2 byte CRC is X16+
X12 + X5 + 1.
ESB provides automatic packet handling and timing. In transmission, ESB assembles the
packet and clocks the bits in the data packet into the transmitter for transmission. In
reception, ESB constantly searches for a valid address in the demodulated signal. When ESB
finds a valid address, it processes the rest of the packet and validates the packet by CRC. If
the packet is valid the payload is moved into the RX FIFO. The high speed bit handling and
timing is controlled by ESB.
2.1.3.3 Data and control interface
The data and control interface gives access to all the features in the nRF24L01. The data and
control interface consists of the following six 5 V tolerant digital signals:
- IRQ: this signal is active low and is controlled by three maskable interrupt sources
- CE: this signal is active high and is used to activate the chip in RX or TX mode
- CSN: SPI enable signal
- SCK: SPI clock signal
- MOSI: SPI serial data input signal
- MISO: SPI serial data output signal
The SPI is a standard SPI with a maximum data rate of 8 Mbps. In this application, IRQ pin
is used mainly to carry out the monitoring of device.
2.1.3.4 nRF24L01 transceiver circuit
The complete nRF24L01 transceiver circuit of 2.4 GHz with the recommended components
according to the manufacturer's data sheet is shown in Figure 6 (Nordic Semiconductor,
2007). The ANT1 and ANT2 output pins provide a balanced RF output to the antenna. The
pins must have a DC path to VDD_PA, through a RF choke, and a recommended
matching network for 50 Ω  load impedance is used in the circuit. To achieve a crystal
oscillator solution with low power consumption and fast start-up time a crystal with a
low load capacitance specification C L  must be used (typically 12 pF), and also with a
lower equivalent parallel capacitance C 0 (typically C0=1.5pF), but may increase the cost of
the crystal.
With respect to PCB layout of the circuit is necessary a good design to achieve good RF
performance.
A PCB with a minimum of two layers including a ground plane is recommended for
optimum performance. The nRF24L01 DC supply voltage should be decoupled as close as
possible to the VDD pins with high performance RF capacitors, and it should be filtered and
routed separately from the supply voltages of any digital circuitry. Long power supply lines
on the PCB should be avoided. Full swing digital data or control signals should not be
routed close to the crystal or the power supply lines. A fully qualified RF-layout for the
nRF24L01 and its surrounding components, including matching networks, is given by the
manufacturer (Nordic Semiconductor, 2007).
212 Practical Applications and Solutions Using LabVIEW™ Software

Fig. 6. nRF24L01 transceiver circuit with single ended 50 Ω RF output

2.1.4 Control unit


The control unit is the most important part of the transmitter, because this unit receives data
of digitized ECG, battery monitoring and transmission and reception via radio frequency.
To perform these tasks a microcontroller Microchip PIC18F252 with RISC architecture was
used. Figure 7 shows the PIC18F252 connected to all its peripherals.

Fig. 7. PIC18F252 as main controller of the transmitter


ECG Ambulatory System for Long Term Monitoring of Heart Rate Dynamics 213

The MCU operates at a speed of 10 MIPs with a 10 MHz crystal and the PLL (Phase-Locked
Loop) enabled. Analog signals from DI, aVF, Vx and BAT are digitized by the internal ADC,
in where the TMR0 sets the sampling rate and the conversion is controlled by TMR0
interrupt. Once digitized the signals are sent to nRF24L01 through the SPI port, where the
control of all radio functions are performed. The RB7 pin of the port B is used only to show
system status through a LED. The port B is reserved for future expansions, being able to
connect an optional SD memory card, LCD screen etc. The MCLR pin is used for MCU Reset
and for development purposes only.
The figure 8 shows the flowchart of the algorithm implemented in the firmware of the
PIC18F252. The language used for development is the C compiler using MPLAB C Compiler
for PIC18 MCUs in professional version 3.00, and the development environment is the
MPLAB version 8.00 both of Microchip, Inc.

Fig. 8. Flowchart of the algorithm implemented in the PIC18F252 firmware as transmitter

2.1.5 Power supply


The general characteristics required of the power supply are:
- Supply with type AA batteries
- Regulated voltage outputs of ± 5 V and 5 V
- Maximum current of 100 mA
- Low ripple
- High efficiency
214 Practical Applications and Solutions Using LabVIEW™ Software

As first stage of the power supply, the high efficiency step-up DC to DC converter NCP1400
is used to generate a regulated voltage of 5 V with 100 mA of output current to generate a
voltage of -5 V from a +5 V a switched capacitor voltage inverter MAX828 is used which has
high efficiency and low operating current. To obtain the reference voltage of 2.5 V required
to shift ECG baseline and the matching with ADC range of 0 to 5 V, a micropower voltage
reference diode LM385 is used which provides a current of 15 μA to 20 mA with a resistor of
200 kΩ.

2.2 Receiver
The block diagram is shown in the figure 2b, and it is composed of a control unit, a RF
module, two communication ports and a power supply.

2.2.1 Radiofrequency module


The design of this section is identical to the RF transmitter module but now the transceiver
is configured as receiver. Due to both modules use the same MCU, driver that is used in the
firmware of both modules is the same. At the reception, data are received first in the lowest
layer referring to the protocol explained previously and inversely on the transmission (Fig.
5). Unpacked data are put into the internal registers of the microcontroller to be processed
later. The electric circuit is also identical to the transmitter (Fig. 6).

2.2.2 Control unit


To perform all tasks in this stage, the same PIC18F252 microcontroller is used. Connection of
the PIC18F252 with its peripherals is shown in Figure 9. The PIC18F252 has connected in pin
MCLR a push button to reset if it is necessary and for development purposes, in pins RA0,
RA1 and RA2, three LEDs for general indication of the system status (red = power, green =
reception and orange = transmission), a 10 MHz crystal for MCU clock, the RF module
connected to the port SPI and in the UART lines (RX and TX) the interface RS232 formed by
integrated circuit MAX232 necessary to match voltage levels or the USB controller only one
at a time.

Fig. 9. PIC18F252 as main controller of the receiver


ECG Ambulatory System for Long Term Monitoring of Heart Rate Dynamics 215

The PIC18F252 firmware is also written in C using the compiler MPLAB C Compiler for
PIC18 MCUs in its professional version 3.00 and the development environment is the
MPLAB version 8.00 both of Microchip, Inc. In the figure 10 shows the flowchart of the
algorithm implemented in the firmware of the PIC18F252.

Fig. 10. Flowchart of the algorithm implemented in the PIC18F252 firmware as receiver

2.2.3 RS-232C Interface


The communications port uses the USART interface of PIC18F252. The configuration and
control of USART is performed by the MCU firmware. The device used that conditions
MCU and RS-232C voltage levels is the MAX232. MCU and computer must be configured to
operate to 115,200 Bauds, without parity, 8 bits data and 1 bit stop. A power supply with a
regulated voltage of 5 V is used in this interface.

2.2.4 Acquisition, display, storage, conditioning and processing of data


The format used to transmit the packet of each digitized sample to the RS-232C interface is
shown in figure 11. The data are sent in hexadecimal and each parameter consists of 1 byte if
we use ADC in 8-bit mode, and 2 bytes if we use the maximum 10 bit allowed for the
digitization of each sample.
216 Practical Applications and Solutions Using LabVIEW™ Software

Fig. 11. Format of the data packet sent by the receiver to the RS-232 interface
The software implementation of this equipment was performed in LabVIEW®. The software
purposes are the acquisition, display and storage of data, and the development of an R wave
peak detection algorithm. In order to achieve these objectives different sub-VIs gathered
together into two different main VIs were realized. The general structure of the first
program (Acquisition VI) is described in Figure 12.

Fig. 12. General block diagram for acquisition VI


In this VI is where the acquisition of data is realized. As shown in the preview diagram
when the VI starts, initial conditions as the position of frontal panel (FP) (Fig. 13) and button
initialization are implemented. Then the user must select a folder in the CPU in order to
continue. Once selected the folder where the data will be stored the program automatically
generates appropriate files for the signal storage. At this point, user must indicate at which
port is connected the equipment and ensure the configuration in the CPU is the correct one.
Start acquisition’s button will be available after this and the user will define when to start
the acquisition. When the initial button is pressed the acquisition process starts during 5
minutes. There is also the option of stopping the acquisition process in this stage by pressing
ECG Ambulatory System for Long Term Monitoring of Heart Rate Dynamics 217

the stop button. Until the acquisition process is finished, exit button is allowed. At this
phase user can choose between two options. One is to start a new acquisition overwriting
previewed data acquired. Or user can choose to finish the acquisition VI program.

Fig. 13. Acquisition VI program frontal panel


Then the program automatically starts the second VI (conditioning VI) where the signal
previously acquired will be processed. General structure of the conditioning VI is shown in
Figure 14. When this VI starts it sets the initial conditions for the graphs charts, the buttons,
and the FP position. The VI knows where the data was previously stored, so when the user
presses the start button it automatically starts to takeoff from the original signal the trend,
the noise and it process this information to obtain the R wave peak detection.
Detrending process performed in this VI is implemented with the LabVIEW® Wavelet
Analysis Detrend VI. It considers the energy in the ECG signal to remove baseline wander
due to low frequency artifacts (Weng et al., 2006). The denoising process is realized with the
Wavelet Analysis Denoise VI. This VI performs noise reduction using the undecimated
wavelet transform (UWT) for the elimination of high-frequency component due to noise.
At the end, the R wave peak detection is performed using a self-programmed variation of
the LabVIEW® Wavelet Analysis Multiscale Peak Detection. This variation allowed the
program a complete and correct detection of all the R wave peaks in the ECG signal. Figure
15 shows the final FP of the conditioning VI.
218 Practical Applications and Solutions Using LabVIEW™ Software

Fig. 14. General block diagram for conditioning VI

Fig. 15. Conditioning VI frontal panel after complete R wave peak detection
ECG Ambulatory System for Long Term Monitoring of Heart Rate Dynamics 219

The programming process of both VI was realized with Queued State Machine-Producer
Consumer architecture (QSM-PC). This architecture is used for event structures that send
commands for asynchronous processes. The different tasks inside the VI (e.g. initializations,
acquisition, and storage) are the consumers or commands handler in the QSM-PC. These
commands are triggered by events or producers (e.g. button pressing, status changes, and
user’s actions) which controls the states of the QSM-PC. These states can be sequentially
assigned by the programmer in order to achieve certain structure (Fig. 16).

Fig. 16. Queued State Machine-Producer Consumer architecture used for the VI’s
programming
The acquisition VI program consists of 6 commands handlers and three producers (Fig. 17).

Fig. 17. Diagram block of the acquisition VI in acquisition’s handler and path’s change value
producer
220 Practical Applications and Solutions Using LabVIEW™ Software

The first command handler is the one that sets all the initial condition such as button
conditions, window position, path conditions and the graphs initial set. The second
handler is to create the file where data will be saved. The next handler is a pre-setting for
showing the data while it is obtained and after this the acquisition handler begins. Once
finished the acquisition the next handler is in charge of setting initial conditions again for
a new acquisition or the end of the program. At least all programs must have a default
handler. This handler is just a loop in the program that waits for a producer to be
triggered. For the producers as stated before there are three. One is for the path’s change
value event that assures the place where data will be stored. The second producer is for
the beginning of data acquisition. This producer is triggered by pressing the start button.
At least, the third producer is for exiting the program. This occurs when the Finish button
is pressed.
Figure 18 shows the Conditioning VI which consists of 6 commands handlers and two event
producers. Just as the first VI, the first handler implements the initial conditions. The second
handler is pre-setting condition where data is arranged. This arranging is made by a sub-VI
constructed for decoding the data previously acquired and stored. After this the
conditioning handler starts.

Fig. 18. Diagram block of the conditioning program in the conditioning handler and the start
event producer
ECG Ambulatory System for Long Term Monitoring of Heart Rate Dynamics 221

This handler has inside a sub-VI in which the detrending, denoising, and peaks detection
are integrated. Then after conditioning is finished, the next handler is the post-conditioning.
This handler configures a display alarm indicating that the conditioning is finished. At least
there is an exit handler that finishes the program. This program also has a default handler
that waits for an event’s producer action. The event producers for this program are just two.
One is for beginning the conditioning, and the other for finishing the program.

3. Results
To quantify the rejection of common mode interferences of the ECG amplifiers, we
measured its Common Mode Rejection Ratio (CMRR), which is the quotient between the
differential mode gain  Ad  and the common mode gain  Ac, and it can be expressed in
decibels where CMRR (dB)=20 lg ( Ad/ Ac). Initially, we measured the frequency response of
the differential gain with one input of ECG amplifier grounded, and later, the common
mode gain with both inputs of ECG amplifier short-circuited. Obtained values were:  Ad=
1000, bandwidth=0.05 to 100 Hz and CMRR of 88 dB at 60 Hz with a mean of 84 dB in all
bandwidth. Similar results were obtained in the other two amplifiers. Figure 19 shows the
frequency response of the Ad and CMRR of the ECG amplifier.
With respect to the maximum value of DC voltage that ECG amplifier can tolerate in its
input, the measured value was of ± 500 mV.

(a)

(b)
Fig. 19. Frequency response of ECG amplifier (a) Ad. (b) CMRR.
246 Practical Applications and Solutions Using LabVIEW™ Software

the signal produced by fan into voltage signal. The amplifying circuit conditions the signal
to a required scope. The A/D converter card PXI-4472 from NI Company acquires the signal
and converts it to digital signal. Then the digital signal is accessed to LabVIEW by the
software of the online wavelet neural network fan fault diagnosis system.

Amplifying
The fan under test Microphone A/D Converter LabVIEW on PC
circuit

(a) Structure of the hardware system

(b)Photo of the hardware system


Fig. 4.6. Structure of the hardware system

4.4.2 Design of the software system


As shown in Fig.4.7, the software system comprises three parts of training sample, network
training and on-line diagnosis. The function of each part is described as follows.

Digital Signal Array

Calculating A Calculating Power Calculating Signal


Weighting Spectrum Gravity Energy of Each
Scale SPL(dBA) Center (FC) Frequency Band
 After Wavelet (d3,d4)

Making up the Characteristic Vector (FC,dBA, d4,d3)

Input
Network Input
Setting the
States of  Network
Correction
 signal Weight
acquired
Forward
Forward
Propagation
Propagation
Calculating, Back
Displaying Propagation
and Saving Is the Training Outputting
N
 the Signal Successful?  Reasults
Characteristic
 Parameter s Y
Saving Displaying ,
Correlation  Alarming
Training Sample and Saving
Parameter 
To Hard Disk
On-Line
Network Training Diagnostics

Fig. 4.7. Structure of the software system


 Acoustical Measurement and Fan Fault Diagnosis System Based on LabVIEW 247

Training sample: relying on the target under test sets frequency of sampling, number of
samples, sample size, state of sampling signal such as normal state, paper choking, eccentric
blade, blade breaks, and so on, acquire a certain number of samples of signal in different states.
Then, calculate the feature vector of each state and save the vector to a specified location.
The function of network training: set the node number of input layer, hide layer and output
layer; initialize the weights and threshold values of each layer; train network and save the
correlation parameter for calling.
On-Line diagnostics: acquire the noise signal of fan; calculate the feature vector; input the
trained network; output and save the fault probability and alarm message.

4.4.3 Extracting the feature vector


How to choose characteristic parameters directly affects the performance of diagnosis
system. In the proposed system, the feature vector consists of A-weighted sound level,
power spectrum gravity centre and signal energy of each frequency band after wavelet
decomposition.
The power spectrum gravity center (FC) is calculated by:


∑ fi pi
i =1
FC = N 
  (4-3)
∑ pi
i =1

where, f i is the frequency, pi is the magnitude and i is the order of the power spectrum line.
If fault occurs, the magnitudes of some frequency will change and affect the position of
power spectrum gravity center, the energy distribution of different frequency band after
wavelet decomposition and the measuring results of A-weighted sound level.

4.4.4 Experiments
Four fans RDM8025S made by RUILIAN SCIENC company of China, are used for the fault
diagnosis experiment. One fan is normal, the other three are paper choking, eccentric blade,
and blade breaks respectively.
1. Network structure design
Suppose FC stands for the frequency power spectrum gravity center. A-weighted sound
level is dbA. d3 and d4 respectively stand for the energy distribution of the third and fourth
frequency band after wavelet decomposition. The feature vector x = (FC , dBA, d 4, d 3) is input
of the network. The fault modes such as normal y 1 , paper choking y 2 , eccentric
blade y 3 and blade breaks y 4 are composed of the output vector y = ( y1 , y2 y3 y 4 ) . For
example, y  = (0,1,0,0)  shows that the fan fault is paper choking.
The node number of input layer equals four which is the dimension of x . Similarly, the
node number of output layer equals the dimension of y . The node number of hide layer is
empirically two. Linear action function is chosen at input and output layer. The action
function of hide layer is the sigmoid  function.
2. Signal acquisition
Set the sampling frequency as 5000 Hz and the number of samples as 2048. db2 is used by
wavelet and the decomposition level is four. Under each one of four states, we acquire ten
sets data in which two sets are selected to calculate the feature vector. The results are shown
in Table4-1.
248 Practical Applications and Solutions Using LabVIEW™ Software

Number of
x1 x2 x3 x4 Mode
Samples
1 200.170 78.350 46.306 27.273 Normal
2 190.829 77.913 44.669 23.890 Normal
3 300.180 83.114 61.277 32.537 Paper choking
4 295.919 82.746 59.160 33.841 Paper choking
5 132.724 80.684 65.717 28.857 Eccentric blade
6 134.868 81.450 83.176 38.774 Eccentric blade
7 113.926 74.022 31.793 18.459 Blade breaks
8 122.163 75.550 36.515 19.621 Blade breaks
Table 4-1. Characteristic value of training sample acquired and the corresponding fault
modes

(a) The first group (b) The third group

(c) The fifth group (d) The seventh group


Fig. 4.8. Time-domain waveforms of signal sample
For the first, third, fifth, and seventh set of signal samples time domain waveforms are
respectively listed in Fig.4.8. The front panel of acquisition process is shown in Fig.4.9.

Fig. 4.9. The front panel of signal acquisition module


 Acoustical Measurement and Fan Fault Diagnosis System Based on LabVIEW 249

3. Network training
To keep a stable learning rate and avoid network oscillation, the learning rate, weight and
the error of target should be selected suitably while executing the network training. If the
learning rate is too fast, there will be a constant oscillation in the network that makes it
difficult to achieve the target value. If the error of target is too small, the requirement of
specified iteration number can not be achieved. The initial weight and threshold value are
set as the random number between 0 and 1. In experiment, the error of target and the
maximal iteration number are set as 0.05 and 5000 respectively.

(a) Learning rate is 0.3 (b) Learning rate is 0.2


Fig. 4.10. Relationship between output error Ep and iteration number N
After the network is trained, the relationship between actual output error Ep and iteration
number N is shown in Fig.4.10. In the figure (a), the learning rate is 0.35. A large oscillation
occurs during training. In the figure (b), the learning rate is 0.2. However, the oscillation
during the training is small. When the output error is decreased from 31.2 to 0.049997 and
the required value is reached, the iteration number is 3677. The fault mode of training
sample (t1, t2, t3, t4) and the actual output of network (y1, y2, y3, y4) is listed in Table4-2. It
can be seen from Table4-2 that the fault mode of acquired samples has already been
recognized accurately by the network. Last, the related parameters of this network are
stored in the specified location. The front panel of the training process is shown in Fig.4.11.

Fig. 4.11. The front panel of network training module


4. On-line diagnosis
The well trained network is used to diagnose the fan under test to acquire the noise signal
produced by fan working at each mode. Using the sampling value, the corresponding
250 Practical Applications and Solutions Using LabVIEW™ Software

feature vector is calculated for input to the well trained network in order to perform on-line
diagnosis. Table4-3 lists the characteristic parameters and the corresponding network
outputs.

Number of Fault modes Outputs of network


samples t1 t2 t3 t4 y1 y2 y3 y4
1 1 0 0 0 0.9695 0.0104 0.0002 0.0005
2 1 0 0 0 0.9769 0.0087 0.0001 0.0009
3 0 1 0 0 0.0567 0.9804 0.0007 0.0000
4 0 1 0 0 0.0441 0.9754 0.0021 0.0000
5 0 0 1 0 0.0003 0.0000 0.9921 0.0054
6 0 0 1 0 0.0005 0.0000 0.9434 0.0236
7 0 0 0 1 0.0268 0.0000 0.0325 0.9194
8 0 0 0 1 0.0299 0.0000 0.0146 0.9858
Table 4-2. Fault modes of training samples and outputs of network

Testing Characteristic parameters Outputs of network


sample x1 x2 x3 x4 y1 y2 y3 y4
1
221.104 79.039 46.127 24.898 0.976 0.047 0.001 0.000
(Normal)
2
273.696 81.797 54.367 31.075 0.016 0.980 0.005 0.000
(Paper hoking)
3
135.684 78.717 60.857 26.812 0.003 0.060 0.994 0.010
(eccentric lade)
4
110.927 74.364 31.303 17.032 0.002 0.000 0.044 0.997
(balde breaks)
Table 4-3. Characteristic parameters of testing sample and outputs of network
Compared to Table 4-3 with Table 4-2, we can find that although the feature vectors of fan
under test are different with the training samples, the proposed system can diagnose the
fault accurately. The front panel of online diagnosis module is shown in Fig.4.12.

Fig. 4.12. The front panel of no-line diagnosis module


 Acoustical Measurement and Fan Fault Diagnosis System Based on LabVIEW 251

5. Conclusion
The proposed virtual SLM is calibrated by using TES-1356 sound level calibrator. Its
accuracy is verified by the comparative experiment with TES-1357. The results indicate the
measurement error is within 0.5 dB and the precision meets the requirements of the type I
sound level meter.
In the proposed intelligent fault diagnosis system, the noise produced by fan is diagnosis
signal, non-connect measurement is adopted and using the wavelet neural network
performs the non-linear mapping from feature space to defective space. Modular
programming is adopted in this system, so it is easier to extend and change the
characteristic parameters of fault and structure parameters of the network. Utilizing the
learning, memory and reckoning abilities diagnoses the fault adaptively. The designed
system has the better capacity of learning, deducing and fault tolerant. The diagnosis results
are reliable and accurate.

6. References
Adeli, H. & Jiang, X.J. (2009). Intelligent Infrastructure: Neural Networks, Wavelets, and Chaos
Theory for Intelligent Transportation Systems and Smart Structures, CRC Press, ISBN
978-1-4200-8536-5, Boca Raton, FL
Burrus, C.S. (2005). Introduction to Wavelets and Wavelet Transforms. China Machine Press,
ISBN 7-111-15911-X, Beijing
Cao, G.Z. & Ruan, S.C.(2002).Design of New Instrument Based on DSP for Measuring Car’s
Noise Combined with Rotating Speed. Instrument Technique and Sensor(in Chinese),
No.08, pp. 11-13, ISSN 1002-1841
Cao, G.Z.; Wu, W. & Ruan, S.C. (2004). A New Method for Measuring the Rotary Speed of a
Car’s Engine Based on the Spacing Measurement of Its Noise and Its
Implementation.  Journal of Xi’an Shiyou University( Natural Science Edition, in
Chinese) ,Vol.19, No.05, pp. 81-86, ISSN 1001-5361
Cao, G.Z. & Luo, C.G. (2007). Design of Virtual Sounnd Level Meter in LabVIEW. Instrument
Technique and Sensor (in Chinese), No.06, pp. 16-18, ISSN 1002-1841
Cao, G.Z.; Lei X.Y. & Luo C.G. (2009). Research of a Fan Fault Diagnosis System Based on
Wavelet and Neural Network. 2009 3rd International Conference on Power Electronics
Systems and Applications, Digital Reference: K210509062, ISBN 978-1-4244-3845-7,
Hongkong
Donald, E. & Hall (1987). Basic Acoustics, Harper & Row, Publishers Inc. ISBN 0-06-042611-X,
New York
Hagan, M. T. & Menhaj, M.B. (1994). Training FeedForward Networks with the Marquardt
Algorithm. IEEE Trans on Neural Networks, Vol.05, No.06, pp. 989-993, ISSN 1045-
9227
Kinsler, L.E.; Frey, A.R.; Coppens, A.B. & Sanders, J.V. (2000). Fundanmentals of Acoustics.
Wiley, John & Sons Inc. Pub., ISBN 0-471-84789-5, New York
Luo, C.G.; Cao, G.Z. & Pan J.F. (2008). Design of a Fan Fault Diagnosis System Based on
Wavelet and Neural Network.  Applied Acoustics(in Chinese), Vol.27, No.3, pp. 181-
187, ISSN 1000-310X
252 Practical Applications and Solutions Using LabVIEW™ Software

Mallat, S.G. (1989). A Theory for Multiresolution Signal Decomposition: the Wavelet
Representation. IEEE Pattern Analysis and Machine, Vol.11, No.07, pp. 674-693, ISSN
0162-8828
Mallat, S.G. & Hwang, W.L. (1992). Singularity Detection and Processing with Wavelet. IEEE
Trans on Inform Theory, Vol. 38, No.02, pp. 617-643, ISSN 0018-9448
Pedro, P.C. & Fernando, D. (2010). Intelligent Control Systems with LabVIEW , Springer, ISBN
978-1-84882-683-0, London
Rumelhart, D.E.; Hinton, G.E. & Williams, R.J. (1986). Learning Representations by Back-
propagating Errors. Nature, Vol.03, No.23, pp. 533-536, ISSN: 0028-0836
Ripley,B.D. (1996). Pattern Recognition and Neural Networks, Cambridge University Press,
ISBN0-521-46086-7, Cambridge
Ruan, Z.K. & Cao, G.Z. (2006). An Acoustic Signal Data Acquisition System Based on DSP.
Electric Instrumentation Customer(in Chinese),Vol.13, No.05, pp. 44-46, ISSN 1671-
1041
12

Condition Monitoring of
Zinc Oxide Surge Arresters
Novizon1,2, Zulkurnain Abdul-Malek1, Nouruddeen Bashir1 and Aulia1,2
1UniversitiTeknologi Malaysia (UTM),
2University of Andalas (UNAND),
1 Malaysia
2Indonesia

1. Introduction
Over voltages in power system may occur due to lightning, fault or switching operation.
These overvoltages could reach dangerous amplitudes for power system apparatus. To
protect the system electrical equipment and to guarantee an economic and reliable
operation, surge arresters are applied in almost all types of electrical power network.
Gapless zinc oxide (ZnO) surge arresters are widely used. The surge arresters are usually
connected between the phase and ground terminals. They limit the voltage level in
equipments such as transformers below the withstand voltage level.
Figure 1 shows the values of overvoltage which can be reached without the use of arrester in
per units. The time axis is divided into the range of lightning overvoltage in microsecond,
switching overvoltage in millisecond and temporary overvoltage in second. In the lightning
overvoltage and switching overvoltage range, the magnitude of overvoltage can reach
several per unit if the system is without arrester protection. Arrester could limit overvoltage
below withstand voltage of equipment. This phenomenon clearly shows the importance of
arresters for lightning overvoltage protection.

Fig. 1. Schematic representation of the magnitude of overvoltage


254 Practical Applications and Solutions Using LabVIEW™ Software

In this chapter, signal processing using LabVIEW is presented to separate the resistive
leakage current from ZnO arrester leakage current using a novel technique called the Shifted
Current Method for the purpose of monitoring the degradation of ZnO surge arrester.

1.1 Zinc oxide surge arrester


The construction of ZnO surge arresters consist of a very simple structure. They basically
consist of an insulating housing which is made of porcelain or polymeric material, and the
inner active column, composed of the ZnO varistors as shown in Figure 2.

Fig. 2. The cross-section view of a polymeric insulated distribution class ZnO surge arrester
The ZnO varistor block elements are the main component of the ZnO surge arrester. They
provide the desired non-linear characteristics and present a strong relation with the
temperature (low current range). The non-linear resistivity is an inherent bulk property of
the composite ceramic resistor, which consists of mainly ZnO with relatively small amount
of several additives of other metal oxides such as Bi 2 O3, CoO2, MnO3, and Sb2O3 (Eda, 1989).
These additives essentially determine the electric properties of the block arresters element.

1.2 Voltage current characteristics of ZnO varistor block


The ZnO surge arrester element is composed of high-purity ZnO, which is the major
constituent, and also slight amounts of some oxides of bismuth (Bi), cobalt (Co), manganese
(Mn), antimony (Sb), and etcetera. These are thoroughly mixed, granulated, formed (pressed
into a disc), specially treated to produce high-resistance layers on all sides of the element
and finally sintered at a high temperature of more than 1000°C.
The blend ratio of ZnO surge arrester and additives is not constant but is about 9:1 (Kobayashi,
1986). The microstructure of this element is clarified by a secondary electron image taken by
EMPA (Electron Probe Micro Analyzer). Figure 3 shows the secondary-electron image of the
element. As shown in Figure 3, fine ZnO grains of 1 to 10 µm size can be seen.
The intergranular layer comprises mainly of Bi 2O3 and spinel (An7Sb2O12) distributed in the
grain boundary. The excellent voltage-current nonlinear characteristics of the element may
be attributable to the junction of the ZnO grain and the intergranular layer consisting mainly
of Bi2O3. While the specific resistivity of ZnO grain is 1 to 10 Ωcm, that of the intergranular
layer is as high as 10 10 Ωcm and therefore almost all of the voltage applied to the element is
concentrated on this high-resistivity intergranular layer. This layer possesses such a non
ohmic characteristic that its resistance decreases suddenly at a certain voltage as the applied
voltage rises.
Condition Monitoring of Zinc Oxide Surge Arresters 255

Fig. 3. Secondary-electron image of the ZnO element (Kobayashi, 1986).


The voltage-current characteristic of this layer shows an excellent non linearity throughout
the range of 10-6 to 104 A. The nonlinearity of this element is attributable to the combination
of insulator (intergranular layer) and ZnO grain. Figure 4 shows the V-I characteristics of
ZnO element which are divided into three regions, being low current region (I), operating
region (II) and high current region (III).

Fig. 4. Voltage-current characteristics of ZnO element (Eda, 1980)


The current density-electric field J-E, relationship in region I is expressed from the physical
point of view as follows:

⎪⎧ φ − β E0 .5 ⎪⎫
 J J0 exp ⎨−
= ⎬  (1)
⎪⎩ kT ⎪⎭
where β = ( e0.75 π εεo), φ  is the potential barrier (Â), E the electric field intensity (V/m), k the
Boltzmann constant, T the absolute temperature (K), e the electron charge (C), εo the vacuum
dielectric permittivity, and ε is the relative permittivity of the barrier substance.
Equation 1 clearly shows that, in low current region (I), the characteristics vary considerably
with the temperature T. This region is located at a point where the line-frequency voltage is
applied in applications for metal oxide arresters and it becomes important to pay attention
particularly to the characteristic change with energized time and the temperature dependence.
256 Practical Applications and Solutions Using LabVIEW™ Software

In operating region (II), the current density is considered to be proportional to a power a of


the electric field intensity and is explained by the Fowler-Nordheim tunnel effect:

⎛γ⎞
 J = J0 exp ⎜ ⎟   (2)
⎝E⎠
1
4 ( 2m ) 2
where γ   = , m is the electron mass, and h=ĥ/2 π  , with ĥ being the Planck's constant.
3he
The nonlinearity is generally given by the following experimental expression:

I = C Vα   (3)
where α = nonlinear exponent and C is a constant.
In applications of ZnO surge arrester this second region relates to protective characteristics
when a lightning impulse current has flowed through the arrester. The greater the value of
α, the better is the protective characteristics.
In high current region (III), the resistivity of ZnO grain is dominant and the characteristic is
given by:
V ≈ KI   (4)
where K is the resistivity of the ZnO grain.

1.3 ZnO arrester model


The non-linear voltage current characteristic of ZnO arrester in low current region (I) is
generally represented by the equivalent circuit shown in Figure 5 (Lee, 2005). The resistor R 1
represents the non-linear resistance of the granular layers, where the resistivity ρ changes
from 108 Ωm for low electric field stress to just below 0.01 Ωm for high stress. The equivalent
capacitor C represents the capacitance between the granular layers with relative dielectric
constant between 500 and 1200 depending on manufacturing process. R z is the resistance of
the ZnO grains with a resistivity of about 0.01 Ωm. To account for rate of rise effects, an
inductor is included as shown in Figure 5. The inductance L is determined by the geometry
of the current flow path.

R
z
(ρ = 10− 2Ω m)

Ir  Ic

R1 ( ρ = 10 8 − 10−2 Ωm) C ( εr = 500 −1200 )

It

Fig. 5. Equivalent electric circuit of ZnO element


Condition Monitoring of Zinc Oxide Surge Arresters 257

When R1 and C changes, the capacitive current (I c), and the resistive current (I r) also change.
The arrester’s leakage current, in particular, the third harmonic component of the resistive
leakage current, is known to be directly related to the degree of degradation of the ZnO
arrester (Lundquist et al., 1990; Spellman et al., 1997; Zhou et al., 1998; Tang et al., 1999). In
this work, in order to extract the resistive component from the total leakage current, the
shifted current method (Abdul-Malek, et al. 2008) was used. The algorithm to extract the
resistive component was implemented using the LabVIEW software.
The proposed method focuses on the ZnO arrester characteristic in low current region (I). In
the low current region, Rz  is much less than R1  and the inductance L may be neglected.
Therefore, in the continuous operating voltage region, the ZnO surge arrester is modelled as
a non-linear resistor with a linear capacitive element in parallel as shown in Figure 6
(Haddad, et al. 1990).

I Ic

R
C

It

Fig. 6. Simplified equivalent model of a typical ZnO arrester


The total leakage current (I t) of the arrester is given by a vector sum of a capacitive
component (Ic) which does not vary with degradation of the arrester, and the resistive
leakage current component (I r) which varies with the degradation of the surge arrester.
Figure 7 shows the typical phasor relationship of all these currents.
Ic It

Ir  Vref 

Fig. 7. Vector diagram of I t, Ic, Ir and reference voltage.


All currents are time dependent, so I t, Ic and Ir can be written as:
I t(t) = Ir (t) + Ic (t)   (5)
The resistive current component can be obtained simply by subtracting the capacitive
current component from the total leakage current as shown below:
Ir (t) = It (t) + Ic (t)   (6)
258 Practical Applications and Solutions Using LabVIEW™ Software

When system voltage is applied on the surge arrester at continuous operating voltage, about
80% of the rated voltage, the arrester experiences some leakage current. The amplitude of
the leakage current depends on the condition of the surge arrester. The leakage current
consists of the capacitive and the resistive current component. The typical specific
capacitance of ZnO varistor block is 75 pF kV/cm 2. Typical values of the capacitive current
range from 0.5 to 3 mA depending on the varistor diameter. For a complete surge arrester,
the capacitive current depends on the number of varistor columns in parallel, the stray
capacitances and actual operating voltage.

2. Shifted current method algorithm


One of the most common and straight forward techniques for extracting the resistive
leakage current (LC) for the purpose of condition monitoring is the compensation technique
(Shirakawa et al., 1998). In order to extract the resistive component from the total leakage
current, the voltage across the arrester terminals is usually measured and used as a
reference so that, based on the phase difference, the capacitive current component can be
established. The resistive component is then obtained by just subtracting the capacitive
component from the total leakage current. Other techniques to discriminate the resistive
leakage current with the need of voltage as reference for the purpose of arrester condition
monitoring have also been reported (Huijia et al., 2009; Kannus et al., 2007; Lira et al., 2007;
Wenjun et al., 2008; Vitols et al., 2009).
Traditionally, measurement of total leakage current in substations or other installations was
easily done using current shunts or current transformers, but the measurement of applied
voltage to obtain the resistive LC make these techniques more appropriate in the laboratory
rather than onsite due to the difficulty of measuring the voltage.
In this work, a new technique called the Shifted Current Method (SCM) is presented. This
technique does not require knowledge of the applied voltage for the resistive leakage
current to be obtained. The method is totally based on the manipulation of the total leakage
current waveform. If the total leakage current is given by Equation 7 and the corresponding
phase shifted (by a quarter of period) current by Equation 8, then the summation of these
two waveforms can be written as Equation 9 below:
I t (t) = It cos(ωt)   (7)

⎡ ⎛ 1 ⎞⎤
I tshifted ( t ) = I t cos ⎢ω⎜ t − ⎟ ⎥   (8)
⎣ ⎝ 4f ⎠ ⎦

⎡ ⎧ ⎛ 1 ⎞ ⎫⎤
Isum (t) = I t ⎢ cos(ωt) + cos ⎨ω⎜ t − ⎟ ⎬⎥   (9)
⎣⎢ ⎩ ⎝ 4f ⎠ ⎭⎦⎥
where It(t) is the total leakage current, I tshifted is the shifted total leakage current (by a quarter
of period of waveform), and Isum  is the summation of the total leakage current and the
shifted current wave form. By signal manipulation technique, from this summation current,
the capacitive component of total leakage current can be determined, and thereafter the
resistive component of the leakage current can also be obtained by subtracting the capacitive
component from the total leakage current.
Condition Monitoring of Zinc Oxide Surge Arresters 259

Based on the above proposed technique, the algorithm to separate the resistive leakage current
from the total leakage current was built. The algorithm for the shifted current method could be
summarized as follows. Firstly, the arrester total leakage current is measured, and then a new
waveform is introduced by shifting the measured arrester total LC by a quarter period of its
operating frequency. Next, both the two total leakage currents are summed together and their
peak time determined. The amplitude of summed total leakage currents at time T p, where Tp is
the time corresponding to the peak value of the summation waveform, is the peak value of the
resistive current. The peak time obtained is used to determine the peak time of the capacitive
current component which is equal to a quarter of period before or after the peak time of the
resistive component. The peak value of the capacitive component is also determined from the
original leakage current waveform. The capacitive leakage current is then generated based on
the peak time, the peak value and the frequency detected. Finally, the resistive leakage current
is obtained by subtracting the capacitive leakage current from the total leakage current. The
block diagram of the algorithm for calculating the resistive leakage current using the shifted
current method is shown in Figure 8.

Analog  Shifted Resistive


Leakage Subtracting  Leakage
Digital Leakage
Current Current
Converter Current

Added Peak Time


Current Detection

Capacitive
Current

Fig. 8. Block diagram of the shifted current method algorithm

3. Implementation of method in LabVIEW


The shifted current method was implemented in NI LabVIEW 8.5 software. Each block was
created and after that combined together to build an arrester monitoring system based on
the SCM algorithm. The subsequent subsections explain the implementation of the SCM in
LabVIEW.

3.1 LabVIEW-picoscope interface


Picoscope is a device that resembles the functions of an oscilloscope but runs on computer.
Usually, Picoscope comes with software that turns it into a PC oscilloscope. In order to
connect with LabVIEW, a VI (virtual instrument) interface was developed. LabVIEW
Picoscope VI program links the Picoscope with LabVIEW software. The block diagram of
the program is shown in Figure 9. The interface indicator shows a graph in front panel of the
block diagram as shown in Figure 10.
Digital Image Processing Using LabView 311

⎛ D⎞
ω ∗ ⎜ R − = v1   (22)
⎝ 2 ⎟⎠

⎛ D⎞
ω ∗ ⎜ R − = v2   (23)
⎝ 2 ⎟⎠
Where v1  and v2  are the wheel’s velocities, R is the distance from ICC to the midpoint
between the two wheels.

v2 + v1 D
R= ∗   (24)
v2 − v1 2

v − v1
ω  = 2   (25)
D
The velocity in the C Point is the midpoint between the two wheels and can be calculated as
the average of the two velocities

v1 + v2
Vc =   (26)
2
According to these equations if v1=v2  the robot will move in a straight line. In the case of
different values in the velocities of the motors, the mobile robot will follow a curved trajectory.
Brief description of the system: A picture of the mobile robot is shown in Fig. 19. The mobile
robot is dived in five important groups: the mechanical platform, the grasping system, the
vision system, the digital control system and power electronics system.
• In mechanical platform were mounted 2 DC motors, each one of the motors has a high
torque and a speed of 80 RPMs. Obtaining with these two parameters a high torque and
acceptable speed of the mobile robot.
• The grasping system is a mechatronic device with 2 DOF of linear displacements, there
are two servos with a torque of 3.6 kg-cm and speed of 100 RPMs.
• The Microsoft webcam Vx-1000 was used for the Vision System section. This webcam
offers high-quality images and good stability.
• The digital control system consists in a Microcontroller Microchip PIC18F4431. The
velocity of the motors are controlled by Pulse Wide Modulation, therefore, this
microcontroller model is important because contains 8 PWMs in hardware and 2 in
software (CCP). Moreover, all the sensors of the mobile robot (encoders, pots, force
sensors, etc.) are connected to the analog and digital inputs. The interface with the
computer is based on the protocol RS232.
• The power electronic system is carried out by 2 H-Bridges model L298. The H-Bridge
regulates the output voltage according to the Pulse Wide Modulation input. The motors
are connected to this device and the velocity is controlled by the PWM of the
microcontroller.
The core of the system remains in the fusion of the computer-microcontroller interface and the
vision system. On one hand, the computer-microcontroller interface consists in the serial
communication between these two devices, therefore it is important to review how a serial
communication can be carried
carried out using LabView. In the other hand, the vision consists
consists in the
pattern matching algorithm which find the template of a desired object in an acquired image.
312 Practical Applications and Solutions Using LabVIEW™ Software

Fig. 19. Mobile Robot.

Fig. 20. Electronics Targets.


Fig. 21 presents an example about RS232 communication (write mode). There is an
important block for serial communication called VISA configure serial port located in
Instrument IO/Serial/. In this block is necessary to place the correct information about the
COM, the baudrate, data bits, parity, etc. For this example COM4 was used, with a baudrate
of 9600, 8 bits of data and none parity. A timed loop structure was selected to write
information in determined time, in this case the timed loop was configured in a period of
50msec. It is important to remark that the data in serial communication is transmitted like
string of characters, therefore it is important to convert any numerical value in a string
value. The block used for this task is: numeric to decimal string, located in
programming/string/string conversion/, this block convert a decimal number into a string
and contains two input parameters, the first one is the decimal number to be converted and
the second one is the width of this decimal number, all the string conversion outputs are
concatenated using the concatenate string block and this information is sent to the write
buffer input of the VISA write block. The VISA write block is the responsible to write the
string information in the specified serial port. Normally a termination character is very
important in the serial communication, in this case it was used the termination character \r.
The block VISA property node is the responsible to add a termination character. In this
block must be chosen
chosen the option TermChar,
TermChar, TermChar En and ASRLASRL End Out. For this
example was written 13 in Termchar that corresponds
corresponds to \r, the TermChar En was activated
with a True value and in ASRL end Out was chosen the TermChar option.
Digital Image Processing Using LabView 313

Fig. 21. Serial Communication and Joystick configuration/control.


The mobile robot can work in automatic and manual way, in the manual way the mobile
robot can be manipulated through a joystick. The configuration of the joystick is a simple
task, there is a block called Initialized Joystick located in connectivity/input device control/.
This block needs the index parameter, in this case there is only one joystick connected and
the index is 0. Once the joystick is configured, the second step is to acquire the data through
the block Acquired Input Data. In data is presented in a cluster format. Therefore an
unbundle block is necessary to obtain the parameters in an individual form.

Fig. 22. Mobile robot observing the scene.


The aim of the mobile robot is to recognize a specific object for the environment using
machine vision. In order to do this task, a specific object
object was selected like the
the pattern image
(in this case was the
the red box Fig. 23) using the Vision Assistant
Assistant toolbox. Once the pattern
pattern
image was selected,
selected, the algorithm can identify
identify the location of the box in real-time.
real-time. Fig. 22
shows the mobile robot observing the environment and looking for the desired object. The
searching algorithms are inside the microcontroller, if the pattern matching does not
recognize any match, the robot moves in different position until a match is recognized. Once
the match is recognized the algorithms gives the x,y position of the match in the image. This
position is important because the robot will try to center the gripper according to the x,y
position of the desired object. There is an infrared sensor that obtains the distance from the
gripper to the desired object and the microcontroller moves the gripper to the correct
position and grasps the object.
314 Practical Applications and Solutions Using LabVIEW™ Software

Fig. 23. Pattern Matching configuration.

Fig. 24. Block Diagram of the Mobile Robot System.


Digital Image Processing Using LabView 315

Fig. 24 shows the complete block diagram of the mobile robot, there is a timed loop where
the joystick and serial transmission are performed in a specific interval of time in the same
time the vision algorithms are carried out in the same loop. Moreover, there is a selector to
switch from manual to automatic control. In the automatic way, the coordinates of the
match are sent to the microcontroller and this device runs special routines to orientate the
robot in a correct position. In the manual way, the control is carried out by the user using a
 joystick.

Fig. 25. Front Panel of the Mobile Robot System.


Fig. 25 shows the results of the pattern recognition algorithm, the robot was capable to
observe its environment and recognize the desired object. This final project presents the
integration of different algorithms that were presented and explained in previous sections of
this chapter. The block diagram presents the initial configuration of the joystick and the
serial port using the Initialize joystick block and the VISA configuration block. In the timed
loop is executed the vision algorithms for the object recognition and the serial data
transmission using the joystick or using automatic form. In the automatic form the
microcontroller receives the x-y position of the object and the carries out all the algorithms
of path planning inside the microcontroller
microcontroller to arrive to this object and grasp it.

9. Conclusions
Different basis techniques of digital image processing using LabView have been boarded in
this chapter. At the beginning some theoretical concepts about the image generation were
discussed for standing out the effects of illumination, scene and acquisition system in the
results of image processing.
Then the stages of a classic system of image processing were described as well as the
necessary tools of the LabView platform to achieve each stage, from the acquisition of the
image to a control of a mobile using the image matching template. The image
transformation leave to know how the output image is generated from an input image with
the use of punctual and grouped operations, some examples were presented of most
comment image transformations.
Finally the pattern recognition section shows how to use an image into a computer vision
application, through an example of object detection and the use of other functionalities of
LabView suggest that the use of LabView as an excellent platform to develop robotic
projects as well as vision and image processing applications. The versatility provided
provided by the
316 Practical Applications and Solutions Using LabVIEW™ Software

software LabView and the capability of IMAQ toolbox increase the possibility to improve
the use of digital image processing in any application area.

10. Acknowledgement
This work is supported by the General Council of Superior Technological Education of
Mexico (DGEST).
Additionally, this work is sponsored by the National Council of Science and Technology
(CONACYT) and the Public Education Secretary (SEP) through PROMEP.

11. References
Chitsaz, H., & La Valle, S. (2006). Minimum Wheel-Rotation Paths for Differential Drive
Mobile Robots Among Piecewise Smooth Obstacles. Robotics and Automation, 2006.
ICRA 2006. Proceedings 2006 IEEE , 1616 - 1623.
Denning, D. (2006). Software Enginnering. IEEE Transaction on ,on  , SE-13, 222-232.
2001 Digital Imiage AnalysisNew YorkUSASpringer-Verlag
Dongkyoung, C. (2003). Tracking Control of Differential-Drive Wheeled Mobile Robots
Using a Backstepping-Like Feedback Linearization. IEEE transactions on systems,
man, and cybernetics—part a: systems and humans , 1-11.
Fairchild, M. (2005). Color Apperance Modeles. Chichester, UK: Wiley-IS&T.
Forsyth, D., & Ponce, J. (2002). Computer Vision: A Modern Approach.   New Jersey: Prentice
Hall.
Frery, L. V., Gomes, A., & Levy, S. Image Processing for Computer Graphics and Vision.  New
York, USA: Springer-Verlag.
Springer-Verlag.
Goshtasby, A. (27. Enero 2009). Pattern Analysis and Machine Intelligence. IEEE transactions
on , 338-344.
Greenwald, L., & Jkopena, J. (2003). Mobile Robot Labs. IEEE Robotics and Automatization
 Magazine , 25-32.
Izak, P., & Hrianka, M. (kein Datum). Biomedical Image Analysis by Program "Vision
Assistan" and "LabView". Advances in Electrical and Electronic Engineering , 233-236.
Papadopoulos, E., & Misailidis, M. (2008). Calibration and planning techniques for mobile
robots in industrial environments. Industrial Robot: An International Journal  , 564-572.
Reinders, M. (1997). Eye Tracking by Template Matching using an Automatic Codebook
Generation Scheme. Third Annual Conference of ASCI  . .
Seong-Min, K., Young-Choon, L., & Lee, S.-C. (18. Octuber 2006). SICE-ICASE , 1508-1512.
Wyszecki, G., & Stiles, W. (1982). Color Science: Concepts and Methods Quantitative Data and
Formulae. New York: John Wiley & Sons.
15

Remote SMS Instrumentation Supervision


and Control Using LabVIEW
Rafael C. Figueiredo1, Antonio M. O. Ribeiro 1,
Rangel Arthur2 and Evandro Conforti 1
1Department of Microwave and Optics - University of Campinas (FEEC/Unicamp),
2Division of Telecommunication
Telecommunication Technology (FT/Unicamp),
Brazil

1. Introduction
The hot emergence of remote monitoring and control systems in recent years is closely
related to the outstanding advance in electronics and instrumentation techniques. As one of
the earliest examples, the telemetry experiments using satellite-relay systems for remote
hydrologic data collection (Glasgow et al., 2004) in the 70’s should be remembered. Since
then, a fast and continual appearance of real time monitoring systems occurred, new devices
and tools have kept coming up, and more and more powerful resources are available with
decreasing prices. Hence, remote monitoring and control systems are gaining market-share
in diversified areas such as industry, security, education and even in health-care
applications.
In every distinct area it is possible to evince different advantages and applications when
using remote systems. To exemplify the industrial field, a remote data acquisition may be
used to monitor machine health and energy consumption in environments where it is
difficult to access or to use wired data acquisition systems (Khan et al., 2004). As another
example, a remote fault diagnostic system to check machines status including data, image,
and video trough the Internet and mobile terminals by wireless application protocol (WAP)
(Wang et al., 2007) was implemented. In the security area, a robot can inspect home
environment giving general information and alarms about dangerous situations using
wireless network (Zhang et al., 2007). In addition, real-time remote health monitoring
systems can acquire and process data to evaluate long bridge structure reliability (Jianting et
al., 2006). Regarding the educational field, there is a web-based remote control laboratory
that employs a greenhouse scale model for teaching greenhouse climate control techniques
using different hardware and software platforms (Guzmán et al., 2005), and also a virtual
laboratory that permits remote access via Transmission Control Protocol/Internet Protocol
(TCP/IP), enabling control and supervision through the Internet (Garbus et al., 2006). In
addition, the results of an evaluation of remote monitoring in home health care show a
reduction in nursing visit and hospitalization rates in the remote monitoring patient group
(Rosati, 2009).
The example list can be much longer. The technological advances allow development of
systems with more and better resources and higher transmission rates, consequently
increasing its complexity and budget. However, in various applications we just need to
318 Practical Applications and Solutions Using LabVIEW™ Software

control or monitor simple tasks, which can be performed by less complex and cheaper
systems. In some cases there is a very small amount of data being collected and the
necessary command to perform a specific action can be sent in a simple text message with a
few characters. In this context, the short message service (SMS) used in cellular networks is
being adapted to several remote applications. Despite some restrictions, such as the limit of
160 characters per message without a user-friendly graphical interface, the SMS is widely
available throughout the digital cellular network. It can be used by any 2G cell phone, it is a
low cost service, and it does not overload the network since this service does not consume
much network resources. These and other advantages led to the development of diversified
remote applications using SMS. Among many examples, the SMS can be used to monitor
and/or control remotely the functions of an automotive alarm (Figueiredo et al., 2008), the
ambient temperature in regions of difficult access (Zarka et al., 2006), a computer network
(Sarram et al., 2008), an electronic switching system (Zahariah et al., 2009), as well as the
status of power earth lines (Xiao et al., 2009).
Addressing now the main focus of this chapter, the Laboratory Virtual Instrumentation
Engineering Workbench (LabVIEW) is a graphical programming environment from
National Instruments that deserves attention not only on remote systems, but in a wide
range of applications. Originally released in 1986, LabVIEW is commonly used to develop
sophisticated measurement, test, and control systems; and its graphical language permits
the development of programs even by inexpert programmers. The popularity of this
platform has been increasing. Some years ago it was included in the curriculum of electrical
engineering students by practical approaches involving experiments in electronics (Alsaialy
et al., 2003; Higa et al., 2002). It is also possible to highlight a long list of applications using
LabVIEW, among which we cite a system to analyze and monitor the mechanical vibration
of industrial machines (Lita et al., 2005); a remote-accessed instrumentation laboratory for
digital signal processors training on the Internet (Gallardo et al., 2006); a solution of data
acquisition/distribution designated for remote process control and long distance learning
(Sgârciu & Stamatescu, 2010); a tele-health system that detects changes in heart rate and
blood pressure of the patient in advance and sends an alert SMS to the doctor (Sukanesh et
al., 2010); and a low cost system to monitor and control laboratory instruments remotely by
SMS (Figueiredo et al., 2009). This chapter will be developed based on this last application,
focusing on the necessary steps for the LabVIEW-based software development and
describing all the programming details for creating a remote monitoring and control system
using LabVIEW and SMS. Additionally, at the end of the chapter, an example of system
applicability is illustrated in a measurement procedure, validating the developed tool and
demonstrating the implementation in a specific application.
In general terms, a computer running LabVIEW is connected to a Global System for Mobile
Communication (GSM) modem via RS-232 serial communication. This GSM modem is
controlled by AT commands, which is a standard-command set with instructions used for
modem control, detailed in Section 2 of this Chapter. The GSM modem enables the user to
monitor and control a specific instrument while away from it, using a cell phone that sends
and receives text messages through SMS. As an example to be discussed here, the
instrument can be connected to LabVIEW via IEEE-488 General Purpose Interface Bus
(GPIB), but it can also be easily adapted for other communication forms.
The chapter is organized as follows:
• Section 2 aims to provide basic knowledge about issues that will be raised during the
system development. The text brings basic information about LabVIEW, SMS and AT
Remote SMS Instrumentation Supervision and Control Using LabVIEW 319

commands, always focusing on the resources that will be applied in this particular
project;
• Section 3 describes the system architecture. Also, the program created in LabVIEW will
be fully detailed;
• Section 4 presents a case study in which the designed tool is applied to an 1.8-GHz
narrow band envelope measurement made in an urban area to characterize the
coherence bandwidth between two frequency-spaced radio mobile signal (Ribeiro et al.,
2007), demonstrating the remote SMS system operation and results.;
• Section 5 gives the concluding remarks followed by acknowledgments in Section 6;
• Section 7 comes with the references.

2. Background
As mentioned earlier, the purpose of this Section is to provide a basic understanding of the
issues to be raised throughout the chapter. Initially, the SMS will be briefly addressed,
followed by some explanation of AT commands, listing the main commands that will be
used to control the GSM modem. Lastly, some basic LabVIEW concepts related to the
development of our remote application will be quickly described.

2.1 Short Message Service (SMS)


( SMS)
The SMS technology evolved from the GSM standard in the early 90’s. It is currently
available in the entire GSM network and can be accessed by practically every cell phone.
The service enables the user to send messages with the maximum length of 160 or 140
characters when using 7-bit or 8-bit encoding, respectively. The system can segment
messages that exceed the maximum length into shorter messages. In this case, it must use
part of the payload for a user-defined header that specifies the segment sequence
information. When a text message is sent from a user to another, the phone actually sends
it to a short message service center (SMSC), where the message is stored and delivered
when the recipient is on the network. Namely, it is a store-and-forward operation. In this
paradigm, the system keeps resending the message for some period of time until it is
successfully received.
received. The SMSC usually has a configurable time limit for how long it will
store the message, and be able to resend it in case of failure in the previous attempts.
Messages can be sent using text mode or protocol data unit (PDU). The text mode is a
character-based protocol and it is the simplest mode to send messages, suitable for
unintelligent terminals. The PDU may contain control information, address information,
or data, i.e., this mode adds the convenience of binary data to be transmitted, not just
characters (Peersman et al., 2000; Brown et al., 2007). In this project the exchanged
messages will be composed only of ASCII characters. Therefore, the SMS text mode will
be used, which, despite allowing only transmission of characters, it is simpler to work
with.
In this project, the GSM modem is responsible for sending and receiving text messages. It
can accesses the GSM network like a mobile phone, differing in the way it is controlled,
which is accomplished through AT commands. The command set may vary according to the
device manufacturers. Here, the GSM modem used was assembled with the Motorola G24
module, whose operation and main AT commands are described below.
320 Practical Applications and Solutions Using LabVIEW™ Software

2.2 AT commands
AT or Hayes commands are a set of data stream commands for communication between
computers and modems. Originally developed by Hayes Microcomputer Products in the
beginning of modem communications, the AT commands became a standard for modem
control. AT is the prefix for almost every command-line set; it is derived from the word
“attention” and tells the modem that a request is coming. Requests can be made to
accomplish a particular action, to change or query a specific parameter and they are sent to
the modem through strings (Figueiredo et al., 2008; Jawarkar et al., 2007; Zhicong et al.,
2008).
An AT command line may be composed by one or more commands, but it must not exceed
140 characters. Extended commands are preceded by the “+” symbol and are separated on
the same line by a semicolon, whereas basic commands can be separated by a single blank
space. The syntax of an extended command enables to query or change more than one sub-
parameter, but the sub-parameters that will not be modified can be omitted from the
command line. In order to clarify the structure of an AT command line, an example is
shown in Figure 1, where the suffix <CR> is the ASCII (American Standard Code for
Information Interchange) character to “carriage return”. After a query, the modem responds
with a result code that can include the current values and the range of possible values of the
consulted parameter. The result code is also emitted after a request, informing the success or
failure of the execution through the strings OK or ERROR, respectively. An example of the
result code is shown in Figure 2, where <LF> is the ASCII character to “line feed”
(Figueiredo et al., 2008; Motorola, 2008).

Fig. 1. Basic structure of an AT command line [adapted from (Motorola, 2008)].


Remote SMS Instrumentation Supervision and Control Using LabVIEW 321

Fig. 2. Basic structure of result codes [adapted from (Motorola, 2008)].

2.2.1 Main AT commands


The list of all AT commands available for a particular device can be obtained from its
manufacturer. Here we listed only the main commands that were used to develop this
project and for the specific employed modem (Motorola, 2008).
• AT&K0: this command disables the flow control and must be the first command sent
when the serial communication cable does not have the pins to transmit the RTS
(request to send) and CTS (clear to send) signals;
• ATE0: disables the echo from the modem, i.e., the ASCII characters sent are not
repeated back;
• AT+CSQ?: queries the modem signal intensity and ranges from 0 (no signal) to 31
(maximum signal);
• AT+CMGF: configures the message format; “AT+CMGF=1” sets to text mode, where
the body of the message and its headers are given as separate parameters;
• AT+CNMI: configures how incoming messages will be handled by the modem;
“AT+CNMI=,2” routes incoming messages directly to the terminal in a result code with
the prefix “+CMT”. Analogously in a cell phone configured with this mode, instead of
an incoming message warning, the content of the message is immediately displayed on
screen;
• AT+CNMA: acknowledges the receipt of a message and when the “CNMI =,2” mode is
configured this acknowledgment must be sent whenever a new message is received;
• AT+CMGS: sends a short message from the modem to a given recipient and its syntax
is “AT+CMGS=<”recipient number ”>,<call type code>” followed by the message content,
the call type code for local calls is “129”.

2.3 LabVIEW
LabVIEW is a powerful platform for algorithm development, design, prototyping, and
interfacing of embedded system with real-world hardware. LabVIEW uses graphical
322 Practical Applications and Solutions Using LabVIEW™ Software

language (G) that enables the creation of programs in block-diagram form, which are called
virtual instruments (VI). The main executable program is called the top-level VI and the
programs used as modular subroutines are called subVIs. Every VI consists of two main
components, the graphical user interface that is named front panel; and the graphical code
that implements the functionality of the VI, called block diagram. Once a VI is created and
saved, it can be used as a subVI in the block diagram of another VI, acting as a subroutine
(Gan & Kuo, 2007; Oussalah & Djezzar, 2010; Sumathi & Surekha, 2007).
The front panel contains objects known as controls and indicators. Controls are the inputs
that provide data to the block diagram, and indicators shows output data from the block
diagram. These objects, such as buttons, switches, LEDs and graphs are selected from the
controls palette. In the Figure 3, the controls palette and the front panel with some examples
of controls and indicators are shown.
Front panel controls and indicators have a corresponding terminal block on the block
diagram, which holds the graphical source code that defines how the VI will operate. A
block diagram is built with terminals and nodes available in the functions palette and that
are connected by wires. An example using the same controls and indicators used in the front
panel is illustrated in the Figure 4; the colors indicate the data type, e.g., numerical
indicators are blue and floating-point ones are orange.
The block diagram code executes based on the principle of dataflow. The rule of dataflow
states that functions execute only when all of their required inputs are populated with data.
This programming architecture allows both sequential and parallel execution to be easily
defined graphically. When a node completes execution, it supplies data to its output
terminals on the right, and follows the dataflow imposed by the wires connecting the block
diagram objects (Gan & Kuo, 2007; Sumathi & Surekha, 2007).

Fig. 3. LabVIEW front panel example and the controls palette.


Remote SMS Instrumentation Supervision and Control Using LabVIEW 323

Fig. 4. LabVIEW block diagram example with the controls and indicator showed in the
above front panel.

2.3.1 Some programming structures


The LabVIEW structures are graphical representations of the loops and case statements of
text-based programming languages. Structures are found in the functions palette and used
on the block diagram to repeat blocks of code and to execute code conditionally or in a
specific order. Among various structures available in LabVIEW, the While loop will be
briefly described in this subsection, including the case structure, and sequence structures.
Illustrations of those graphical LabVIEW structures are shown in Figure 5.

Fig. 5. Some LabVIEW programming structures and the functions palette.


Remote SMS Instrumentation Supervision and Control Using LabVIEW 331

Fig. 13. Structure that executes the subVI corresponding to the received command.

Fig. 14. Routine that deals with cases where an invalid command is received by the modem.
332 Practical Applications and Solutions Using LabVIEW™ Software

The subVIs to be executed for each command must be placed within the first frame (frame
zero) in the sequence structure that is inside the case structure, as illustrated above in Figure
13. After running the subVI, the next frame assembles a text that confirms the execution of
the requested action and sends it to the front panel, through the “info” indicator, as shown
in Figure 15. This same text is used by the modem to send the user mobile phone a message
via SMS. This text message is sent through a subVI that runs only if the confirmation option
is active, and it is detailed in the next subsection.

3.3.4 SubVI to write message


This subVI is built in a sequence structure, numbered from I to VII, as shown in Figure 16.
The frame I specifies the resource to be opened informing the VISA name to a “VISA Flush
I/O Buffer” block, in this case the resource to be opened is the serial communication port
COM1. The frame II gets the phone number informed by the user and passes it to the frame
III, where it is assembled in the AT command to send a text message from the GSM modem.
Frame IV only transmits the ASCII code for “carriage return”, enabling the entry of the
characters that form the message payload, which is transmitted in the frame V. In frame VI
the “\1A” ASCII characters, which correspond to the “CTRL+Z” command, are sent to the
modem, indicating that the message was written, and enabling the modem to send the SMS.
In this frame is used a large time delay for allow the modem to send the text message.

Fig. 15. Sequence structure that assembles and sends the text message.

Fig. 16. SubVI to send messages from the GSM modem to the user mobile phone.
Remote SMS Instrumentation Supervision and Control Using LabVIEW 333

The frame VII just informs that the subVI for writing and sending the message was executed
correctly, showing this information in the “tab control” placed on the front panel.
All procedures described as the heart of the system are inside a While loop. Hence, after
performing all these actions described, the program returns to the point where it awaits for
the arrival of new text messages by the modem. When a message arrives, this whole process
is repeated until the user press the stop button located on the front panel.
When the stop button is pressed, before the program stops running completely, it goes to
the last frame of the sequence structure, which can be seen in Figure 9 shown earlier. This
last frame function is just to close the communication with the COM1 port through the
“VISA close” block, leaving it available for other possible activities that need to use this
communication port.
At this point it is possible to redesign the flowchart showed earlier in Figure 8, adding now
all program features and also the routine hierarchy, including the subVIs, as shown in
Figure 17. Thus, the block diagram explanation is closed with a summarized review of its
overall operation.
As seen in Figure 17, the computer communication port and GSM modem settings are the
first tasks accomplished. Then, the signal intensity of the modem is checked and the
program enters in a routine waiting for incoming text messages. When a message arrives,
the program searches for a valid command in the text, and once it has been found, the
corresponding subVI is executed. Next, if the confirmation option is active, a text message is
sent the user mobile phone by the modem, confirming the action execution. Lastly, when the
program is stopped, the serial communication port is closed and liberated for other
applications.

Fig. 17. Complete flowchart of actions performed by the block diagram in LabVIEW.
334 Practical Applications and Solutions Using LabVIEW™ Software

3.4 Front panel


The front panel of the program developed in LabVIEW is shown in Figure 18, and its
resources are explained below.
The graphical programming allows the creation of detailed interfaces and with high
iteration levels. However, in this application it is not necessary to provide many resources in
the graphical user interface (GUI), because the user will use it only to start the program and
after will work in the distance using SMS. The functions available on the front panel
designed for this project will be explained according to the numbered blocks showed in
Figure 18.

Fig. 18. The application GUI created in the LabVIEW front panel.
Block I is composed of a table created by the arrays “command” and “action”. The user
should fill the array “action” with a brief description about each code function.
Subsequently, the text of these fields will be used to assemble the confirmations messages
sent to the user.
In Block II there is the switch that lets the user choose whether to receive or not the
confirmation messages after running a requested command. This feature will send the user
mobile phone a text message reporting success or failure of the requested action. Therefore,
it is necessary to inform the phone number to which the confirmations will be sent. Since the
Remote SMS Instrumentation Supervision and Control Using LabVIEW 335

sending of messages implies in additional charges, the switch was designed to enable or
disable this feature.
In Block III there are the signal intensity indicator and a button that closes the program. As
explained before, the indicator is processed through a subVI and its operation is similar to
that seen in cell phones displays: the stronger the signal, the greater the number of bars. The
inactive bars are gray and the active bars are represented in the blue color.
Block IV is formed by the errors indicators. Although there were no failures during the tests
performed in this project, errors may occur during the program execution while reading or
writing in the serial communication buffer, and the error description is displayed in the
corresponding box. Besides, when an error occurs the red LED indicator located in block V
is turned on.
Block V is also composed by information about the program execution. In the “info” box
appears the text of the confirmation messages, which will be sent the user mobile phone by
the GSM modem if the switch of this resource is activated. The indicators X0 to X9 indicate
the last command executed, by turning the corresponding LED to green.
The Block VI is a tab with information about the serial communication channel. The buffer
content is displayed in the “read buffer” box, and the remaining fields show if a valid code
was found in a received message, besides the current string sent to the buffer, and if the
subVI for writing and sending messages was performed correctly. This tab information is
very useful to the programmer, because allows to analyze the status of the serial
communication and locate possible errors with the modem communication. However, it has
no great value to the user, so it is possible to hide the tab by using the button on the left.
Thus, the creation of a user-friendly panel with some basic features allows the user to put
the program to run and accesses its key information without the need to access the block
diagram. It permits to evaluate if everything is fully operational before start to operate the
program remotely via SMS. Moreover, such panel can be useful if there is the need to
publish a web page to monitor the program via Internet.
Once explained the whole operation and programming of the remote SMS system using
LabVIEW, the application will be evaluated in a measurement process described in the next
section.

4. Case study
The objective of this case study is to test and evaluate the proposed remote SMS control and
monitoring. Hence, the developed system was applied to an 1.8-GHz radio mobile envelope
measurement carried out in an urban area. This section will describe the measurement
process and how the SMS tool was used in these measurements, followed by the achieved
results.

4.1 System and measurement description


In the mobile radio channel, signal propagation frequently takes place in a typical urban
environment. In such a situation, there is normally no line-of-sight condition between the
transmitter and mobile receiver and multipath propagation is the predominant
phenomenon. This fact leads to frequency selectivity, since the frequency response of the
channel is no longer flat over all frequencies. One measure of the channel frequency
selectivity is the coherence bandwidth. The coherence bandwidth refers to the frequency
separation between two signals, which results in a given level of correlation between their
Remote SMS Instrumentation Supervision and Control Using LabVIEW 339

sent until the moment when the confirmation returns. Thus it was possible to analyze how
long the system took to receive, interpret and execute the command, and then assemble and
send the confirmation message to the user. Accounting for the delays intentionally inserted
into some LabVIEW routines, the execution times were around thirty seconds. Additional
tests were performed during times of network congestion and the full response time of an
execution did not show large variations (Figueiredo et al., 2009).
Further tests were performed in the vehicle, during the measurement process, in different
days and times. In these tests the confirmation messages were disabled, because it is
possible to note if the action was executed through the spectrum analyzer screen in the
vehicle. As in the previous tests, all requests were correctly executed with times below thirty
seconds, since in this case there are no times of confirmation messages included.
In addition to the tests conducted for this case study, preceding tests were executed for
controlling and monitoring of car alarm functionalities via SMS, where the results were
satisfactory, and with runtimes similar to those obtained here (Figueiredo et al., 2008).
Furthermore, measurements conducted by other authors investigated the transmission time
and message loss probability, in order to analyze the SMS reliability for emergency warning
systems. The measurement results have shown that it is possible to use SMS in such
systems, since there was no message loss and almost every message was received within a
short time, increasing the trustworthiness of applications based on SMS (Pries et al., 2006).

5. Conclusion
Considering the growth of remote monitoring and control systems and knowing that a large
number of such applications can be achieved using simple text messages, this Chapter has
presented the feasibility of a flexible and low cost monitoring and control solution using
SMS, which can be easily applied and adapted to various applications.
The system is LabVIEW-based and uses standard interfaces for communication. So, it does
not require expert programmers to perform adjustments in the program. It requires basically
a computer with LabVIEW, and a GSM modem, besides the instruments to be controlled
and/or monitored. The access to the system can be carried out using any 2G cell phone
without the need to use high cost devices.
This Chapter showed all the details of how to develop the programming framework with
detailed instructions of each routine within the main program, which makes easier the task
of adapting the system for applications different from that illustrated here.
The developed system was applied to a RF signal procedure measurement saving time and
staff in this process. The tool development and its use in a specific application showed the
LabVIEW versatility. Furthermore, the results showed that SMS is suitable and reliable for
several kinds of applications.
At last, the remote SMS instrumentation supervision and control using LabVIEW allows a
wide range of future work, because it is just needed to adapt the program in accordance
with the requirements of any application where it is desirable to control or monitor
instrumentation remotely, and this Chapter gives the necessary foundation for such work.

6. Acknowledgment
This work was supported in part by the Brazilian agencies FAPESP ( Fundação de Amparo a
Pesquisa do Estado de São Paulo ), CAPES (Coordenação de Aperfeiçoamento de Pessoal de Nível
340 Practical Applications and Solutions Using LabVIEW™ Software

Superior ), and CNPq (Conselho Nacional de Desenvolvimento Científico e Tecnológico ), under


CEPOF-FAPESP, FOTONICOM and TIDIA-Kyatera programs.

7. References
Alsaialy, S.D.; Tawy, D.M & Lord, S.M. (2003). Introduction to LabVIEW two-part exercise,
Proceedings of the 33rd Annual Frontiers in Education (FIE) , Vol. 1, pp. T4E-1 ― 6, ISBN
0-7803-7961-6, Nov. 5-8, 2003
Bitter, R.; Mohiuddin, T. & Nawrocki, M.R. (2006). LabVIEW Advanced Programming
Techniques (2nd edition), CRC Press, ISBN 978-0-8493-3325-5, Boca Raton, FL, USA
Brown, J.; Shipman, B. & Vetter, R. (2007). SMS: The Short Message Service, Computer , Vol.
40, No. 12, pp. 106-110, Dec. 2007, ISSN 0018-9162
Figueiredo, R.C.; Arthur, R.; Bonani, L.H. & Arnold, F.J. (2008). Wireless Control System
Based on SMS, Proceedings of IEEE Andean Region IV International Conference
(ANDESCON), Cusco, Peru, Oct. 15-17, 2008
Figueiredo, R.C.; Ribeiro, A.M.O.; Arthur, R. & Conforti, E. (2009). Remote instrumentation
control and monitoring based on LabVIEW and SMS, Proceedings of the 35th Annual
Conference of the IEEE Industrial Electronics (IECON) , pp. 2477-248, ISBN 978-1-4244-
4648-3, Porto, Portugal, Nov. 3-5, 2009
Gallardo, S.; Barrero, F.; Toral, S.L. & Duran, M.J. (2006). eDSPlab: A remote-accessed
instrumentation laboratory for digital signal processors training based on the
Internet, Proceedings of the 32nd Annual Conference of the IEEE Industrial Electronics
(IECON), pp. 4656-4661, ISBN 1-4244-0390-1, Paris, Nov. 6-10, 2006
Gan, W.S. & Kuo, S.M. (2007). Embedded Signal Processing with the Micro Signal Architecture
(1st edition), Wiley-IEEE Press, ISBN 978-0-471-73841-1, Hoboken, NJ, USA
Garbus, R.U.; Aguirre, I.J.O.; Sanchez, R.C. & Pureco, O.R. (2006). Virtual Remote Lab for
Control Practices, Proceedings of Electronics, Robotics and Automotive Mechanics
Conference, Vol. 2, pp. 361-366, Sept. 26-29, 2006
Glasgow, H.B.; Burkholder, J.M.; Reed, R.E.; Lewitus, A.J. & Kleinman, J.E. (2004). Real-time
remote monitoring of water quality: a review of current applications, and
advancements in sensor, telemetry, and computing technologies,  Journal of
Experimental Marine Biology and Ecology , Vol. 300, No. 1-2, March 2004, pp. 409-448,
ISSN 0022-0981
Guzmán, J.L.; Berenguel, M.; Rodríguez, F. & Dormido, S. (2005). Web-Based Remote
Control Laboratory Using a Greenhouse Scale Model, Computer Applications in
Engineering Education, Vol. 13, No. 2, Jul. 2005, pp. 111-124, ISSN 1099-0542
Higa, M.L.; Tawy, D.M. & Lord, S.M. (2002). An introduction to LabVIEW exercise for an
electronics class, Proceedings of the 32nd Annual Frontiers in Education (FIE), Vol. 1,
pp. T1D-13 ― T1D-16, ISBN 0-7803-7444-4, Nov. 6-9, 2002
 Jawarkar, N.P.; Ahmed, V. & Thakare, R.D. (2007). Remote Control using Mobile through
Spoken Commands, Proceedings of International Conference on Signal Processing,
Communications and Networking (ICSCN) , pp. 622-625, Feb. 22-24, 2007
 Jianting, Z.; Hanmin, H.; Shanglian, H.; Weiming, C.; Zhen, J.; Zhixiang, Z. & Simeng, L.
(2006). Remote Real-time Health Monitoring and Evaluation System for Long
Bridge Structure, Proceedings of the Multiconference on Computational Engineering in
Systems Applications (IMACS), pp. 1751-1755, Oct. 4-6, 2006
Remote SMS Instrumentation Supervision and Control Using LabVIEW 341

Khan, S.; Islam, M.R. & Khalifah, O.O. (2004). Wireless and wired remote measurement unit
design and applications, Proceedings of 39th International Universities Power
Engineering Conference (UPEC), pp. 1282- 1285, Sept. 6-8, 2004
Lita, I.; Visan, D.A.; Mujea, G. & Ghita, D. (2005). LabVIEW Application for Analysis of
Mechanical Vibrations from Industrial Environment, Proceedings of the 28th
International Spring Seminar on the Electronics Technology: Meeting the Challenges of
Electronics Technology Progress, pp. 463-467, ISBN 0-7803-9325-2, May 19-20, 2005
Motorola, Inc. (June 2008). Motorola G24 Developer’s Guide - AT Commands Reference
Manual, In:  M2M Wireless Modules, 11.Mar.2011, Available from
http://motorola.com/web/Business/Products/M2M%20Wireless%20Modules/G
24%20Lite/_Documents/static%20files/AT_Commands_Reference_Manual2.pdf
Oussalah, S. & Djezzar B. (2010). Automated MOS Transistor gamma Degradation
Measurements Based on LabVIEW Environment, In: LabVIEW  - Modeling
Programming and Simulations, Riccardo de Asmundis, pp. 163-176, InTech, ISBN
978-953-307-521-1, Rijeka, Croatia
Peersman, G.; Griffiths, P.; Spear, H.; Cvetkovic, S. & Smythe, C. (2000). A tutorial overview
of the short message service within GSM, Computing & Control Engineering Journal,
Vol. 11, No. 2, pp. 79-89, Apr. 2000, ISSN 0956-3385
Pries, R.; Hobfeld, T. & Tran-Gia, P. (2006). On the Suitability of the Short Message Service
for Emergency Warning Systems, Proceedings of the IEEE 63rd Vehicular Technology
Conference (VTC), pp. 991-995, May 7-10, 2006
Ribeiro, A.M.O.; Castelli, C.S.; Barrientos, E.M.M. & Conforti, E. (2007). Coherence
bandwidth in a 1.8-GHz urban mobile radio channel, Proceedings of Microwave and
Optoelectronics Conference (IMOC), pp. 599-602, ISBN 978-1-4244-0661-6, Oct. 29 -
Nov. 1, 2007
Rosati, R.J. (2009). Evaluation of Remote Monitoring in Home Health Care, Proceedings of the
International Conference on eHealth, Telemedicine, and Social Medicine (eTELEMED) , pp.
151-153, Feb. 1-7, 2009
Sarram, M.; Ghasemzadeh, M. & Aghaei, V. (2008). Remote Control and Overall
Administration of Computer Networks, Using Short Message Service, Proceedings of
the International Conference on Information and Communication Technologies: From
Theory to Applications (ICTTA), pp. 1-5, April 7-11, 2008
Sgârciu, V. & Stamatescu G. (2010). Distance Process Monitoring using LabVIEW
Environment, In: LabVIEW - Modeling Programming and Simulations , Riccardo de
Asmundis, pp. 67-88, InTech, ISBN 978-953-307-521-1, Rijeka, Croatia
Sukanesh, R.; Gautham, P.; Arunmozhivarman, P.T.; Rajan, S.P. & Vijayprasath, S. (2010).
Cellular phone based biomedical system for health care, Proceedings of the IEEE
International Conference on Communication Control and Computing Technologies
(ICCCCT), pp. 550-553, ISBN 978-1-4244-7769-2, Oct. 7-9, 2010
Sumathi, S. & Surekha, P. (2007). LabVIEW based Advanced Instrumentation Systems   (1st
edition), Springer, ISBN 978-3-540-48500-1, New York, NY, USA
Wang, W.; Tse, P.W. & Lee, J. (2007). Remote machine maintenance system through Internet
and mobile communication, The International Journal of Advanced Manufacturing
Technology, Vol. 31, No. 7, Jan. 2007, pp. 783-789, ISSN 0268-3768
342 Practical Applications and Solutions Using LabVIEW™ Software

Xiao, J.; Xu, S. & Wu, G. (2009). Monitor System of the Intelligent Power Earth Lines Based
on GSM SMS Protocol, Proceedings of the International Conference on Electronic
 Measurement & Instruments (ICEMI), pp. 3-178-3-181, Aug. 16-19, 2009
Zahariah, M.; Mardiana, B.; Hazura, H.; Fauziyah, S. & Hanim, A.R. (2009). Designing a Low
Cost Electronic Devices Switching System Controlled by Short Message Service,
Proceedings of the International Conference on Computer Technology and Development
(ICCTD), Vol. 2, pp. 292-295, Nov. 13-15, 2009
Zarka, N.; Al-Houshi, I. & Akhkobek, M. (2006). Temperature Control Via SMS, Proceedings
of the International Conference on Information and Communication Technologies: From
Theory to Applications (ICTTA), Vol. 2, pp. 2678-2683, April 24-28, 2006
Zhang, R.; He, F.; Du, Z. & Sun, L. (2007). An Intelligent Home Environment Inspecting
Robot, Proceedings of the International Conference on Mechatronics and Automation
(ICMA), pp. 1683-1688, Aug. 5-8, 2007
Zhicong, Q.; Delin, L. & Shunxiang, W. (2008). Analysis and Design of a Mobile Forensic
Software System Based on AT Commands, Proceedings of the IEEE International
Symposium on Knowledge Acquisition and Modeling (KAM) Workshop , pp. 597-600,
Dec. 21-22, 2008
346 Practical Applications and Solutions Using LabVIEW™ Software

The height of the copper strip was 2 m. A pair of RG 59 coaxial cable was laid horizontally to
mimic the TSL in a certain distance, d, and height, h. The impulse current was measured using
a Rogowski coil that has a sensitivity of 0.01 V/A. The induced voltage on the cable was
measured through a 50 Ω resistor at the cable’s end. A Tektronix 3052 oscilloscope was with a
10m cable was used to measure the induced voltage, the time scale was set to nanosecond
range. In this experiment, the end of the cables closer to the copper strip were left opened and
the other end was terminated through resistor for measuring purpose.

Coaxial
cable

High Surge High Surge


current current copper 
Generator  Generator  strip
copper  Coaxial
strip d cable
d l
h

Measuring
resistance
(a) (b)

Fig. 3. The circuit connection to simulate the lightning induced voltage on a coaxial cable for
reduced scale model (a) top view and (a) side view, where d is the distance between copper
strip and the coaxial cable and h is the height of cable laid down above the ground or floor.

4. Travelling wave speed


The speed of the travelling wave in the cable was calculated based on the experimental
result as follows:

v = l /t   (3)
where ν = velocity,
l = distance travelled, and
t = time travelled
The velocity, ν  refers to the induced voltage signal speed in telecommunication cable. In this
work, the speed was calculated based on the measurement results.
Figure 4 shows the set-up to determine the travelling wave velocity in the
telecommunication and coaxial cables. The lengths of cable 1 and cable 2 were varied. Table
1 shows the tabulated results. Figure 5 shows the correlation between difference of distance
(DoD) and time diference of arrival (TDoA) of twisted telephone line (in Figure 5a) and RG
59 coaxial cable (in Figure 5b). Based on the measurements, it can be concluded that an
average TDoA of 4.6 ns and 5.1 ns represents 1 m propagation for the telecommunication
cable and coaxial cables respectively.
Lightning Location and Mapping System Using Time Difference of Arrival (TDoA) Technique 347

Oschilloscope

Function Generator 

Cable 1

Cable 2

Fig. 4. The speed of travelling wave measurement in the cable to get the TDoA/m

Do D (m) 0 1 2 7 8 9 10 11 18 19 20
TDoA (ns) 0 4.64 9.28 33.5 37.12 41.53 46.4 51.04 84.6 88.2 92
DToA per meter
0 4.64 4.64 4.79 4.64 4.614 4.64 4.64 4.7 4.64 4.6
(ns/m)
DToA in avarage
4.660
(ns/m)
(a)
DoD (m) 0 1 2 7 8 9 10 11 18 19 20
TDoA (ns) 0 5.2 9 35.6 41.6 45.8 52.4 57.6 91.8 96.6 101
TDoA per meter
0 5.2 4.5 5.09 5.2 5.089 5.24 5.236 5.1 5.084 5.1
(ns/m)
TDoA in avarage
5.082
(ns/m)
(b)
Table 1. Time difference of arrival (TDoA) and the travelling wave speed in (a)
Telecommunication Subscriber Line (b) RG 59 coaxial cable.

(a) (b)
Fig. 5. The correlation between difference of distance (DoD) and time diference of arrival
(TDoA) of (a) twisted telephone line and (b) RG 59 coaxial cable

5. Impulse current generator


Two types of impulse current generators were used in the research work. Firstly, a manually
set up impulse generator described in (Aulia, 2008a and Aulia, 2008b) and secondly a
348 Practical Applications and Solutions Using LabVIEW™ Software

commercial impulse generator manufactured by Haefely. The former was used during
working with the small scale system while the latter was used during the calibration process
of MTSL. Pictorial view of the impulse generators are shown in Figure 6.

(a) (b) (c)

Fig. 6. (a) The manually set up impulse current generating unit, (b) the corresponding input
voltage control unit, (c) Commercial impulse current generator

6. The measurement, transmission and central processing station


Several types of voltage transducers installed at the line ends can be used to measure the
induced voltage due to lightning strikes (Altafim, 1992). In this work, specially modified
voltage transducers were used. Since the lightning strike coordinate was calculated based
on the arrival time delays of various induced voltage impulses, any delay or interference in
the transmission of the induced impulses can influence the calculation. Therefore, the
transmissions of data from the voltage transducers to the central processing station (within
P06 building) were implemented using optical fibres. Optical transmitters and receivers
(transceivers) similar to the ones described by (William, 2006; Kurata, 2007) were used.
Apart from the optical receivers, the central processing station consisted of a LabVIEW-
enabled four-channel high speed oscilloscope and a personal computer (PC).
The block diagram of the measurement and data acquisition system for this work is shown
in Figure 7 and the typical flowchart for the data acquisition implementation is as shown in
Figure 8. LabVIEW 8.5 software was used for the control of the data acquisition system.
All measuring equipment was physically checked to make sure they have been correctly
connected and installed. Referring to Figure 8, when the system is switched on, it will
initialize and be in standby mode waiting for a trigger. In the event of a trigger data will be
acquired and then verified. If the correct signal has been captured, the system determines
the lightning time of arrival, induced voltage, current and map the lightning location in the
Cartesian. On the other hand if the signal captured was not correct the system will be in
standby mode and waits for another event. The location will then be mapped in the
Cartesian system. These parameters will then be stored and printed. If another lightning
event is to be captured, the system returns back to standby mode else stops.
Lightning Location and Mapping System Using Time Difference of Arrival (TDoA) Technique 349

Lightning Strike
Nearby

Electrical to
Voltage
Telecommunication Optical
Transducer 
Transducer 
Subscriber Line (TSL)

Optical data

PC and data
Electrical to Optical data Optical to DAQ and
Voltage collecting,
Optical Electrical signal
Transducer  processing
Transducer  Transducer  conditioning
and analyzing

Laser Bias

Fig. 7. The measurement and data acquisition system of the LLLS

Start

Read Co nfiguration file

Initialize

Determine delay limit

Wait for event trigger

Acquire Data

Verify The Data


yes

Yes No No
Determine The different Correct signal Continue Stop
time of arrival

Determine Lightning Yes


Location Determine the induced
voltage

Calculate t he Lightning
Curernt

Store data

Print or display

Fig. 8. Typical flow chart for lightning data acquisition system


Dynamic Wi-Fi Reconfigurable
Reconfigurable FPGA Based Platform for Intelligent Traffic Systems 385

respective package will be resent. The programming procedure will end with a Stop
Programming command.

Fig. 6. General configuration process (Xilinx, 2009)


The messages exchanged between the entities involved in the FPGA configuration process is
presented in the following figure.

Fig. 7. Description
Description of the communication
communication protocol
386 Practical Applications and Solutions Using LabVIEW™ Software

The application installed on the Tag4M device is responsible for performing the FPGA
programming procedure. The application has an event-driven architecture with a main loop
(presented in Table 1) in which events are handled.

Table 1. Events executed in the main application thread


Without entering into implementation details, the basic activities implemented at Tag4M
level are presented in this paragraph. When the application is started, the first action
performed is the search for an available access point (AP). If one AP is found, the
application will acquire a dynamic IP address and then will wait for messages from the
Configuration Server. When a new message is received by the Tag4M device, it will be
decoded, and depending of its content a new event will be fired. For example, when a Start
Programming message is received this will result in firing a START_PROGRAMMING event
which will be detected and handled by the event loop described in the table above. As
described in the Configuration section, the FPGA configuration bits are sent on the rising
edge of the CCLK signal (the clock is generated on the DIO1 line) using the FPGA DIN line
(which is connected to the Tag4M DIO2 line). The bit sending process is implemented in the
 fpgaPackageSend() function.
Dynamic Wi-Fi Reconfigurable
Reconfigurable FPGA Based Platform for Intelligent Traffic Systems 387

4. Applications of the Wi-Fi FPGA platform for ITS


4.1 Detecting vehicle location using Wi-Fi RSSI
The simplicity and cost efficiency of the Received Signal Strength Indicator (RSSI) based
localization makes it the best candidate for specific applications like tracking systems and
dynamic networks where precision is not crucial.
In the following paragraphs an application implemented in LabVIEW for vehicle
localisation using a FPGA and a Tag4M device is presented.
A “scan” operation which finds all access points and reads the corresponding RSSI values is
implemented at Tag4M level. These values are packed and sent to the FPGA using a serial
communication link where the localisation algorithm is implemented.
Table 2 presents a scan operation result. In this case four APs are detected. The
corresponding RSSI values (in dBm) measured by the Tag4M are reported for every AP.

Table 2. A sequence of results for the “scan” operation executed on the Tag4M device
The program for reading the RSSI values from the Tag4M device was implemented in
LabVIEW2010. Three APs (which are placed on a crossroad) named witagserver, Hawk and
Tag4M, are displayed by the application in this case.

Fig. 8. Front Panel of the program for reading RSSI values


388 Practical Applications and Solutions Using LabVIEW™ Software

The data received by the program are parsed and only data from APs which we are interested
in are processed. The RSSI values are converted to distance values using formula (1).
The value of the received signal strength is a function of the transmitted power and the
distance between the sender and the receiver. The received signal strength will decrease
when the distance increases as the following equation shows (Aamodt, 2006).

RSSI = −(10n ⋅ log 10 d + A) (1)

Where:
- n represents the signal propagation constant, also named propagation exponent,
- d represents the distance from the sender,
-  A represents the received signal strength at a distance of one meter.
The distance values are grouped into an array which is sent to another application using a
Shared Variable. This option offers the possibility for the user to read the location from his
application which runs locally on a Touch Panel Computer (TPC) installed on the car or on a
mobile phone.
The program for localization using the Wi-Fi FPGA platform was implemented in
LabVIEW2010. The application displays the distances between the Wi-Fi FPGA placed in a
car and the three APs placed on a crossroad. The number of APs can be increased for
obtaining a more accurate position estimate. The distances between the Wi-Fi FPGA and
each AP are represented as circles having the centre in the AP locations which have
previously known coordinates.

Fig. 9. Block Diagram for the Tag4M RSSI value reading program
The application was tested for only one crossroad because of the difficulty of placing a
larger number of APs on a road. The car’s position is given by the point at the intersection of
the three circles.
The distance data are received from the program that reads the RSSI values using a Shared
Variable. The local applications which run on a TPC or mobile phone convert the data to
graphical representations which are afterwards displayed.
Dynamic Wi-Fi Reconfigurable
Reconfigurable FPGA Based Platform for Intelligent Traffic Systems 389

Car

Fig. 10. Front Panel of the localisation program

Fig. 11. Block Diagram of the localisation program

4.2 Detecting vehicle movement using accelerometer


accelerometer and the gyroscope sensors
Another application of the presented FPGA platform can be used for detecting the dynamic
vehicle parameters. By attaching a gyroscope sensor and a 3-axis accelerometer to the FPGA
board, the implementation of an application for determining the vehicle’s state (moving or
stopped, running on a straight road or making a turn) is possible. A LabVIEW application
was implemented and installed on a FPGA in order to determine the vehicle’s dynamic
behaviour.
390 Practical Applications and Solutions Using LabVIEW™ Software

A correlation between the signals from a 3-axis accelerometer and a 2-axis gyroscope is
realized in order to determine the state of the car. The signals acquired by the accelerometer
and gyroscope sensors were filtered implementing a Butterworth filter (Figure 12) which
has an essential characteristic: a smooth and monotonically decreasing frequency response
(National Instruments, 2009). The Butterworth filter is available in LabVIEW FPGA, and the
Express VI from the Help documentation and configure panel is presented in Figure 12
along with the settings. LabVIEW allows the operative and rapid change of the filter
parameters and the usage of other types of filters.

Fig. 12. Butterworth filter, FPGA implementation


3-Axis Acceleration Sensor
The acceleration sensor (Figure 13) allows the measurement of static or dynamic acceleration
(in ±3g range) on three axes. The ADXL330, iMEMS type, from Analog Devices was chosen
to be used for this purpose.

Fig. 13. Acceleration


Acceleration sensor scheme
External components are used for establishing the period of the output signal between 2 and
1000 ms, and the frequency band is limited to values between 0.5 and 1.6 kHz. The typical
noise level is 280 μg/√Hz rms and allows the acquisition of signals under a 5 mg level
(Analog Devices, 2006).
Dynamic Wi-Fi Reconfigurable
Reconfigurable FPGA Based Platform for Intelligent Traffic Systems 391

2-Axis Gyroscope Sensor

Fig. 14. Gyroscope sensor scheme


The gyroscope chosen to be used (LPR530AL) integrates one actuator and one accelerometer
in a single micro machined structure. It is based on the Coriolis principle and it is able to
react when an angular rate is applied to the sensing element which is kept in continuous
oscillating movement (STMicroelectronics, 2009). The electric scheme is presented in Figure
14. It has a full scale of ±300 °/s and it is capable of detecting rates of up to 140 Hz with a -3
dB bandwidth.
A series of tests has been performed in order to determine a correlation between the
vehicle’s movement and the signal generated by the two sensors.
The program for displaying data acquired by the Wi-Fi FPGA platform from the 3-axis
accelerometer and the 2-axis gyroscope was implemented in LabVIEW2010 and the
application panel is presented in Figure 15. The application displays the signals received
from the two sensors.

Fig. 15. Front Panel of the “Display Data” program


392 Practical Applications and Solutions Using LabVIEW™ Software

Fig. 16. Block Diagram of the “Display Data” program

Fig. 17. Accelerometer


Accelerometer and Gyroscope signals
Dynamic Wi-Fi Reconfigurable
Reconfigurable FPGA Based Platform for Intelligent Traffic Systems 393

In this case, the Tag4M device is used as a serial RS232 to Wi-Fi gate between the FPGA
board (Spartan-3E Starter Kit) and the PC application that runs on the server. The block
diagram of the PC application is presented in Figure 16.
One initialization step is necessary for reading the data from the Tag4M device. During this
stage, the Tag4M sends a package containing the IP received through DHCP from the AP.
This IP is used in the application for sending commands to the Tag4M device after the
initialization step. The data are read in a loop and are validated if they are received from a
previously known MAC address which is used as a validation mask. The latency
determined after performing a number of experiments lies between the value of 5 and 20
milliseconds and it depends on the RSSI values. The values of the latency are greater in case
of a poor signal.
Figure 17 presents the experimental results obtained from an IVU device installed on a
vehicle performing
performing a series of manoeuvres in a test field.
The length of the “Vehicle stopped” period is of 1500 samples which represent 7.5 seconds
at a rate of acquisition of 200 Sps.

5. Conclusion
The first part of this paper presents a solution for remote Wi-Fi FPGA reconfiguration using
Tag4M devices. The resulting system represents a versatile equipment with multiple
applications in various fields, including ITS.
In the second part two applications developed for a FPGA platform that can be used in road
traffic systems are presented. The first application exemplifies the way in which a vehicle
can be tracked by using access points installed in the field and by using the Tag4M device
which can read the RSSI values for each of them. The approximate of the vehicle’s location is
computed by applying a triangulation algorithm.
In the second application, the dynamic behaviour of a vehicle is determined by using a
gyroscope and an accelerometer sensor attached to a FPGA board.
The work outlines the advantages provided to the developer and to the user by the
employment of the FPGA technology and the features of the LabVIEW programming
language in an Intelligent Transportation System. The reconfigurable systems’ flexibility
and the simplified way of creating programs for FPGAs by using the LabVIEW platform
lead to a system that allows facile in the field hardware upgrades, runtime reconfiguration
and adaptation to unexpected events or to changing environmental conditions.

6. References
Aamodt, K. (2006). CC2431 Location Engine, Application Note AN042, from
http://focus.tij.co.jp/jp/lit/
http://focus.tij.co.jp/jp/lit/an/swra095/swra095.pdf
an/swra095/swra095.pdf
Adly, I.; Ragai, H. F.; Al-Henawy, A. & Shehata, K. A. (2010). Wireless Configuration
Controller Design for FPGAs in Software Defined Radios, The Online Journal on
Electronics and Electrical Engineering (OJEEE), vol. 2, no. 3, pp. 293 – 297.
Altera (2009). AN 307: Altera Design Flow for Xilinx Users, from:
http://www.altera.com/li
http://www.altera.com/literature/an/
terature/an/an307.pdf.
an307.pdf.
Altera (2010). Medical Imaging Implementation Using FPGAs, White Paper , from
http://www.altera.com/lit
http://www.altera.com/literature/wp
erature/wp/wp-medical.pdf
/wp-medical.pdf
Altera (2011). Military End Market, from
394 Practical Applications and Solutions Using LabVIEW™ Software

http://www.altera.com/end
http://www.altera.com/end-markets/militar
-markets/military-aerospace/mil
y-aerospace/mil-index.html
-index.html
Analog Devices (2006). Small, Low Power, 3-Axis 3g MEMS Accelerometer”, Technical
Report, from
http://www.analog.com/en/mems-se
http://www.analog.com/en/mems-sensors/inertial
nsors/inertial-sensors/adxl330/-
-sensors/adxl330/-
products/product.html
Andretzky, B. (2005). FPGAs Build Bridges To Wireless Connectivity, from
http://electronicdesign.com
http://electronicdesign.com/article/em
/article/embedded/fpgas-bu
bedded/fpgas-build-bridges-to-
ild-bridges-to-wireless-
wireless-
connectivity9820.aspx
Banovic, K.; Khalid, M.A.S. & Abdel-Raheem, E. (2005). FPGA-Based Rapid Prototyping of
DSP systems, 48th Midwest Symposium on Circuits and Systems, pp. 647 – 650,
Covington, KY.
Bitter, R.; Mohiuddin, T. & Nawrocki, M. (2006). LabVIEW Advanced Programming Technique ,
CRC Press, second edition.
Bolchini, C.; Miele, A. & Santambrogio, M. D. (2007). TMR and Partial Dynamic
Reconfiguration to mitigate SEU faults in FPGAs, Proceedings of the 22nd IEEE
International Symposium on Defect and Fault-Tolerance in VLSI Systems , pp.87 – 95,
Rome, Italy.
Compton, K. & Hauck, S. (2002). Reconfigurable Computing: A Survey of Systems and
Software, ACM Computing Surveys, vol. 34, no. 2, pp. 171 – 210.
El-Medany, W.M.
W.M. & Hussain, M.R. (2007). FPGA-Based Advanced Real Traffic Traffic Light
Controller System Design, 4th  IEEE Workshop on Intelligent Data Acquisition and
 Advanced Computing Systems: Technology and Applications (IDAACS 2007), pp. 100 –
105, Dortmund, Germany.
G2 Microsystems1 (2008). G2C547 SoC, Technical Report, from
www.g2microsystems.com
G2 Microsystems2  (2008). G2C547 Software, Example Application. Technical Report, from
www.g2microsystems.com.
G2 Microsystems3  (2008). G2M5477 Wi-Fi Module Data Sheet, Technical Report, from
www.g2microsystems.com.
HPCWire (2009). FPGA cluster accelerates bioinformatics application by 5000×, from
http://www.hpcwire.com/offt
http://www.hpcwire.com/offthewire/FPGA
hewire/FPGA-Cluster-Accele
-Cluster-Accelerates-Bioinformat
rates-Bioinformatics-
ics-
Application-by-5000X- 69612762.html
Kalte, H.; Langen, D.; Vonnahme, E.; Brinkmann, A. & Rückert, U. (2002). Dynamically
Reconfigurable System-on-Programmable-Chip, Proceedings 10th Euromicro
Workshop on Parallel, Distributed and Network-based Processing , pp. 235 – 242, Canary
Islands, Spain.
Kuon, I.; Tessier, R. & Rose, J. (2007). FPGA Architecture - Survey and Challenges,
Foundations and Trends® in Electronic Design Automation, vol. 2, no.2, pp. 135 – 253.
Lyke, J. (2002). Reconfigurable Systems: A Generalization of Reconfigurable Computational
Strategies for Space Systems, 2002 IEEE Aerospace Conference Proceedings , vol. 4, pp.
4-1935 – 4-1950.
Maye, J.; Supervisors: Upegui, A. & Prof. Ijspeert, A. J. (2005). Bluetooth Configuration of an
FPGA: An Application to Modular Robotics, Semester Project, from
http://birg.epfl.ch/webdav/
http://birg.epfl.ch/webdav/site/birg/
site/birg/users/147507/public
users/147507/public/semester/
/semester/report.pdf
report.pdf
Mitra S.; Shirvani, P. P. & McCluskey, E.J. (1998). Fault Location in FPGA-Based
Reconfigurable Systems, IEEE Intl. High Level Design Validation and Test Workshop.
Dynamic Wi-Fi Reconfigurable
Reconfigurable FPGA Based Platform for Intelligent Traffic Systems 395

National Instruments (2007). CompactRIOTM   and LabVIEW TM   Development Fundamentals


Course Manual , Course Software Version 8.2.
National Instruments (2009). Working with LabVIEW Filtering VIs and the LabVIEW Digital
Filter Design Toolkit Vis, , from
http://zone.ni.com/devzone/cda/t
http://zone.ni.com/devzone/cda/tut/p/id/4851
ut/p/id/4851
National Instruments1 (2010). What is LabVIEW? , from
http://zone.ni.com/devzone/cda/
http://zone.ni.com/devzone/cda/pub/p/id/1141
pub/p/id/1141
National Instruments  (2011). FPGA Technology, from
1

http://www.ni.com/fpga_technology/
National Instruments2  (2010), Building Programmable Automation Controllers with LabVIEW
FPGA, Tutorial, from:
http://zone.ni.com/devzone/cda/t
http://zone.ni.com/devzone/cda/tut/p/id/3068
ut/p/id/3068
National Instruments  (2011). NI LabVIEW FPGA, from
2

http://www.ni.com/fpga/
Patel, P. & Moallem, M. (2010). Reconfigurable system for real-time embedded control
applications, IET Control Theory and Applications , issue 11, pp. 2506 – 2515.
Prasanna, V. K. & Dandalis, A. (2007). FPGA-based Cryptography for Internet Security,
Online Symposium for Electronics Engineers (OSEE), pp. 1– 6.
Reis, R. &  Jess,  Jochen A. G. (2004). Design Of System On A Chip: Devices & Components,
Kluwer Academic Publishers.
Sander, O.; Glas, B.; Roth, C.; Becker, J. & Muller-Glaser, K. D. (2009). Design of a Vehicle-to-
Vehicle Communication System on Reconfigurable Hardware, International
Conference on Field-Programmable Technology (FPT 2009), pp. 14 – 21, Sydney, NSW,
Australia.
Smith, M. J. S. (1997). Application-Specific Integrated Circuits”, Addison-Wesley Pub Co.
STMicroelectronics (2009). LPR530AP MEMS motion sensor: dual axis pitch and roll 300/s
analog gyroscope, Technical Report, from
http://www.st.com/internet/com/-
TECHNICAL_RESOURCES/TECHNICAL_LITERATURE/DATASHEET/CD0023
7209.pdf
Straka, M. & Kotasek, Z. (2008). Design of FPGA-Based Dependable Systems, Proceedings of
the 4th Doctoral Workshop on Mathematical and Engineering Methods in Computer
Science, pp. 240 – 247, Znojmo, Czech Republic.
Tessier, R. & Burleson, W. (2001). Reconfigurable Computing for Digital Signal Processing -
A Survey, Journal of VLSI Signal Processing, vol. 28, issue 1/2, pp. 7 – 27.
2 7.
Xilinx (1998). The Low-Cost, Efficient Serial Configuration of Spartan FPGAs, XAPP098,
Application Note by Kim Goldblatt, November 13 (Version 1.0), from
http://www.xilinx.com/sup
http://www.xilinx.com/support/documentat
port/documentation/application_note
ion/application_notes/xapp098.pdf
s/xapp098.pdf
Xilinx (2006). Spartan-3E Starter Kit User Guide, User Guide, (Version 1.0), from
http://www.xilinx.com/sup
http://www.xilinx.com/support/documentat
port/documentation/boards_and_kits/
ion/boards_and_kits/ug230.pdf
ug230.pdf
Xilinx (2009). Spartan-3E FPGA Family: Data Sheet, Product Specification, August 26
(Version 3.8), from
http://www.xilinx.com/suppor
http://www.xilinx.com/support/documentation/
t/documentation/data_sheets/ds3
data_sheets/ds312.pdf
12.pdf
Xilinx (2010). Partial Reconfiguration User Guide, from
http://www.xilinx.com/-
support/documentation/sw_manuals/
support/documentation/sw_manuals/xilinx12_1/ug702.pdf
xilinx12_1/ug702.pdf
396 Practical Applications and Solutions Using LabVIEW™ Software

Zhenggang, L.; Jialong, X.; Mingyun, Z.; Jun, Y. & Hongwei, D. (2009). FPGA-Based Dual-
Mode Traffic Light System Design, 1st International Conference on Information Science
and Engineering (ICISE), pp. 558 – 561, Nanjing, China.
Part 6

Programming Techniques
0
19

Extending LabVIEW Aptitude for Distributed


Controls and Data Acquisition
Luciano Catani
Istituto Nazionale di Fisica Nucleare (INFN) - Sezione Roma Tor Vergata
Italy

1. Introduction
LabVIEW is probably the most comprehensive environment for setting up a control/data
acquisition system (CS) for a scientific/laboratory experiment. It provides ready to use
solutions for both control and data acquisition for a large number of equipments and for the
analysis of various types of data.
In the scientific environment, especially, these features are particularly useful because CS are
frequently developed and managed by scientists willing to spend more time in operating
their experimental apparatuses than in maintaining software for controlling components and
reading instruments outputs.
In a scientific laboratory, or a medium/small experimental apparatus, typical selection of 
equipments is unavoidably heterogeneous: scopes, digital I/Os, motors, digital cameras and,
quite often, a mixture of new and relatively old technologies for connecting devices to the
computer managing the system.
Moreover, CS for scientific experiments are quite often far from being developed once forever;
instead they are continuously updated by replacing and/or introducing new components in
order to follow the evolution of the apparatus.
LabVIEW easy to learn graphic programming and its large number of instrument drivers and
libraries for data analysis and graphical display, successfully fulfill the above requirements.
When the scientific apparatus became larger and more complex a single computer may not
 be sufficient for the management of all the components. Additionally, in some environment
the equipments need to be operated from remote or it might be preferable to separate data
acquisition from on-line analysis in order to optimize the performances of both.
In other word the single computer CS needs to be upgraded to implement a distributed control
system (DCS).
LabVIEW provides quite a number of solutions also for the development of DCS by offering
tools for remote control of Virtual Instruments (VI) and sharing of data across the network by
means of dedicated LabVIEW components that allow communicating with remote computers
and devices.
Developers can easily find ready to use solutions for their needs among these resources
although, in some cases, they might either lack in flexibility or cannot offer the required
compatibility with all the software components of the DCS.
In these situations a communication solution for the DCS should be necessarily based on the
widely accepted standard protocols ensuring highest compatibility.
400
2 Practical Applications and Solutions Using LabVIEW™ Software
Will-be-set-by-IN-TECH

There exist numerous possible alternatives. One such model is Microsoft’s component
object model COM(mscom, 2011) and its associated distributed component object model
DCOM which allows COM objects to run and communicate in a distributed manner. Also
from Microsoft is the .NET environment, supporting Internet-based connectivity between
components.
Another option is offered by the CORBA(corba, 2008) proposed by the Object Management
Group (OMG). CORBA is a software standard for component-based development that has
 been quite successful among developers of DCS.
Yet another model is the Java-based proposal by Sun Microsystems, which encompasses basic
infrastructure such as Java Beans and Enterprise Java Beans and remote method invocation
(RMI) but also more ambitious solutions for interoperation of distributed intelligent systems
such as Jini(jini, 2006).
The aim of this paper is to present the development of a communication framework for
distributed control and data acquisition systems, optimized for its application to LabVIEW
distributed controls, but also open and compatible with other programming languages
 because it is based on standard communication protocols and standard data serialization
methods. In the next Paragraph the LabVIEW tools for Distributed Systems and their field
of application will be briefly presented. In Paragraph 3 the general purpose communication
framework will be discussed, with particular attention to the problem of data serialization
and the definition of the communication protocol. Paragraph 4 and subsequents will discuss
in details the implementation of the communication framework in LabVIEW, focusing on the
development strategies and the solutions for achieving the performances required for this
field of application.

2. LabVIEW tools for distributed systems


LabVIEW offers a number of tools for transferring, via network, data between the components
of a distributed control/data acquisition system.
The Table 1 shows some solutions provided built-in by LabVIEW, a subset of the networking
features suggested by National Instruments for developing distributed control systems (Lima
et al., 2004). Common to all these solutions is the ease of implementation because they have
 been designed to require very limited programming effort.
Shared Network Variable, DataSocket, VI Server, VI reference, TCP/IP and UDP
communication libraries and also interfaces to .NET and ActiveX are the main communication
tools offered by LabVIEW. They are powerful and well suited for many applications but, with
the exception of TCP/IP and UDP, are not flexible enough to allow the implementation of a
real communication protocol.
Shared Variable and Data Socket, for instance, basically provide data sharing across the
network, others (VI Server, VI reference) allow access to remote VI, with some relevant
restrictions in some cases, and their use is limited to LabVIEW environment.
In addition the LabVIEV Internet Toolkit includes a HTTP server and the possibility to operate
the VIs (Virtual Instruments, i.e. the LabVIEW applications or subroutines) as CGIs that a
client can invoke using the HTTP protocol to execute particular procedure on the server side.
This is a relatively flexible solution but offers low performances and limited features.
In conclusion it’s hard to find the best candidate for developing an open, general purpose
communication framework because the before mentioned solutions are either offering limited
features or performance, or they are proprietary so that, for instance, integration with the
control system of a nearby experiment or with a bigger apparatus, that could have been
406
8 Practical Applications and Solutions Using LabVIEW™ Software
Will-be-set-by-IN-TECH

0 1 3 4 5

Connect.
ID
error

Fig. 4. Portion of block diagram of the the XMLvRPC_Server.vi showing the execution of the
server loop.

receives the methodCall from the client and parses it, looking for methodName and params.
The   methodName is then used (2) to find out the full path of the VI that serves that particular
method, that is expected to be stored in a dedicated directory with the other methods available
for that particular server. The full path allows to dynamically load and run the target VI with
Call by Reference Node.
This solution simplifies very much the server’s structure. Methods don’t need to be placed
directly on the block diagram provided they all have the same connector pane because the
Call By Reference Node requires a strictly typed VI refnum.
Fortunately this isn’t a severe limitation. In fact, since data provided as input for the method
execution are serialized onto the  params string of the XML coding, for VI implementing any
of XMLvRPC methods, basically, only one input connector (a String control) is sufficient.
Similarly, data produced by the methods, either a single value or a complex data structure,
are returned from a single output connector.
In the following paragraph it will be explained why a Variant indicator is used as output
instead of a String data type. At this point it is sufficient to mention that Variant data do not
conform to a specific data type allowing a program to pass it from one VI to another without
specifying what kind of data type it is at compile time.
In LabVIEW, variant data type differs from other data types because it stores the control or
indicator name, the information about the data type from which was converted, and the data
itself, allowing to correctly convert the variant data type back to the original or to another
one.
As for the input connector, the Variant allows methods VIs to output any type of data, or
combination of thereof, after the Call By Reference Node.
For that reason the  XMLvRPC_Server.vi is a generic server for requests issued by clients and it
doesn’t need to be specialized for a particular controller, i.e. for a particular set of tasks to be
executed or components to be controlled, because the methods are not statically linked subVI
calls. The VIs implementing the methods only need to be available at run time, ready to be
loaded and executed upon request of the remote client.
Block diagram of  XMLvRPC_Client.vi is even simpler, as shown in Fig.5 (next page).
In conclusion XMLvRPC client and server are based on four symmetric functions.
Extending LabVIEW
Extending LabVIEW Aptitude
Aptitude for Distributed forandDistributed
Controls Data Acquisition Controls and Data Acquisition 407
9

1 3 4 5

Fig. 5. Block diagram of the the XMLvRPC_Client.vi.

The VIs implementing these functions are, on the server side,   XMLvRPC_ReadRequest.vi
and   XMLvRPC_WriteResponse.vi, on the client side,   XMLvRPC_WriteRequest.vi and
XMLvRPC_ReadResponse.vi.
These VIs, depending to their specific function, perform coding or parsing of XML
request or response or network socket read or write operations. The block diagram of 
XMLvRPC_WriteRequest.vi is shown as example in (Fig.6 next page).

4.2 Data serialization


Before going into details of data serialization for XMLvRPC, it should be noted that XML is
not the unique choice for providing a human-readable serialization of a given data structure.
Another option for text-based serialization is, for instance, JSON(JSON, 2009) derived from
 Java Script syntax and, as well as XML, well supported from many programming languages.
Compared to XML, JSON is more lightweight though, probably, a bit less readable.
Similarly to XML-RPC, a remote procedure call protocol based on JSON encoding has been
proposed with the name of JSON-RPC(JSONRPC, 2009). The XML-RPC   methodCall and
methodResponse  examples shown in Fig.2 would translate to JSON-RPC as the following:
Request from Client: {"jsonrpc": "2.0", "method": "get_elements",
"params":[all], "id": 1}
Response from Server: {"jsonrpc": "2.0", "result": ["cam_01",
"cam_02"], "id": 1}
Clearly JSON coding, being less verbose and more compact, provides a clear advantage with
respect to XML when used for web services.
However, taking into account all the possible data structures that are routinely transferred
across the network in the case of distributed controls for scientific applications, neither XML
nor JSON can address the crucial problem for the final size of serialized data that is the coding
of large binary arrays that client applications may receive from some particular devices.
Typical example could be the read out of the buffer of a digital scope, consisting of few
hundreds of floating point values or, what’s worse, raw images produced by a digital
monochrome camera consisting of hundreds of thousand pixels, eight or more bits each.
In this case, the text-based serialization produced by either JSON or XML could be really
unfavorable because of the large number of single values to code and, especially, because of 
the much larger size of the serialized data with respect to the original.
408
10 Practical Applications and Solutions Using LabVIEW™ Software
Will-be-set-by-IN-TECH

1 2

Fig. 6. Block diagram of the the XMLvRPC_WriteRequest.vi.

4.2.1 Binary arrays management


Embedding of binaries in XML format has different options. Binary data, for instance, can
 be enclosed with the XML  CDATA  tag, a special tag for processing data that isn’t going to be
parsed during XML processing.
Unfortunately, this method is not perfectly safe and might lead to messy results as, for
instance, when binary data contains the ]]>   sequence, which would indicate to the XML
parser the end of the non parsed data even though it’s not the end of the binary data.
Another option is binary encoding, a process that changes the binary bytes into ASCII bytes
using relatively simple algorithms. The two most popular binary encoding algorithms are
UUencode and base64(base64, 2006) encoding. They are commonly used when binary data
needs be stored and transferred over media that are designed to deal with textual data.
However, binary encoding introduces some processing overhead and, moreover, it expands 3
 bytes into 4 characters, thus leading to an increase of data size by one third.
In other words, a well recognized and efficient standard for handling binary data in text-based
serializations is not available, at least so far, and since this work is aimed to developing a
communication framework for LabVIEW based distributed systems, it’s worth trying to find
a suitable solution among the LabVIEW features.
The natural approach to an efficient serialization of large binary arrays is to flatten the binary
data into characters and then handle the result as any other string in XML.
In LabVIEW this data transformation is provided by one of the  flatten to string functions that
convert to string either variants or directly any kind of data type.
LabVIEW flatten to string transforms numeric arrays, as well as any other data type, to strings
of binary digits in big-endian form. In the case of arrays, the binary sequence of the data is
preceded by the record of the size, in elements, of each of the array dimensions.
Obviously, an arbitrary flattened data or data structure can be specified in an XML-RPC
communication as the content of a   <String>   element, i.e. its associated <Val>   container,
as long as any special characters such as "<" are represented as entities ("&lt;").
XML provides five pre-declared entities that can be used to escape special characters(xml,
2000) in an XML encoded document. This process is under the responsibility of the server
Extending LabVIEW
Extending LabVIEW Aptitude
Aptitude for Distributed forandDistributed
Controls Data Acquisition Controls and Data Acquisition 409
11

1 2 4 5 6 7

Fig. 7. Pre-processing of LabVIEW data converted to Variant to replace binary arrays with
correspondent flattened strings.

side application after encoding the data it has to send, while the client receiving the flattened
data will need to check the binary sequence to replace the escaped characters before it process
the flattened string to recover the original binary stream.
To preserve compatibility with standard LabVIEW XML functions, instead of introducing
modification in the XML coding to process binaries as previously mentioned, it is worth to
pre-process the LabVIEW data before it’s converted to XML by inserting a VI that inspects
the input data structure and replace, when it finds it, any binary array with the equivalent as
flattened to string.
Because the pre-processor, similarly to the XML coding tool, must be ready to accept any
possible type of data structures as input, the latter is first converted to LabVIEW  Variants, that
sort of type-less container for any (simple or structured) data type that has been introduced in
Par.4.1. The Any-to-Variant function converts any LabVIEW data to this particular format that
can be passed between VIs and manipulated independently from the original data type.
A Variant can be unpacked, its content modified (adding, deleting or replacing data, for
instance) and at the end converted back to a "standard" LabVIEW data (numeric, text, array,
cluster, etc. or any combination thereof).
The pre-processor developed for XMLvRPC is a VI that recursively searches for nested binary
arrays into a LabVIEW data structure, previously converted into a Variant, and replace them
with the correspondent flattened strings.
Since the binary array(s) in the Variant structure is(are) flattened and coded into a XML string
the reduction in size, with respect to the non pre-processed data, can be significant especially
when size of the binary array is large.
In Fig.4 the  XML_preR-processor.vi is executed just before the XMLvRPC_WriteResponse.vi that
serialize the LabVIEW data into an XML format and then send the MethodResponse to the caller.
In Fig.7 a portion of the block diagram of   XML_preR-processor.vi is shown. The VI inspects the
input Variant (1) looking for either a  Cluster or a Array  data type. When a Cluster is found
the VI recursively inspects its inner elements (2). If, at some point, an  Array is found (3), it’s
flattened to string (5), checked to escape special characters, and finally replaced to the original
 Array (7) into the Cluster.
Later, the XML encoder will handle the string corresponding to the flattened binary array as
well as any other string type data, i.e. by encoding the data into a <String> element and by
410
12 Practical Applications and Solutions Using LabVIEW™ Software
Will-be-set-by-IN-TECH

HTTP/1.1 200 OK
LabVIEW Connection:  close XML-RPC
Content-length: 450
<?xml version="1.0"?>
<methodResponse>
  <methodName>get_scope_data</methodName>
  <params>
  <Array>
  <Name>chan1</Name>
  <Dimsize>4</Dimsize>
  <DBL>
  <Name>data</Name>
HTTP/1.1 200 OK
XMLvRPC   <Val>1.76365E-1</Val>
Connection: close
  </DBL>
Content-length: 215
  <DBL>
<?xml version="1.0"?>
  <Name>data</Name>
<methodResponse>
  <Val>2.75606E-1</Val>
  <methodName>get_scope_data</methodName>
  </DBL>
  <params>
  <DBL>
  <String>
  <Name>data</Name>
  <Name>chan1(1)(DBL)</Name>
  <Val>7.96079E-1</Val>
  <Val>¿¿¿¿?Ô58B‡FD?Ït∏‚wöE?‚^∫[tæ‹?‰G&amp;’Y÷û</Val>
  </DBL>
  </String>
  <DBL>
  </params>
  <Name>data</Name>
</methodResponse>
  <Val>1.57441E-1</Val>
  </DBL>
¿ represents non-printable cahracters   </Array>
  </params>
</methodResponse>

Fig. 8. Binary arrays coding in XML and XMLvRPC.

enclosing the string as it is in Val tags (Fig.8)


As consequence, compared to standard XML, the quantity of bytes to be transferred on the
network is very much reduced, overhead is almost negligible and the throughput of the
communication protocol become compatible with the requirements of a control system.
If considering, for instance, XML coding of a data structure (e.g. a LabVIEW cluster) that
includes a 640x480 2D-array of unsigned-bytes, a typical pixels map of a raw image produced
 by a CCD camera, the reduction in size obtained by applying the pre-processing just described
can be a factor 100 or more with respect to standard XML.
It should be mentioned that development of the XMLvRPC’s pre and post-processor has been
significantly simplified by complementing the LabVIEW functions with the OpenG(Jim Kring,
2003) LabVIEW Data Tools library providing a number of useful functions for manipulating
Variants.
Fig.9 presents the execution time in ms for the pre-processing and post-processing VIs as
function of the size of the input array. The latter is a 2D-array of unsigned-bytes with equal
sizes in both dimensions. In Fig.9 values in abscissa are the (equal) dimensions of the 2D-array.
Since pre and post processing are executed separately by the two partners in the
communication process (data sender does pre-processing while receiver post-processes data
received), their contribution (green and light blue areas) to the total time budget (blue) has
 been evidenced.
Total execution time, well below 10 ms even for large binary arrays, is comparable to the
typical time needed to transfer the same amount of data through the network (from few to
several tens of milliseconds).
It must be noted that when a LabVIEW binary array is flattened into a string, some relevant
information about the original array is lost. As consequence reconstruction of a binary
Extending LabVIEW
Extending LabVIEW Aptitude
Aptitude for Distributed forandDistributed
Controls Data Acquisition Controls and Data Acquisition 411
13

9 8.68

Pre+Post-processing
8
Pre-processing
Post-processing
7

   )
  s 6
  m
   (
  e
  m
   i 5
  t
  n
  o
   i
  t
  u 4
  c
  e
  x
  e
3
2.12
2
1.41
0.946
1 0.531

0
0 100 200 300 400 500
2D-array size

Fig. 9. Perfomances of pre-processing and post-processing routines for different sizes of 2D


 binary array. Values in abscissa (2D-array size) represent the two equal sizes of a 2D array,
e.g. the value 128 corresponds to a 128x128 U8 binary array given as input to processing
routines.

array on the receiver (client) side is not possible unless it is supplied, by other means, the
dimension(s) of the array and its data type and size. It has been already mentioned that the
number of elements for each dimension is included by LabVIEW in a header of the flattened
string.
The solution that has been chosen for XMLvRPC serialization is straightforward: the missing
information, i.e. the dimensions of the array and its data type (U8, U32, I32 etc.), properly
coded and formatted is appended to the name of the variable. This part of the procedure
corresponds to step (6) in the block diagram of Fig.7.
As an example, the variable   image, being the 640x480 2D unsigned-bytes array previously
mentioned, after the pre-processing procedure transforming it into a string will change its
name into image(2)(U8). On the receiver side a post-processor parses the LabVIEW Variant
obtained converting the XML data. It selects the strings that it recognizes, by their particular
names, as flattened binary array and un-flatten them into an array having the indicated
dimensions (2) and data type (U8).
As alternative additional XML elements can be introduced into <String>, e.g.   <ArrayDim>
and   <ArrayDataType> to specify the original array structure.
Results of some tests have been carried out to evaluate the performance of the communication
protocol are shown in Fig.10.
To the overall command execution time shown in the graph contribute, beside the time
needed to transfer data-in and data-out from/to client to/from server, the execution time
of the method.vi on the server side and time needed to open/close communication sockets for
the transmission of the   methodCall and the   methodResponse between client and server.
Performance, especially when dealing with large data sets, can be improved by optimizing
the network parameters (e.g. ethernet packet size) as evidenced by the two curves resulting
412
14 Practical Applications and Solutions Using LabVIEW™ Software
Will-be-set-by-IN-TECH

data size (kB)


90 160 250 360 490

400 390
370
1500 MTU
350 3000 MTU
330

   )
300
  s 300 290
  m
   (
  e 260
  m
   i
  t 250 230
  n
  o
   i 215 215
  t 200
  u
  c 200
  e 180
  x
  e
150
150 140
120
100 100 100
100

200 300 400 500 600 700


2D-array size

Fig. 10. Time needed to complete a client/server  methodCall and   methodResponse as


function of different data size returned by the server. The two curves correspond to results
obtained with different settings of Maximum Transmission Unit (MTU, i.e. Ethernet
maximum packet size) on the network interface of the client computer in a 100 MBps
switched network.

from different settings of MTU.


Moreover, when a continuous flow of large data buffers needs to be implemented as,
again, in the case of streaming the output of a digital camera, one can consider to
implement a dedicated streaming-like communication between server and client(s) that can
 be initiated/terminated on demand by XMLvRPC commands.

4.2.2 Enhancing the client/server communication


It was mentioned before that the XMLvRPC protocol supports asymmetric   methodCall/
methodResponse   communications. It means that on the client side the method.vi  that is
required to handle the data received from the server can be different from the one that
originated the   methodCall.
The   methodResponse can indicate another method (i.e. another client application) to deal
with the response on the client side, according to the data produced from the  method.vi on the
server.
The client’s   methodRequest, for instance, might ask for the newest data on the controller,
i.e. the most recently updated value among the I/O channels read from equipment assigned
to this particular controller. In this case the result will have a data format that cannot
 be defined a-priori and needs the appropriate client application to be displayed. Another
example of asymmetric XMLvRPC communication will be given later in Par.5 when the
services registration procedures will be discussed in details.
Interestingly, this feature of XMLvRPC can be employed for extending the client/server
communication discussed so far by introducing another option for data transfer between a
server and the client application.
458 Practical Applications and Solutions Using LabVIEW™ Software

indicates the function. You can do the same on some function (it is done on a Bundle
Function in the Figure 19).
Suggestion 2) Using free labels to document the diagram is highly suggested.
Suggestion 3) From version 2010 on use the “wire label tool” to give a label to single wires,
indicating the data transported.
With a well-organized and documented set of SubVIs you do not risk that even after two
months, when you reopen your project, you will not remember what you did.

6. Data filing in LabVIEW


Data filing is not a trivial job in any programming language: LabVIEW makes no exception
in this regard. There is, in fact, a very wide range of choices concerning how you can save
your data on files, and the decision of using one format instead of another must be steered
by the following two points:
•  What kind of data, in a “logic sense” you are saving.
• What is the future utilization of this data?
These two points are not clear at all to the novel developer, and sometimes even to an
experienced one.
Typically, once learned how to save data onto spread-sheet files, the tendency is to continue
using spread-sheets even in cases that would require a more convenient solution: the Spread-
sheet format is supported by the fact that it is Excel compatible, in the sense that files can be
directly read by Excel and eventually transformed into Excel format. But we mustn’t forget
that there exist a lot of other possibilities whose utilizations can be strongly recommended.
First of all, let’s try to give some explanations of the statements above.
• The “logic sense” of data to be saved means a sort of category to which data needed or
produced by an Application belong. Here is a possible list reported as a series of
examples:
a. [configuration data] The physical channels to which the program must acquire data
from the field via ADCs or other related hardware.
b. [configuration data] On-Off status which decide if some Data Acquisition Channels
must be taken or not (to temporary inhibit DAQ from certain channels).
c. [Internal data] Information related to the user (ID, account, a possible password).
d. [internal logging] Log information concerning the correct functioning of an
Application for debugging purpose.
e. [internal logging] Journal file of actions taken by the user / Journal file of actions
taken by the Application for getting a strong redundancy on delicate processes.
f. [log raw data] Real (physical) data acquired that must be saved on disc for future
analysis.
g. [log analysed data] Online analysis is performed and we want to save basics results
of analysed data.
The list is far from being complete. Pay attention to the fact that we are not speaking about
the format. The format, in fact, is an independent choice: all the logical categories of data
indicated in the above list are subject to be saved into different formats, but there are no
fixed rules for this. One must clarify, before deciding the format, what is the logical aspect
of data to be saved. For each of them a different and more indicated solution is suggested.
• The second point is in some way related to the first and, from a certain point of view,
the choice must be done by considering both aspects. Saved file can be:
The Importance of a Deep Knowledge of LabVIEW Environment and
Techniques in Order to Develop Effective Applications 459

a. Successively used as source of data to be analysed.


b. Retrieved intact, just as they have been written.
c. Subject to be archived  in a long term historical archive and sometimes
retrieved for future reference.
d. Hidden because it is used by the program itself for its internal setups (typical
case of Configuration Files).
e. Subject to be used on the same machine  which took it or moved to be
opened/used on a different machine.
f. Their destination is on the same Operating System or on a different one.
And this list could also continue.
Another aspect is the format: text file or binary file? What exactly is the difference? What is
more convenient and for what reasons? I found that sometimes even experienced people
make some trivial mistakes by choosing a wrong solution on this point.

6.1 An overall analysis of the file functions


The File Functions are very well divided and organised in LabVIEW. After an overall analysis
of them we will switch to a series of useful hints for deciding file saving in LabVIEW. The
Figure 20 represents the main File Function palette at the centre with four sub-palettes opened.
The first row of the main palette contains the “basic” File Functions, the ones you use when
you don’t want to worry about how, technically speaking, you are saving your files.

6.1.1 Basic file functions


This first line provides two different and pre-ordered ways of file saving: spread-sheet file
(Write and Read respectively) and express VIs which use LabVIEW Measurement file format.

Fig. 20. The very extended and rich File Functions palette of LabVIEW.
Even if these two methods are useful in several situations, they suffer from some drawbacks:
• Spread-sheet file
460 Practical Applications and Solutions Using LabVIEW™ Software

a. Spread-sheet files can only save numeric values  in double precision


representation. Moreover some old LabVIEW versions saved these data as single
precision representation. If your floating data are usually treated in double
precision , a loss of representation or loss of data  can be introduced if you saved
them with the Write to Spread-sheet File Function.
b. You cannot write on your file any other auxiliary information  like strings, Booleans,
annotations etc.: you cannot save date and time string   information; date and time
can only be saved as floating point, i.e. using the absolute timestamp of LabVIEW,
but that is to be decoded by another program and is not clearly understandable by
human operators if written as a double number and not interpreted.
c. The machine format is a text file, whose fields are separated by tab character. This
means that huge files can be created even for not such a large amount of data to be
stored.
d. When you record spread-sheet files you must be careful in developing the file
towards bottom direction instead of to the right one: in other words, spread-sheets
must grow toward the bottom by appending lines, avoiding too many columns on
the right. In this case, spread-sheet programs can fail in opening these files.
e. The numeric precision can be lost because you chose the number of significant
digits at the moment of the file save, just as in a print-out sheet.
The last point is particularly significant when critical numerical data must be saved. It is an
important issue concerning text file which will be considered later.
• LabVIEW Measurement files. They can be very useful, but I suggest to adopt this
solution for a relatively small amount of data. They are driven by an Express VI, so a
specific setup panel is opened when you introduce these functions into your diagram.
The main advantage of using LabVIEW Measurement Files is the rapidity in defining
the file and obtaining it. The read-back of the file is also easy.
Here are some drawbacks:
a. They are usually text file unless you select “binary (TDMS)” into the setup page, so
they reflect the usual problems of text files.
b. Their utilization is basically foreseen as a LabVIEW tool, being incompatible with
any other analysis software or platform.
c. Files can grow a lot if you try to save uncontrolled data banks, like big multi-
dimensional arrays and so on.
The last point can be a very critical issue. Often the data size treated by an Application is
hidden by the apparent ease in which the diagram handles it: a simple array, for instance,
can grow to hundreds of Megabytes   without any particular indication or problem. This
aspect is so transparent that risks can be under evaluated by the developer: in the case of
saving such an amount of data, very huge files can be abruptly created, causing slowness in
the machine response.
In conclusion use the first line of File Function  if you have little data, in small or moderate
Applications, or to do initial tests of data saving of a new Application. Then consider using a
more sophisticated method for  file saving   even for moderate Applications and whenever
more control and care must be taken in saving data.

6.1.2 Owner’s file functions


The second and third lines (on Figure 20) provide a complete control of file writing and
reading which should be well understood. These functions are able to manipulate files as
The Importance of a Deep Knowledge of LabVIEW Environment and
Techniques in Order to Develop Effective Applications 461

you want: you can open, write/read data repeatedly and finally close. You can use these
function for every situations of data I/O to disc. You can decide:
- If the file is a text or a binary file;
- The data representation in the case of binary files;
- The number of characters/data elements to be read;
- The adoption of data streaming  technique.

6.1.3 File Constants Palette


The upper right palette of figure 20 is the File Constant Palette. It is an important series of
tools useful for path definition and handling. Consider using them to create the correct path
to access the disc area in which files are stored (the whole path to the actual folder). In
particular the “Current VIs Path” function is extremely useful for getting the current path in
which the VI is acting: wherever you move the VI, on different machines also, the function
shows you the current and complete path to locate the VI. From there, with the strip and
building path functions , you can define your own path.

6.1.4 Advanced file functions


This is a very plenty toolkit with all sorts of functions: you can move within an (opened) file,
by positioning the “pick up head” wherever you choose, calculate file sizes, list directories,
create or destroy folders or files, and so on. These functions are not frequently used, but when
needed they are really useful. A typical use is the positioning within a file with Get/Set File
Position functions, which allows you to move in binary files like on a tape recorder. Some
experience is needed to use these functions; always start with little tests: create new, small
VIs to do the test and study the effects and the results. Then integrate the test VIs as SubVIs
into your final application. This process is the only way to learn and clarify the utility of these
functions kit. Since the functions are low level Functions, you can almost do anything on your
File System, even delete important System Files! They must be used carefully.

6.1.5 Text files or binary files?


At this point in our discussion, some time must been spent on the format. Text files are
usually preferred to binary ones, at least because when we open them with a text editor we
can see the contents. The same thing does not happen for binary files which are somehow
unreadable. A binary file can only be read by using the same procedure as when it was
written: the same data type must be declared when we read and the number of bytes of
elements must be input to the read function.
But what is the real difference between the two types ?
Consider that a file (binary or text) is composed of a sequence of bytes, groups of 8 bits on
the disk (independently from how the File System of the machine has fragmented them on
the disk). A single byte can have a value that, if translated into integer, goes from 0 to 255.
Well, a file which can potentially contain all combinations of the 8 bits within the bytes, i.e.
bytes which contain all values from 0 to 255, is called a binary file. On the contrary, if the
values are limited to a certain subset of the range 0..255, they are called text files. The subset
is a precise one: “allowed codes” cover all ASCII printable characters (form ‘space’ to ‘z’,
numerically 32..127 code range) and some other “control character” which indicates line or
page feed, carriage return etc.. Under certain points of view there is not a big difference
between the two categories, but practically the difference is enormous.
The following table reports some hints concerning the possible choices for file saving:
462 Practical Applications and Solutions Using LabVIEW™ Software

Table of suggestions for choosing format of files


Use Text files when Use Binary files when
You do not have big amount of data to be The amount of data starts to be significant.
saved.
You want to have the “feel” on the data just Your utilization of data in the future is for
saved by watching them. analysis or archiving purposes.
You are not concerned about space on the You are concerned about saving space on
disc. the disc: Binary files are extremely more
compact than Text ones.
You don’t have to worry about speed in data You are concerned about speed: if you need
writing or reading, since text file operations to get data quickly and save on disc “into
are slow. the loop” Binary files is the only solution,
often accompanied with the “data streaming
technique” (see later).
You don’t have to worry about machine You are concerned about machine overload:
overload: text files are somehow a heavy writing in binary is a light process and no
process for it. data conversion is needed.
You do not care about precision for saving You are interested in definitively storing
numerical data: suppose you have a 15 data with the original precision or the
significant digits number to be saved. When original conditions (i.e. all data must be
saving it in a text file you de facto print it on saved “as they are”).
the disc by using a character representation.
If you, by mistake, ask for 5 significant digits
to be saved, the remaining 10 digits are
definitively lost.
Your data must be read from other Your data must be read in the same
programs, different machines or different environment (LabVIEW); some extra work is
Operating Systems. needed as a specifically-written program
into a different Language (C, C++, …), even
on a different Operating System, in order to
read binary file on other platforms.
Table 1. A compendium of indications for steering the choice of a correct file format.
Binary files seem to be more complicated or difficult to manipulate. Well, it is not so: they
are quite simple and easy to understand. Consider the following example. We have the
following eight numbers (as signed integers) to be saved:
667283 -134452 235567 7894451 -5569852 7789663 -3363331 -445874
Each of them, to be stored in memory, needs a 32 bits Integer (I32) representation and takes
4 bytes in the computer memory.
• If we save them into a Text file, we need approximately 67 bytes: each digit is, in fact,
transformed in an ASCII character (1 byte) and we do not save numbers   but their
representation in a character writing. It is like printing a sheet of paper and saving it
on the disc. The text files need some control characters like ‘tab’ to move from one
number to the next, ‘EndOfLine’ to end the rows and so on.
• If we save them into a Binary file, the effective file size containing data is 32 bytes: 8
numbers times 4 bytes each, simply the dump of the memory onto the disc. Negative
numbers are already taken into account thanks to the two’s complement representation.
The Importance of a Deep Knowledge of LabVIEW Environment and
Techniques in Order to Develop Effective Applications 463

Try to figure out how they work: take some time before deciding and do not make rapid
decisions which usually end up in text files.

6.1.6 TDMS Files


In recent years, starting from version 7, National Instruments introduced the LabVIEW
Measurement Files format (LVM files). We already cited this format while talking about the
Basic Files Functions: it is a text file well organized to record on disc “sessions” of data
taking under the form
[Date-Time] | [X] | Channel 1 | [Channel 2] | …
Where ‘[]’ means optional fields. The format and storing parameters (name, paths,
automatic naming,…) can be set up by Express VIs. A prefix header can be optionally
recorded to store further descriptions.
A few years later the TDMS format was introduced, together with the TDM Streaming palette
(the bottom-left palette in figure 20). TDMS File format is an evolution of LVM, recorded in
binary mode and optimized for search and access thanks to a specific indexing technique. The
details of how the files are stored or indexed are transparent to the developer, who can take
advantage from the intrinsic structures and handling related to this format. TDMS is a
LabVIEW “internal” format, in the sense that it is conceived as an efficient method for data
storage and retrieving in LabVIEW environment : you can save large amounts of data,
perform data streaming and classify your data into different channels and categories. This
choice can be particularly useful in several situations in which you have a consistent amount
of data and/or numerous sources of it (i.e. several channels which produce data).

Fig. 21. An example of the TDMS file Viewer in which some data is shown.
The Importance of a Deep Knowledge of LabVIEW Environment and
Techniques in Order to Develop Effective Applications 467

- Second, if the program halts or is subject to an internal error which induces the VI to
abort, all accumulated data can be corrupted or is lost.
- Third, since accumulation memory cannot be infinite, you need to stop some processes
to dedicate machine time to write the data in a shot: the writing time can have,
unfortunately, a duration of several seconds in the case of a large amounts of data to be
saved. This situation can be attenuated with the correct handling of parallel processes,
which constitute another important aspect of good programming in LabVIEW.
For all these reasons, in similar cases, use Data Streaming . The concept is simple and is
based on the following processes:
1. open your data file
2. enter a loop which takes data and write immediately into the file, usually in binary
format
3. stop the loop when finished and close the data file
4. check for errors.

Fig. 26. Example of a simple Data Streaming implemented with a text file. (From National
Instruments 2009-Core 1 Course presentation slides, Lesson 6 “Managing Resources”).
In the Figure 26 the simplest data streaming technique is reported, in this case made by
writing on a text file. Such a structure must be implemented as an independent one with
respect to the rest of a VI, like parts which operate on the User Interface, for instance. The
next paragraph will present some complex structures and Design Patterns which help for
such a kind of design.

6.2 A conclusion concerning the files


Filing in LabVIEW (and in all programming languages) is a very extensive topic which has
lots of implications. A mistaken choice in file format or recording technique can cause
serious problems in using the data stored in your DAQ systems. It often happens that a
series of conversion programs (under the form of several new VIs in the case of LabVIEW)
must be written just to convert data files in order to make them compatible with some
analysis system. A list of suggestions follows:
Suggestion 1) Plan carefully regarding your file format before starting to write code abruptly.
Suggestion 2) Decide, on the basis of the amount and type of data to be stored, how many
files you need to write “in parallel”: LVM files, Configuration, TDMS, Datalog, actual row
Data Files, analysed results, etc..
Suggestion 3) Choose carefully the files locations (folders) related to your application, and
use an automatic naming technique for data files which is based on a correct archiving logic:
468 Practical Applications and Solutions Using LabVIEW™ Software

for example a basic file name followed by date and time of your DAQ and a standard file
extension.
Suggestion 4)  Decide about the format for your data file: text file or binary ones. Both of
them have advantages and disadvantages. A binary file is compact, rapid to write and read,
and reports the actual values taken during DAQ; if correctly formatted, it can be read under
different platforms too, even if this is an advanced task. Text files are nice because they are
comprehensible, but take more time to be written and read, they need more space on the
disc and limit the numerical precision because you cast your native precision by an “internal
printing” operation.
Suggestion 5)  Save files in streaming mode  using an adequate structure if the DAQ or
related processes are long term processes. Avoid accumulating large amounts of data and
save them at the end of your process or from time to time by interrupting your DAQ.

7. Structures and parallel programming in LabVIEW


Structures in LabVIEW include For and While (Timed or not) loops, Case and Event structures
and Sequences (flat or staked). Most beginners use structures in an incorrect way: they
superimpose one structure over another by adding pieces which try to satisfy the increasing
demands in the features of the application under development, again without any planning.
First of all try to avoid using the Sequences Structures.  All LabVIEW programs can be done
without them, and data dependency can fully substitute the sequencing of operations in
most cases. Sequence Structures must be used in very restricted cases, when, for example,
stringent timing issues are present during, suppose, a dialogue with an instrument.
Sequences Structure is in contrast with the data dependency paradigm typical of LabVIEW,
and must be used expressly to circumvent it when necessary.  They tend to hide code in
different frames, generating poor diagrams not clearly understandable.
Bad usage of structures implies several problems and under-utilization of LabVIEW system
features. LabVIEW is an implicit parallel environment  in the sense that it is designed to
generate parallel and optimised code without particular intervention of the developer: but
the latter must know how to arrange structures   in order to induce LabVIEW to work
parallel.
A last point is that Structures are related to the so-called Design Patterns techniques: this
topic is a very important point which is expressly studied in several official LabVIEW
courses (from Core 1 on).

7.1 Parallel processing issues


Putting more than one loop structure on the same diagram, automatically generates parallel
code in LabVIEW, if no data dependency exists among the loops. Loops (While or For, but
the usefulness is basically on While ones) cannot be interconnected to one another with wires,
because this would create a data dependency, and the second loop should wait for the end of
the previous to start its execution. Even transmitting a “STOP” flag needs a specific technique.
LabVIEW compiler optimizes code in order to be executed in separate threads of the
Operating System or, if it is the case, in separate sub-processor of a multi-core system.
Similar precautions must be taken to transmit data among parallel loops, and for this aspect
several synchronization VIs are available (see the “Synchronization Function” palette). We
cannot do a large excursus here, but I want to show you some general principles in order to
encourage you to continue in carefully study and learn about these techniques.
The Importance of a Deep Knowledge of LabVIEW Environment and
Techniques in Order to Develop Effective Applications 469

Fig. 27. Example of a very simple parallel structure. The Stop signaling must be passed via
Local Variable (as in the case of figure), Global or Shared Variable or Propery node (on Value
item). (From LabVIEW 2009-Core 1 course presentation slides, Lesson 9 “Using Variables”).
Consider the example in Figure 27 the two loops are timed using the metronome function
and the stop signal is sent via local variable. This is the simplest way for implementing
parallel processing.
If you need to send data from one loop to another, which is the case for some particular
design patterns, you must use Synchronization Functions.

Fig. 28. Two parallel processes which exchange data via Notification Functions and control
the end of process using the “Running” flag.
470 Practical Applications and Solutions Using LabVIEW™ Software

By looking at the Figure 28, several techniques for parallel processing and data exchange are
presented:
1. The loops exchange information using Notification VIs Functions.
2. Notifiers allow you to pass a single data to the receiver.
3. The data can be of any type: here a cluster containing two enumerated types is passed.
4. You can ask to create “the same notifier” (whose name here is “ModuleCommand”):
it will be created only once by the first Create Notification Function which is
executed. Using multiple initializations with the same notifier name adds clarity to
the diagram.
5. The upper loop signals the action of the user that has been taken into account by the
Event Structure, by writing the “new value” of the notified variable (the cluster) into the
notifier reference.
6. The lower loop receives the data and processes it. You have the possibility of tracing, in
the lower loop, if any data has arrived, thanks to the “timeout” technique: the Boolean
coming out from the notification receiver (lower loop) is the timeout flag.
7. Both loops need no timing: the upper one waits for an event from the users that is
processed by the Events Structure (typical way of functioning for this structure); the
lower loop uses the timeout of the notification function as internal timing, and
performs different operations in the case the notifier has sent a data or not (timed out or
not).
This technique is an application of the so called “Master-Slave Design Pattern”, in which a
short information, like a sort of flag, is sent from a “Producer” loop to alert a “Consumer”
loop to do something.
An extension of this technique is the “real” Producer-Consumer Design Pattern  in which
Queues Functions are used instead of Notification Functions. Use Producer-Consumer
design patterns, when more data must be sent from an acquisition loop to a data treatment
loop, for example. Using notifier can cause data to be lost since it can treat one item at a
time: queue functions, on the contrary, allow you to send streams of data from a producer
loop to a consumer loop without losing any.
In the figure 29 Data Consumer  is the bottommost loop. It is a state machine which
“knows”, from outside, if a Data Acquisition Process is in action or not.
• In the first case it provides to extract data packets from the queue, analyse and write
them into an archiving data file using data streaming on a binary file ; it finally sends
formatted events (I mean  physical events) data to a second queue for event monitoring
purpose: a third loop (not represented in the figure) provides for this extraction and
online presentation.
• In the second case it just does a monitoring of the incoming events.
This example is extracted from an actual Data Acquisition System for the “RD51” research
activity at CERN (Geneva, Switzerland), on a Data Acquisition System for MicroMGas
particle Detectors. This example carries several technicalities into it: two queues are used,
one for UDP (raw) data and the second for pre-analysed data (built physical events). A
Producer-Consumer design pattern is used where the consumer features a state machine
which handles Run status on the experiment: state machine stays “idle” if no Run is active,
and makes a series of operations (like initialization, file opening, flags settings,…) when a
Run is started. Then it takes data, analyse it creating actual physical events and save it into
formatted, binary streaming file; and eventually sends events to the online monitor via the
second queue.
The Importance of a Deep Knowledge of LabVIEW Environment and
Techniques in Order to Develop Effective Applications 471

Fig. 29. A more complex example of parallel loops in a “Producer-Consumer” Design


Pattern.
Using design pattern is extremely advantageous for a lot of reasons:
1. It is clear at the beginning of the development operation, how to implement things in
the VIs.
2. Design patterns feature the logic and the “place” for implementing all that you need in
an Application: from User Interface which gets commands from the User and formats
information toward the “Command Consumer” which actually executes the command,
to data getting and distributing onto secondary processes.
3. The design becomes clear and standard: a known framework helps to insert code. You
already know where and how to process an User command, for instance, where to get
data or write a file.
Definitively the work can be well organised in a rational, standard way. Future extensions
of code can be added easily, but also reusing of code in new applications, since the
framework is basically the same.
472 Practical Applications and Solutions Using LabVIEW™ Software

8. Conclusions
This Chapter does not want to substitute official LabVIEW courses, but, on the contrary,
pushes in the direction of encouraging following some course, at least Core 1 and Core 2 if
you are a beginning programmer. It is only a collection of considerations and suggestions in
the direction of improving the knowledge in what a developer should know as a minimum
to develop rational, well organized and effective Applications. Extending Applications in
the future, which is a common job for programmers, can be done without altering the
existant structure with the risk of obtaining a non effective solution. Remember that it is not
convenient that diagrams go over the screen size, for clarity and readability: if that is not
important make sure that the Diagram goes out of the screen in one direction only;
horizontal direction is preferred. If you are starting to go over the screen, stop for a while
and reorganize by creating more SubVIs, compacting structures and wiring and so on.
Avoid excessive usage of local and global variables and sequence structures, since these
features overcome the data dependency paradigm.
Many other suggestions can be made. A lot of other topics exist in LabVIEW programming,
from Active-X usage to priority setting of SubVIs, from extensive use of Variants to complex
data structures, from interaction of machine with the external field (via specific hardware) to
Instrument Driver designing techniques. This list can be basically infinite.
I hope this work can stimulate new or inexperienced developers in adopting a well-planned
strategy for development their job, in the direction of creating effective Applications which
are finally understandable, reliable and scalable. This strategy starts from a good knowledge
of the language features that can only be reached by a careful study before and during
LabVIEW development process. In this way a complete experience can be accumulated
which make, at the end, a very capable LabVIEW programmer.
In the end I would like to conclude with a final remark. The Figure 16 is an indication in
understanding to which level of difficulty a diagram can arrive, when the developer thinks to
“know everything” concerning  LabVIEW. Several people, in particular if coming from the
scientific environments, are convinced that just by giving few spots on the LabVIEW
development system they are capable of doing everything: this is a big mistake, and anyone
who wants to develop effective Applications in LabVIEW should have the ability to stop at a
certain point and take the time to study LabVIEW.

9. References
Bishop R.H. (2009) LabVIEW 2009 Student Edition, National Instruments
Essic J. (2008) Hands-On Introduction to LabVIEW for Scientists and Engineers, Oxford Press
 Johnson G. W. (1994) LabVIEW® Graphical Programming , Mc Graw Hill
National Instruments (2010) LabVIEW Core 1 Course Manual and presentation slides , ©National
Instruments
National Instruments (2010) LabVIEW Core 2 Course Manual and presentation slides , ©National
Instruments
National Instruments (2010) LabVIEW Core 3 Course Manual and presentation slides , ©National
Instruments
Sumathi S., Surekha P. (2007) LabVIEW based Advanced Instrumentation Systems , Springer-
Verlag
Travis J., Kring J. (2004) LabVIEW for everyone, Prentice Hall

You might also like