Virtual instrumentation using LabVIEW : principles and practices of graphical programming [2 ed.] 9780070700284, 0070700281

2,288 293 18MB

English Pages [246] Year 2010

Report DMCA / Copyright

DOWNLOAD FILE

Polecaj historie

Virtual instrumentation using LabVIEW : principles and practices of graphical programming [2 ed.]
 9780070700284, 0070700281

Table of contents :
Cover
About the Authors
Contents
Preface to the Second Edition
Preface to the First Edition
Foreword
Chapter 1: Intorduction to Virtual Instrumentaion
Chapter 2: Basics of LabVIEW
Chapter 3: For and Vhile Loops
Chapter 4: Other Structures
Chapter 5: Arrays and Clusters
Chapter 6: Graphs and Charts
Chapter 7: State Machines
Chapter 8: File Input/Output
Chapter 9: String Handling
Chapter 10: Basics of Data Acquisition
Chapter 11: Data Acquisition with LabVIEW DAQmx and DAQ VIs
Chapter 12: Interfacing with Assistants
Chapter 13: Interfacing Instruments: GPIB and RS232
Chapter 14: Adanced Topics in LabVIEW
Chapter 15: Distributed Systems
Chapter 16: The VI LAB
Chapter 17: LabVIEW Resources
Glossary
Index
Plate
Untitled

Citation preview

VIRTUAL INSTRUMENTATION USING LabVIEW (Principles and Practices of Graphical Programming) Second Edition

About the Authors Sanjay Gupta is currently working as Chief Scientific Officer (Research Professor) in the Advanced Centre for Materials Science at the Indian Institute of Technology, Kanpur. He was head of the Centre from 1997 to 2000. He has earlier worked as a Senior Research Fellow at the JJ Thomson Physical Laboratory, University of Reading, UK from the year 1989 to 1991. Born in Lucknow, he graduated from Lucknow University in 1971, obtained his MSc in Physics from IIT Kanpur in 1973, and PhD in Physics from the University of Reading, UK in 1976. He has worked extensively on two of the most powerful neutron sources in the world, namely, the High Flux Reactor at Institut Laue Langevin, Grenoble, France, and the ISIS Spallation Source at Chilton, UK. Dr Gupta is one of the pioneers of computer-based instrumentation in India, and his book on PC Interfacing was published by the Instrument Society of America in 1986. A second edition followed in 1994. He has over fifty publications to his credit and is a member of various professional bodies including the Institute of Physics, UK. Dr Gupta is also a Life Fellow of the IETE. He has travelled extensively and is socially active. He has been the President of his Rotary Club, and Master of his Masonic Lodge. He is married to Ira, and they have two children, Anurag (Neurosurgeon) and Madhurima (Lawyer). His main area of interest is computer-based instrumentation. Joseph John is currently Professor of Electrical Engineering at the Indian Institute of Technology, Kanpur. He headed the Centre for Laser Technology and the Laser Technology Programme at IIT Kanpur during 2001–2004. He has over 16 years of teaching and research experience. He was born in Kerala and graduated from Kerala University in Electronics and Communications Engineering in 1978. He continued his studies and completed his Master of Technology (MTech) in Electrical Engineering at IIT Madras in 1980. Then, he started his career at IIT Kanpur where he worked as a Research Engineer in the Advanced Centre for Electronic Systems in the Department of Electrical Engineering, from 1981 to 1989. Subsequently, he did his PhD in Electronics Engineering from the University of Birmingham, UK and rejoined IIT Kanpur in 1993 as Assistant Professor in the Department of Electrical Engineering. Dr John is a Life Fellow of the IETE. He is married to Nina, and they have two children, Tim and Jamie. His areas of interest are fiber optic communication, electronic instrumentation, and analog and digital circuits.

VIRTUAL INSTRUMENTATION USING LabVIEW (Principles and Practices of Graphical Programming) Second Edition

Sanjay Gupta Chief Scientific Officer and Former Head Advanced Centre for Materials Science Indian Institute of Technology Kanpur

Joseph John Professor Electrical Engineering Indian Institute of Technology Kanpur

Tata McGraw Hill Education Private Limited NEW DELHI New Delhi New York St Louis San Francisco Auckland Bogotá Caracas Kuala Lumpur Lisbon London Madrid Mexico City Milan Montreal San Juan Santiago Singapore Sydney Tokyo Toronto

Tata McGraw-Hill

Published by the Tata McGraw Hill Education Private Limited, 7 West Patel Nagar, New Delhi 110 008. Copyright © 2010, 2005, by Tata McGraw Hill Education Private Limited. No part of this publication may be reproduced or distributed in any form or by any means, electronic, mechanical, photocopying, recording, or otherwise or stored in a database or retrieval system without the prior written permission of the publishers. The program listings (if any) may be entered, stored and executed in a computer system, but they may not be reproduced for publication. This edition can be exported from India only by the publishers, Tata McGraw Hill Education Private Limited. ISBN (13): 978-0-07-070028-4 ISBN (10): 0-07-070028-1 Managing Director: Ajay Shukla Head—Higher Education Publishing: Vibha Mahajan Manager—Sponsoring: SEM & Tech. Ed.: Shalini Jha Assoc. Sponsoring Editor: Suman Sen Editorial Researcher: Koyel Ghosh Executive—Editorial Services: Sohini Mukherjee Sr. Production Manager: P L Pandita General Manager—Marketing: Higher Education: Michael J. Cruz Dy. Marketing Manager—SEM & Tech. Ed.: Biju Ganesan Asst. Product Manager—SEM & Tech. Ed.: Amit Paranjpe General Manager—Production: Rajender P Ghansela Asst. General Manager—Production: B L Dogra Information contained in this work has been obtained by Tata McGraw Hill, from sources believed to be reliable. However, neither Tata McGraw Hill nor its authors guarantee the accuracy or completeness of any information published herein, and neither Tata McGraw Hill nor its authors shall be responsible for any errors, omissions, or damages arising out of use of this information. This work is published with the understanding that Tata McGraw Hill and its authors are supplying information but are not attempting to render engineering or other professional services. If such services are required, the assistance of an appropriate professional should be sought. Typeset at Tej Composers, WZ-391, Madipur, New Delhi 110063, and printed at Sai Printo Pack, A-102/4, Okhla Industrial Area, Phase - II, New Delhi - 110 020. Cover Printer: Sai Printo Pack RZZQCRZZRQZXL

Dedicated to Ira and Nina

Contents Preface to the Second Edition Preface to the First Edition Foreword

xi xiii xix

1. Introduction to Virtual Instrumentation Introduction 1 1.1 Computers in Instrumentation 1 1.2 What is Virtual Instrumentation (VI)? 5 1.3 History of VI 7 1.4 LabVIEW and VI 9 1.5 Conventional and Graphical Programming 1.6 Distributed Systems 12

1

10

2. Basics of LabVIEW

15

Introduction 15 2.1 Components of LabVIEW 15 2.2 Owned and Free Labels 16 2.3 Tools and Other Palettes 17 2.4 Arranging Objects 18 2.5 Pop-Up Menus 19 2.6 Colour Coding 19 2.7 Code Debugging 20 2.8 Context Sensitive Help 21 2.9 Creating Sub-VIs 21

3. For and While Loops Introduction 24 3.1 The For Loop 24 3.2 The While Loop 26 3.3 Additional Loop Problem 27 3.4 Loop Behaviour and Interloop Communication

24

27

viii

Contents

3.5 3.6 3.7 3.8 3.9 3.10 3.11

Local Variables 29 Global Variables 30 Shift Registers 31 Feedback 32 Autoindexing 32 Loop Timing 33 Timed Loops 35

4. Other Structures

36

Introduction 36 4.1 Sequence Structures 36 4.2 Case Structure 38 4.3 Formula Node 40 4.4 Event Structure 40

5. Arrays and Clusters Introduction 42 5.1 Arrays 43 5.2 Clusters 48 5.3 Inter-Conversion of Arrays and Clusters Summary 52

6. Graphs and Charts

42

51

53

Introduction 53 6.1 Waveform Chart 53 6.2 Resetting Plots 54 6.3 Waveform Graph 57 6.4 Use of Cursors 59 6.5 X-Y Graph 60 Summary 61

7. State Machines

63

Introduction 63 7.1 What is a State Machine? 63 7.2 A Simple State Machine 64 7.3 Event Structures 65 7.4 The Full State Machine 67 7.5 Notes and Comments 68

8. File Input/Output Introduction 69 8.1 File Formats 69 8.2 File I/O Functions 71 8.3 Path Functions 76

69

Contents

ix

8.4 Sample VIs to Demonstrate File WRITE and READ 77 8.5 Generating Filenames Automatically 79 Summary 81

9. String Handling

82

Introduction 82 9.1 String Functions 83 9.2 LabVIEW String Formats 85 9.3 Examples 87 9.4 Some More Functions 87 9.5 Parsing of Strings 91 Summary 92

10. Basics of Data Acquisition

94

Introduction 94 10.1 Classification of Signals 94 10.2 Real-World Signals 95 10.3 Analog Interfacing 96 10.4 Connecting the Signal to the Board 100 10.5 Guidelines 103 10.6 Practical vs. Ideal Interfacing 104 10.7 Bridge Signal Sources 105

11. Data Acquisition with LabVIEW DAQmx and DAQ VIs

107

Introduction 107 11.1 Measurement and Automation Explorer 108 11.2 The Waveform Data Type 111 11.3 Working in DAQmx 112 11.4 Working in NI-DAQ(Legacy DAQ) 116 11.5 Use of Simple VIs 118 11.6 Intermediate VIs 122 Summary 130

12. Interfacing with Assistants

132

Introduction 132 12.1 DAQ Assistant 134 12.2 Analysis Assistant 136 12.3 Instrument Assistant 138 Summary 140

13. Interfacing Instruments: GPIB and RS232 Introduction 141 13.1 RS232C vs. GPIB 142 13.2 Handshaking 143

141

x

Contents

13.3 GPIB Interfacing 143 13.4 RS232C/RS485 Interfacing 147 13.5 Standard Commands for Programmable Instruments 13.6 VISA 151 13.7 Instrument Interfacing and LabVIEW 158 Summary 160

150

14. Advanced Topics in LabVIEW Introduction 162 14.1 Inter-process Communication 162 14.2 Other Related Tools (Queue, Semaphore, Rendezvous and Occurrence) 14.3 Wait for Front Panel Activity 167 14.4 Data Sockets 168 14.5 Programmatically Printing Front Panels 176

15. Distributed Systems

162

166

177

Introduction 177 15.1 Basics 178 15.2 Programming in FPGA 181 15.3 Operating in a Batch Mode 184 15.4 Web Server vs. Data Socket 184 Summary 184

16. The VI LAB

185

Introduction 185 16.1 Laboratory Set-Up 185 16.2 LabVIEW Versions 187 16.3 LabVIEW Toolboxes 188 16.4 Laboratory Exercises 189 Lab Set 1: Get Started 189 Lab Sets 2 and 3 192 Lab Set 4 194 Lab Set 5 195 Lab Set 6 197 Lab Set 7 198 Lab Set 8 200 Lab Set 9 202

17. LabVIEW Resources

204

Introduction 204 17.1 Internet Resources 204 17.2 Books 206

Glossary

207

Index

216

Preface to the Second Edition The second edition of the book Virtual Instrumentation Using LabVIEW is now in your hands. At the outset, we wish to thank our readers for the excellent response to the first edition, which resulted in five reprints within five years. This response has put a greater responsibility on our shoulders—we have the twin challenge of revising the material in this fast-changing world of computers, while at the same time of maintaining continuity with the past. Objective The challenge was to remain faithful to our original concept of writing an entry to a midlevel text; while updating and changing the material to move from Version 7 of LabVIEW to Version 2009 (Version 9). We had the objective of making the content fully up-to-date and at the same time preserving the flavour of the first edition. While all chapters have been updated to conform to the latest version of LabVIEW, some have undergone major changes to keep abreast of the latest developments and ideas. Chapter 15 has been replaced totally by a new chapter on Distributed Systems. At the time of publication of the first edition, the future trend in computer-based instrumentation was not very clear. Now, the drift is decisively towards Real Time and Embedded (FPGA based) systems. Ironically, the widespread adoptions of USB and High Speed Ethernet have accelerated this trend. Both of us have been involved in the Technology Mission on Railway Safety, and our experience there has helped us in understanding and refining our understanding of many of the advanced concepts. While most of this work has been of a somewhat advanced nature, it has nevertheless contributed a lot in giving us a more complete and global view of LabVIEW as a development system. This understanding would not have been possible with normal academic type of work. Acknowledgements We would be failing in our duty if we do not acknowledge the continued support of National Instruments, and our colleagues in this endeavour. Mr. Dev Dutt Pal, who has been our constant support in the VI Lab and Course, deserves a very special mention. This course has been the testing ground for all the material in this book. Dr. Devaraj, as always, has happily contributed a revised foreword, a very heartfelt note of thanks is due to him. The unstinted support of our families has played a major role in our being able to revise and complete this book. Thanks are also due to the reviewers, Umesh Chandra Pati of National Institute of

xii

Preface to the Second Edition

Technology(NIT), Rourkela and M V Vaidyan of National Institute of Technology (NIT), Calicut, whose comments and suggestions proved very useful in shaping this text. We welcome feedback and suggestions from readers.

SANJAY GUPTA JOSEPH JOHN ([email protected]) ([email protected]) Publisher’s Note Tata McGraw Hill Education looks forward to receiving views, comments and suggestions for improvement from teachers and students, all of which may be sent to [email protected], mentioning the title and author’s name in the subject line. Piracy-related issues may also be reported.

Preface to the First Edition The development of Virtual Instrumentation is a paradigm shift in the way computer-based instrumentation is implemented. Not so long ago, working with reams of sometimes obscure and often obtuse code in C (or Pascal or Modula or BASIC) was de rigueur. System developers were like high priests performing mysterious rites. After some time, when a change was required, the priest had either moved on, or forgotten the details, and long hours were put in either rewriting the code, or figuring out how it worked. Now the same task is done in a jiffy using VI methods, especially those using graphical or data flow programming techniques, of which LabVIEW is the first and foremost implementation. This book is based on our extensive experience in VI systems ranging from small laboratory systems all the way to tackling complex industrial level problems. The first VI Laboratory (in collaboration with the then nascent NI-India) was set up at IIT Kanpur and has served as a model for similar laboratories elsewhere. Courses for teaching VI methods to students from various disciplines in Science and Technology were developed and have evolved with successive generations of students. It may not be far from the truth to state that these have served as a model for similar courses across India. The model syllabus for colleges across India was enunciated in an ISTE sponsored workshop at IIT Kanpur in the year 2000. This book is designed to meet two similar but different requirements. On one hand, the practising technologists getting started with VI need a practical text to enable them to translate their experience into productive code using this new technique. They also want the text to serve as a reference for subsequent work. On the other hand, the academic community requires a book which can be used for instruction. The background of an average Indian student is different from the students in the West. Our students are better equipped in theory and mathematics, but they lack in practical skills. The vital links for translating their theoretical expertise into practice are often missing. This book is designed to meet the requirements of the industry as well as the academic community. The practicing engineers will find the hands-on approach with a strong practical bias very suitable for their requirements. The teachers as well as the students will find it as a useful source of information. To cater to this requirement, the level of the book has been deliberately kept at the beginner to intermediate level. This allows the enunciation of the principles highlighting of the specifics, while at the same time avoids the obfuscation of the specifics in too much detail. Many advanced areas are touched upon to provide the user with a framework to develop and exploit these as and when required.

xiv

Preface to the First Edition

It is often claimed that there is very little or even no common thread between programming in LabVIEW, and in conventional languages. This is strictly not correct. It is true that LabVIEW has many features and functions specific to it, which do not have any parallels in conventional programming. However, the underlying logic is no different. This book breaks with tradition by highlighting the parallels between LabVIEW and conventional programming methods. A developer starting out in LabVIEW is all of a sudden faced with a different vocabulary and tools set, which is icon based. The parallels between this new environment and the familiar environment help make this transition painless. Chapter 1 gives a historical Introduction to the use of computers in Instrumentation. Virtual Instrumentation required the parallel developments in hardware as well as software. The development of ever more powerful computers which had the capacity to support powerful GUI-based Operating Systems, the development of these software platforms, progress in instrumentation bus standards, all contributed to the development of VI, and one could not have progressed without the others. This interaction is highlighted and the interplay explained. The conventional (program flow) and graphical (data flow) environments are compared and contrasted. A brief history of the development of LabVIEW is also given. Chapter 2 on the Basics of LabVIEW explains some elements which are used extensively in LabVIEW programming. This chapter is not meant as a tutorial but is in the nature of a summary highlighting some of the basic features and techniques in LabVIEW. Methods of debugging code, use of context sensitive help, and making code into sub VIs (analogous to creating subroutines) are discussed. The FOR and WHILE loops are discussed in Chapter 3. Loops are intrinsic to all programming languages, and LabVIEW is no different. However, dataflow programming provides its own flavour in the form of tools for enhanced convenience and productivity, while at the same time imposing some restrictions. The restrictions (and differences) are highlighted, while the newer tools in the shape of Local and Global Variables, Shift Registers and Feedback loops, auto-indexing, etc. are explained. Precise timing of loops is far more critical in control applications than in computation. The subtle differences between the timing tools in LabVIEW are explained. Chapter 4 discusses the Other Structures in LabVIEW. Due to the parallel operation of code, the Sequence Structure is unique to Data Flow programming. It ensures that blocks of code operate sequentially. The need is evident in a stimulus–response scenario, so common in instrumentation applications; the stimulus must be given before looking for the response! The Case Structure is common to all languages, with some additional requirements of data flow, while the Formula Node permits the user to embed small bits of code in C (or in the somewhat cryptic Backus-Naur form) in LabVIEW. Chapter 5 deals with Arrays and Clusters. Arrays are intrinsic in all programming applications, while Cluster is the LabVIEW term for a Data Structure. Data acquisition applications use these very heavily and it is not out of place to say that a good understanding of arrays and clusters is mandatory for any LabVIEW programmer. The very special flavour given to these in data flow is highlighted and discussed in detail. Graphical presentation of data is an essential requirement in most applications. Chapter 6 deals with Graphs and Charts. Not only is data viewed graphically, but sometimes data has to be extracted from the display for subsequent analysis. Understanding the proper use of cursors is necessary for this, and is discussed in some detail. No area in LabVIEW programming is more surrounded by myth than the use of State Machine which is discussed in Chapter 7. The state machine is an extremely powerful tool for the development of code for most applications. Once properly understood, it is very easy to implement. This chapter, though somewhat

Preface to the First Edition

xv

short, draws heavily on our experience in teaching this concept to successive batches of students, and tries to totally demystify the State Machine and bring out its inherent simplicity and logic. Chapter 8 discusses File Input and Output. After all, almost any application will demand either the storage or access to stored data, or both. At one time, storage was scarce and expensive. Now storage space is seldom, if ever, a limitation. Therefore, this chapter concentrates on the handling of data in the form of normal text (or ASCII) files. The various tools are extensively discussed. The use of spreadsheets for quick access to tabular data is an intrinsic part of routine work. Therefore, storage of data in a form compatible with these is very desirable. The Spreadsheet File format provides this convenience. Placement of files in proper directories (or folders) is also of great importance. The management of paths is therefore also discussed. Many laboratory automation applications can benefit from sequential generation of file names, based on the calendar. Code for this is given towards the end of the chapter. Almost all communication with instruments takes place in the form of strings. On the other hand, scientific computing tends to totally neglect this aspect. String Handling is arguably more richly endowed with functions than any other area of LabVIEW. Chapter 9 discusses String Handling in detail. For most users the reason of using Virtual Instrumentation in the first place, is Data Acquisition. Therefore, two chapters are dedicated to this vitally important area. The Basics of Data Acquisition is discussed in Chapter 10 while Data Acquisition using LabVIEW DAQ VIs is discussed in Chapter 11. Chapter 10 deals with various aspects of handling signals, while Chapter 11 concentrates on the LabVIEW VIs used for the purpose. Signal interfacing is required by all, but there is an erroneous belief that only electronics engineers can understand it. This is not true and it is not difficult to acquire the basic skills for the purpose. Chapter 10 endeavours to provide this basic set which should be of use to all technologists irrespective of their parent discipline. It not only provides the basics of signal handling (especially analog signals) but also expands the theme to include the requirements for handling analog signals in a digitized environment. Chapter 11 goes on to build on this knowledge, with a detailed discussion of the various Simple and Intermediate VIs available in LabVIEW. The use of the Measurement & Automation Explorer is also discussed in detail, since in our experience, it is useful not only for configuration, but is also an invaluable tool for rough and ready testing and debugging. Version 7 of LabVIEW has added a very powerful tool in the form of Assistants. Chapter 12 discusses Interfacing with Assistants. Assistants provide a very powerful method of automatically generating code for various applications. However, they have been discussed separately for several reasons. Firstly, users of LabVIEW versions prior to 7 do not have access to this facility. Secondly, in our experience National Instruments often takes one major revision of LabVIEW before a new tool is fully stabilised, and therefore major changes in the area of Assistants cannot be ruled out at present. Thirdly, the very power of Assistants tends to make the user place total reliance on them and this has two handicaps. Assistants (using DAQmx) require far more hardware resources than conventional DAQ and the new generation (M series) of NI hardware is just starting to appear. Older NI (and third party) hardware may not have these resources (esp. in the counter-timer area). Also, a user working exclusively with Assistants will not acquire the basic understanding and skills which may be required when he is called on to address complex tasks in an efficient manner. Interfacing Instruments is the other way of acquiring data, and is discussed in Chapter 13. Conventional interfacing using the GPIB and RS232C standards is discussed within an application oriented framework. The RS232C standard is notoriously difficult to get going, and tips for the successful interfacing of instruments using this are given. Various standards have evolved over the years making communications with instruments

xvi

Preface to the First Edition

progressively simple. These are discussed with a historical perspective to enable the user to understand and appreciate them. This is one area where Assistants can be used to great advantage. These are also discussed. Chapter 14 deals with some Advanced Concepts. While the knowledge of these is not strictly necessary for many simple and intermediate applications, in the increasingly networked world, with distributed systems (the latest mantra), understanding of these can be very useful. These tools are all relatively recent, since older operating systems could not have supported them. Data Sockets are integral to any distributed applications. The use of Notifiers not only makes code easier to develop, but it is then only a small step to convert it to a network application using Data Sockets. These areas have often been shunned even by experienced LabVIEWers simply due to the lack of understanding. The use of Notifiers and DataSockets is discussed in detail, with examples to make them familiar to the reader. Some utilities like printing front panels, and use of noise to improve accuracy are also included shunned by all but the specialist. However, with the availability of very powerful signal manipulation tools in LabVIEW (versions other than the basic package) in both conventional and ‘assistant’ modes, this area is very much within the purview of the non-expert. The elementary set comprising the use of Anti-aliasing filters, Fourier Transforms (and the need for windowing), etc. can go a long way for most users. This chapter will be of particular interest to readers who are not from an electronics background. Various VIs available in LabVIEW for the purpose are also highlighted. Once the basics are understood the user can better exploit the tools in LabVIEW as well as the specialised toolboxes available. The VI Lab is discussed in Chapter 16. This chapter will be of special interest to readers in the academic environment. The exercise set used for teaching LabVIEW to Electrical (and Electronics) Engineers is listed. Also, some ideas about setting up the lab, and hardware which may be useful are given. Information on the various versions of LabVIEW and the toolboxes is also provided. Users learning LabVIEW on their own may also wish to work their way through the exercises. This is more important since NI have discontinued ‘Learning LabVIEW with Activities’, in the help menu. The exercises have been developed keeping the knowledge and skills of students in India, and have evolved over many years. These are being successfully used by both undergraduate and graduate students. LabVIEW Resources are briefly discussed in Chapter 17 which is the last chapter. Here some web resources, esp. the Users’ Groups (both Indian and International) are listed, as are some books, etc. There is a massive set of drivers available for hardware. Almost any popular hardware will in all likelihood have drivers available. The majority of these drivers are for free. There is however, a vast range of developers specialising in drivers who will naturally charge for these drivers for (often) more uncommon items. We would be failing our duty if we did not acknowledge the various people who have contributed directly or indirectly to this book. Our families had to bear with us for the long hours we spent on the manuscript. NI Systems India supported us throughout with information, software, hardware, and in myriad other ways, without which this book would not have been possible, and therefore Jayaram Pillai and his merry men deserve a very special thanks! Our colleagues from the core group of the VI Cell, namely, Dr Kamal Poddar and Dr N S Vyas who collaborated in the student courses for non-electrical students deserve a special word of thanks. The experience of developing the control and acquisition system for the National Wind Tunnel Facility with Dr Poddar, and the HUDEU Test Panel with Mr PVK Reddy were invaluable. The help rendered by the staff associated with the VI Cell, namely, Chaturi Singh, S Karthikeyan and D D Pal is gratefully acknowledged. Dr Santosh K Gupta provided valuable inputs by reading some of the material from the point of view of the non-specialist. The feedback from successive batches of students as well as colleagues who participated in the

Preface to the First Edition

xvii

various courses, was invaluable in refining the material. Dr Ganesh Devaraj, Managing Director of Soliton, and a LabVIEWer par excellence, deserves special thanks for writing the foreword for the book. Dear readers, we welcome suggestions, comments, and criticism from you and look forward to your active feedback. We hope you will find this book useful in your endeavours in the ‘wire-workers’ community. Our addresses are available elsewhere, or you may e-mail us at ([email protected], or [email protected]).

SANJAY GUPTA JOSEPH JOHN

Foreword It is indeed an honor to write the foreword for the second edition of this landmark book on Virtual Instrumentation using LabVIEW. When I wrote the foreword to the first edition of this book in 2005, LabVlEW was growing fast in India with widespread adoption by industries, research institutions, and academia, for data acquisition, signal analysis, control, and presentation. In less than five years, LabVIEW has become the dominant programming-language-of-choice for Measurement and Automation. The power of LabVIEW has grown from strength to strength by leveraging the latest developments in software and communication technologies, like distributed computing. But the most interesting fact is that the Graphical Programming paradigm in LabVIEW, which automatically took advantage of a parallel computing architecture, is looking extremely prescient with the advent of multicore microprocessors in computers and FPGAs, in embedded systems. LabVIEW already runs on all such computing platforms and its importance is certain to grow exponentially in the coming years. This book will enable everybody, from beginners to seasoned practitioners, to take advantage of this coming revolution. Dr Sanjay Gupta and Dr Joseph John had set a Virtual Instrumentation milestone in India with the release of the first edition in 2005. With the release of their updated second edition, they have clearly established the success of their endeavor. Virtual Instrumentation, for a long time had remained the domain of researchers at the premier educational and research institutions in India. With the advent of liberalization in the 90s, India became one of the fastest growing economies in the world, and Indian industries started to benchmark themselves against global standards of quality and productivity. This resulted in the adoption of Virtual Instrumentation in the Indian industry which clearly recognized the need to replace manual sample testing with automated inline testing. Virtual Instrumentation began moving beyond the proverbial ‘ivory towers’ into widespread deployment. But it was not until 1998, when National Instruments set up their office in Bangalore, that Virtual Instrumentation really started to come into its own in India. Since then, Virtual Instrumentation has seen astonishing growth, catalyzed by National Instruments’ training initiatives in academia and industry. The first Virtual Instrumentation laboratory in India was set up by National Instruments at IIT Kanpur in 1999 under the stewardship of the authors who were by that time already long-time users of Virtual Instrumentation and LabVIEW. Through conferences and seminars, the authors, have, over the years, done much to demystify Virtual Instrumentation for those who wanted a general understanding of this technology’s capabilities and applications while also conducting rigorous training programs for those who wanted to gain in-depth

xx

Foreword

knowledge and develop usable skills in this area. The first academic course in Virtual Instrumentation and LabVIEW was developed by the authors and given at IIT Kanpur. The largest Virtual Instrumentation project done by an academic institution in India was executed by Dr Sanjay Gupta and his colleague Dr Kamal Poddar at IIT Kanpur, along with their students and research associates. This Virtual Instrumentation project, implemented at the National Wind Tunnel Facility, received international acclaim at NIWeek, the worldwide conference on Virtual Instrumentation, by winning the ‘Best Application Award’ in the category of Aerospace and Defence in 2000. It is extremely heartening that the acknowledged experts in the field, who have been long-time users and very active promoters of Virtual Instrumentation in India, are releasing the second edition of their popular book. It is sure to make Virtual Instrumentation and LabVIEW much more accessible to the beginners while also providing new insights to the seasoned practitioners who can learn from the experience of the authors and their wide interactions with the experts in this field. Written in an extremely pedagogical style, ‘Virtual Instrumentation Using LabVIEW: Principles and Practices of Graphical Programming’ 2e, contains details which come from the authors’ own extensive experience in developing Virtual Instrumentation systems to address challenging real-world applications. This comprehensive book covers the latest developments in Virtual Instrumentation and LabVIEW, and includes excellent chapters on essential concepts like State Machines and Data Acquisition. They have also shared in the book their unique experience of developing the Virtual Instrumentation and LabVIEW course at IIT Kanpur which will be very useful for educationalists as LabVIEW spreads throughout the engineering and science colleges of India. In closing, this book is an important addition to the literature in Virtual Instrumentation and LabVIEW and will go a long way in further promoting this important field in India.

DR GANESH DEVARAJ Managing Director & CEO Soliton Technologies Bangalore

1 INTRODUCTION TO VIRTUAL INSTRUMENTATION INTRODUCTION This chapter introduces the concept of Virtual Instrumentation (VI). It begins with a brief historical review of computers in instrumentation and how VI evolved to its current shape and scope. The importance and emergence of VI as the new paradigm in instrumentation and its inherent advantages

1.1

II

over conventional techniques are discussed. The relationship of VI and graphical programming methods is explored followed by a discussion on the relationship of LabVIEW with VI within the framework of virtual introduced.

COMPUTERS IN INSTRUMENTATION From the very early days, computers found a role in process monitoring and control. The early computers were bulky and costly. Their uses were limited to the top end of applications, and they were found only in a few large plants, experimental systems, etc. Furthermore, their computational capabilities were minuscule by modern standards. One can safely say that the supercomputer of any age is less powerful than the simplest computer of a couple of decades later. The average calculator (or even a digital wristwatch) of today is more powerful than the earliest supercomputers. Subsequently, as the prices dropped and capabilities expanded, the use of computers grew. Following the development of powerful and inexpensive personal computers, this growth has exploded, and today a computer is more often than not, an integral part of the instrument.

2

Virtual Instrumentation Using LabVIEW

The progress in the application of computers in instrumentation can be divided into three separate but inter-related areas—computer hardware, software and interfaces. Computer Hardware The development of computer systems can be classified into three distinct periods–first, the age of mainframes; second, the age of minicomputers and finally, the age of personal computers. The earliest computers were large mainframes. These were large, bulky and expensive and were used only for very high-end applications. In the 1960s, experimental systems in the areas of nuclear and particle physics used computers not only for data processing, but also for acquisition and control. The advent of minicomputers (the PDP8 family of the late 60s and early 70s being the prime example) saw a major jump in the application of computers in control and data-acquisition applications. The PDP8 (launched in April 1965) is often described as the first mass-produced minicomputer. The capabilities of these systems stood nowhere compared to the modern standards; for example, the PDP8 came with 4k words of 12-bit memory. But then, one must contrast this with the supercomputers of the day. The supercomputer of the early 1970s—the CDC7600, came with 64k words (60-bit) of memory with a clock speed of 27 ns! However, the PDP and similar systems were used extensively for control and data-acquisition applications in industry as well as in academics. The VAX series of computers, released in 1977, was based on a 32-bit architecture and was the next popular series of computers in the interfacing area. Another major development was the development of bus-based computers. Buses are shared data highways, on which data, commands, etc., move and are used by various components. Buses may be internal to the computer (e.g., UNIBUS, PCI bus, ISA bus) or external (e.g., GPIB, USB, Firewire). RS485 (a multidrop extension of the common RS232C) is in many respects a bus. The first computer bus—UNIBUS made its debut in the PDP 11/20 in 1970. This was the first bus-based computer, which made it possible to add additional modules in a simple and systematic manner. The PDP11 initially did not find popularity in interfacing, though its later variants (DEC 11/23 and 73) were popular in high-end instruments. The development of the personal computers changed the picture dramatically. For the first time, relatively inexpensive systems with the requisite capabilities became available. Systems of the Intel 8080 family (Intel 8080/8085 and Zilog Z80) along with the Apple II became quite popular. All these were 8-bit systems with a limitation of 64 kB of memory. While the Apple had its own bus, the S100 bus emerged as the de facto standard in the 8080 world. This development of

Introduction to Virtual Instrumentation

3

bus-based systems, and their standardisation had major beneficial consequences for instrumentation as will be discussed later. While Apple progressed to MacIntosh, the Intel world moved on to the IBM Personal Computer. The PC was announced to the world on 12 August 1981. Subsequently, the system capabilities were enhanced with successive generations of computers, with the PC-AT having a 16-bit bus, making its appearance in 1984. In 1987, IBM launched the PS/2 with micro-channel architecture. However, even though it was a major advance on the ISA bus, the regressive marketing step of making the architecture proprietary led to its failure in the market. Variants to the PC (and AT) buses like the VESA and the EISA were developed but were short-lived and in 1993, Intel announced the Peripheral Components Interconnect (PCI) standard which today is used by almost all PCs as well as the Power Macintosh and later systems. Further, the PC came with a well-thought-out Interrupt (IRQ) and Direct Memory Access (DMA) structure permitting fast data transfers with peripherals. Some of these resources were available, allowing users to integrate their own hardware into the system. Prior to the development of buses, each interface problem was unique, and to connect m experiments to n different computers required m ¥ n solutions to be developed, each of which was unique. This problem was reduced to a very large extent with the development of buses and interfaces as shall be seen a little later. Starting with the PDP8, computers started being mass produced. Over 50,000 PDP8’s were produced; a number which pales when compared to the millions of PCs sold every year. This made them affordable for run-of-the-mill applications. After the development of PCs, computers became commodity items, prices crashed and at the same time reliability went up by leaps and bounds. This led to their widespread adaptation for almost every application imaginable. Computer Software In the early days, every family of computers had software unique to itself. The first time-sharing environment was developed very early when the operating system for the PDP1 was released in September 1962. These operating systems were of variable quality. and over a period of time some operating systems (like the VAX-VMS introduced in February 1978) came to dominate the controls applications industry. These have subsequently been superseded by various flavours of UNIX. Some of these (like HP-UX) have been specially modified for control applications. In the personal computer world, the Windows operating system is almost universal, barring some aficionados running various flavours of UNIX (or rather, Linux). However, with the rapid strides in PCs and networking, the world today is almost entirely dominated by these systems. The first-generation systems did not

4

Virtual Instrumentation Using LabVIEW

provide any standard way of integrating user software into the system. However, the release of (PC/MS) DOS 2 in 1983 changed all this. While most users were excited by the availability of the hierarchical directory structure in DOS 2, the facility to integrate device drivers into the operating system went unnoticed by most. Now, for the first time, there was a mechanism through which software for additional user hardware could be properly integrated into the overall system through drivers developed for the specific devices. While the MacIntosh had a good graphical user interface right from its introduction on 24 January 1984, the PC world had to wait till May 1990 when Windows 3 was released. The earlier versions of Windows (286 and 386) were very unstable, and did not gain popularity with users. The development of LabVIEW must be seen in light of these software developments, and is discussed later. Interfaces The problems of connecting real-world systems to computers have been mentioned earlier. After the Unibus was announced, it was rapidly realised that the simple concept of connecting all hardware on a single bus was flawed. It was realised that different types of devices required interfaces of different capabilities. For example, a teletype or terminal does not require the same resource capacity as a memory or disk storage. This led to the development of various buses and interfaces for different purposes. These normally coexist in the same system. In computer interfacing, both internal-computer buses as well as various interface standards play a role. The internal buses can be used to integrate add-on hardware into the computer, and also as platforms for standardised hardware. In this context, three computer-related buses have been extended to cater to instrumentation. The VME bus was extended for instrumentation and was named VXI (VME eXtensions for Instrumentation). Similarly, the PCI bus (de facto standard in desktop PCs today) has led to the PXI (PCI eXtensions for Instrumentation) standard. PCI Express has spawned the PCIe bus. The SCSI bus which is a bus for peripherals has been similarly extended to the SCXI (SCSI eXtensions for Instrumentation) standard. Various vendors supply hardware conforming to these standards. These can be in the form of backplanes in a box (crates) as well as modules. Modules from different vendors can be freely mixed together and installed into crates conforming to a particular standard. Mixed crates for VXI-SCXI and PXI-SCXI are also available. While VXI is today more of historical interest, SCXI, PXI and (increasingly) PXIe are very popular. Various interface standards are used to connect external devices to the computer. In a serial connection, all the bits of data are transmitted sequentially, i.e., one after another, while in a parallel link, there are separate lines for each bit.

Introduction to Virtual Instrumentation

5

Thus, a parallel transfer has traditionally been expected to be faster than the serial transfer. However, as data rates increase, the need to maintain synchronisation between various lines starts limiting data transfer rates. On the other hand, hardware (cable) costs as well as timing limitations restrict parallel transfers to short distances. Nowadays, serial connections are quite fast, for example, the USB design has been extended up to 1600 Mbps. This is the reason most hard disks use the SATA (Serial AT Attachment). Here, data rates of up to 1.5 Gbps (3 Gbps in revision 2, and 6 Gbps in SATA II) are available. The most popular external interface standards are RS232C (and its variants, especially RS485), GPIB, USB and Firewire. All these standards, except for the GPIB, are serial connections of varying capabilities. Also, barring RS232C, which is a one-toone protocol, most interfaces are buses. RS232C evolved out of the current loop standard which was developed to connect teletypes to early computers. It must be borne in mind that interfaces like Firewire, USB and Ethernet were not developed as instrumentation buses, but for other purposes. However, they are finding ever-increasing application in instrumentation. However, these are not optimised for instrumentation applications. The relatively high latency of the bus makes the use of distributed systems necessary much before than one may expect from the data rates alone.

1.2

II Any person coming across the term ‘Virtual Instrumentation’ for the first time is naturally curious to know what it is. In order to answer the question, one must look into the evolution of VI. As has been pointed out, from the very early days, computers have played a role in process monitoring and control. Their role and scope have grown phenomenally over time. As the interest in the usage of computers grew, users duplicated the front-panel control functions of the existing instruments through the computer interface. One of the earliest such applications was in multi-channel analysers. Thus, the instrument could be controlled through the front panel as well as the computer. Then somebody had a bright idea—since almost all the time the instrument was being controlled by the computer, why not do away with the front panel altogether? And voila, the first virtual instrument was born. This was the period when the most popular interconnection bus for test and measurement instruments was the GPIB. The use of the GPIB for setting up a test system can also be considered to be the first virtual instrument. Since then, VI has come a long way. Today it is a technique in its own right finding widespread application over a vast range of applications, ranging from small laboratory experiments, to large automation applications encompassing

6

Virtual Instrumentation Using LabVIEW

complex plants, and even towns, districts and countries. At the lower end, you have a scientist controlling a small experiment or instrument, and on the other end, VI is used for managing the distribution of natural gas in Switzerland, and electricity in Southern California, or controlling experiments in outer space (SpaceLab). From humble beginnings, VI has evolved into a multifaceted technique encompassing the entire area of computer-based instrumentation. The crux of VI lies in progressively moving the intelligence of the instrument into software. The hardware is reduced to the actual sensors (sensing and measuring devices, like thermocouples, bridges, multimeters, etc.) and actuators (the actual devices for changing the system like switches, motors, valves, etc.). All the signal handling and control action is done through software. As will be evident in subsequent discussions, all other benefits of VI derive to a very large extent on this fundamental concept. Another definition of VI (given by National Instruments) is—Industrystandard computers equipped with user-friendly application software, costeffective hardware and driver software that together perform the functions of traditional instruments. This definition is not complete, but encompasses some of the basic tenets of VI. Look at the various components of the definition. Industry-standard Computers: The PC is by far the dominant computer system in the world today. VI in its various flavours is supported on the PC under both the Windows and Linux operating systems. In addition, it can also be found on other systems, especially the MacIntosh. Equipped with User-friendly Software: All VI platforms provide powerful Graphical User Interfaces (GUIs) for development and implementation of the solutions. VI solutions tend to gravitate towards the use of general-purpose data-acquisition hardware as against custom hardware. The general-purpose hardware has many more users than custom hardware which naturally gives it a major cost advantage. Furthermore, the vast user base ensures that the manufacturers try and provide the cutting-edge hardware than custom hardware. Thus, in addition to cost, there are also benefits of improved reliability, and reduced obsolescence. Today drivers (interface software) for most instruments, as well as interfacing hardware are available either for free or at nominal cost. This reduces the cost and development time for applications utilising these products. In today’s environment, it is almost mandatory for an instrument developer to provide (or arrange to make available) a driver on one or more of the VI platforms. To cater to popular hardware where the manufacturer does not provide

Introduction to Virtual Instrumentation

7

support for VI, there is now a very large number of small vendors specialising in the development of these drivers. Many of these are excellent products, and are usually available at a reasonable cost. For example, LabVIEW drivers are available as downloads for almost all instruments of Agilent (formerly HewlettPackard), Tektronix, etc. Similarly, in the case of the family of imaging hardware from Matrox, which is very popular, drivers are available from independent vendors. The same is the case for digital cameras, etc. Given the correct software and front-end, a system based on general-purpose hardware can very effectively and efficiently operate as if it were a dedicated instrument costing many times as much. This logic can be extended and multiplied manifold to encompass complete control systems. For example, once the code for generalpurpose programmable logic controllers is available, it can be used to function as a system encompassing multiple Programmable Logic Controllers (PLCs) effectively replacing the control electronics of an entire processing plant. The term PLC has evolved into PAC (Programmable Automation Controller).

1.3

II

HISTORY OF VI The development of VI is linked to the evolution of small inexpensive personal computers, or PCs, and progress in computer hardware and software. Graphical User Interfaces (GUIs) too played a vital role in the development of VI. While the original application of replacing the controls with a computer link used a command-line interface, the use of sophisticated GUI soon became an essential component of VI software. The major developments that helped VI become successful were development of low-cost computer systems of adequate computing power, evolution of good GUIs, development of standards for buses, and increasingly stable networking platforms. With the development of user-friendly graphical interfaces (in many ways pioneered by the Mac) the development of interactive user applications became much easier, and the availability of on-screen graphics markedly enhanced their scope. Simultaneously, the computing power of the processors improved by leaps and bounds permitting the development of all these resource intensive techniques. There are three important elements in the development of the VI paradigm: (i)

As the computing power of systems increased, it became possible to move more and more of the intelligence into the host computer which forms the heart of the system.

8

Virtual Instrumentation Using LabVIEW

(ii)

The evolution of good standard interactive environments played an important role in the evolution of VI. While the early systems on the Intel platform did not provide a good standardised GUI, the Apple family based on the Motorola platform offered this from the very outset. In the early days, (iii) when both computers and systems to be interfaced were few in number, each interconnect was a unique solution. This was immensely wasteful in effort. To connect m-computers to n-instruments required m ¥ n solutions to be developed. Now assume that both the computer and instrument manufacturer agree on a standard interface. Then, the computer manufacturers will be required to develop m solutions, and likewise the instrument manufacturers will have to develop only n solutions. Thus, a total of only m + n and instruments. Therefore, the advantage of standards is obvious and leads to a massive reduction in development effort. It is this advantage which has led to telecommunication technology moving from circuit switching to packet switching. All these developments have occurred in parallel and have taken us to the situation where VI is the dominant tool for the development and implementation of instrumentation applications and systems. We have come a full circle—from instruments being controlled through VI to VI being embedded in the instruments themselves, as is happening in the latest generation of oscilloscopes. Over the past two decades, the concept has led to a major paradigm shift. While earlier systems were based on hardware linked together through software, today it is just the opposite. The system resides in software with hardware forming the front end. The major investment of time and effort is in software and the hardware is increasingly regarded as an interchangeable constituent. Early VI-based instruments were not strictly cutting edge. Here, a distinction is made between VI-based instruments, and VI-compatible instruments. Any instrument with a computer interface (most commonly, RS232C or GPIB) is VI compatible, though the capabilities available through the computer interface may vary drastically. On the other hand, VI based instruments require a computer to operate, and their operating functionalities are built around the host computer. Such instruments may directly plug into the computer bus, or may plug into a popular instrumentation chassis like VXI PXI or PXIe (SCXI is relatively less common). A few years ago, the top 10–15% of the performance range was almost the exclusive domain of classical instruments (often VI compatible), and VI-based instruments were available for the remaining applications. However, this gap has progressively shrunk and vanished over the years, and today there are some areas where the cutting-edge performance comes from VI-based instruments. The instrument manufacturer finds it more efficient in time and

Introduction to Virtual Instrumentation

9

cost to use the computational capabilities of standard computers as the basis for developing the instrument.

1.4

II

LabVIEW AND VI The term VI, as we understand it today, owes a lot to the development of the Laboratory Virtual Instrument Engineering Workbench (LabVIEW) by National Instruments of Austin, Texas, USA. LabVIEW was the first implementation of the graphical programming paradigm and other products like Agilent (formerly, HP)Vee, DasyLab, Genie, etc., followed. DasyLab has become a part of LabVIEW after their acquisition by National Instruments. However, LabVIEW continues to be an evermore dominant implementation of graphical programming. LabVIEW made its appearance as an interpreted package on the Apple Macintosh in 1986. This was about two years after the launch of the Mac. Thus it is not that old, having celebrated its twentieth birthday only in 2006. LabVIEW 2 was released in 1990, and was a compiled package as against an interpreted package. This change provided a massive improvement in the performance. It may be noted that at that point, the IBM PC universe still did not have a stable graphical environment. The first reasonably stable graphical environment (Windows 3.0) made its appearance only in 1990. In 1992, LabVIEW was ported to the Wintel platform and became available for the PC. Once again the time gap between the availability of a graphic environment and release of LabVIEW was about two years. LabVIEW 3 was released in 1993 and was the first version taking an integrated view of the Mac, PC and Sun-Sparc environments. Subsequent versions have followed with time intervals of two to three years between major releases. In 1999, LabVIEW also became available for the Linux platform. Networking support was first introduced in Version 5. Version 6 of LabVIEW was highly network oriented and was called LabVIEW 6i (i for Internet). The basic support in the form of DataSockets had been introduced in Version 5 but this was extensively modified and enhanced in Version 6. Version 7 expanded the horizon to make it simpler for the inexperienced user by providing various Express utilities and Assistants. It has also shown the pointer by supporting embedded systems, Personal Digital Assistants (PDAs) and the like. Recognising the evolution of instrumentation towards distributed systems, Version 8 has progressed significantly in that direction. While vastly expanding the universe of Express Vis, it has also moved significantly towards distributed systems by the introduction of things liked shared variables, etc. These make data transfers across systems faster and more convenient. The same trend continues with Version 2009.

10

Virtual Instrumentation Using LabVIEW

For some time, there was a closely related product—BridgeVIEW, which could be called LabVIEW Industrial. It was customised for industrial control applications, with support for multi-level security, passwords, and optimised for a large number of sensors and transducers rather than for speed on a smaller number of nodes. In addition, LabVIEW has two very closely related add-ons – LabVIEW RT (a separate product at one time) and LabVIEW FPGA, which will be discussed towards the end of this chapter. These are not entirely within the gamut of this book, but given the current trends some understanding from the outset is nevertheless necessary. The reasons for the dominance of LabVIEW are manifold. It provides a powerful and integrated environment for the development of instrumentation applications. Any such environment is critically dependent on the availability of support software for various instruments which may be interfaced with it. This leads to a classical chicken-and-egg situation, the hardware will not sell unless driver software is available, and the platform of choice for the software will naturally be the one which is most popular. Today, LabVIEW drivers are available for almost all major families of instruments, usually at nominal or zero cost. The wheel has come a full circle, and indeed one major oscilloscope vendor has gone as far as to embed LabVIEW inside its oscilloscopes, i.e., the user can boot LabVIEW from inside the scope. Earlier, the scope software was called to make the instrument behave like one, now LabVIEW allows the scope to behave like a virtual instrument of the user’s choice. However, this approach is far costlier than using external LabVIEW.

1.5

II

CONVENTIONAL AND GRAPHICAL PROGRAMMING The development of VI closely paralleled the development of graphical programming tools. However, to think that VI is limited only to graphical programming will be incorrect. VI can be implemented using conventional programming languages. This may come through the use of extension libraries for languages (like in the case of Visual C, Visual BASIC, etc.) or as dedicated compilers containing VI tools (like the LabWindows CVI from National Instruments). As a LabVIEW program is called a VI, it is sometimes believed that virtual instrumentation is synonymous with LabVIEW. This is incorrect, since virtual instrumentation need not be implemented only in LabVIEW, and, in fact, even the use of a graphic or DataFlow environment is not required. Programmers migrating to the graphical environment (G language) from conventional languages tend to be bewildered and lost at first. Many dedicated

Introduction to Virtual Instrumentation

11

G programmers try and present it as a totally different environment. This is only superficially so, and a little thought would reveal that below the surface, things are not very different. Any system with a GUI can be looked at as being composed of two parts, namely, the user interface and the underlying code. The former is about the same, irrespective of whether it is in the classical or graphical environment. Looking at the underlying code, things appear to be very different at first. The code in a conventional language like C will comprise of a number of routines, while in G, one barely sees any text. Instead, what is seen is a collection of icons interconnected by multicoloured lines. The routines in a conventional language are of the form subroutine alfa ()

If one was programming in C, will comprise of a series of constants. Due to this restriction, any variable which is to be modified by the routine, is transferred as a pointer to it instead of the value itself. Various items in may be changed if they are pointers to the values rather than the values themselves. (The location, i.e., the pointer is a constant, while the value stored at that address may change). If one were to slightly modify the call by separating the input and output lists, the following will appear in conventional programming subroutine alfa (, )

Consider a situation where there are 5 input parameters and three output parameters, with OP3 echoing the fourth input. Figure 1.1 shows the routine in G. There is an icon for ALFA. There is a set of wires corresponding to the and a second set corresponding to the . The will only allow data into alfa while caters to the outputs. Thus, below the skin two apparently very different methods are almost identical. Once exposed, the differences are essentially cosmetic in nature.

Fig. 1.1

Diagram of a VI

Thus, while in text-based programming the function is characterised by its name and variable list, in graphical programming one talks about the icon and

12

Virtual Instrumentation Using LabVIEW

wiring plane. The only real difference lies in the separation of the input and output lists. This is very much in line with the basic philosophy of data flow. The separation of the two lists effectively prohibits the routine from modifying the input data.

1.6

II

DISTRIBUTED SYSTEMS LabVIEW starting with Version 6 has evolved towards the world of networked systems. Version 6 was called 6i due to Internet Support. For some time, there was a flavour of LabVIEW, called LabVIEW RT (for Real Time), a quasiindependent product. Now RT is an add-on module to LabVIEW. Version 7 introduced support for FPGA (Field Programmable Gate Arrays). This was acknowledging the trend towards embedded systsms, and stand-alone applications thereon. FPGA is again an add-on module for LabVIEW. RT is designed to support real-time applications. While all users tend to believe that their applications are real time, in coding terms RT is required if the loops have to be faster than a few ms. The major problem running LabVIEW in Windows is that Windows is not a Real-Time Operating System (RTOS). It supports multithreading rather than multitasking. The latency (time lag taken by the application to actually execute) can vary depending on what other tasks are active at the time. Under Windows, this lag and the accompanying jitter can be as high as a millisecond or more. Using a proper RT environment, loops of as short as a few microseconds are routinely implemented. Using FPGA (which is essentially hardware designed in software), this time can be further reduced to under fifty nanoseconds. Thus, working in a non-RTOS environment, it is not possible to maintain tight control on the timing of loops and the latency. Generally, RT runs on a daughter computer system running an RTOS. RTOS is a far smaller (a few MB at most) OS than Windows. RTOS is optimised to take full advantage of the hardware to get the most stable timing performance. Also, the OS itself supports features like prioritising loops allowing timing critical operations to override other operations. The system clock can now be synchronised in microseconds rather than milliseconds. In a typical RT environment, the code is split into two parts—a small kernel under RTOS which is downloaded to the application hardware/processor, and the rest of the code including the user interaction (front panel) which normally resides on the host computer. The front panel can also be accessed through a Web server on an RT system, and often is not required to be permanently connected. The two work in conjunction. The host may be a regular PC or a palmtop which gets connected to the node as and when required. This may be a physical link (Ethernet, USB, etc.) or may be over a wireless

Introduction to Virtual Instrumentation

13

line. A PDA may be used to download (and also upload) to the node. This also serves to make the RT device immune to failures in the host. In many cases, the RT system once set up is only periodically connected to the host. Using a Web server, extends the flexibility even further. LabVIEW FPGA adds support for Field Programmable Gate Arrays in embedded systems. These systems can be extremely rugged and compact but are typically characterised with limited intelligence and capabilities. LabVIEW provides path for developing embeddable code using a normal high-level language like LabVIEW. LabVIEW FPGA internally translates the code to VHDL (Very high speed integrated circuit/Verilog Hardware Description Language), and then invokes a Xilinx compiler to produce a downloadable bitstream. While both these operations do not require user intervention, they are carried out in a batch mode. Working in LabVIEW, one can develop both RT codes as well as FPGA codes. While the available palette for RT is very similar to normal LabVIEW with a few additions specific to RT, in the case of FPGA this palette is significantly different and smaller. One obvious restriction is the non-availability of realnumber arithmetic. In the chapter on Distributed Systems, these will be taken up in some depth. Normal LabVIEW, RT and FPGA often coexist, at least in the developmental phase. Subsequently, the code can be ‘burnt’ into the FPGA module, making it autonomous. Similarly, the RT module can also be made autonomous. The use of a Web server makes this even simpler. PACs normally use autonomous FPGA hardware. LabVIEW 8 was again evolutionary with increasing emphasis on Express VIs or case tools for code development. After Windows Vista with its own multicore support there was the obvious and inevitable conflict with the task scheduler of LabVIEW. LabVIEW became Windows Vista compatible starting with Version 8.2.1. While Version 2009 is Windows 7 compatible, earlier versions may also be but National Instruments takes no responsibility. LabVIEW has taken a very distinct evolutionary step towards distributed computing, embedded systems, and the like. Thus it appears that both RT and FPGA will continue to coexist. One will have autonomous FPGA applications, stand-alone RT applications as well as hierarchical applications. Thus, all permutations of Normal, RT and FPGA systems are possible. There appears to be an increasing emphasis on smart sensors. Looking at the development of FPGA one can expect wide support for Digital Signal Processing (DSP) hardware, which forms an integral part of smart sensors. Today LabVIEW supports most microcontrollers and DSP hardware. Also, support for smart sensors including TEDS (Transducer Electronic Data Sheet) forms an integral part of LabVIEW. Support for wireless sensor networks through Zigbee is also becoming increasingly available.

14

Virtual Instrumentation Using LabVIEW

Overall, LabVIEW has evolved into a reasonably comprehensive product. One should expect that developments in the basic package are more likely to be evolutionary rather than revolutionary. One trend which will be accommodated is better support for newer interface standards like Firewire, USB, BlueTooth, etc., which are progressively replacing serial and GPIB links. The legacy systems may get phased out in time. For example, today hardly any laptop systems support the serial (RS232C) port, and link hardware (USB to Serial) is a must for serial applications. National Instruments has also been emphasising the area of process simulation and has its own libraries. However, it now has extensive support for various established products like MATLAB, Simulink, etc. LabVIEW can now integrate in MATLAB in a nearly transparent manner. It is likely that future development of LabVIEW will be more of an incremental nature than revolutionary. User interfaces will keep trend with the times, and the software development will be facilitated by increasing use of Assistants. It is now a mature product and also the emphasis of NI seems to be shifting towards hardware. Furthermore, with the original patents approaching their expiry date, efforts to develop a clone under Open Source are reportedly underway and well advanced.

2

BASICS OF LabVIEW INTRODUCTION

2.1

II

COMPONENTS OF LabVIEW Any instrumentation application will have two components, namely, the user interface and the underlying code. In LabVIEW, the user interaction takes place through the front panel (called the panel in short) while the code itself resides on the block diagram (diagram in short). When LabVIEW is first started up for editing a new VI, the screen looks like Fig. 2.1. The user sees two overlapping panes, the grey pane is the Panel and the white pane the Diagram (assuming default settings). The panel can be populated with two kinds of objects—the controls and the indicators. As the names suggest a control is an input to the code, while the indicator displays the output from the code. Any control or indicator placed on the panel automatically produces an icon in the diagram which is used to connect the code from and to it. Controls can be immediately distinguished from the indicators by their thicker border. Figure 2.2 shows two examples each of controls and indicators as they appear on the diagram. LabVIEW versions starting with 7, supports the iconic and normal representations (which have been named Old). The object as shown in the diagram carries the same name as its

16

Virtual Instrumentation Using LabVIEW

Fig. 2.1 A blank LabVIEW VI (panel and diagram)

parent in the panel. There are additional clues in the form of small arrows placed on the left (as inputs) for Indicators and right (as outputs) for Controls. The iconic representation also shows an indication as to the corresponding front panel object. The colour and text inside the symbol shows the data type (DBL for Double Precision Real). However, most experienced programmers Fig. 2.2 Controls and indicators prefer the older (non-iconic) representation (Note thicker borders in controls) since it saves space on the diagram and allows the developer to make optimal use of the screen space. As applications become complex, space on the diagram is at a premium. This can be changed for the object through right clicking on it, or permanently by Tools > Options > Block Diagram. It should be noted that in versions of LabVIEW prior to 7, front-panel objects could only be created or deleted from the front panel. While it was possible to create a front-panel object by popping-up on a terminal, deletion of control or indicator was not permitted.

2.2

II

OWNED AND FREE LABELS Whenever, any control or indicator is created it automatically comes with a label, which is highlighted and the user is (almost) invited to change it. Using

Basics of LabVIEW

17

the text tools, labels can always be edited. The label attached to an object is called an owned label, as it is owned by that object. If the object is selected and moved on the panel/diagram, the label moves with it. The label alone has to be selected if its relative position to its owner is to be changed. Text (for identifying blocks or other purposes) can be placed anywhere on the panel and diagram, and such text is called a free label. The display of labels on the panel (or diagram) can be turned on and off through popping-up on the object, as is discussed later. If a label is displayed on the panel, it need not be displayed on the diagram and vice versa. When developing complex or large VIs, space in the diagram space is often in short supply. In these cases, space limitations tempt the developer to switch labels off, while clarity of code demands that they be visible, A very useful technique is to have the label overlap a part of the symbol (Fig. 2.3). This shows the labels Fig. 2.3 Placement of a with a minimum of space penalty. label for an object

2.3

II

TOOLS AND OTHER PALETTES There are various palettes available to the user. These can be selected through the Windows drop-down menu. The tools palette (Fig. 2.4) is common to both the panel and diagram. The pointer can take various shapes depending on the function selected through the buttons. The large button on the top is for auto-selection, which if enabled, tries to automatically select the proper tool. The various buttons starting from the next row are—Operate, Select, Text, Wire, Object (or pop-up), Scroll, Breakpoint, Probe, and Colour Pickup. The button in the bottom row is for colour selection. It is strongly suggested that the user keeps the select button active except when he specifically needs one of the other operations. Pop-up is very useful in selecting various options for various objects, and can be activated by right-clicking, which is the preferred way for most users. Fig. 2.4 Tools palette Please refer to the LabVIEW documentation for detailed operating instructions for the various tools. In addition to the Tools palette, there are two other major palettes in LabVIEW, namely, the Controls and Functions palettes. The Controls palette is specific to the panel and the Functions Palette to the diagram. In version 2009 of LabVIEW, the main palettes are under the commands All Controls or All Functions. These

18

Virtual Instrumentation Using LabVIEW

are shown in Fig. 2.5 (In reality you will never see them together since only one will appear at a time). If activated, they are automatically selected and show up as the panel or diagram are selected. They can also be called by popping-up on the panel or diagram.

Output

Fig. 2.5 The Controls and Functions palettes

2.4

II

ARRANGING OBJECTS Since the user interacts with the program through the panel, it should be properly laid out. One must remember that the user may not be highly skilled, or may be tired or confused, and hence the need for a well-laid out front panel. However, many developers tend to neglect the diagram. Remember, this is where your code resides, and proper and neat layout is necessary to develop good code, and to be able to debug it successfully. One very common error is sloppy wiring. In icons with multiple terminals, part of the wire is hidden and visually appears to be connected to some other terminal. This practice is confusing and is strongly condemned. Objects can be selected and dragged around. Multiple objects can be selected by either putting them into a block (using the select tool to ‘draw’ a block encompassing the objects), or using to mark individual objects. Once selected, the object(s) can be dragged or moved with the arrow keys. The latter is specially useful when moving wires around.

Basics of LabVIEW

19

Align and Distribute toolsets are very handy in neat placement. Also, if you need to create identically sized controls or indicators, create one object and adjust its size, etc., to what you want. Then copy and paste multiple copies. Using Clean-Up Diagram (an option introduced in version 8) the diagram can be organised in a jiffy.

2.5

II Various objects in LabVIEW have a vast range of options. These are accessed by popping-up on the object. In Windows, the easiest way is to just right click on the object. One can use the pop-up menu as well from the tools palette. When you pop-up, the options relevant to the situation are displayed. Some of these are on the menu itself while others are accessed through sub-menus. These options are highly context sensitive and shall be dealt with in later discussions. Popping up also permits the user to convert a control into an indicator. One should be wary of inadvertently changing a control to an indicator or vice versa. This is a very common source of error with beginners. Also, one can use a pop-up to create an indicator or control. Another area where pop-up is indispensable is in defining the variable types. Integers are by default I32 (32-bit signed) and reals of type double. In Version 8 onwards they can all be changed by popping up and then either go into representation (for changing the data type) or the Properties (also Display format from the panel) to change other parameters like, range, display type, increment of button click, etc. In versions up to 7, these had to be changed through a somewhat different menu structure.

2.6

II

COLOUR CODING LabVIEW is highly visually interactive. The size and colour of the wires joining various objects provides information about the type of object (integer, real, Boolean or string) as well as whether it is a single entity, a one-, two- or multidimensional array or a cluster (construct). Wires connecting single entities are shown in Fig. 2.6. The colour clearly identifies the type of entity being connected. In case there is a permissible conversion (e.g., integer to real) it is indicated by a black dot in the destination object.

Fig. 2.6

Various types of wires

20

Virtual Instrumentation Using LabVIEW

These are the basic data types. There are also specialised data types like path, variants, waveform, etc., which are essentially specific or commonly used collections of basic data types. For example, a waveform data type comprises of a time Element and date stamp, data rate, and the data. Figure 2.7 shows the wires for an 1D Array element, 1D-array, 2D-array and a three 2D Array (multi) dimensional array. The 1D-array wire is thicker than the wire for an element. 3D Array Higher dimensional arrays are shown with twin wires, with the spacing being smaller for 2D-arrays.

Fig. 2.7 Wires for scalars and arrays

2.7

II

CODE DEBUGGING Any good programming language must provide good aids to debugging. The Run icon (Fig. 2.8) shown alongside the Continuous Run icons is broken if there is a coding error. Clicking on it brings up the Error display which is pretty informative. Logical errors have to be tracked down in running code. The basic tools available are Highlight Execution, Breakpoint, and Probe. The Highlight Execution tool is available on the diagram in the form of an unlit bulb. When activated, the bulb is lit (Fig. 2.9), data values flow down the wires and are displayed. Naturally, execution of the code is slowed down. This is the most commonly used debugging tool. In case this is not enough, code is big, or timing considerations preclude any slowing time then the twin tools of Breakpoint, and Probe (Fig. 2.10) are used. These are selected from the Tools palette and placed at the appropriate place. A probe is like putting a temporary indicator at a selected point in the code. The probe is displayed on both the Panel and Diagram, and closing the probe does not require any clean up of the wires. Also, the probe can be moved around on the screen as convenient. The Breakpoint, as the name suggests, stops (pauses) execution of the code at that point. Pressing the Pause button resumes execution. When the code is large, using the Highlight Execution tool in conjunction with the Breakpoint is often resorted to. A Breakpoint is placed at the beginning of the suspect area of code. The execution of code is started and it halts at the Breakpoint. At this point, highlight is enabled, execution is restarted and the results monitored. In addition there are also the Single Step, Step Over and Step Out functions. Single Stepping makes the code execute one instruction at a time (very rarely used), while Step Over and Step Out are used to enter and come out of sub-VIs or blocks of code. Since sub-VIs are normally debugged pieces of code single stepping through them is not normally required.

Basics of LabVIEW

Fig. 2.8 Run and Continuous Run icons

Fig. 2.10

2.8

II

21

Fig. 2.9 Highlight execution on

Breakpoint and Probe icons

CONTEXT SENSITIVE HELP While all LabVIEW documentation is available on-line, the context sensitive help is normally what is required. This may be full or simple. In simple help the information for the optional terminals is not displayed. Users can easily (and they should) document any sub-VIs they create.

2.9

II In any program subroutines play an important role. The two characteristics of a subroutine visible to the outside world are its name, and the input-output list. If one wishes to use a subroutine then this is the information needed to make it part of a bigger code. In LabVIEW subroutines are called sub-VIs. A sub-VI is characterised by the icon and the connector panel (or the wires). The one-to-one correspondence between conventional programming and LabVIEW is obvious. There can be two ways in which the user can create a sub-VI. If a block of code is becoming large, then a part of the code may be converted into a sub-VI. The fastest way of achieving this is to block out the code, using the pointer tool, then from the drop down menus do Edit > Create Sub VI. This will convert the blocked-out code into a sub-VI. Save this VI. Later you can modify this sub-VI (most users at least modify the icon). Alternatively, one may develop a piece of code and wish to make it into a subVI. This requires two steps—making the icon and then preparing the connector panel. The former may be done at any time, but the connectors are best defined when the code is (almost) complete.

22

Virtual Instrumentation Using LabVIEW

To access the various options for VIs, its icon on the top right corner of the front panel can be right clicked to select various options. Using ‘Edit Icon’ you can use a simplified version of Paint to edit the icon. Some users prefer a text description, while others prefer a graphic, while some may prefer a mix. It is only a matter of preference and there is no distinct advantage in any approach. In case of creating sub-VIs by block selection, a default icon is assigned. This is normally edited. Similarly, whenever you create a VI a default icon is associated with it. One important tip when editing icons, is to either frame the VI or give it a background colour. Otherwise, while wiring the VI there will be blank space between the wire(s) and the (invisible) boundary of the icon. Once the icon has been made, the next task is to create the wiring panel. For this right-click on the icon in the panel as before, and then select Show Connector. You can select the connector to be used through patterns, and these once selected can be Flipped as well as rotated through 90°. In cases where the code is not fully developed (or likely to be modified later) it is a good idea to place some additional terminals, which are left unwired at this stage. Now all that remains is to establish the relationship between the connector panel and the controls (and indicators). For this, click on the terminal in the connector panel, then on the Control or Indicator associated with it and then at some blank area in the panel. The area of the connector associated with the object takes on its colour. Repeat for all the terminals you wish to associate with various objects. Now your VI is complete. The usual practice is to keep inputs on the left (sometimes also parts of the top and bottom) and the outputs on the right. Even though LabVIEW allows a large (28) number of terminals on the connector, precisely attaching wires becomes difficult. In practice, most programmers try to limit the terminals to at most ten or so. Larger number of inputs can always be grouped together into a cluster, so that only one terminal is required. Finally, you can define the connections to a Control as Required, Recommended, or Optional through This Terminal is. A Required terminal is mandatory to connect, otherwise you get a broken wire, and an Optional Terminal does not appear in Simple Help. Default values can be assigned to various terminals which are Recommended or Optional. The system assumes this value if the terminal is left unwired. The normal practice is to put the default value in parenthesis on the label. To create or edit documentation for a VI you select VI Properties > Documentation and then incorporate the necessary changes. Now when contextsensitive help is on, the documentation appears in the same way as for any other VI. It may again be reiterated that unlike in ‘C’ you cannot change and return values of input variables. The only way is to wire it out through another variable.

Basics of LabVIEW

23

The following are some guidelines for good programming: 1. Keep the diagram neat by good positioning of the symbols. 2. Try and arrange controls and indicators in logical groups on the panel. You can use the various decoration options to highlight these groups. 3. Keep the wiring neat. Avoid inadvertently covering wires with objects, since these are the most frequent causes of errors. Also, ensure that wires are clearly connected to the correct terminals of the various icons. Users of Version 8 and later can ‘Clean up’ the diagram to rapidly get the screen into shape. 4. Try and limit each VI to one screen as far as possible. Due to this, most workers prefer to work with monitors of larger (17” or more) sizes, working in XGA (1024 ¥ 768 or higher) resolution. A good mouse is almost mandatory. Most users use external mice when working with laptops. 5. Clean coding saves space and is, therefore, a good programming practice.

3 FOR AND WHILE LOOPS INTRODUCTION Repetitive operations/calculations are usually a necessary part of any application. In order to work

For

3.1

II

While

discussed and explained in detail.

THE FOR LOOP The construct for a For loop can be described formally as FOR

DO

The For loop has existed in programming languages from the days of the earliest FORTRAN. LabVIEW supports the For loop (Fig. 3.1) in a fashion almost identical to the DO loop implementation in FORTRAN. The user will immediately observe that the For loop comprises of a box structure with the iteration (i) and count terminals (N). Formally, the syntax of the For loop in LabVIEW is FOR I = 0 to (N-1), Step 1 DO

The count terminal is placed at the corner of the loop and the value of N has to be specified prior to entering the For loop. This may be done explicitly

For and While Loops

25

or implicitly. The iteration value starts from 0 and automatically increments by 1 at the end of each loop. As the iteration count starts at 0, it is a common practice to set up VIs requiring initialisation to do so at i = 0. Normally in LabVIEW, both i and N are of data type I32. The For loop is also invaluable for creating and manipulating data in arrays, and the convenience is further enhanced by the facility of auto-indexing which will be Fig. 3.1 The For loop discussed later in this chapter. One major deviation in the original implementation of the For loop in DataFlow is that there was no equivalent to the break or the GOTO statement available. This forces the For loop to complete the full quota of iterations specified at the time of entering the loop. In conventional programming, it is a common practice to set up a For loop, and to check inside the loop whether the desired condition is satisfied or not. If not, the loop executes again, otherwise the loop is terminated and the code either proceeds to the first statement outside the loop (break command) or branches to the start of the next piece of code (GOTO command). This is considered to be inappropriate in DataFlow. Therefore, in LabVIEW once the For loop has been initiated there is no mechanism available to the user for terminating it prematurely. This restriction reduces the applicability of the For loop, and any situation where the iterations may have to be terminated prematurely have to be implemented using the While loop. However, starting with version 8, LabVIEW gives up this purity of concept and allows the user to do a conditional exit. The condition terminal is created by right clicking on the border and then selecting conditional terminal (Fig. 3.2). The alert reader will notice the small icon in the Count terminal indicating that the Conditional Terminal is in use.

Fig. 3.2 Conditional Terminal in For loop.

26

3.2

Virtual Instrumentation Using LabVIEW

II

THE WHILE LOOP Conventional programming languages support two types of While constructs, as is illustrated in Fig. 3.3. These are called pre- and post-test modes. In the pretest mode, the condition is tested prior to the execution of every loop and if the result is false then the execution of the loop is aborted. In the post-test mode the test is carried out only at the end of the loop. Functionally, the major difference is that under the post-test mode even if the condition is false at the very outset, the loop will be executed at least once, since the test is only performed at the end of the loop. WHILE ~ ~ DO

DO ~ ~ WHILE

Pre-test Mode

Post-test Mode

Fig. 3.3 The While Loop

LabVIEW supports only the post-test form of the While construct (Fig. 3.4). The While loop contains two terminals, namely, the iteration terminal, and (i) the condition terminal. As is the case with the For loop, the iteration terminal starts at 0 and increments by 1 at each iteration. At the end of each iteration, the loop tests the and if true, the next loop is initiated. This is defined as . In earlier versions of LabVIEW, Fig. 3.4 While loop this was the only test mode available. The default of all Booleans in LabVIEW is false and as a consequence a user wiring a Boolean control (say a Stop button) to the terminal for stopping the loop was forced to add a negation to the control (to make its default value True). This proved to be a minor inconvenience to the users. Starting from version 6, LabVIEW also supports an alternative (Fig. 3.5) form of the condition terminal . This proved to be very popular and consequently from version 7 onwards this is the default condition. This duality has added to the convenience of a majority of the users. However, in the view

For and While Loops

of some purists, this has diluted the purity of the concept. In versions using adding a negation routinely to the Boolean controls became second nature very quickly. Although both the styles are equally acceptable, yet for consistency, it is recommended that the user tries to stick to one form or the other. Indiscriminate mixing of the two forms, especially in the same VI or a group of VIs should be avoided. This can lead to problems in debugging of the code, and also makes the code more difficult to understand.

3.3

II

27

Fig. 3.5 Stop if true

ADDITIONAL LOOP PROBLEM Since LabVIEW does not operate in the left to right and top to bottom fashion like the conventional languages, it is possible that if a Stop button is used to control the While loop, an additional iteration is performed during the execution of the code. This can come about in the following manner. LabVIEW reads the Stop button at the beginning of the loop and stores the value while executing the rest of the loop. Say, now sometime during the execution of the code the status of the Stop button is changed. At the end of the execution, LabVIEW will use the value of the Boolean it had read at the beginning of the loop, and start the next loop, and only during this loop will the altered value be read and the execution stopped at its end. In the vast majority of cases this goes unnoticed, or proves to be at worst a very minor irritant. However, there may be situations where this is undesirable. In these circumstances the user must ensure that the STOP button is read only at the end of the loop. This is particularly important where the loop execution time is long, or there are safety considerations. The easiest way for this is to use a sequence structure where the STOP button is read in the last frame.

3.4

II

LOOP BEHAVIOUR AND INTERLOOP COMMUNICATION The behaviour of the loops in most respects is very similar. The loop, whether For or While, is like a closed chamber, unaffected by the changes of the input parameters once started. Whatever values are provided as inputs at the outset

28

Virtual Instrumentation Using LabVIEW

will remain so till the end of the execution of the loop, unless special techniques are adopted. Thus, if a value is input into the loop the same value will be used in all subsequent loops. In case the value is manipulated and the new value is required for the next iteration then the value will have to be fed in through either a local variable or a shift register. Another problem faced is—how does one stop two parallel loops with a single Stop button? Some possibilities which look promising will not work. One possible solution is to place the Stop button outside the loops (Fig. 3.6).

Fig. 3.6 Stop button outside loops

This will not work since once the loop starts executing, it is oblivious to any changes outside. Thus, the net effect is that if the Stop button is initially false the loops will execute forever, being oblivious to changes in the state of the Stop button. The next solution that comes to mind is to place the button inside one of the loops as is shown in Fig. 3.7.

Fig. 3.7 Stop button inside one loop

For and While Loops

29

This again will not work. The output of the left-hand loop is now an input to the other loop. If executed, the left-hand loop will start executing but the other loop will be waiting for the input. Once Stop is set true the first loop terminates, and then the value is transferred to the second loop which will execute exactly once and stop. What is required is to have the same button in both the loops. This is achieved by the use of a local variable and is illustrated in Fig. 3.8.

Fig. 3.8 Solution using local variables

3.5

II

LOCAL VARIABLES The local variable enables the right hand loop to have a copy of the Stop button value. As soon as its value is changed, the same value also appears in the other loop, and both of them then terminate. This illustrates the use of a local variable to transfer data between loops. A local variable is produced by selecting the object and popping up to Create Local on either the palette or the diagram. There can be multiple copies of a local variable and these copies can be either read (i.e. dummy controls) or write. If a variable is being written to in multiple places then the user must ensure that the logic precludes a race condition, in which the values can go into an endless loop. A local variable is essentially a copy of the variable which reads from (or writes into) the parent variable. It may be noted that a Button cannot be in a Latch Mode for local variables to be used because a Latch Mode will amount to the changed status waiting to execute while a local may be overwriting it. Thus if local copies of a Boolean are used, it is a common practice to reset the value just outside the loop by inverting the value and writing it to the variable (Fig. 3.9). It may be noted that

30

Virtual Instrumentation Using LabVIEW

the default mode for the Stop button is Latch when Released and can be changed to one of the switch modes through the Mechanical Action pop-up.

Fig. 3.9 Resetting a local variable

Other techniques, namely, global variables and notifiers can also be used to achieve the same results. Global variables are discussed next while notifiers are discussed later in the text.

3.6

II

GLOBAL VARIABLES The scope of a local variable is limited to the VI in which it is created. There may be situations where data has to be shared or transferred across VIs. Here, recourse is taken to global variables. Global variables are functionally similar to local variables and can always substitute them. Creation of global variable(s) is however more involved. A global variable has a panel but no diagram associated with it. For this in the Structures Palette, GLOBAL has to be selected. This will put a black box in the diagram with a miniature Globe (indicating a Global) and a ?. Next the user double clicks in the box and enters the panel of the global where the appropriate object(s) are placed. Then keeping this open, the programmer returns to the original diagram pops-up and selects the appropriate global for the black box. Globals can also be write or read. The button reset through globals is shown in Fig. 3.10. Multiple objects can be placed on the same global and then selected by the user. One very common use of globals is to initialise various parameters in a code, especially if the code is to be used for repetitive runs. The parameters are configured and transferred to subsequent run VIs through global variable(s) and when the user repeats the loop the new values are automatically available.

For and While Loops

31

Fig. 3.10 Resetting a global variable

3.7

II

SHIFT REGISTERS Often there is a requirement to use the previous value(s) in subsequent iterations. For example, the user needs to calculate a moving average. Similarly, there are many situations where the input value is manipulated and the new value is required in subsequent iterations. This is possible through local (or global) variables, but there is a more powerful and convenient tool available in the form of shift registers. In a shift register, the value at the end of a loop is transferred to the left-hand terminal at the beginning of the next loop. In case the register has multiple nodes then the values are successively transferred down the stack. The use of shift registers will become very clear from the example shown in Fig. 3.11. In the For loop, a shift register has been created by popping-up on the border and selecting Add Shift Register. Additional nodes can be created by popping-up on the left terminal of the shift register and (Adding Terminal).

Fig. 3.11 Shift register operation

32

Virtual Instrumentation Using LabVIEW

The shift register should invariably be initialised. Here, a shift register with three terminals has been created. All the values are initialised to –5. In the first iteration of the loop, all the three terminals have a value of –5. At the end of the first loop, the value at the right-hand side terminal of the loop (0) is transferred to the top terminal. In succeeding loops, these values are shifted down the stack on the left. For example, consider that the user wants to calculate a moving average of m-values. He will create a shift register with m-1 nodes and initialise all of them with some value. Then he will feed the latest value to the right-hand node. In each successive operation, the left-hand nodes will read from the top and will have the previous value, the one before, and so on. He will simply average the latest value along with the previous values in left-hand nodes to get the moving average.

3.8

II

FEEDBACK Feedback is a tool introduced in LabVIEW 7 and was not available earlier. It is functionally identical to a single-node shift register and is created whenever the output of a function or sub-VI in a loop is wired back to an input. Figure 3.12 shows a loop for adding integers up to 10. The Feedback loop creation and its initialisation is done in the same way as explained for other loops. The benefit in using Feedback is that code becomes more obvious.

Fig. 3.12 Use of feedback

3.9

II

AUTOINDEXING LabVIEW provides a very powerful and convenient tool for handling arrays through Autoindexing. Every While or For loop can support autoindexing. A For loop has it enabled by default while a While loop has it disabled. This status

For and While Loops

33

can be easily changed. If autoindexing is enabled, in the simplest mode it works as an accumulator, i.e., the data coming out of the loop will be automatically accumulated in an array. If an array is input to the loop then the successive elements of the array are automatically stripped and made available inside the array. In the example shown in Fig. 3.13, an array of 10 elements is created with all the values set at –10. Using autoindexing (–10 + i) is calculated, stored at the border, and moved out of the For loop. On the left-hand side (i.e., input), autoindexing strips out the individual elements of the array and similarly the accumulator on the right-hand side sends out the new array containing (–10 + i). Also, with autoindexing the Count terminal need not be initialised since LabVIEW automatically sets the lowest of the array size(s) and the value of N as the actual value of N. Use of autoindexing will be further discussed in the chapter on arrays and clusters.

Fig. 3.13 Autoindexing

3.10

II

LOOP TIMING Many applications require that precise timing be maintained between successive operations of the loop. In the PC, the internal clock is programmed to tick about 18.2 times a second (every 55 ms). This is not precise enough for most applications. LabVIEW reprograms the internal clock to a timing of 1 ms when it loads. Therefore, loops can be timed to an accuracy of 1ms. There are two timing VIs available in LabVIEW, namely, Wait ms and Wait Until Next ms Multiple. For loop timing operations, the latter is preferred. Wait (ms) waits for exactly n ms from the time it is first called (Fig. 3.14). Since there may be other code which is executed in parallel with the timing loop there is no guarantee that the actual delay will be exactly n ms. In general, this delay will be a variable with a minimum of n ms, since it is n ms from the call to the timing loop.

34

Virtual Instrumentation Using LabVIEW

Fig. 3.14 Wait (ms)

The Wait Until Next ms Multiple system uses an internal timer (say, T). This is not of much use by itself since T = 0 is not well defined. Suppose a value n is input as millisecond multiple (Fig. 3.15). Then the timing of the loop is set at T mod n = 0. This has two effects. In the first loop the actual delay will in general be less than n ms, since it is very unlikely that the loop has initiated exactly at T mod n = 0. Subsequent loops will however be exactly timed since even if some other part of the loop has been initiated before the wait, the modulus operation will ensure that the timing is precise.

Fig. 3.15

Wait Until Next ms Multiple

Thus, with Wait Until Next ms Multiple, the loop timing is exact (after the first iteration). Wait (ms) will not guarantee the same precision in timing. The millisecond timer value is available as an output from both the VIs. This is not directly used for timing since T = 0 is undefined. It is however a useful input for developing artificial data dependencies. Wait (ms) finds use in operations involving reading data from an external instrument. The user may have to send a Trigger and then wait for a minimum time before interrogating the instrument for the data. Also, it is preferred in sequence structures because in Wait Until Next ms Multiple the timing for the first loop is not defined precisely. Thus in For and While loops Wait Until ms Multiple is almost invariably used while in sequential operations like instrument interfacing Wait (ms) is the timing function of choice. Starting with LabVIEW 7.1, hardware timing has been added. This is primarily for real-time applications, where the timing capabilities of the hardware are exploited. In case of fast systems like FPGA and PXI it is possible to set up a base clock of 1 MHz as against 1 kHz in the computer system. This permits faster execution and precise timing of the loops. It also provides for synchronisation and prioritisation of these loops through the facility of setting up a single timing

For and While Loops

35

source and then using it for multiple processes. Also, any loop which is delayed is flagged, and the actual duration information is available to the user.

3.11

II

TIMED LOOPS The implementation, the hardware timed loops started with LabVIEW 7.1. The timed loop is very similar to the While loop.

Fig. 3.16 Timed loop

It has the additional feature of being able to select the processor (in a multicore or CPU system), assign priority, etc., though in practice the LabVIEW scheduler does an excellent job and processor selection is rarely required. It can also indicate if the previous loop had timed out; i.e., taken more time that the loop time. The way things are progressing it is likely that the e-timed loop may one day become the preferred option to the While loop.

4 OTHER STRUCTURES INTRODUCTION We have seen the two most commonly used structures— the For and the While loops—in the previous chapter. The Timed Loop being functionally almost identical to the While loop has also been discussed in Chapter 3. The other items on the Structured Palette are

4.1

II

variables. In this chapter we will examine the Sequence and Local Variables do not fall strictly in the domain of structures and have been discussed earlier in Chapter 3.

SEQUENCE STRUCTURES Sequence Structures are unique to DataFlow programming. In conventional programming where code executes left to right and top to bottom, sequencing is automatic. In DataFlow programming, any block of code will execute whenever all the inputs are available. This may result in multiple blocks of code ‘firing off ’ at about the same time. In many operations it is necessary to force the code to execute in a sequence. This is achieved by the use of sequence structures. Originally, there was only one type of sequence structure in LabVIEW— the Stacked Structure. LabVIEW 7 introduced another sequence structure, the Flat Structure. The two structures are almost identical and will, therefore, be discussed together. Differences will be pointed out wherever applicable. It is always possible to switch from one type to another with minimum effort through the pop-up menu. The sequence structure (Fig. 4.1) is created in the diagram by placing and dragging like the For and While loops. It has the appearance of a frame of perforated 35-mm film. Code can be placed inside the frame and wires drawn

Other Structures

37

to and from the frame. At this point, a sequence structure is no more than a grouping of code. Additional frames are added by popping-up on the border and selecting Add Frame. In the case of a stacked structure, only one frame is visible, with the Frame Number appearing in the middle of the top border. In a flat structure, a second frame appears after the first. Subsequent frames can be added by repeating the operation. A stacked structure has the advantage of occupying less space on the diagram since various frames are stacked on top of each other like a pack of cards, and only the frame selected by the user is visible at any given time. The user can scroll through the frames by clicking on the tabs in the frame counter or through the pop- up menu by selecting the frame to view. In a flat structure, all frames are visible, but at the cost of occupying more space on the Diagram. As real estate is always at a premium, most experienced users prefer to work with stacked sequences, or at least switch to these as the code approaches completion. Users may find it convenient to develop VI using the flat structure and then change to a stacked structure once the structure is coded. The various frames operate sequentially. Figure 4.1 shows a sequence structure to find the execution time of a block of code. The code as shown in the flat sequence is self-explanatory. The same code when put in the stacked sequence shows only one frame. The illustration shows both Frames 1 and 3. The code appears very similar except for the Sequence Locals.

Fig. 4.1 Sequence structure

How does one transfer data between frames in a stacked structure? One needs a mechanism to transfer data between frames, which is not possible using conventional nodes. One way could be to separate sequence structures where

38

Virtual Instrumentation Using LabVIEW

data from previous frames is required but this is quite cumbersome. A Sequence Local is very handy for carrying out this operation. To make data from a frame available to subsequent frames, the user selects Add Sequence Local from the pop-up menu on the borders. This produces a small box (like a node) to which data can be wired. The first frame where this node is used has the data wired to it, and is indicated by an outward arrow in the box (colour appropriate to the data type). This data is then available to all subsequent frames and the node appears in exactly the same position with an inward arrow. In frames before the point where data is input to the node, the node appears as a blank (shaded) box. An alternative and convenient way of creating sequence local is to code in the flat sequence and then convert to stacked sequence. And discussed in the previous chapter, if delays are required between two frames of a sequence structure, Wait (ms) is a better option than Wait Until Next ms Multiple.

4.2

II

CASE STRUCTURE A case structure (Fig. 4.2) corresponds to the classic if ... then ... else construct. Case structures appear as stacked sequences in the diagram, very similar to the stacked sequence. The case structure has a condition terminal (originally in the centre of the left boundary) to which the condition is wired. The condition can be Boolean, numeric or string.

Fig. 4.2 Case structure

Figure 4.2 shows all three types of case structures, namely, Boolean, numeric and string. In the case of Boolean conditions, there are two cases corresponding to True and False. In case of numeric and string conditions, the number of cases can be many and additional cases are added in a manner similar to that for a stacked sequence. It is necessary that one of the cases must be defined as default to which the code reverts in case none of the conditions are satisfied. The frame visible for the numeric condition is the default condition in the illustration.

Other Structures

39

In case of a numeric condition, the number is rounded to the nearest integer for the condition to operate. The use of numeric conditions in case structures corresponds most closely to the Computed GOTO in FORTRAN. In situations where there were more than two possibilities this was the only case structure available in FORTRAN. However, this had some inherent drawbacks. Often the condition comes from some other piece of code, and if another possibility is added to this code, then there is an additional condition to cater to in the case structure which makes matters complex. Also keeping tab of the various options numerically is not very convenient, and often the programmer unwittingly ends up using the wrong case for a particular situation. Earlier versions of LabVIEW only supported the use of Booleans and numbers for the case structure. Support for strings was introduced in later versions. Due to reasons outlined above strings are increasingly being preferred for the control. This leads to clarity of the code, and the addition or deletion of frames does not lead to the unwitting application of wrong code to particular conditions. However, one must make absolutely certain that the strings being sent to the Condition terminal match the actual conditions exactly, otherwise the default case will be executed which may lead to execution errors. When data is taken out of a case structure, a tunnel is created. This tunnel is white in colour until all the cases have been wired to it. Once they are all wired in, the tunnel takes on the colour corresponding to the data type. This requirement is obvious when one looks at the basic tenets of DataFlow, whereby every case must provide a value for the succeeding code to use. Users must be careful when wiring the tunnels. It is very easy not to connect to an existing tunnel, and actually create another (overlapping) tunnel instead. Such bad connections can be quite difficult to track down. The case structure is very important since it forms the heart of the state machine, which is probably the single-most powerful tool for developing code for non-linear execution. The support for string case structures almost certainly was due to the demands of the state machine. The use of state machine(s) is almost mandatory in developing any medium or large application. Use of Ring Controls for Case Structure Implementation: The case structure is often implemented through a ring control. This provides an integer output from the selection with a good text interface for the user to work with. Alternatively, a cluster of Booleans will have to be used (as is discussed in the chapter on state machines). As compared to the cluster (or array of Booleans) it saves valuable space on the front panel. The common ring controls are text ring, menu ring and enumerated. In all of them, the ring user selects the operation through the front panel and the ring control in the diagram gives an integer output corresponding to the selection, which in turn is used to select the option in the case structure.

40

4.3

Virtual Instrumentation Using LabVIEW

II

FORMULA NODE Sometimes there is a requirement to program a piece of code in a conventional or quasi-conventional way. This is possible in LabVIEW through the use of the Formula Node. While earlier versions of LabVIEW supported the Formula Node, they required code to be written in rather cryptic Backus–Naur Notation. Later versions support coding in C-syntax. Conditional statements, branches, etc., are all supported. Users envisaging the use of Formula Nodes are faced with the issue of reconciling the graphical symbolism of LabVIEW with the alphanumeric representation in text based languages. This is done by popping-up on the boundary of the formula node and selecting Add Input and Add Output to create these nodes for input and output, respectively. The name assigned to the particular variable is typed into the box created whenever an Add Input/Output operation is performed. As expected in a DataFlow environment, separate nodes have to be associated with the input and output lists, i.e. if the user changes the value of an input variable inside the formula node the output has to be done through a separate node.

Fig. 4.3 Formula node

Furthermore, a formula node does not support multithreading, i.e., as long as the formula node is executing, operation of other blocks of code is not permitted. This is seldom a constraint since very rarely does the code in the formula node takes any appreciable time to execute. Any complex coding is best left for linking through DLLs or CINs. A single line formula node is also available for convenience.

4.4

II

EVENT STRUCTURE The last structure is the Event Structure (Fig. 4.4). This was originally developed to cater to mouse press events, but has expanded in scope ever since. As

Other Structures

41

discussion of this is beyond the scope of this book, further details are not covered.

Fig. 4.4 Event structure

The Timed Loop has been discussed in the previous chapter since it is very analogous to the While loop. Functionally, are being almost identical. There is also a Timed Sequence (Fig. 4.5) which is no different from a Flat Sequence placed inside a timing loop, and hence the functionality is very obvious.

Fig. 4.5 Timed sequence

5 ARRAYS AND CLUSTERS INTRODUCTION Handling of compound data like waveforms, graphs, data from multiple sensors, etc., is often required in several applications. LabVIEW, like other conventional languages, uses arrays and data structures for this purpose. In LabVIEW, data structures are referred to as clusters. A LabVIEW array is a homogenous collection (i.e., all of the same type) of data elements. An array can have one or more dimensions and up to 231 elements per dimension (subject to the memory capacity). An array data element can be of any type except another array, a chart or a graph. An array with n elements is indexed from 0 to (n 0 and the last one at index (n – 1). A LabVIEW cluster is also a data structure that groups data. Unlike an array, a cluster can group data of different types. It is analogous to struct in C or record in Pascal. controls, whereas a cluster might contain a digital control, a pushbutton switch and a string control. Another difference between arrays and clusters is that arrays can change dynamically. Arrays and clusters are similar in the sense that both are made up of either controls or indicators.

While the behaviour of arrays and clusters in LabVIEW is very similar to that in conventional languages, there are some significant but vital differences. A cluster may be thought of as a bundle of wires and is shown as a ‘rope’ in the block diagram. Clusters reduce wire clutter and the number of connector terminals in a sub VI. On the block diagram one can connect cluster terminals with another cluster wire only if they have the same type, the same number of elements and the same order of elements. The cluster elements can be accessed by unbundling them all at once or by indexing one at a time. While any array can be converted into a cluster (in a priori), a cluster can only be converted to an array when all the elements are of the same kind. Clusters are commonly used to pass a record across VIs. This not only leads to the orderly grouping of data but also reduces the need to clutter up the diagram with multiple wires, since now the clusters are connected with a single wire, albeit thicker. Clusters are also used for passing error information between multiple VIs in a block diagram.

Arrays and Clusters

5.1

II

43

ARRAYS

Creating Array Controls and Indicators An array control or indicator is created by first choosing the array shell and then depositing a data object into it. The element display window will automatically resize as per the new data type. It should be noted that all the elements of an array must be either controls or indicators. Figure 5.1 shows a blank array shell, and the same shell after being populated and converted into a two-dimensional array of numeric controls. Initially, the block diagram terminal of the array shell is black to indicate that the data type is not defined. Once a data type is assigned to the array shell, the block diagram takes the colour and lettering (in [ ] brackets) of the data type. For example, if the data type is a numeric indicator, the colour will be orange with [DBL] written inside the terminal. Arrays can be identified easily by their thicker (or double) wires.

Fig. 5.1 Creating an array control

Figure 5.2 shows simple nested FOR loops to generate a 3 ¥ 3 ¥ 3 array of random numbers. Note the thick wire for a onedimensional array from the innermost loop, the double wire with narrow spacing for a two-dimensional array and the increased spacing for the three-dimensional array. Fig. 5.2 Use of for loops for creating arrays through auto-indexing

44

Virtual Instrumentation Using LabVIEW

Array Constants Array constants are often required on the block diagram for initialisation, etc. They are created by first choosing Array Constant from the Array subpalette of the Functions palette, followed by placing an appropriate data type in the shell. Auto Indexing LabVIEW allows the indexing and accumulation of arrays at the boundaries of for loops and while loops automatically, one element at a time for each loop operation. This capability is called auto indexing. By default, auto indexing is enabled on for loops but disabled on while loops. In a for loop with auto indexing, each iteration creates the next element and after the loop is completed, the array is accumulated at the boundary, which can be taken out. Figure 5.3 shows two two-dimensional arrays going into two nested for loops. The upper trace has the auto-indexing disabled in the input, while in the lower trace the indexing is enabled. Note that in the former, the two-dimensional array continues into the innermost loop, while in the latter it becomes a onedimensional array inside the outer loop and becomes a scalar in the inner loop, i.e., the dimension is reduced by one at each stage. The tunnel is filled in cases where indexing is disabled, and shows [ ] to indicate that it is enabled. On the output side, auto-indexing is enabled in both cases on the outer loop, and at each loop (due to the accumulator) the dimension is increased by one, Thus the two-dimensional array becomes three-dimensional and then four-dimensional in the upper trace, while in the lower, the scalar continues as a scalar and then becomes a one-dimensional array.

Fig. 5.3 Operation of Auto-indexing

As is evident, if only a scalar value (i.e., the last value of the loop) is to be taken out of a for loop, the auto-indexing must be disabled. In a while loop, auto-indexing is disabled by default, as it is more natural for it to output the last value. Again, if it is needed to wire an array out of a while loop, auto indexing

Arrays and Clusters

45

is enabled. It is important to keep track of the auto-indexing in a particular code by observing the wire size. Similarly, auto indexing is applicable when wiring arrays into the loops. If indexing is enabled, the loop will index off one element from the array each time. If indexing is disabled, the entire array passes into the loop at once. When auto indexing is enabled on an array entering a for loop, LabVIEW automatically sets the loop iteration count to the array size, thus eliminating the need to wire a value to the count terminal. In case the count value is already wired, the lower of the two is taken to be the count value. Similarly, if auto indexing is enabled for more than one array, and the count value is not specified, the smaller of the two array sizes is taken as the count value. Multi-Dimensional Arrays One can add dimensions to an array control or indicator by popping up on its index display and choosing Add Dimension. Similarly, unwanted dimensions can be removed by selecting Remove Dimension from the pop up menu. Alternatively, the dimension can be changed by dragging the index display on the panel. Two-dimensional arrays are very commonly used in data acquisition applications. For example, when waveforms from several channels are read from a data acquisition (DAQ) board, the data is stored in a two-dimensional (2D) array, where each column in the array corresponds to data from one channel. A 2D array can also be generated easily using two nested for loops, i.e., by placing one for loop inside the other, as is shown in Fig. 5.2. In this case the outer loop will correspond to the rows of the array and the inner one to the columns. 2D and multi-dimensional arrays are indicated by two lines (with colour appropriate to the data type) in the block diagram. Arrays of larger dimensions are also indicated by two wires, but with a greater spacing. A three-dimensional (3D) array, a (i, j, k) will have i indicating the page, j the row and k the column. One can consider the array to be like a pack of cards, with the page indicating the card in the deck. All indices start from zero. Figure 5.3 earlier, shows the wires corresponding to a scalar as well as 1D, 2D, 3D and 4D arrays. Array Operations LabVIEW provides many functions to manipulate arrays. These can be accessed from the Arrays subpalette of the Functions palette. Some of the commonly used functions are Array size, Initialize Array, Build Array, Array subset, and Index Array. These functions are briefly explained below.

46

Virtual Instrumentation Using LabVIEW

Array Size: The Array Size (Fig. 5.4) function returns the number of elements in each dimension of array. If the input array is n-dimensional, the output will be a one-dimensional array with n-elements.

Fig. 5.4 Array Size Function

Initialize Array: The Initialize Array (Fig. 5.5) function creates an n-dimensional array with elements with values specified at the input. One important use of this function is to allocate memory for arrays. The data type of the array is determined by what is connected to the input.

Fig. 5.5 Initialize Array Function

Build Array: The Build Array (Fig. 5.6) function is used to concatenate multiple arrays or to append extra elements to an array. Initially, when the function is placed on the block diagram, the function will appear with only one input available. Inputs can be added by the positioning tool or by selecting Add Input from the pop-up menu. The inputs can be single-valued elements or arrays. The Build Array function has two modes of operation, based on whether the Concatenate Inputs option is selected or not. If this option is selected, the function appends all inputs in order, in which they appear in the function, top

Fig. 5.6 Build Array Function

Arrays and Clusters

47

to bottom, forming an output array of the same dimensionality as the highestdimension array input wired. If the Concatenate Inputs option is not selected, the output array will have one dimension higher than the dimension of the inputs. Array Subset: The Array Subset (Fig. 5.7) function returns a portion of the input array starting at the specified index and containing length number of elements. Once the array is wired to the input, the function automatically resizes to display index inputs for each dimension in the array.

Fig. 5.7 Array Subset Function

Index Array: The Index Array (Fig. 5.8) function returns the element or sub-array of the n-dimension array at index. The function resizes automatically to display index inputs for each dimension in the connected n-dimension array. Additional element or sub-array terminals can be added by resizing using positioning tool. This function is especially useful in extracting a sub-array of the given array. This can be done by leaving one or more of the index terminals unwired. For example, the column 2 of a 2D array can be extracted by specifying 2 in the column index and leaving the row index unwired. This operation is very commonly required to extract a particular sensor output in multi-channel data acquisition applications.

Fig. 5.8 Index Array Function

Polymorphism in Array Operations Polymorphism of LabVIEW is applicable to arrays as well. Hence, one can add a scalar to an array or add two arrays using the same function. It is important

48

Virtual Instrumentation Using LabVIEW

to note that for the same function different types of operations are performed for different combinations. For example, if a scalar and an array are added, the scalar is added to each element of the array. However, when two arrays are added, each element of one array is added to the corresponding element of the other array. Array Size In LabVIEW, the size of arrays need not be predetermined. The array will grow as more elements are added to it. However, if large arrays are used, efficiency considerations may dictate that the arrays are not incremented by units, but in groups. This can be easily understood if one looks at the way data is stored. Say, an array of size n is stored. Then a space corresponding to n-elements is reserved in the stack for it. Now when an element is added to the array, fresh space (now for n + 1 elements) has to be found. Then the n-elements from the old array have to be transferred to this space. This exercise has to be repeated each time the array size is incremented and hence it is recommended that large arrays are incremented by groups and not by units. Newer versions of LabVIEW do this automatically to a extent.

5.2

II

CLUSTERS

Creating Cluster Controls and Indicators A cluster can be created by placing a cluster shell on the front panel and then placing one of the front panel objects inside the cluster. On the block diagram, the cluster wire will appear as a rope. Figure 5.9 shows a cluster of three controls, a numeric and two Boolean. The icon (showing an assortment of objects, which is what a cluster really is) appears in the block diagram along with the rope indicating that it is a cluster. Similar to the arrays, objects can be deposited inside the cluster, making sure that all of them are either controls or indicators. One important function of the clusters is to bundle a number of controls or indicators, thus using a single terminal and wire to pass several values into or out of a sub VI. Cluster elements have a logical order unrelated to their position within the shell. The first object placed in the cluster is defined initially as element zero, the second object element one, and so on. The cluster order can be changed by popping up on the cluster border. The menu will display the elements with their current order and new orders, which may be changed as required. It is important to keep track of the cluster order to connect the cluster to another cluster. Interconnection of clusters is possible only when both the order and data types match. Cluster order information is also required while unbundling a cluster.

Arrays and Clusters

49

Fig. 5.9 Creating a cluster

Cluster Operations The main cluster operations, viz. Bundle, Unbundle, Bundle by Name and Unbundle by Name are explained briefly below. Bundle: The Bundle function (Fig. 5.10) assembles individual components into a single new cluster and also allows one to replace elements in an existing order. Initially, the function shows only two inputs, which can be increased by dragging a corner of the function. As each input terminal is wired, a symbol representing the data type of the wired element appears on the empty terminal. The order of the resultant cluster will be the order of inputs to the bundle. The cluster input at the centre of the function is used only when one or more elements of the cluster are to be replaced. Hence, this terminal is ignored while creating a new cluster. When the above function is used to replace an element, the number of input terminals must match with those in the cluster. However, one needs to wire only the new value(s) of the element(s) to be replaced.

Fig. 5.10

Bundle Function

50

Virtual Instrumentation Using LabVIEW

Unbundle: The Unbundle function (Fig. 5.11) splits a cluster into its individual components. The output components are arranged top to bottom in the same order that they have in the cluster. If the elements have the same data type, the order of the elements in the cluster is the only way one can distinguish between them. It is important to resize the function to contain the same number of outputs as there are elements in the input cluster.

Fig. 5.11

Unbundle Function

Bundle by Name: Sometimes, it is required to operate on an element or two and not the entire cluster. In the Bundle by Name function (Fig. 5.12), elements are referenced by names rather than by position. Here one can access only the elements needed. Also, this function cannot create new clusters, but can only replace an element in an existing cluster. The only prerequisite, for the Bundle by Name function to work is that all the elements must have names.

Fig. 5.12

Bundle by Name Function

Unbundle by Name: The Unbundle by Name function (Fig. 5.13) returns the cluster elements whose names are specified. The major advantage of this function is that one does not have to keep track of the order of the elements within the cluster. Also, this function does not require the number of elements to match the number in the cluster.

Fig. 5.13

Unbundle by Name Function

Arrays and Clusters

51

The use of Bundle and Unbundle by Name functions is now preferred by most programmers since this reduces the chances of picking up and operating on the wrong element. Also, when large clusters are used, these functions save a lot of space on the diagram, which is often scarce while developing code.

5.3

II Often it is required to change arrays to clusters and vice versa. This is especially useful since LabVIEW has many more functions for arrays than for clusters. The main functions available for conversion between arrays and clusters are the Cluster to Array and Array to Cluster functions. Thus a cluster can be converted into an array first, and converted back to a cluster after performing the required operation from the available array functions. Cluster to Array: The Cluster to Array function (Fig. 5.14) converts a cluster of n elements of the same data type into an array of n elements of that data type with Fig. 5.14 Cluster to array conversion function the array index same as the cluster order. This conversion is possible only if all the elements in the cluster have the same data type. This function cannot be used on a cluster of arrays, since LabVIEW does not allow an array of arrays type of structure. Array to Cluster: The Array to Cluster function (Fig. 5.15) converts an n element, one-dimensional array into a cluster of n elements of the same data type. This function Fig. 5.15 Array to cluster conversion function is useful when one would like to display the elements of the same type in a front panel but still want to manipulate the elements on the block diagram by their index values. Since clusters do not size automatically, one needs to specify the cluster size by popping up on the function. The default cluster size is 9, while the maximum size permitted is 256. Build Cluster Array: The Build Cluster Array function (Fig. 5.16) is used to create an array of clusters where each cluster contains an array. This function does it by first bundling each component input into a cluster and then assembling all component clusters into an array of clusters. Note that each cluster contains only a single component. It is required that component 0. n – 1 inputs must be of the same type.

52

Virtual Instrumentation Using LabVIEW

Fig. 5.16

Build cluster array function

Index and Build Cluster Array: This function (Fig. 5.17) indexes a set of arrays and creates a cluster array in which the ith element contains the ith element of each input array. The input array of x…z can be one-dimensional array of any type. Here all the array inputs do not have to be of the same type. The function will yield a cluster array containing one element from each input array.

Fig. 5.17

Index and Build Cluster Array Function

SUMMARY constants. by the user.

are accessed through the cluster order.

6 GRAPHS AND CHARTS INTRODUCTION Displaying data is equally important and sometimes even more important than acquiring it. Therefore, good display tools are a necessity. More often than not data needs to be presented graphically. One can repeat the cliché: a picture is worth a thousand words. Also, when data is being analysed graphical output of the analysis is often required. Even in cases where data is analysed numerically, like in the case of regression analysis, a data points. In process control applications, trends are also required to be shown to the operator. Therefore, it is evident that the graphical display of data is a very important aspect of programming in LabVIEW. In most situations, two-dimensional X-Y displays are required. LabVIEW provides three tools for this, namely, the waveform chart, the waveform graph, and the X-Y graph equally spaced along the X-axis, the last is especially for situations where the X-intervals are not equal. All these objects can be accessed from the panel through

6.1

II

either the Express VI function on the Graph Indicators palette, or through the All Controls palette and the Graph Menu. If the latter is used, other displays like three-dimensional, parametric, intensity, etc., are also available. The major plot types chart, graph and X-Y graph), customisation for various situations and their tools like cursors, etc., which are required to interact with graphical data are discussed in the chapter. These are very powerful, and relatively simple to use. However, their use is somewhat poorly documented. The user should have a good grasp of the use of arrays and clusters since these are the heart of the graphical operations. LabVIEW also supports specialised graph types, such as polar plots, Smith charts, parametric charts, etc. These are beyond the scope of this book and are hence not discussed. The following discussion details the three basic graph types: waveform chart, waveform graph and X-Y graph.

WAVEFORM CHART The first and the simplest graphical display available is the waveform chart. It is the only type of display where individual data points or data point sets

54

Virtual Instrumentation Using LabVIEW

can be directly displayed. In the simplest waveform chart, the data is created and connected to the waveform chart icon. Figure 6.1 shows a waveform chart set up to display a random number every 500 ms. The graph appears in the diagram as an indicator of the data type being sent to it. A very high degree of customisation can be done by popping up at an appropriate place on the chart. Among the parameters that can be changed are the colours, scaling and point display methods. These are of particular interest and selections about colour, symbol, line style, interpolation (whether points are joined by polygons, histogram, etc.) can all be made. This customisation is done by popping up on the Plot Legend on the top right-hand side.

Fig. 6.1

6.2

II

Waveform Chart

RESETTING PLOTS If the user were to run the code repeatedly, he will find that the subsequent traces include the old data, and it is not cleared. This is so since a waveform chart internally stores the data as an array which is set at 1024 elements by default. The chart can be manually cleared by popping up and then selecting Data Operations Æ Clear Chart. The array size to store previous data can be varied by popping up and changing the Chart History Length. The data in the chart history can be accessed for both reading and writing through the property node. Thus if this array is reset then the trace is removed. This is shown in Fig. 6.2. The user first creates a property node for the history (Create Æ Property

Graphs and Charts

55

Fig. 6.2 Resetting the Chart

Node Æ History Data Æ Change to Write) and then pops up on it and creates a constant. This creates a null array of the appropriate data type. The reader should note that the chart history array is wired to the border of the loop in order to create an artificial data dependency. For multiple traces the data is first bundled together before being wired to the chart, as is shown in Fig. 6.3. Here the code is modified to show the data

Fig. 6.3 Multiple Traces in a Chart

56

Virtual Instrumentation Using LabVIEW

as well as its four point moving average using shift registers. There are a few other points which the reader may note. In the panel the data is displayed as open squares and the points are not interconnected. Since the data is now a cluster the icon changes appropriately. This illustrates a very common use of the waveform chart in real-life applications. Data can be displayed in a chart in three ways—as a Strip Chart, as a Scope Chart and as a Sweep Chart. This is selected through Advanced Æ Update Mode. The three modes are shown in Fig. 6.4. The Strip Chart is the most common mode. Here the data display proceeds from left to right, and when the right border is reached the chart moves to the left as succeeding points are shown in

Fig. 6.4 Strip, Scope and Sweep Charts

Graphs and Charts

57

the right border. It is as if the chart paper is scrolling and the right limit of the window shows the latest data. The Scope Chart, as the name suggests, is like the display in an oscilloscope. The trace moves from left to right, once the right border is reached, the display is erased and again starts from the left. The Sweep Chart is a variant of the Scope Chart. Here, the trace is not erased at the end of the sweep. The new data is displayed from the left and the old data is progressively erased, with a reference line showing the border. This mode of display is very useful in process control type of applications, since any tendency for the data to drift becomes very apparent. While being very handy and versatile, the waveform chart suffers from some major handicaps. First, the x-axis increments are always unity, except for some waveform data types. Second, it is not possible to place and use cursors on the waveform chart. Despite these handicaps, the waveform chart is in many respects the workhorse of graphical displays. The way the various other displays (namely, the waveform graph and x-y graph) work, is very similar to what has been described for the waveform chart. The underlying philosophy does not change between various types of display in LabVIEW. Data for both waveform graph and x-y graph must be in arrays. But, while the waveform graph may be considered to be a more powerful version of the waveform chart (because here also the data must be equally spaced along the x-axis), the x-y graph is a different entity altogether.

6.3

II

WAVEFORM GRAPH The immediate change that the user faces while working on the waveform graph is that the data must be in an array. The simplest representation of a waveform graph (in many ways equivalent to the waveform chart) is to simply wire the array to the waveform graph. Let us consider the case in Fig. 6.2. Since the data must now be in an array, the array has to be ‘built’ to append the last value to it. For this the use of a shift register and Build Array is necessary. This has been done in Fig. 6.5. On the other hand, since there are no internal arrays, the graph is reset by simply sending in a null array into the shift register. The user is advised to understand how the array is built up since this code is often used in a wide variety of applications. For multiple traces the data should be organised in a two-dimensional array with each trace as a row of the plot. Since in many cases the data comes in as columns instead of rows, a Transpose Array function is available on the pop-up menu from the panel. When the waveform graph is used, the user will more often than not wish that the X-axis is also properly marked in X0 and DX. This is done by bundling X0 and DX along with the data. If there are multiple traces having with the same

58

Virtual Instrumentation Using LabVIEW

Fig. 6.5 Building an Array for Waveform Graph

increments, then the data can be in a two-dimensional array as earlier. Figure 6.6 shows a situation where two traces, both with X0 = 0 and DX = 0.15 are created. However, if the scale parameters are different for various traces then clusters corresponding to individual traces have to be assembled and made into an array as shown in Fig. 6.7. Here, the intervals are 0.15 and 0.25 respectively for the two traces. While Fig. 6.6 uses an icon representation of the graph, Fig. 6.7 uses a symbol. The reduced space requirements of a symbol are quite evident.

Fig. 6.6 Waveform Graph with Scaling on X-Axis

Fig. 6.7

Graphs and Charts

59

One specific situation which often arises in applications is the need to show different parts of a trace in different colours. This is not directly possible in LabVIEW, since any change in colour (through property node) immediately affects the entire trace. However, a workaround which achieves the same purpose is as follows. Say, you need to show parts of a trace in two different colours. You should set up two traces for the two colours. Now feed the data to the trace where you wish to display the data and a NaN (not a number, which is a defined constant) to the other trace. Then when both the traces are displayed they will appear as a continuous trace in two colours.

6.4

II

USE OF CURSORS Cursors are used extensively in analysis to extract data from graphs. Figures 6.8 and 6.9 illustrate the use of cursors to identify two points in the data, as may be done when a range of data is extracted. The panel is shown in Fig. 6.8. Note that the cursor display has been turned on (by popping up and selecting Visible items Æ Cursor legend) and two cursors, Cursors 1 and 2 are placed (by popping up on the cursor legend). The various icons in the cursor panel can be set through the use of the Operate tool. The cursors have been locked to the charts, as is indicated by the closed lock icon.

Fig. 6.8 Panel with Two Cursors

60

Virtual Instrumentation Using LabVIEW

In the diagram shown in Fig. 6.9 there are quite a few interesting points which may be of interest to the reader, and will give some idea as to how the cursors really work. A sine wave with Gaussian noise is simulated using the express

Fig. 6.9

VIs. The output is displayed in a waveform graph. The array is extracted and its size is determined. Now two cursors are placed at 1/3 and 2/3 of the range. This is done by finding the length of the data array and then placing the cursors at 1/3 and 2/3 of it. This ensures that the cursors are placed neatly for future manipulation by the user. If this is not done both the cursors will overlap and start at the left end of the trace. Note the selection of cursors through Active Cursor attributes. Whenever a cursor is selected, the subsequent properties apply to it, till such time that another cursor is selected. The actual movement of the cursors and the extraction of their indices is done through a while loop where the cursor indices are read out. The data dependency ensures that the while loop operates only after the rest of the code has executed. Almost, all properties of cursors can be accessed and modified through the Property Nodes, and many of them are also available through the front panel. Newer versions of LabVIEW support the use of multiple Y-axes, and the use of this feature permits the user to conveniently view data with vastly dissimilar scaling and/or offsets without having to manually manipulate the data.

6.5

II When data is not equally spaced on the X-axis, or the axis values do not progress monotonically then the user has to take recourse to the X-Y graph. This operates in a manner akin to that for the waveform graph except that the display is an X-Y graph. Naturally, this requires the use of both an X-array and a Y-array. These have to be available for each trace in case there are multiple traces in the display. Figure 6.10 shows the Lissajous figures from sine waves with a frequency ratio

Graphs and Charts

61

of 1:3 and a phase difference of 90°. In the block diagram shown in Fig. 6.10 bundle of the two arrays is assembled and wired to the X-Y plot. As may be expected for multiple plots, the clusters for individual traces are assembled into arrays and wired to the X-Y plot, as is shown in Fig. 6.11.

Fig. 6.10

Fig. 6.11

X-Y Graph

XY-Graph with Multiple Traces

The use of clusters and arrays for graphs is emphasised in the above discussion. In many respects these are dictated by convenience as well as by the limitation that an array of arrays is not permitted. The alternation between arrays and clusters appears to The use of arrays and clusters in various graph forms can be summarised as under:

62

Virtual Instrumentation Using LabVIEW

Waveform Chart Single Trace: Wire the scalar to the waveform chart. Arrays can also be used for this purpose. The data is stored internally in an array whose length is controlled by History Length. This is the only graph type which supports scalar input. Multiple Trace: Bundle the data together into a cluster prior to wiring to the waveform chart.

Waveform Graph Single Trace (X0 = 0, D = 1): to the waveform graph.

Functions like waveform chart; wire the array

Multiple Traces (X0 = 0, D = 1): Assemble data in a two-dimensional array (one row per trace) and wire it to the waveform graph. For columnar data, the Transpose Array option can be selected instead of transposing the array. Single Trace: Bundle actual value of X0, D along with data array(s) into a cluster and connect to the waveform graph to get a properly scaled display. multiple Traces (X0, D same for all): Make a two-dimensional array with data in rows, and then assemble a cluster of X0, D and Data Array and connect it to the waveform chart. Multiple Traces (X0, D not same for all): Assemble clusters for individual traces as in the case of Multiple Trace (X0 = 0, D = 1) and then put them together in an array (an array of clusters is permitted in LabVIEW).

X-Y Graph Single Trace: Put the X and Y-arrays in a two-dimensional array (row-wise) and connect it to the X-Y graph. Multiple Traces: Assemble the data for each trace as above, bundle the various traces into a cluster and then connect to the X-Y graph.

7 STATE MACHINES INTRODUCTION There is no concept of LabVIEW programming surrounded by more mystery and hype than that of State Machines. As a result, many beginners are scared to try and understand this concept, and use it in their code. In reality, a state machine is very simple and logical to understand and implement. This concept is not unique to LabVIEW programming but is common to all control applications. State machines can be exploited to develop very complex systems with very little effort and in a remarkably elegant and simple code. The highly modular code inherent in LabVIEW makes it ideally suited to programming a state machine. Conceptually, it is easy to understand. Any application can be considered to comprise of a number of defined states and to move from one state to another state as it progresses. For example, a simple

7.1

II

test and analysis system may comprise of operations retrieval and data analysis. One can expect the user to progress through these stages sequentially. However, he may wish to start at a state which is not at the top. For example, he may be interested in analysing data which is already stored in the system. Each of states. A state machine will allow the user to execute any of these states, and also permit any state to exit to a different state when required. Through the state machine, each state can be developed independent of the other states, and then linked together through the state machine. Additional states, e.g., for handling errors can also be added which need not necessarily be accessible (or of direct interest) to the user.

WHAT IS A STATE MACHINE? In its simplest form, a state machine comprises of a while loop, with a shift register and a case structure (Fig. 7.1). The operation can now be easily understood. The code starts by initialising the shift register to the initial state of the system (from outside the while loop) which is entered into by the case

64

Virtual Instrumentation Using LabVIEW

structure. At the end of the execution of the code corresponding to this state, the case structure then sends the next state to the shift register. Then in the following iteration of the while loop, this state is executed. This continues until the While loop is terminated by the case structure. Note that the code is no longer constrained to operate in a linear fashion, but can progress from state to state in a non-linear manner. What is required is that the various states of the system must be clearly defined. The next state can also be decided by the previous state, depending on the logic in it. In the above example, a user acquiring data can easily select options to acquire more data, change the configuration, save the data, analyse the data, or stop the program and output the code of the appropriate case to the shift register. Coding all these possibilities normally would be very difficult, if not impossible. The labyrinth of the various possible transitions will render the code a nightmare to develop, understand and debug. Developing and debugging such a code is a Herculean task. Add similar sets of possibilities to other options and the complexity of the task can be well imagined.

Fig. 7.1 Components of a State Machine

However, using the state machine, such a code can be easily developed and debugged. The code for each state becomes an independent VI. These can be developed and tested individually and subsequently combined in a state machine. There is nothing to stop any particular state from spawning a state machine of its own. The possibilities are mind-boggling.

7.2

II

A SIMPLE STATE MACHINE A simple state machine is a menu selector, which always returns to the main menu. For this purpose, the use of the shift register is not required. This can be

State Machines

65

implemented using the case structure. The panel is shown in Fig. 7.2. The diagram is shown in Figs 7.3 and 7.4. The heart of the code is the cluster containing the buttons. The reason why a cluster is preferred is that an array cannot have individually labelled buttons. At best, free labels have to be used. The cluster is converted into an array. This array is searched for a button having a value True. The Search 1D Array gives the index of this button which is used to select the case. If no button is pressed then a value of –1 is returned. The case corresponding to –1 contains no code. The dialog box for configure is representative of the code for that case. For exit, the Boolean used to control the loop is inverted before exiting the case structure. A small delay prevents the code from hogging too much of Fig. 7.2 Panel of a simple state machine the resource. Note that the selector is very simple, and does not have the facility to move from one condition to the next. Every condition returns the user to the uppermost level of the menu where the buttons should be in one of the latch states. This code can also be implemented using the Event Structure construct which is now discussed.

7.3

II

EVENT STRUCTURES The case-structure approach discussed above used polled input–output, i.e., the code continues to loop while waiting for a button to be pressed. The same can be implemented through an interrupt-driven route using event structures (Fig. 7.4). In this, until a front-panel event occurs, the system waits without using as much of the system resources. The use of the event structure for the selection is shown in Fig. 7.4. One difference in the panel as compared to Figs 7.3 and 7.4 is that the buttons are not placed in a cluster. The other events are similarly coded, except that for the operation of the Exit button, the Boolean is inverted (output is False to terminate the loop). In normal applications, the system is in any case idling, when in the topmost or controlling state, so repeated looping does not really matter. The main advantages of using an event-structure approach lies in the possibility of assigning processors in a multiprocessor system, and also for multi-node systems (as in RT/FPGA applications) the interprocess

66

Virtual Instrumentation Using LabVIEW

communications only occur when required. Thus, in an RT application, the master loop can easily be moved from the RT chassis to the host.

Fig. 7.3 Diagram of a simple state machine

Fig. 7.4 Simple state machine with event structures

State Machines

7.4

II

67

THE FULL STATE MACHINE The above discussion provides for simple selection of the various states of operation but all driven from the top level. However, it does not permit automatic transfer of control from one state to another. This is achieved by adding the shift register to the code and moving the selector to the No Button Pressed case (–1), as is shown in Fig. 7.5. The code ‘idles’ in the selection mode (no button pressed) and as soon as a button is pressed it moves to that state in the next iteration of the loop. The user now has the option of sending the next selection from his code, which is what is executed in the next loop. If the control is to be returned to the top level, –1 should be returned to the shift register. In the example, the code is in the Acquire mode. From here, the user has the option of either proceeding to Analyse (TRUE) or returning to the top level menu (FALSE) through the two-button dialog. Depending on the state of the button, the appropriate values (2 or –1) are returned to the shift register. This illustrates the operation of the full state machine.

Fig. 7.5 A full state machine

68

7.5

Virtual Instrumentation Using LabVIEW

II

NOTES AND COMMENTS One has to be very careful in the indexing of various cases. Any careless editing or modification can easily change the indices. Some users prefer to use string constants for the case structure. This permits easy addition of additional cases, but the No Button Pressed case has to contain a look-up table to output the appropriate strings. Also, the strings must be exactly matched, as any mistake in spaces or case can lead to problems. The ‘labelling’ approach is becoming increasingly popular in the Implementation of state machines. The illustrations are very simple but in practice, the cases or events will comprise of whole VIs. The outputs of these VIs may contain information about the subsequent blocks of code to be executed. In addition, there may be data to be transferred from one state to another. Such data may be stored in shift registers, global variables or local variables. Storage in shift registers (different from the shift register assigned for the state machine operation) has obvious advantages, but this has to be balanced against two irritants. Firstly, a cluster has to be designed to take in various parameters which may be sent in by various cases. Secondly, in a case structure the cluster must be sent out from all the cases. The latter is not usually a major problem since in most cases, the cluster is just ‘passed through’ while in others (where parameters are to be sent) one or more elements are substituted. The use of the full state machine also provides a method of handling various error conditions. For this, one or more cases are defined for the error handler and then the control can be programmatically transferred to this code in case of errors. This case may not appear in the cluster used to control the operation, since it will only be called from another case and not the main menu. Keeping these in mind, the use of state machines in complex algorithms can be easily appreciated. The use of state machines also makes the development and testing of complex code easy, since the blocks are effectively decoupled.

8 FILE INPUT/OUTPUT INTRODUCTION Most instrumentation applications require storage of

8.1

II

FILE FORMATS

ASCII Text-Format Files ASCII text-format files store data in the ASCII format. This is the simplest format and since most software packages can retrieve data from an ASCII text file, naturally it becomes the most commonly used format, especially in instrumentation applications. Needless to say, one has to convert all data to ASCII strings before saving data. The major disadvantage of this format is that the text files tend to be larger than the other formats. At one time this was a major handicap, but with the ever-increasing capacity of storage media, this is no longer a major handicap. Another disadvantage was speed, since the conversion of binary data (internal format) to ASCII, and the transfer of the larger volume of data to the disk were both slow. This is no longer so with modern systems.

70

Virtual Instrumentation Using LabVIEW

Binary-Format Files These files store data in binary form and look like an image of the data stored in the computer’s memory. These files cannot be read by word processors. Also, it is impossible to retrieve data from these files without detailed knowledge of the file’s format. The main advantage of these files is that they are much smaller than text files and reading and writing operations can be done with little data conversion. Binary file format is useful in applications requiring writing and reading of large chunks of data due to its size advantage. However, with the increasing availability of large storage devices at reasonable cost, this advantage is being progressively lost. Also, binary format is often system (or processor) dependent. LabVIEW Measurement Files LabVIEW measurement files are special files which are either text-based files (.lvm) or binary files (.tdm or .tdms). Generally, these files are written and read using Express VIs. Here data is stored as a sequence of records of a single arbitrary data type specified during creation of the file. The data is indexed in terms of these records. Each record in a measurement file must have the same data types associated with it. One interesting feature of these files is that timestamps are also included with each record. Also, LabVIEW allows random read access to the binary versions of these files. What to Use and When? Text and binary files are both byte stream files, i.e., they store data as a sequence of characters or bytes. Text files are the easiest format to use and to share. Almost any computer can read from or write to a text file. When one is interested in retrieving the data using a word processor or spreadsheet, text files are the best. However, text files take up more space than binary files if the data is not originally in text form, like in the case of graph or chart data. This is because ASCII representation of data usually is larger than the data itself. For example, a 32-bit integer occupies 4-bytes in binary, but may occupy more than double the space in ASCII. Furthermore, it is difficult to randomly access numeric data in text files. Storing of binary data, such as an integer, takes a fixed number of bytes on disk. Hence binary files are useful in saving and accessing numeric data from a file, and also in random access of data from a file. Binary files are the most compact and fastest format for storing data. However, binary files are machine

File Input/Output

71

readable only. They are the most efficient since for numeric data the files contain a byte-by-byte image of the data stored in the memory. Measurement files may be used only in applications where LabVIEW is used to access and manipulate data. Measurement files when used require little manipulation, thus making access faster during both reading and writing. Data retrieval is simplified since the original blocks of data can be read back as a record without having to read all records that precede it in the file. Random access is thus fast and easy with Measurement files. However, measurement file formats are peculiar to LabVIEW so files are not interchangeable with other applications, and converters have to be written to make them available. Nowadays, text files (mostly Tab delimited in a spreadsheet format) are almost universally used. The binary format (regular binary or measurement) is used when there are transfer rate bottlenecks. Also, when working with Flash media as in cRIO the storage space is limited and binary files may be preferred. For massive files with indexing, measurement files (binary formats) may be the format of choice.

8.2

II

FILE I/O FUNCTIONS The three basic file input and output (I/O) operations to store and retrieve data from files are

LabVIEW provides several file I/O functions to write or read. Most applications require only writing or reading of one of the following data types:

most convenient format for these is the spreadsheet file format (tab delimited ASCII). This is the most popular format for data access and an extensive library of VIs is available to support it, both as files records and as strings.

functions comprise high-level and intermediate file function as well as path function and other special file VIs. The high-level VIs are placed at the top row of the palette, intermediate VIs at the second and third rows and the sub-palette for the advanced VIs on the rightmost end of the last row. Path and other special file functions are placed below the intermediate VIs.

72

Virtual Instrumentation Using LabVIEW

The first two polymorphic functions VIs for file I/O can be used for writing formats. The other two high-level VIs can be used to write and read binary and measurement files. For most applications, the high-level VIs are all that are required. Occasionally one might like to use the Intermediate VIs. The commonly used VIs are briefly discussed below.

Fig. 8.1 File I/O palette

Write to Spreadsheet File As most data is stored (and read) in a spreadsheet format (line-wise tab delimited ASCII) readymade VIs to handle these are available. The function Write to Spreadsheet File (Fig. 8.2) first converts a two-dimensional or a one-dimensional array of numbers (by default real numbers of format x.3f) to a text string separated by tab characters for elements in the same row. This is a polymorphic VI which can choose string, integer or double as inputs. The figure shows the VI for the double instance. The rows are separated by EOLs. The string is then written to the file. This may be a new file or appended to an existing file depending on the status of the Boolean Append to File. The facility to transpose data is also available. This is often required to display data collected from two or more channels using DAQ boards, since the graphs and charts require data row-wise whereas the data from multiple channels are stored in the array columnwise. However, it is more common to store data column wise since then the data can be more easily handled outside LabVIEW).

File Input/Output

73

Using the format input one can specify how to convert the numbers to characters. The default is %.3f, meaning that the decimal numbers will have a precision of three digits after the decimal point. Various formats are possible using the format specifier syntax for strings. The output, new file path can be wired to all subsequent writes to the same file as a file handle. Once writing of characters is over, VI automatically closes the file.

Fig. 8.2

Write to Spreadsheet File Function

Read From Spreadsheet File Data stored in a spreadsheet file can be read using the Read from Spreadsheet File VI (Fig. 8.3). When placed on the diagram the instance (double, integer or string) of this VI can be selected using a pull down menu. One can specify the number of rows to be read from the file. If this input is left open, all rows of the file are read. This VI also allows a delimiter to be specified, which may be the character or string of characters, such as tabs, commas, and so on, to use to delimit fields in the spreadsheet file. The default delimiter used is Tab. The all rows output stands for the data read from the file, while first row output is the first row of the all rows array. This output may be used when you want to read one row into a one-dimensional array.

Fig. 8.3

74

Virtual Instrumentation Using LabVIEW

Write to Text File The Write to Text File function intermediate VI (Fig. 8.4) writes a string of characters or an array of strings as lines to a file. If path to the file is not given the VI would open a file dialog. Appending to an existing file can be done by setting the file position to the end of the file by using the Set File Position function. Similarly, file position needs to be set appropriately for performing random access file reads or writes.

Fig. 8.4 Write to Text File Function

Read from Text File The Read from Text File intermediate VI (Fig. 8.5) reads a specified number of characters or lines from a byte stream file. Count input is the maximum number of characters or lines the function reads. In the default mode, count specifies the number of characters to be read. By right-clicking on the function count could be changed to specify the number of lines. If count is < 0, the function reads the entire file.

Fig. 8.5

Write to Binary File The Write to Binary File function (Fig. 8.6) writes binary data to a new file, appends data to an existing file, or replaces the contents of a file. The input data can be of any type. The byte order (big-endian, little-endian, etc).can also be specified for integers, default being big-endian.

File Input/Output

75

Fig. 8.6

Read from Binary File The Read from Binary File function (Fig. 8.7) reads binary data from a file and returns it in data. How the data is read depends on the format of the specified file. The data type input sets the type of data the function uses to read from the binary file.

Fig. 8.7

File I/O for Writing and Reading Waveforms With the increasing use of waveform data type, a set of VIs for supporting this data type have now become available (Fig. 8.8). These are used in a fashion akin

Fig. 8.8 Waveform File VIs

76

Virtual Instrumentation Using LabVIEW

to that for spreadsheet access, and are self-explanatory. With distributed controls waveform I/O is very handy for data transfer across nodes. Waveform file I/O VIs can be accessed through the Waveform File I/O sub-palette on the Waveform Palette. The VIs available for the purpose are Write Waveforms To File, Read Waveform From File, and Export Waveforms to Spreadsheet File.

8.3

II

PATH FUNCTIONS Path management is a critical part of practical file I/O operations. Even through paths are very similar to strings they are handled internally in a different manner, and VIs to interconvert paths and strings are available. The user wants to write (as well as access) his files in a specified directory. Sometimes this path may be an absolute path in which case the path management functions are not required. However, more often than not, the path is set relative to the place from which the VI is run. For example, data may be stored in a subdirectory data under the current path of the VI. For this path management functions are critical. Most of the work can be done with three functions, (Get) Current VIs Path, Strip Path, and Build Path. These are now discussed.

Current VIs Path This VI is the starting point for all relative path operations. As is evident from Fig. 8.9, the VI simply provides the path of the current (calling) VI. LabVIEW has several functions for file path manipulations, such as Build path, Strip Path.

Fig. 8.9 Current VIs path

Strip Path

a path and the stripped path that leads to that component. This if called after Current VIs Path function gives the relative path to the current VI. This can be used as a starting point to define the relative path of the VI.

Fig. 8.10

Strip path function

File Input/Output

77

Build Path The Build Path (or a relative path) to an existing path. This is useful to add a desired filename, etc., to the default directory.

Fig. 8.11 Build path function

8.4

II

SAMPLE VI TO DEMONSTRATE FILE WRITE AND READ Simple VIs can be cascaded to get fairly complicated file I/O operations. During the write operation, the character is used to separate each row of the data file. The data is subsequently accessed taking advantage of the lines to read parameter in conjunction with the Start at Read Offset and Mark after Read parameters. Each line after it is read gives the offset in the file through Mark after Read, which is then used to set the Start at Read Offset of the next read operation. The fact that the file is repeatedly opened and closed for both read and write is irrelevant since every operating system buffers the file I/O and therefore will take care of this. The examples assume that the data is in the following format: Line 1 Header (no carriage return, line feed or end of line allowed) Line 2 Date and time separated by a tab Line 3 Experimental parameters Lines 4 onwards Data in two (or more) columns

entered through the string control (or may be generated internally), while the date and time strings are obtained using the in-built function. The first two lines of the input are assembled using the concatenate strings function. Note the use of the EOL character at the end of the first line, and tab to separate the date and time. A second EOL character is not required after the date/time string as it is automatically generated by the Build Array function used before writing. All the lines in the example are written using the Write to Spreadsheet File function. The string data containing the header and the date and time stamp are Build Array function. Since no file path

78

Virtual Instrumentation Using LabVIEW

is given, LabVIEW automatically opens a file dialog box for giving the file name, etc.

Fig. 8.12

The Append to File input is left unwired, and is hence assumed as False, indicating that a new file is to be created. The Write to Spreadsheet File function is again called twice. Both times the file path is provided (and cascaded) from the initial write operation, and Append is made True to add to the file rather

numbers created by a for loop) is transposed into columns added likewise. The transposition could also be done by setting Transpose to True, in the Write to Spreadsheet file function. Note the cascading of the File Path and the state of Append. file. The first two lines of header and date and time are read back by the Read from Spreadsheet File function with the string instance, reading one line at a time. Note that the Mark after Read is cascaded to the Start at Read Offset

File Input/Output

79

of the next call to start the read operation from where the previous operation left. As in the earlier example, LabVIEW opens up the file dialog to obtain file path, which is used by the subsequent read functions. The parameters, stored in a single line, are read through the second call of Read from Spreadsheet File, while the last read operation gets the remaining (columnar) data.

Fig. 8.13

8.5

II

GENERATING FILENAMES AUTOMATICALLY

function which may be used for this purpose, Check if File or Folder Exists. vi. As the name implies, this function checks whether a file or folder exists on disk at a specified path. The Boolean output file or folder exits could be used as a conditional input to create a folder/file.

Fig. 8.14

It is often required to generate filenames sequentially. The VI shown in AutoName

80

Virtual Instrumentation Using LabVIEW

File/Directory Info gives a file size of zero for the named file. It can be easily modified through code for rejecting filenames which contain data. AutoName generates file names in the format mmddnn where nn starts

Fig. 8.15

Fig. 8.16

File Input/Output

SUMMARY

81

9 STRING HANDLING INTRODUCTION A string is a sequence of displayable and nondisplayable ASCII characters. The major advantage of strings is that they provide a platform-independent format for exchanging information and data. Some of the common applications of strings are

programmable instruments

The scrollbar option is dimmed by default and becomes operational only when the string control or indicator is resized. LabVIEW allows strings to be displayed in one of the four ways, i.e. printable characters only (Normal display), printable characters with backslash codes for all non-printable characters (‘\’ codes display), password display where each of the characters is indicated by an asterix ‘*’ (Password display), asterisk ‘*’, or the ASCII value of each character in hexadecimal (Hex display). By default, LabVIEW chooses the Normal display. This can be changed to any of the other three types by popping up on the front-panel string control or indicator and choosing the required option. A list of the backslash codes is shown in Table 9.1.

In instrumentation, strings are the basis for most communications between the computer and the instrument. Commands are invariably sent to the instrument in the form of strings, which in turn returns the data which again is almost always in the form of a string. Thus, for any meaningful dialogue with an instrument, a Table 9.1 List of Backslash Codes good understanding of string manipulation is absolutely Code LabVIEW Interpretation necessary. \00 - \FFHexadecimal value of an 8-bit character, in String controls and indicators are placed in the upper case String and Path sub-palette of LabVIEW. The text in \b Backspace (ASCII BS, equivalent to \08) a string control is typed-in using the Operating tool or \f Formfeed (ASCII FF, equivalent to \0C) the Labeling tool. The Positioning tool can be used to \n Linefeed (ASCII LF, equivalent to \0A) resize the string control or indicator. If the space on \r Carriage return(ASCII CR, equivalent to \0D) the front panel is limited, one can use the scroll bar \t Tab (ASCII HT, equivalent to \09) to minimise the space occupied by a string control or indicator. The scroll bar can be activated by popping \s Space (equivalent to \20) \\ Backslash (ASCII \, equivalent to \5C) up and choosing Scrollbar option under Visible item.

String Handling

Note that while using backslash codes, upper case letters must be used for hexadecimal characters and

9.1

II

83

lower case letters for special characters.

STRING FUNCTIONS LabVIEW provides numerous string functions to cater to almost all types of string manipulations. These functions are quite useful in building as well as parsing strings to suit the application in mind. As strings are used very extensively in all interactions with other instruments, as well as for file I/O (in ASCII files), the library available is very extensive. This is a boon for the technologist since traditionally scientific computing has tended to ignore the area of strings. FORTRAN, the mother of scientific computing, until very recently had almost no string manipulation capabilities and even now these are quite rudimentary. Some string handling functions available in LabVIEW are now discussed. String Length: This function (Fig. 9.1) gives the number of characters (bytes) in the input string. Being a polymorphic function, the length output has the same structure as the input.

Fig. 9.1

String Length function

Concatenate Strings: The Concatenate Strings function (Fig. 9.2) is useful in concatenating input strings into a single output string. In addition to simple strings one-dimensional arrays of strings can also be wired as inputs; the output will be a single string containing a concatenation of all the strings in the order they are connected, top to bottom, left to right. This function can be used to concatenate strings to be written as text in files. In addition to the text or characters indicating the application, string constants such as tab, line feed, end of line, etc. can also be appended to the characters as required by the application. This function is used very often to assemble commands for instruments. In these cases (especially in serial interfacing) the string often has to be terminated with an appropriate character or characters. Similarly, for preparing data for writing

Fig. 9.2 Concatenate Strings function

84

Virtual Instrumentation Using LabVIEW

to a file < TAB > is used as a separator between items, and a terminator (an < EOL > is preferred to < CR > and/or < LF >) since this makes the code platform independent. Match Pattern: This function (Fig. 9.3) searches for a string pattern (regular expression) in the input string beginning at offset, and if it finds a match, it splits the string into three substrings, viz., before-substring, match-substring and after-substring. If the Function does not find the regular expression string pattern, match-substring is empty, before-substring will have the entire string, after-substring is empty, and offset past match is –1. The offset past match output is useful as an offset input for another match pattern search.

Fig. 9.3 Match Pattern function

String Subset: The String Subset function (Fig. 9.4) returns the substring of the input string beginning at offset and containing number of characters as specified by length input. This function is useful to remove unwanted header/ data in a string.

Fig. 9.4 String Subset function

Get Date/Time String: The Get Date/Time String function (Fig. 9.5) is available on the Timing & Dialog palette. It converts a time stamp value or a numeric value to a date and time string in the time zone configured for the computer.

Fig. 9.5 Get Date/Time String (timing dialog palette)

String Handling

9.2

II

85

LabVIEW STRING FORMATS Several string functions (and a few file I/O functions) require the use of an input called Format String, which specifies the format used in the input string, or the format to be used in the string output. The format string input is useful in producing or handling string data in one of the standard formats. The usual formats are: automatic formatting, decimal, floating-point, scientific/engineering, SI notation, hexadecimal, octal, binary, string, etc. A detailed description of all these formats is beyond the scope of this book. Format specifier syntax for the above can be obtained through the online help on LabVIEW. The syntax is almost identical to what is used in C. Functions which produce string as an output, such as Format into String, Format Value, Array to Spreadsheet String can accept elaborate format specifier syntax to take care of width, precision, significant digits, etc. in addition to the conversion code. However, for most applications the following syntax would suffice. % [#] [Width] [.Precision] Conversion code

where the square brackets [ ] enclose the optional parameters. Width is a number greater than zero and .Precision is a number greater than or equal to zero. Precision when used with floating-point numbers specifies the number of digits to the right of the decimal point and when used with string parameters, width specifies the exact width of the scanned field. The # symbol when used removes trailing zeros. The essential elements of the format syntax are the symbol % indicating the beginning of the syntax, and the conversion code, specified using a character. The conversion codes for integers and floating-point numbers are indicated as follows. Table 9.2 Conversion Codes for Floating Point Numbers and Integers Conversion Codes for Floating-point numbers Code f e g p

Floating-point (FP) format FP number with fractional format (eg. 15.234) FP number in scientific notation (eg. 1.523E1) Uses f or e depending on the exponent of the number FP number in SI notation

Conversion Codes for Integers Code

Integer type

x

Hexadecimal integer

o

Octal integer

b

Binary integer

d u

Signed decimal integer Unsigned decimal integer

86

Virtual Instrumentation Using LabVIEW

LabVIEW string functions that produce an output string are given below. All these functions can accept elaborate format specifier syntax. Format Value: The Format Value function (Fig. 9.6) converts a number connected at the value input into a regular string according to the format specified in format string and appends this to the output string. This is a polymorphic function. In case no value is connected to the function LabVIEW outputs ‘0’ as the output string.

Fig. 9.6 Format value function

Format into String: This function (Fig. 9.7) formats string, numeric, path or Boolean data as text. This function is useful to format data as text and write the text to a file. Several inputs can be connected as inputs from 0 to n, which will be converted as text in the same order. For multiple inputs the format string input should have as many specifiers as the inputs.

Fig. 9.7 Format into string function

Array to Spreadsheet String: This function (Fig. 9.8) converts an array of any dimension to a table in string form, containing tabs separating column elements,

Fig. 9.8 Array to spreadsheet string function

String Handling

87

an EOL character separating rows, and for arrays of three or more dimensions, headers separating pages. Some other functions in the file I/O palette, viz. Format Into File and Write To Spreadsheet File, also use format specifier to define the format of the text to be written to the file.

9.3

II

EXAMPLES A few examples illustrating the use of string functions are given below. The first one in Fig. 9.9 uses the Format Value function to convert an integer into an output string in an unsigned decimal integer format using %u. In the second example (Fig. 9.10) the same integer is formatted to give a hexagonal string using %x.

Fig. 9.9 Converting an integer string to unsigned integer string using format string

Fig. 9.10 Converting an integer string into a hexadecimal string using format string

9.4

II

SOME MORE FUNCTIONS The use of Format Into String function is illustrated using the following three examples. The first one in Fig. 9.11 specifies an output string having a floating-

88

Virtual Instrumentation Using LabVIEW

point fractional format with four decimal places. The next two examples in figures 9.12 and 9.13 illustrate the use of this polymorphic function to convert a decimal, an integer and a string data at its input with and without ‘,’ between the output strings. In the latter example, in place of the comma any string (other than what is used in the format specifier syntax) may be used. Since LabVIEW does not recognize these as a format code, it returns the character(s) literally at the output.

Fig. 9.11 Formatting a real number using format into string (continuous)

Fig. 9.12 Formatting multiple quantities using format into string (continuous)

Fig. 9.13 Formatting multiple quantities using format into string with separator

String Handling

89

The example in Fig. 9.14 illustrates the use of Array To Spreadsheet String function. The output string converts the input two-dimensional array to a table of strings, containing tabs separating column elements and an EOL character separating rows.

Fig. 9.14 Array to spreadsheet string conversion

LabVIEW functions that scan a string using a specified format string input and producing appropriate numbers are explained below. For these functions LabVIEW uses the following simplified syntax. % [Width] Conversion Code

where Width is the width of the string to be scanned for conversion. These functions give a default output in case of an empty input string. Detailed descriptions of these scan string functions are given below. Scan From String: This function (Fig. 9.15) scans the input string and converts the string according to format string specified. An initial scan position can be defined, which is ‘0’ by default. This function is useful when the exact format of the input text is known. Multiple values can be converted simultaneously by resizing the function and specifying appropriate format strings.

Fig. 9.15

Scan from string function

Scan Value: The Scan Value function (Fig. 9.16) converts characters at the beginning of string to the data type represented by default, according to the

90

Virtual Instrumentation Using LabVIEW

conversion codes in format string. It returns the converted number in value and the remainder of string after the match in output string. If no data type is specified, the default is taken to be a double-precision, floating-point value of 0.

Fig. 9.16 Scan Value function

Spreadsheet String To Array: This function (Fig. 9.17) is used to convert the spreadsheet string to an array of the dimension and representation specified by array type. It can be used for arrays of strings as well as arrays of numbers.

Fig. 9.17 Spreadsheet String to Array conversion

Fract/Exp String To Number: This function interprets the characters 0 through 9, plus, minus, e, E, and the decimal point in string starting at offset as a floating-point number in engineering notation, exponential, or fractional format and returns it in number. Offset of the first character is taken to be 0.

Fig. 9.18

Fract/Exp String to Number conversion

A few examples of functions that scan a string to produce numbers etc. are given below. The first example in Fig. 9.19 shows how multiple values present in the input string are converted to values using format string. The format

String Handling

91

‘%5f%2d’ specifies the first 5 characters from the initial scan location to be a floating-point number, and the next 2 characters as a signed decimal number. In our example the remaining string, which was not converted is also shown.

Fig. 9.19

The next example in Fig. 9.20 shows the conversion of a fractional/exponential number to a real number. The offset of 5 in the example ensures that LabVIEW starts conversion of the string past the text ‘CURVE’.

Fig. 9.20

9.5

II

Fractional/exponential number to real-number conversion

PARSING OF STRINGS One of the important uses of string functions is to extract numbers and other data from the given string. Parsing using a single string function was illustrated in Fig. 9.20. By judiciously choosing a combination of functions such as String Length, String Subset, Match Pattern and Scan from String, almost any string parsing is possible. These functions are widely used for parsing, especially in instrument I/O.

92

Virtual Instrumentation Using LabVIEW

A parsing example is illustrated in Fig. 9.21, where the date/time string obtained from the Format Date/Time String function is parsed to get day, month, year, weekday and time information. Note the use of date/time format to get the date as dd/mm/yyyy and time as hh:mm:ss. All parameters of the date/time format start with a ‘%’ symbol followed by a character to specify the format. Any other string is ignored by LabVIEW and literally reproduced at the date/string output. The example illustrates the use of characters such as ‘/’, ‘ ‘, and ‘,’ as separators between the various outputs. For more details about date/time format the reader may refer to LabVIEW online help.

Fig. 9.21

Parsing of Date/Time Array to get components

SUMMARY

simple text messages, sending and receiving data/commands to programmable dialog boxes. display, or Hex display. conversion codes.

String Handling

building strings.

By combining different string functions, numbers and other data can be extracted from input strings.

93

10 BASICS OF DATA ACQUISITION INTRODUCTION Many interfacing applications require the acquisition or generation of signals from the interfaced system. The connection could be through a digital interconnect protocol—GPIB, RS232/485, USB or IEEE1394, or (more commonly) through the use of analog and digital lines. Analog and digital interfacing thus forms a very important and vital application in the area of instrumentation. In this chapter, we will examine some basic aspects of interfacing, purely from the practical (or user’s) perspective. There can be essentially two kinds of applications— digital and analog. Digital signals are handled by dataacquisition hardware almost universally belonging to

10.1

II

the Transistor–Transistor Logic (TTL) family. The most common front-end is Low-power Schottky TTL (LSTTL). Some hardware primarily meant for industrial usage uses other voltages, here the de-facto standard of 24 V is quite common. In addition to analog and digital I/O, any multifunction Data Acquisition (DAQ) hardware will also have an assortment of counters, timers, triggers, etc. All but the most rudimentary plug-in boards support the use of Interrupts (IRQ) and Direct Memory Access (DMA) operations. In modern-day systems, the installation of the boards and assignment of IRQ and DMA channels is automated and is transparent to the user.

CLASSIFICATION OF SIGNALS The nature of the signals to be acquired and analysed dictates the degree of sophistication required in the acquisition system. One can broadly classify signals and their requirements as follows:

Basics of Data Acquisition

95

Analog Signals DC Signals: These are signals which do not vary at all or vary slowly with time. Such signals are quite common in the process industry. The data-handling hardware does not need to be sophisticated since speed is not an issue. Almost any data-acquisition system (hardware and software) will fit the bill. Waveform Shape (Time Domain): These are essentially ac signals and require to be handled with precise timing. DAQ hardware with on-board buffers, as well as efficient data-transfer capabilities is required for handling these signals. The computers involved do not need to be particularly fast since they are not called upon to do a lot of number crunching. Waveform Content (Frequency Domain): Even though the signal itself is of the same complexity and speed as the time domain signals, the computer system is called upon to do heavy computation in calculating the Fourier transforms, etc. Here, the computer system should also be powerful along with good data acquisition hardware. This is seldom an issue with modern computer systems. Digital Signals Level Signals: These may comprise of digital signal levels to be sensed or generated. Commonly sensed signals are states of interlocks, valves, etc., and generated signals are often used to switch electrical systems on or off. Again, simple digital I/O capability is all that is required for processing these signals. Pulse and Wave-train Signals: Such signals require precise timing and therefore good on-board counters and timers are necessary. Most DAQ hardware these days is capable of catering to all of these requirements. However, all but the simplest of signals require (or at least should preferably be supported by) good interface characteristics, viz., buffers, DMAs and interrupt-driven transfers. Modern computers usually have sufficient ‘muscle’ to cope with the analysis requirements. The user must ensure that sufficient RAM is available for the task at hand, since the moment the system starts using the disk as a buffer, the throughput slows down dramatically. However, older systems using P-II and P-III can also be used, but with plenty of RAM.

10.2

II The basic problems in connecting real-world signals to any computer system are the following:

96

Virtual Instrumentation Using LabVIEW

(i) Real-World Events are Random: While a computer prefers to work in a totally systematic manner with events occurring at precisely defined intervals, real-world events tend to be random in nature, both in terms of time and sequence. Thus, a mechanism is required to handle these random events. The use of IRQs provides this tool. The computer is not obliged to go and check for data ever so often. The hardware signals that it has some data to send, which the user software then goes and collects. The mechanism of DMA permits fast transfer of blocks of data between the computer and the DAQ system. (ii) Real-World Signals are Noisy: In reality, all real signals are noisy. With digital signals, the specifications themselves provide a good amount of noise immunity so mistaking a 0 for a 1 is not likely. On the other hand, analog signals are continuous and any noise has to be dealt with by the user hardware and software. Since digital transitions are abrupt and noise is not an issue, almost all hardwire provides for separation of the grounds for digital and analog signals, often referred to as the digital ground and analog (sometimes called the signal) ground. Proper consideration has to be given to keep the two separate, otherwise there can be problems. One common mistake made even by experienced users is not to separate the safety ground from the signal grounds.

10.3

II

ANALOG INTERFACING Most users are interested in acquiring (and sometimes generating) real-world signals which are mostly analog. Once properly understood, analog signals can be measured and generated in a fairly straightforward manner. However, the user has to have a basic understanding of the principles and their application to his specific needs.

Resolution One basic issue to be decided before choosing hardware is the resolution required. The most commonly used general-purpose data-acquisition hardware has a 12-bit resolution, with 16-bit boards becoming increasingly popular. Fast systems (like oscilloscopes) may have only an 8-bit resolution. 12-bit resolution is adequate for most applications. Almost all general-purpose data-acquisition boards have a range of ±5 V. This for a 12-bit system gives a resolution of 2.44 mV, and in a 16-bit system the resolution becomes 0.1528 mV. In case a preamplifier of gain G is used, the resolution improves by this factor. The resolution of a board with n-bit resolution is Range/2n. Actually, a board with n-bits resolution will have only (2n – 1) intervals. However, in order to align

Basics of Data Acquisition

97

zero exactly in bipolar applications, the range is actually defined from (– 2n–1) counts to (2n–1 – 1) counts, i.e., a 12-bit card with a nominal range of ±5 V will have a true range from – 5.000 V to + 4.998 volts. For an n-bit board with a nominal range of V volts, the resolution can be estimated as follows. Resolution = V/2n The effect of resolution is graphically illustrated in Fig. 10.1. A sine wave signal is digitised with 2-, 4- and 8-bit resolution. The match between the true and digitised value improves dramatically as resolution increases. The 8-bit signal is barely distinguishable from the actual value, since it tracks within 0.4% {1: (28 – 1) = 255}. With 12-, 16- or more bits the results are even better. It should be borne in mind that the digitised value is the highest value available from the system which is less than the true value, therefore it is 0.75 for 2-bit conversion.

Fig. 10.1

2-, 4- and 8-bit resolution

All but the cheapest DAQ hardware has the provision of preamplifiers on board, the gain of which can be set through the user software. For example, the low-cost DAQ hardware from National Instruments comes with four gain

98

Virtual Instrumentation Using LabVIEW

settings, namely, 0.5, 1, 10, and 100 on a basic ±5 V bipolar Analog-to-Digital Converter (ADC). This gives bipolar ranges ±10, ±5, ±0.5 and ±0.05 volts. On the other hand, high-cost boards may provide gains of 0.5, 1, 2, 5, 10, 20, 50 and 100 with the option of both uni-and bipolar operation. In practice, the source signal range is normally not the same as that of the DAQ hardware, and this mismatch leads to some of the range being lost. Unipolar signals into a bipolar board lead to a loss of 1-bit of resolution straightaway. In general, one can expect a loss of about 2–3 bits on the low cost boards and 1–2 bits on the high end boards. It should be noted that the loss may be higher if the maximum signal expected is inadequate for the highest gain setting. Nowadays, low-end 16-bit boards are often cheaper than high-end 12-bit boards and are better value for money. The 4-bits of extra resolution will in most cases more than cover for the loss of better signal matching. For example, a unipolar signal when fed to a bipolar board will immediately lose 1 bit. Then the remaining 3 bits cover another factor of 8 which is better than the loss of precision due to the coarser gain settings. Maximum Conversion Rate Most DAQ hardware uses a successive-approximation analog-to-digital converter which has a constant conversion time. Some high-end hardware with variable resolution uses a sigma-delta converter, which gets slower as the resolution is increased. However, for a given resolution, the conversion time is again constant. The maximum conversion rate available is controlled by various parameters. This is best understood if one examines the internal aspects of a typical dataacquisition board. A signal entering a general-purpose board will proceed through the following: Multiplexer Æ Programmable Gain Amplifier Æ ADC The programmable gain amplifier and the ADC are the expensive components of the system. Therefore, these are normally preceded by a Multiplexer (MUX). This is a switching unit which selects the input to be actually sent to these stages. Some hardware where the multiplexer is slower than the other components may specify two sampling rates—single channel, where the MUX is not used, and multi-channel, where it is used. The Programmable Gain Amplifier (PGA) puts its own limitations on the system. The gain-bandwidth product for an amplifier is specified. Thus, as the gain increases the available bandwidth (or maximum sampling rate) decreases. It should be kept in mind that the PGA bandwidth required will be much more than that of a normal amplifier since for an accuracy of 1-bit (i.e., 1:4095 for 12-bit conversion) the drop in gain has to be limited to a tiny fraction of a dB

Basics of Data Acquisition

99

(0.027dB for 1-bit in 12-bits) and not –3dB (1:2) as is normally the case when rating amplifiers. The ADC requires a sample-and-hold circuit before the actual conversion circuitry. As the name implies, the sample-and-hold circuit samples the incoming data, and holds or locks the level while the conversion actually takes place. Taking into account all these limitations, the actual measurement rate has to be kept in mind when selecting the hardware. For example, take the case of a user with a 200 kS/s (samples per second) board who wishes to sample 10 channels. Then the 10 channels will limit him to 200,000/10, i.e., 20,000 scans per second. Now assume the signals are low-level signals necessitating the use of a gain of 100. If the gain-bandwidth product of the PGA is matched with no overcapacity then this will reduce the scan rate by a factor of 100, i.e., to 20,000/100 = 200. This is the reason that manufacturers try and provide amplifiers with a gain bandwidth product of at least 10 times the maximum conversion rate. In the above discussion, the MUX switching time is not discussed since the MUX at high gain levels will not affect the maximum scan rate available. However, when running at low-gain settings, MUX switching speed may come into play. What happens if the user tries to convert data at a higher rate? In principle, the ADC can work as long as the data rate is less than the limit set by the ADC. However, since the data would not have stabilised at the sample-and-hold stage, the output will be junk. A good software interface will be aware of the limitations and give an error. However, the user should not rely on this alone. He can easily work out the maximum conversion rate. The time taken will in the worst case be the sum of the MUX switching time, PGA stabilisation time and the conversion time. In other words, the worst-case scan rate will be where ti represents the time required for the particular operation (say i). Rate = 1/(no. of channels (tMUX + tPGA + tADC)) Sampling Theorem and Over-sampling The Nyquist sampling theorem states that in order to faithfully reproduce a signal of frequency f, the signal must be sampled at the rate of 2f or faster. Furthermore, to avoid artifacts due to aliasing, the signal should not contain information at frequencies higher than the maximum frequency of interest. This has practical implications. More often than not, the users tend to implement this lowpass filter in software. Ideally, the signal should go through a filter which removes the high-frequency artifacts, but this is seldom done in practice. Over-sampling is very commonly done, in order to reduce the impact of noise and aliasing. In this, the data may be acquired at many times faster the

100

Virtual Instrumentation Using LabVIEW

rate dictated by the sampling theorem. This permits the efficient implementation of software lowpass filters, and the subsequent averaging helps eliminate most of the noise. The user should realise that when computing the sampling rate of the board, the requirements of over-sampling and the sampling theorem should also be kept in mind. Inter-channel Delay Unless specialised sample-and-hold boards are being used, where all the channels are sampled and locked in a very narrow time window, the board takes some time to acquire data from a channel (the basic design of an n-bit successive approximation ADC required n clock cycles for digitising on data point). Thus, even if all parameters are fast enough, the next sample (whether from the same or different channel) cannot be processed until the earlier conversion is done. This is the inter-channel delay and is inherent to the process. In most non-electronic applications, this is not of any consequence. However, it should be noted that the system will scan all the channels as fast as possible and then wait. For example, if the system can scan 10,000 samples per second and 10 channels are being measured at 100 scans per second then these 100 scans take up only 10% of the time available (10/1000 s = 100 ms). The system will complete the scans and then wait for 90% of the time before starting the next scan. However, for the rare cases where more uniform timing distribution is desired, the user can increase the inter-channel delay. On the other extreme, if the same signal is being sampled flat out then successive scan channels will carry an offset equal to this delay.

10.4

II

CONNECTING THE SIGNAL TO THE BOARD Having selected an appropriate board based on the resolution required, speed, etc., the next issue the user has to address is the type of connection to use. The selection of input type is intimately linked to the issue of grounding and is discussed together in some detail. As is mentioned earlier, there are three ground points to consider: (i) Safety Ground: This is connected to the ground of the mains. As the name implies this is a safety line and is not suitable for signal lines. (ii) Digital Ground: This is a signal ground defined for digital signals and should be used as such. Connecting analog signals to this line is not desirable.

Basics of Data Acquisition

101

(iii) Analog Ground or Reference: This is also referred to as signal ground. This is the ground to be used with all the analog signals. Grounding considerations can form the text matter for a book by itself. Let us consider the various types of connections in detail. The interface card has the safety (or system) ground, analog ground, digital ground and the signal sense (analog reference) lines. The analog and digital grounds are connected to the safety ground at some (ideally only one) point. There are three options available (National Instruments nomenclature in parentheses): 1. Differential (Differential—DI) 2. Referenced to a common signal reference (Non-Referenced Single Ended—NRSE) 3. Referenced to the safety ground (Referenced Single Ended—RSE) The multiplexer is in two halves which are operated in a linked pair for differential input. For the other two connections, the multiplexer is connected as a single body. This immediately brings out the main drawback in the DI connection. Half the input channels are lost to the user, i.e., a 16-channel board when used in a differential configuration can accept at most 8 inputs. It is good practice to ground the unused input connections, though one must add that this advice is more often than not followed in the breach. The configuration of the multiplexer and the various signal lines in a differential connection is shown in Fig. 10.2. For a 16-channel board, the input lines Fig. 10.2 corresponding to channel n are n and (n + 8) pin numbers. As has been stated earlier, the board capacity in terms of the number of channels is reduced by a factor of two. Any signal arriving on both the input lines (common-mode signal) will be rejected by the amplifier which is set up to operate as a differential amplifier. The output of the amplifier is referenced to the analog ground. The signal sense line is not used. In this configuration, the safety ground of the system will at some point be connected to the signal ground. For the average user, some simple thumb rules can be prescribed:

102

Virtual Instrumentation Using LabVIEW

The differential configuration is by far the best from the noise point of view. However, the loss of 50% capacity in terms of the number of channels is a serious handicap. The DI connection is the only one useable for floating signals, as is invariably the case in bridge connections. Also, for low-level signals, e.g., thermocouple (typical output 6–50μV/°C), the differential connection is the only one suitable due to noise considerations. In many transducers which are now available with built-in electronics (e.g., dc–dc LVDTs), the signals are floating and hence have to be used with the DI connection. Differences between the NRSE and RSE signals are more subtle. These are illustrated in figures 10.3 and 10.4, respectively. Close examination would reveal the following. First, the two halves of the multiplexer are operating as a single

Fig. 10.3

NRSE connection

unit providing the full complement of 16 channels. Second, while in NRSE all signals are referenced to the signal sense (or common) line, in RSE the signal ground is used instead. Consequently, in an NRSE or RSE, the user loses the benefit of rejection of the common-mode signal. In RSE the risk of ground loops is far higher.

Basics of Data Acquisition

Fig. 10.4

10.5

II

103

RSE connection

GUIDELINES A few simple guidelines should save the user from a lot of heartburn. Some of these are listed below: (i) If a differential connection is being used then make sure that somewhere a signal-return path is provided. For example, if a dc power supply is used in a bridge then the negative line (0 V for bipolar) should be connected to the signal ground. Quite often the safety grounds somewhere in the system take care of this, but if this is not proper then a misbehaving signal (noise or drifting) results and is very difficult to track down. Even the famous analog devices 5B modules are known to suffer from this problem. (ii) Avoid the formation of ground loops. If grounds are connected together indiscriminately, ground loops can result. These loops act as antennae and then pick up noise (especially mains) from the environment. The simplest way of ensuring this is to ensure that the reference lines are singly connected, i.e., there is only one path between two reference lines.

104

Virtual Instrumentation Using LabVIEW

(iii) Make sure that the voltage limits are adhered to. Boards specify maximum voltages for input (both with power on and off) as well as maximum voltage above ground (float), etc. These are as much for the safety of the hardware as the user. (iv) For volt-level signals in most situations, the type of signal connection used is irrelevant. In practice, very little difference will be found whether DI, NRSE or RSE connections are used. (v) Keep the wiring neat and tidy and separate the digital (especially fast pulsed) signals from the low-level analog signals. (vi) Make sure the signals are terminated properly. Remember the input impedance of the DAQ hardware is approximately 10 G . (vii) In case of a thermocouple, signals provide for line-break detection. This is easily provided by connecting the line to + 5 V through a resistance in the M range. Normally, the thermocouple shorts out the input but in case of a break, a voltage overload immediately gives the alarm.

10.6

II

PRACTICAL vs. IDEAL INTERFACING Ideally, one would like to have a system configuration which looks something like Source Æ Pre-amplifier Æ Filter Æ Multiplexer Æ ADC Æ Computer The logic behind this sequence is that the signal should be amplified as close as possible to the source so that least possible noise is added to it. Placing the preamplifier very near to the signal source ensures this. Then, in order to eliminate any high-frequency artifacts, and also to avoid any aliasing problems during the digitising process, the signal should be passed through a lowpass filter with a bandwidth not greater than half the sampling rate. The filter and preamplifier are often conveniently combined in a single module or unit. The MUX and the rest of electronics can then follow. However, in practice, all the elements are placed on the DAQ board using general-purpose hardware, and the actual sequence is more like Source Æ Multiplexer Æ Preamplifier Æ ADC Æ Computer The multiplexer is the first module encountered by the signal with no hardware filter of any kind. Furthermore, the close proximity of the signal I/O module to the host computer often necessitates the use of a longer cable prior to the signal conditioning. Also, any high-frequency component of the signal is now the responsibility of the software. While not ideal, the bulk of the real-life interfacing

Basics of Data Acquisition

105

situations face this scenario. However, once the basic rules are understood and followed, this interfacing does not throw up too many problems. It is recommended that when dealing with signals, especially from existing equipment, they should be checked by sampling at a very high rate to ensure that there are no high-frequency components (e.g., from modulation–demodulation) or spikes present. The original equipment may be feeding this signal to a recorder which effectively filters out these and hence they do not pose a problem to the designer. If present, a simple RC filter at the input normally takes care of these. In cases where there is a significant low-frequency component, it is often useful to average measurements over an integral number of cycles. For example, a significant 50-Hz component, averaging for 20 ms or multiples thereof, is very effective in removing the noise.

10.7

II

BRIDGE SIGNAL SOURCES Bridge connections are very frequent in the instrumentation industry. Various resistive sensors—strain gauges, resistive temperature sensors, etc., all have to be run in a bridge configuration (Fig. 10.5). These have to be used under the differential connection, since any attempt to use RSE or NRSE will effectively short circuit one limb of the bridge, as is evident from the figure. Bridge configurations, in most cases, are dc based and require an excitation voltage. Furthermore, the bridge signals are quite often low (~ mV). Therefore, the use of dedicated signal conditioning hardware to provide excitation, filtering, and gain is quite common for these applications.

R1

R2

Vdc

G1

Fig. 10.5

R3

R4

Bridge Connection

A bridge configuration may be Quarter Bridge, Half Bridge or Full Bridge. In a Quarter Bridge configuration only one element is active. The others are

106

Virtual Instrumentation Using LabVIEW

normally high precision and stability resistors. In some cases dummy elements are also used. A Half Bridge has two active elements, which are configured a way that the signals are additive, while a Full Bridge has all four elements as active. Obviously the Full Bridge is the best, and most expensive.

11 DATA ACQUISITION WITH LabVIEW DAQmx AND DAQ VIs INTRODUCTION The acquisition, generation and analysis of signals play an important role in most interfacing. As may be expected, LabVIEW provides a vast selection of ready-made VIs for this purpose. LabVIEW before and up to Version 6 only had NI-DAQ which is now called Legacy DAQ. With Version 7, a new set of software called DAQmx was introduced. Today DAQmx is the de-facto standard. Over the years as hardware evolved, the limitations of DAQ became obvious. When the early dataacquisition boards were introduced, hardware was expensive and there was a premium on providing additional capacity. Every board had to have a clock to power the on-board processor, the data converter, etc. These required different clock rates, and also the data hardware interface required its timing which has set of counters deriving from one or more clocks. This is called the system timer counter. Different AI, AO and DIO applications required separate timers. The earliest boards had very limited capabilities in this regard, and in some cases even ADC and counter-applications

could not be run in parallel. With the E-series boards, National Instruments introduced their own hardware for the purpose called STC. With the STC chip it became possible to have one task each for analog input, analog output and DIO. This was considered to be adequate, and NI-DAQ catered to this requirement. As applications became more sophisticated, one task per function was increasingly considered a necessary to measure at more than or at the highest rate required by the fastest channel. However, as hardware became increasingly more powerful and cheaper with the M-series boards, NI introduced STC2 which further increased the number of counters by a

to make optimal use of the counters. Unfortunately, it was not found feasible to extend DAQ to support this newer hardware. Therefore, a new version of DAQ called DAQmx (pronounced DAQmax) was introduced. The modern boards (M-series and S-series) do not support Legacy DAQ while most E-series boards can

108

Virtual Instrumentation Using LabVIEW

run under either Legacy DAQ or DAQmx (most but not all E-series boards support DAQmx). Naturally, the DAQmx applications to about the same of DAQ. Most third-party hardware lacks the capabilities of STC2 and thus has support software at the lower level. Thus, it is often very similar (or nearly identical) to DAQ. Hence, DAQ as well as DAQmx. Given the totally different nature of the two packages, it is not possible to run both DAQ and DAQmx tasks simultaneously. The user has to reset the board before switching from one protocol to the other. However, there is no bar against running both DAQ and DAQmx in the same block of code, as long as only one type is run at any time, and proper reset is given prior to changing from one mode to another.

11.1

II

a big way by providing a very large set of Express VIs (or Assistants) which are essentially case tools for software development. The Express approach only supports DAQmx and not DAQ. The subsequent sections will discuss both DAQmx and DAQ in detail. Version 7 of LabVIEW introduced DAQmx as a newer and more powerful variant of DAQ for hardware which used STC or STC2. Since DAQmx is now the preferred way of programming, it similarities and difference will become obvious. While DAQmx uses polymorphic VIs for all purposes (i.e., the same VI is used for AI, AO and DIO), in the case of Legacy DAQ the sets are distinct, but functionally very similar.

MEASUREMENT AND AUTOMATION EXPLORER The Measurement and Automation Explorer (MAX) is a user-interactive frontend which is used to install and configure various interfaced devices. It is the basis under which all hardware is configured, and also provides a convenient way of testing things out. MAX otherwise does not play any role in LabVIEW programming. Most of the programmable settings of hardware can also be modified in LabVIEW programs. In that case, LabVIEW settings override the MAX settings. MAX when fired up shows the various options shown in Fig. 11.1. The Data Neighborhood function deals with various systems like CAN, Fieldpoint, etc., which may have been installed. Devices and Interfaces is the area of interest in this chapter. This lists various options like DAQ boards (under DAQmx as well as Legacy NIDAQ devices), PXI crates, serial ports, etc. The Legacy option has to be installed by the user, and is not there by default. Some versions of the drivers demand that the hardware not be present in the system when Legacy drivers are installed. The Fig. 11.1 Options in MAX

Data Acquisition with LabVIEW DAQmx and DAQ VIs

109

Scales function helps to change the scaling of various channels. This includes the definition of polynomial scales, look-up tables, etc. However, unless it is a totally dedicated system, data manipulation in LabVIEW code is preferred. The Software function helps to launch and update various software items from NI. Remote Systems, which is a top-level option, at par with My System, provides access to various DAQ systems connected through the Ethernet, or other parts. This is important for RT and FPGA applications. The Devices and Interfaces function, when called, shows various hardware items. Similarly, once selected, the Help/Interaction panel shows properties of a particular device. These include a property sub-function, which is used to select/configure various properties. Device Number or Board Number reflects the logical name or address assigned to a particular board. These are assigned sequentially by the system. Since the first, and more often than not the only board is assigned the value of one, software developers very often hardwire this parameter in their code, without permitting the user to change it. This should be kept in mind when porting to (and from) multi-board systems. There are various options on the top. Properties, for example, allows you to change the configuration, including the board ID. In case of DAQ hardware, you can change the nature of the connection (RSE, NRSE or DI), the gain settings of the various analog channels (through specifying the voltage range), and so on. Properties can also be used to call Test Resources which in turn tests that the hardware is properly installed. This was a great help earlier, but the modern versions of Windows show up bad installs in the Device Manager, and thus the utility of this function is somewhat reduced. When Properties is called in GPIB, the board numbers are assigned from GPIB0 onwards. The options available are Properties, Scan for Instruments, NI Spy and Analyzer. Properties helps to configure the board, timeout, etc. Scan for Instruments sends a series of *IDN? requests to various addresses and builds up a map of the instruments that are connected and active. NI Spy is useful even when LabVIEW is running as it captures the transactions on the bus for subsequent analysis. Analyzer works only if the board has analyser capabilities, and can be used for a more detailed monitoring of the transactions, including individual hardware lines. By clicking on the specific device, the user can open a communication channel for that particular device and then work in a command-line mode interactively to develop and test sections of code. Some of the functions for GPIB and serial communication are discussed in Chapter 13. MAX can be used to communicate with all VISA devices, and the usage mechanism is very similar to that required in developing LabVIEW (or for that matter Labwindows CVI) code. Running a test panel (Figs 11.2 and 11.3 for DAQmx and DAQ respectively) are extremely useful utilities in MAX which many users tend to neglect. Use the

110

Virtual Instrumentation Using LabVIEW

appropriate one for your application. Just remember, if you change modes make sure to reset the board. They are useful for checking out signals, deciding on the need for filtering, detecting the presence of data spikes, operating digital I/O lines, etc. The check for purity of signals in legacy instruments is more often than not carried out with the Test Panel. Similarly, when very little is known about the signal a priori, it is the Test Panel which comes to the rescue. Running the Test Panel is tantamount to running code containing a loop to acquire and display the waveform. In test panels, it is very convenient to play around with voltage ranges, sampling rate, etc., and see the effects immediately. The only handicap is that only one channel can be visualised at a time.

Fig. 11.2

Test panel in MAX under DAQmx

Data Acquisition with LabVIEW DAQmx and DAQ VIs

Fig. 11.3

111

Test panel in MAX under DAQ

The subsequent discussion will concentrate on the use of multi-function DAQ boards, which cater to the requirements of a majority of the users. Unless there are specific reasons, it is only after gaining considerable experience that users migrate to other platforms like Fieldpoint, PXI, VXI, SCXI, etc. Furthermore, coding practice on other platforms also follows the same general principles. Hence, this discussion will be relevant to the vast majority of users.

11.2

II

THE WAVEFORM DATA TYPE Recent versions of LabVIEW have started using a new data type called the waveform data type. A waveform is essentially a cluster comprising of three components, t0, dt and Y. Normal cluster tools cannot, however, be used to manipulate waveform data. There are functions which are virtually identical to the cluster tools that are used for waveform handling, and are available on the Waveform palette. For example, Fig. 11.4 shows the Build Waveform function. If

112

Virtual Instrumentation Using LabVIEW

a new waveform is being created then the function is extended to incorporate all the three parameters. If an existing waveform is being modified then it is wired to the input-terminal labelled waveform, and the parameter(s) to be replaced are handled in exactly the same way as is done with clusters. All waveform functions are self-explanatory and are therefore not discussed in detail.

Fig. 11.4

Build waveform function

The waveform data type evolved due to the requirements of distributed data acquisition where it becomes necessary to put a time stamp on the data. Also, the remote location may change the sampling interval and, therefore, this too needs to be communicated to the host. The waveform data type caters to all these requirements in an elegant manner. With DAQmx permitting (and even preferring) multiple tasks for various channels (and purpose), time stamps are important for synchronising processing and analysis of the data. Furthermore, with increasing emphasis on distributed systems, the role of the waveform data type (especially time stamp) cannot be over-emphasised. In most cases the second component of the cluster is the time interval, dt. However, for simple applications it is still convenient to work with data in arrays and this option is almost invariably available. dt can be very useful and convenient for subsequent analysis. In waveform charts it should be noted (in some versions of LabVIEW) that if a waveform data type is connected by mistake then the only way to correct the x-axis behaviour is to delete the chart and place a new chart instead. Most VIs which take waveform as an input also accept arrays, so there is no problem. However, in the rare event of the VI refusing, popping up on the terminal and changing the data type to array may be necessary.

11.3

II

WORKING IN DAQmx Assistants automatically generate DAQmx based code. However, they have limitations and for the good developer, knowledge of coding in DAQmx is very desirable. Often experienced programmers use an assistant to generate the code, which they then modify for their own needs. However, the use of DAQmx is

Data Acquisition with LabVIEW DAQmx and DAQ VIs

113

fairly straightforward and for the experienced developer, the use of assistants may not be desirable except for very simple situations where the code can be used as developed. It will be observed that under DAQmx, seven VIs are required in general for any task, while in DAQ this number is four (Intermediate VIs). This forms part of the trend of moving DAQ operations towards lower levels in hardware. Users will find the DAQmx arrangement more logical. However, these are not likely to be of much importance to the users of this book. However, it should be kept in mind that the use of assistants/DAQmx requires more hardware resources. As a consequence, users have reported that at the limit DAQmx code is somewhat slower than DAQ code. Figure 11.5 shows continuous analog data acquisition using DAQmx. The VIs are quite logical to understand and it is better if the user works by logic rather than trying to memorise the sequence.

Fig. 11.5

Continuous analog data acquisition using DAQmx

There are seven DAQmx VIs involved. The first VI is DAQmx Create Virtual Channel (Fig. 11.6). In this, the user selects the function from the drop down

Fig. 11.6

DAQmx Create virtual channel VI

114

Virtual Instrumentation Using LabVIEW

at the bottom, and selects the channels, etc., i.e., performs the basic settings of the board. Physical channels are the names assigned in MAX, e.g., dev1/ai0 for the analog input 0 of Board 1. The hardware set-up (allocation of buffers, timing, etc.) is handled by the DAQmx Timing VI (Fig. 11.7). By the selection of the source and the edge, it sets up the system to look for a trigger VI (if required).

Fig. 11.7

DAQmx timing VI

Selection of the Triggering Source is handled separately by the Trigger VI (Fig. 11.8). This VI is optional. In most cases, an external trigger is not required, and then it can be dispensed with. In case a trigger is specified by the Timing VI, it is necessary to ‘arm’ the system through this VI.

Fig. 11.8

DAQmx trigger VI

It is but logical that the next stage in the process is to start the measurement through the DAQmx Start Task (Fig. 11.9) which only serves to start the task since all parameters have been set in the previous VIs. If continuous measurements are being started with no external trigger then this VI is also optional. However, its use is highly recommended for reasons which will presently become clear.

Fig. 11.9 DAQmx start task VI

Data Acquisition with LabVIEW DAQmx and DAQ VIs

115

As continuous measurements are being made, the DAQmx Read VI (Fig. 11.10) is normally placed inside the while loop. It is essential that the Stop be ORed with the Stop command, in case of some board error. Otherwise, the system will be simply caught in an endless loop.

Fig. 11.10

DAQmx read VI

The next VI which appears outside the loop is the Stop VI (Fig. 11.11) to stop the acquisition. task/channels in

task out

error in

error out

Fig. 11.11

DAQmx stop task VI

While the use of Start and Stop VIs are optional for continuous acquisition without any external trigger they become necessary if data acquisition is in a burst mode. One can divide almost all DAQ applications into either continuous or burst type. In the former, data is acquired continuously until stopped, through user or software intervention. In a burst mode, blocks of data are acquired periodically. For such applications, the Start and Stop VIs are necessary. The differences in terms of coding are the following—the clock is set for finite acquisition (no circular buffer), and the Start and Stop buttons are inside the while loop. The final DAQmx VI is the DAQmx Clear Task (Fig. 11.12) which closes the task and releases the resources reserved for the same. This essentially undoes what has been done with the Create Virtual Channels VI. As usual, Fig. 11.12 DAQmx clear task VI the Error Handler must be placed to handle errors in most cases.

116

Virtual Instrumentation Using LabVIEW

For analog output (waveform generation) applications, the user must load the waveform to the buffer before starting the ‘Write’ operation (in place of Read). The Write VI is shown in Fig. 11.13.

Fig. 11.13

DAQmx write VI

There is one additional VI which may sometimes be used (mostly with waveform generation). It is Wait Until Done. (Fig. 11.14). This again is selfexplanatory.

Fig. 11.14

DAQmx wait until done VI

In case of doubt, the user is advised to try and set up a simple dummy VI through the assistant route and then ‘Open Front Panel’ and see the sequence of the VIs inside the code.

11.4

II Prior to the DAQmx, the hardware was programmed and controlled using NI DAQ. Most third-party board makers adopted essentially the same logic and structure to interface their hardware with LabVIEW. Thus, a working knowledge of DAQ is desirable. Note: At the point of writing, LabVIEW 2009 under Windows 7 does not support Legacy DAQ. This is expected to be addressed in the not too distant future. When (traditional) DAQ is fired up, the user will see separate sub-palettes for AI, AO, DIO and counter timer operations. This is in line with separate pre-assigned hardware for these functions in board design. Next, the appropriate sub-palette is selected. Figure 11.15 shows the sub-palette for analog input.

Data Acquisition with LabVIEW DAQmx and DAQ VIs

Fig. 11.15

117

Palette for analog input VIs

The same structure will be found for all the groups. These VIs are classified into three categories—simple, intermediate and advanced. While the simplest of requirements can be met with simple VIs, the intermediate VIs are the workhorses of the DAQ fraternity. They also have a sub-category in utility VIs which are frequently used combinations of intermediate VIs in the form of a single VI. The advanced VIs are the low-level VIs which form the basis for intermediate VIs, which in turn are embedded in the simple VIs. The first row has the simple VIs with the intermediate VIs in the second row, and the utility and advanced VI menus in the third. The user has to first decide whether to develop using simple, intermediate or advanced VIs. Since the majority of the functions can be performed using simple and intermediate VIs, advanced VIs are rarely used. In all the years of working in data acquisition, the authors have never felt the need to use advanced VIs. The capabilities and limitations of the three types of VIs are summarised below. Simple VIs: These offer a single VI solution. However, they suffer from the following limitations: (i) Data is accessible only at the end of the acquisition. (ii) Repetitive operation necessitates the full internal cycle of configuration, acquisition (or generation) and cleanup is to be repeated every time. Only the digital VIs do not suffer from this problem. (iii) There is an internal error handler which interrupts the code and comes up with a pop-up whenever an error occurs. This is often undesirable as it prevents the user from putting the system in a safe state before exiting the code.

118

Virtual Instrumentation Using LabVIEW

(iv) The internal buffer(s) are not accessible to the user. (v) The user has minimum flexibility. Intermediate VIs: These are the most commonly used VIs. They provide a mix of convenience and flexibility which meets almost all the requirements. The utility VIs should logically be included in these, since they are single VI equivalents to commonly used groups of intermediate VIs. They offer the flexibility of intermediate VIs with the convenience of single VI coding. However, as can be expected, these have a large number of I/O lines which have to be wired (some or most of these lines may be left at their default values). The strengths and weaknesses of intermediate VIs are summarised as follows: (i) These solutions require a small number of VIs (typically 3 – 4) to be used together. Utility VIs are convenient ready-made combinations in single VIs. (ii) Data is accessible during acquisition (and generation). (iii) Repetitive operations with reduced overheads are readily available. (iv) There is no error handler, so the user must provide for this in his code. The simple error cluster provides ready access to the error information. However, this permits the user to use his own code to exit the system in a safe and orderly manner. (v) Internal buffers in the software can be defined and controlled by the user. (vi) These provide a good degree of flexibility without compromising on the ease of use. Advanced VIs: These provide the ultimate in user control but with the accompanying complexity. The user is advised to double click on some simple VIs to observe the embedded intermediate VIs, and likewise to see the advanced VIs embedded in the intermediate VIs. Opening up the utility VIs immediately shows up the intermediate VIs which are their constituents. These allow for a relatively simple single VI-based code with all the flexibility of Intermediate VIs.

11.5

II

USE OF SIMPLE VIs

Simple Analog VIs Let us first consider the case of analog input. For analog input, there are four simple VIs, two labelled AI Multi-Point, and two AI One Point. A quick examination of the icons immediately suggests that they deal with data for one or multiple traces or channels.

Data Acquisition with LabVIEW DAQmx and DAQ VIs

119

Logically, the simplest VI is AI One Point (Fig. 11.16). This has four inputs (two optional, shown in dull type) and one output. Device is the assigned logical number of the board or device. The default value for the first unit is 1 (remember the discussion in the MAX section). The second input is the channel number, which can be either a string, or the name assigned to the channel in DAQmax. The default value here is 0. The high and low limits correspond to the voltage range. Placing zeros here leaves the values as default.

Fig. 11.16 AI ONE PT (Single) VI

If the maximum and minimum values which the board may encounter are specified, the system internally programs the PGA for the best range available. This is decided based on the board in use. Most boards have an ADC with a basic range of ± 5 V. If the signal limits are specified as 2 V and 0 V then with inexpensive boards (gains of 0.5, 1, 10, 100; bipolar only), the gain will be set at 1. However, on the better boards (PGA gains in the 1, 2, 5 sequence, with unipolar/bipolar selection), the gain will be set at 2-unipolar. Therefore the entire resolution will be divided over 2.5 V as against 10 V in the first case. This will provide a 2-bit (4 ¥) improvement in the effective resolution for the same signal, even though nominally both boards are similar. The output is in the waveform format and comprises of a scalar value. One may pop-up on the output terminal and change the output to a scaled value. The multiple point version of AI ONE PT (Fig. 11.17) is very similar but has two differences. The channel(s) input can handle multiple definitions, which may be specified as a range (say, 1– 4) or numbers separated by commas (4, 6) or a mixture of both (4, 6, 0 –3). The output will be either an array (shown) or as an array in the third component of the waveform. Note that the voltage range (and hence gain) has to be the same for all the channels, or in other words it is not possible to customise the range for individual channels.

Fig. 11.17

AI ONE PT (Scan) VI

120

Virtual Instrumentation Using LabVIEW

One point worth remembering is that the data output by the VI will be in the order in which the channels are specified. In the last case mentioned above, indices 0 corresponds to channels 4, 1 to 6, 2 to 0 and so on. In subsequent discussions when waveforms are acquired, the output will be columnwise, following the same logic, i.e., the channel 4 will be column 0, etc. While using the single point VIs, hardware timing in the DAQ boards is not used, and putting them in a loop will seldom exceed an acquisition rate of ~ 100 samples/second. These are, therefore, of no use for measurements of waveforms. The remaining two VIs—namely, AI MULT PT (also known as AI Acquire Waveform(s) cater to the need of data acquisition from waveforms. AI Acquire Waveforms is shown in Fig. 11.18. AI Acquire Waveform is very similar to AI ONE PT except for the obvious changes, in that the channel is now channels, sample rate is replaced by scan rate, and the resulting data array in the output waveform is two-dimensional instead of one-dimensional. Device and channel specifications are same as in the case of single-point VIs. High and low limits (if specified) are arrays for the respective channels. Scan rate refers to the number of scans per second to be performed. This rate is independent of the number of channels being measured. Thus, if five channels are being scanned at 1000 scans per second then the cumulative acquisition rate is 5 ¥ 1000 = 5000 samples per second. If the number of channels is increased to six, and the scan rate is not changed then the measurement rate will now be 6000 samples/s. This point has to be kept in mind when approaching the limit of the device, since it is possible to inadvertently cross this limit in multi-channel measurements. The number of samples per channel (earlier called number of scans) defines the total number of measurements, and thus the buffer size. Output data can be in waveform data type, where the third component will be the data array (one-dimensional in Acquire Waveform and two-dimensional in Acquire Waveforms). The data will be columnwise as discussed earlier.

Fig. 11.18

AI multi point VI

These VIs use hardware timing on the board and also full DMA and interrupt capabilities. Data is available on request when the specified data has been obtained. Similarly, for analog output there are four VIs, i.e., two AO ONE PT

Data Acquisition with LabVIEW DAQmx and DAQ VIs

121

and two AO MULTI PT VIs as shown in Fig. 11.19. The structures are also very similar to the input VIs except that the data is now an input.

Fig. 11.19 AO one point and AO multi point VIs

Remember that most general-purpose boards support a maximum of two channels of analog output, with 12-bit resolution. The maximum update rate is also limited, since most low- and mid-end boards do not have an on-board buffer, and the cumulative rates seldom exceed 10,000 updates/s on such hardware. Simple Digital I/O VIs Digital I/O follows a similar pattern with Read/Write Digital Line, and Read/ Write Digital Port being the four simple VIs. Read Digital Line and Write Digital Port are shown in Fig. 11.20. The line VIs deal with Booleans (levels), while the port terminals deal with bytes. The logic is self-evident. One interesting addition is the iteration terminal. This can be wired to the count terminal in a loop to reduce system overheads, since the port is initialised only once and subsequent accesses do not involve this overhead.

Fig. 11.20

Read digital line and write digital port VIs

122

Virtual Instrumentation Using LabVIEW

The simple VIs for counter and timer operations are somewhat more complex. These require a significant number of connections and, therefore, in terms of complexity can be treated as utility VIs. However, since the error management is internal to the VIs they fall in the simple VIs category. They are Count Events or Time, Generate Delayed Pulse, Generate Pulse Train, Measure Frequency, Measure Pulse Width or Period. Count Events or Time is shown in Fig. 11.21. The usage is self-explanatory and is not discussed here. However, it should be noted that counter size is normally left at zero since all E-series boards from NI use the STC counter, and the management of counters is then internal to the board and software.

Fig. 11.21

Count events or time VI

The simple VIs are seldom used in real-world applications. In case of an error, the code is terminated with a pop-up giving the error information. This feature alone precludes their use in most applications, since the user will at least need to make a proper exit from the rest of the code. Also, in repetitive operations this involves large overheads.

11.6

II

INTERMEDIATE VIs The intermediate VIs are very similar to the DAQmx VIs. The basic organisation is somewhat different in that a total of four VIs are used, as against seven in the DAQmx. As mentioned earlier, the sets are different for AI, AO, DIO and timer– counter operations. So naturally some functions are combined into a single VI. The inherent logic follows the sequence of

Data Acquisition with LabVIEW DAQmx and DAQ VIs

123

For data aqcuisition, there are four VIs which are used together in exactly this sequence. These are AI Config, AI Start, AI Read and AI Clear. The first VI is AI Config and is shown in Fig. 11.22. It can be immediately seen that the Create Virtual Channels and some parts of the Timing Functions in DAQmx are combined here.

Fig. 11.22

Some parameters of historical interest are interchannel delay and number of buffers. Interchannel delay could be used to increase the time between channels during a scan and buffers to define multiple buffers. Most of the parameters which are dimmed in the figure (excluding input limits) are seldom, if ever, used and are not discussed. Input limits is a two-dimensional array to specify the voltage ranges for individual channels (in the order defined by channels), and is used by the software to set the gains of the PGA. Number of buffers is increased from one only if the user envisages a multi-buffer acquisition. This was sometimes done when there was very fast acquisition and some improvement in the performance could be obtained by separating out the current acquisition and processing buffers. The number of buffers may also be reduced to zero for unbuffered acquisition but this is rarely seen. Number of channels in the output simply contains the number of channels being actually scanned (as specified by Channels). Having configured the system, the user next starts the acquisition through the AI Start VI (Fig. 11.23). This combines (parts of) the timing, Trigger and Start VIs of DAQmx. Number of scans to acquire is used to set the actual number of scans the user wishes to get, and must not exceed the number of buffers defined during configuration. Setting it to zero puts the system into a continuous scan mode, where the buffer is configured into a circular buffer and data is acquired indefinitely, until stopped. Scan rate defines the scan frequency as in the earlier

124

Virtual Instrumentation Using LabVIEW

VI. Error in and Error out are there for continuity and to abort the VI in case of an error. One of the optional parameters may be of interest. Pre-trigger Scans is a very useful feature since it essentially permits the specified number of scans before the trigger is to be recorded. Thus, data before the trigger level reached is not lost. It is also very useful for glitch detection. The scan clock source selects between internal (default), digital I/O or RTSI signal sources. RTSI is a special NI bus which permits multiple boards to be synchronised, and operate as if they are driven by a single clock. A cable connects the various boards inside the chassis. Analog Channel and Level are used for the purpose when analog triggering is used. Additional trig parameters is used to control other triggering parameters. Two parameters which may be of interest are the delay after triggering, and number of triggers to skip before DAQ commences.

Fig. 11.23 AI start VI

The actual scan rate is of interest for analysis. Depending on the internal clock on the board and the digital scaling, the actual scan rate may not necessarily be the same as specified. For analysis, the actual scan rate should be used. However, the waveform data type makes this parameter somewhat redundant, since dt forms part (second element) of a waveform data. Once the data acquisition has been started, AI Read (Fig. 11.24) is used to extract the data from the buffer. TaskID in is wired to the TaskID out of the AI Start. Error in is wired to the Error Out of the previous VI (i.e., AI Start). Number of scans to read provides access to data during acquisition if required. If the default value of –1 is used then data is available only when all the scans have been read. Otherwise, data is read in blocks of the number of scans to read specified by the user. Data is available in the waveform data type.

Data Acquisition with LabVIEW DAQmx and DAQ VIs

Fig. 11.24

125

AI read VI

Conditional Retrieval permits the user to approximate analog triggering with hardware which does not support it. This is done by running the acquisition and not actually transferring data to the buffer until the conditions—slope, level, rising or falling, etc., are met. The Read/search position permits the user to read data from the specified place in the buffer, and is useful with conditional retrieval. Scan backlog is a parameter that cannot be ignored, especially when either fast data acquisition is taking place or extensive analysis is being carried out on the data as it is received. If data is being stored into the buffer faster than it is read then a point will come where the buffer will be full and the acquisition will fail. Number read is normally the same as the number of scans to read unless the acquisition is complete, there is an error, or a timeout. It is very rarely of much use in modern computers. Retrieval complete is a Boolean used to signal completion of the acquisition. Please note that many of these parameters are irrelevant in continuous acquisition. The Stop function in DAQmx may be considered to be included either here or in the Clear VI. Once acquisition is complete, or the user wishes to terminate it then the last VI, AI Clear (Fig. 11.25) is used to clear the buffers, etc. This is a simple VI to which the TaskID and error in are wired.

Fig. 11.25

AI clear VI

There is also an additional intermediate VI, AI Single Scan which can be used to read a single scan of data. This permits the user to skip the AI Start and AI Read VIs for acquisition where on-board timing is not required. In practice, the user connects together AI Config, AI Start, AI Read and AI Clear VIs to get his data. These may be wired together for a single acquisition

126

Virtual Instrumentation Using LabVIEW

of the specified buffer. As is more frequently the case, the user either wants to acquire data continuously or in repeated bursts. Continuous Acquisition: Here, the system is set up for continuous acquisition and data is read repeatedly until the user decides (either manually or based on some code) to stop the acquisition. This is shown schematically in Fig. 11.26. No. of scans to acquire in AI Start is set at 0 for continuous acquisition and 20 points at a time are read out in the loop. The status in the error cluster is monitored to stop the execution in case of error, and the stop condition may be user controlled or generated alogrithmically. Note that AI Start and AI Clear are called only once. Most users put the Simple Error Handler VI after the output of AI Clear to get information, in case of error.

Fig. 11.26 Continuous acquisition

A similar function is available in the Utility VI—AI C-Scan (Fig. 11.27). The combination of the VIs is obvious from the various parameters listed. This VI is

Fig. 11.27 AI C-scan utility VI

Data Acquisition with LabVIEW DAQmx and DAQ VIs

127

normally placed in a while loop with the Error out being monitored as above. The counter is wired to the iteration terminal (which runs AI Config and AI Start) and Clear Acquisition takes a Boolean to stop and clear the acquisition process. If the user opens the AI C-Scan by double clicking on it, the code will reveal that all the four aforementioned VIs are being used. Acquisition of Data in Bursts: Sometimes data comes in bursts, i.e., acquisition has to be carried out repeatedly in blocks. Here, the AI Start and AI Read VIs are moved inside the loops for the repeated acquisition of the bursts. This is shown schematically in Fig. 11.28 for a burst measurement every second. Compared to Fig. 11.26, the differences are—the while loop now includes AI Start, number of iterations to acquire is no longer zero, and –1 is wired to AI Read in order to get the entire block. In case the data has to be accessed during acquisition, the user must put AI Read inside another while loop, take the error handler inside, and check for retrieval complete, before dropping back into the outer loop from the inner loop.

Fig. 11.28

Acquisition of data in bursts

Figure 11.29 shows the equivalent AO Write Utility VI, and again its relationship with the intermediate VIs is evident. For analog-signal generation, the situation is very similar except that all the VIs carry an AO prefix. There is, however, one major and apparent difference, AO Write comes before AO Start. There is also a VI named AO Wait which is used to wait for the generation to be completed, before further action is taken. This is understandable since AO Write now only deals with the buffer in the PC and AO Wait takes over the task of monitoring the hardware. The waveform must be written into the buffer before the generation begins. AO Config also is very similar to AI Config.

128

Virtual Instrumentation Using LabVIEW

AO Write is shown in Fig. 11.29. The new parameter here is a Boolean, allow regeneration. The working of allow regeneration can be understood as follows. Data when written to the buffer is fresh. After it is ‘generated’, it becomes stale. If regeneration is allowed then the same data again becomes fresh and can be generated again, otherwise fresh data has to be fed to AO Write. If regeneration is not allowed then it becomes incumbent on the user to load the data fast enough for multiple loops. The operation of AO Start is also self-evident. AO Wait is shown in Fig. 11.30. Any waveform generation involves the use of AO Config, AO Write, AO Start, AO Wait, and AO Clear in the same order. The loops for generation will comprise of AO Write, AO Start and AO Wait. For continuous generation, regeneration must be allowed and numbers of buffers for generation set to zero in AI Start. In continuous generation of waveforms, the user should make sure that the end and start match properly. Otherwise, when the new cycle starts there will be a discontinuity in the waveform. This will occur at the beginning of every iteration except the first. The operation of the utility VIs is again very similar to what may be expected in the above discussion, and the case of AI utility VIs and is hence not discussed.

Fig. 11.29 AO write VI

For digital output and pulse generation, the VIs are very similar (and much simpler) to the analog VIs. Namely, for DIO these are DIO Config, DIO Read, DIO Write, DIO Start, DIO Wait and DIO Clear.

Fig. 11.30 AO wait VI

For pulse operations the intermediate VIs again follow the same operational sequence. However, there are some major differences. There are five configuration routines, namely Continuous Pulse Generator Config, Delayed Pulse Generator

Data Acquisition with LabVIEW DAQmx and DAQ VIs

129

Config, Down Counter or Divider Config, Event or Time Counter Config, and Pulse Width or Period Measurement Config. The user has to select the configuration VI most appropriate to his application. Continuous Pulse Generator Config is shown in Fig. 11.31. The similarity to other Intermediate VIs is again obvious. Note the device as input, and taskID as output, frequency input leading to actual frequency, and duty cycle as input and actual duty cycle as output. Both of these may not necessarily be exactly the same as input due to clock divider. Configuration is followed by the Counter Start and Counter Stop with Counter Read and Wait + (ms) interspersed where required. Counter Start and Stop are very simple as compared to AI Start and AI Read. Counter Stop (Figure 11.32) has an additional terminal which is used to stop the task, and thus functions like AI Clear.

Fig. 11.31

Fig. 11.32

Counter stop VI

The user can safely mix conventional DAQ and DAQmx in the same code as long as no attempt to run the same hardware through both DAQ and DAQmx simultaneously is made. For example, if different boards are present, some may be run with DAQ and others through DAQmx at the same time. However, if the same board is to run under DAQ and DAQmx (but not simultaneously) then it is advised that an explicit reset is given at the end of each set. The two resets are shown in Fig. 11.33. All issues with mixed DAQ and DAQmx programming on the same device are still not settled and the user will be well advised to steer clear of this area.

130

Virtual Instrumentation Using LabVIEW

Fig. 11.33

Reset VIs

Hardware and software from National Instruments (and some of their associates) have an excellent structure and, therefore, offer a very high degree of the interchangeability. Thus, any software developed on a particular DAQ hardware and software platform will transparently port to another unit as long as both units support the features used. Even porting to a different family, say, from PC-based DAQ boards to PXI, is also relatively simple, though not transparent. Most laboratory environments tend to collect a variety of DAQ boards. This may happen as boards are discontinued; faster boards are procured for particular applications, etc. With this transparency of porting the user can use all boards fulfilling his needs, with no change of software. Thus the development system, the trouble-shooter system and the destination systems need not have the same hardware.

SUMMARY DAQmx is best used for automatic generation of code with Assistants. However, use of this for programming is also fairly simple. The main difference between DAQmx divided into three (or four if external triggering, etc., is also required) VIs. Moreover, the same VIs are used for AI, AO, DIO and timer/counter operations. In many ways, the breakup adopted in DAQmx is more logical, as is only to be expected in a later version. three categories—simple, intermediate and advanced. The user is not likely to need to use the advanced VIs. Use of simple VIs is also very limited, especially if there are outputs from the system (for control actions). With simple VIs the error handler will pop-up, if activated, effectively freezing the code at that point. This will prevent the user from putting the system in a safe state before exiting the code. However, simple VIs are very handy for rough and ready work while testing and developing code. The user of MAX for such work should be kept in mind. Another option (discussed in the next chapter) is to use DAQ assistants which provide the power of intermediate VIs (or even more) in a user-friendly interactive environment.

Data Acquisition with LabVIEW DAQmx and DAQ VIs

Using Legacy DAQ the bulk of the code will be developed using intermediate VIs or their close cousins, the utility VIs. Intermediate VIs follow a very similar structure for analog as well as digital and timer operations and are very easy to master. Some important points when working with intermediate VIs are given here: (i) Error handling is now the job of the developer. It is advisable to wire the error handler at the end of the code so that in case of an error, information about it is displayed. Common areas of mistakes are that the inside loops the error cluster must be checked to terminate the loop on error, and in control situations the system must be put into safe mode, before the code is terminated. , Start, (ii) In analog input, the VIs are grouped together in the sequence Device/Board no. as input and generates the Read, and Close TaskID which is used by all subsequent VIs in that set. With multiple tasks the TaskID (iii) Analog output uses the sequence , Write, Start, Wait and Close. (iv) Digital I/O uses a similar sequence as analog I/O. (v) The simple VIs for counter/timer have a large number of wires to be connected giving the impression that they may be intermediate. However,

must be selected as required by the task on hand. Otherwise, the sequence is again similar to that in case of simple VIs. , Start, Read and Close (vi) Remember the sequence of the VIs is for analog input. In analog output Write precedes Start and Wait is also required to ensure that the generation is complete. Wait is also used for most counter/timer based digital operations. The user must manage the Error Cluster which normally requires that the Error Out and Error In lines be daisy chained, checking and managing of the status inside loops, and if required, the Simple Error Cluster handler at the end of the code to show the error. In any complex code, Status will trigger a module of code for the safe shutdown of the system.

131

12 INTERFACING WITH ASSISTANTS INTRODUCTION LabVIEW version 7 introduced a new concept in interfacing—the use of Assistants also referred to as Express VIs. The idea behind their introduction is to provide a user interactive way for the development of data acquisition, instrument interfacing, and analysis code. The code developed using an Assistant can be frozen into code using a set of normal (or nearly normal)

of Assistants. The Input sub-palette is shown in Fig. 12.2. The DAQ Assistant and Instrument Assistant, are named as Assistants, while the other icons, though not named as Assistants explicitly, also follow a very similar logic. The idea here is a very simple one. Most applications require a signal (be it from a device, or simulated), along with may be some other user

to get Assistant support on that sub-VI. Thus the Assistants provide a user-friendly face to the somewhat complex task of interfacing, be it an instrument or a multifunction device. Considerable effort (claimed to be in excess of 100 man years) has gone into the development of this concept. The user faces this as soon as LabVIEW

gives the rationale behind the Input and Output palettes. For an input signal, the user may need to select the gain, and also the signal conditioning (e.g., strain-gauge bridge voltages will require both a gain higher than 1, and also the conversion to say, strain, while thermocouple signals require a high gain, cold junction compensation and linearisation in order to get the temperature). For many common sensors,

diagram is the new functions palette (Fig. 12.1). In the Functions Palette, if the user tries opening any of the various sub-palettes, he is met by a totally different (from previous versions of LabVIEW) display which comprises of a series

specifying the acquisition parameters. In other cases through the Signal Processing Assistant sub-palette. This makes coding very easy, especially for the non-

Interfacing with Assistants

expert programmers. One must keep in mind that the LabVIEW user community has a fairly large fraction of users who do not have background in physical or of Assistants very useful, since it abstracts almost all the complexity of VI programming. However, there is a downside to programming with Assistants. Firstly, the hardware must be physically

Fig. 12.1

Main Functions Palette

133

present in the computer (connected, as the case may be) for the Assistants to be used. Most latter-day versions of LabVIEW do permit the hardware to be set up under simulation. For multi-channel acquisition, requiring different conditioning for different channels, conventional DAQmx or DAQ may be preferable to setting up separate processes for each type of signals using Assistants.

Fig. 12.2

Input Palette with Various Assistants

134

12.1

Virtual Instrumentation Using LabVIEW

II

DAQ ASSISTANT The DAQ Assistant icon when placed on the Diagram initialises itself and comes up with a display appropriate to the hardware installed. With a multifunction DAQ device, the display asks the user to select the interface required (Fig. 12.3). This may take quite some time since the Assistant is slightly system intensive. Now the user selects the function he wishes to perform. Fig. 12.3 Options for Multifunction DAQ Let us select Analog Input. Now the various options (i.e., types of Analog Input) are displayed (Fig. 12.4). The user

Fig. 12.4

Analog Input Options

Interfacing with Assistants

135

selects the particular type of signal he wishes to acquire. Now he selects the type of signal, and the various channels available are displayed. After selecting the channel (say, all) a display appropriate to the type of signal appears on the screen. Figures 12.5 and 12.6 show the displays for voltage and thermocouple signals. These are obviously quite different. While the voltage signal is a relatively simple palette, the thermocouple palette includes the necessary inputs; namely, the thermocouple type, temperature range, and Cold Junction Compensation (CJC) value (alternatively, the channel which provides this signal can also be specified). Thus, this Assistant not only handles the gain, but also the thermocouple CJC, linearisation, etc. The user does not have to add these additional VIs.

Fig. 12.5

Analog Input Voltage Task

136

Virtual Instrumentation Using LabVIEW

Fig. 12.6

12.2

II

Thermocouple Input Task

ANALYSIS ASSISTANT As is the case with data acquisition, Assistants for signal processing are also available. For example, Fig. 12.7 shows the VI for signal measurement and Fourier Analysis (for power spectrum) using Assistants. The code just comprises of two Assistants and the Graphs in a while loop. The Spectral Analysis Assistant (Fig. 12.8) includes windowing, etc. Once again, ease of operation is very evident. The rationale for windowing for those not familiar with signal processing is as follows. Fourier analysis assumes that the signal is infinite, in length or duration and is composed of the signal as available repeated ad infinitum. Now in case of a mismatch between the ends of the signal, the discontinuity may result in spurious peak(s) in the Fast Fourier Transform (FFT). By windowing, the signal is ‘smoothly’ reduced to zero at either end, so that this discontinuity is avoided.

Interfacing with Assistants

Fig. 12.7

VI Using both DAQ and Spectrum Analysis Functions

Fig. 12.8 Spectral Analysis Assistant

137

138

Virtual Instrumentation Using LabVIEW

As long as the Assistant is active there are some restrictions. The code is still soft (i.e., under development) and, therefore, the hardware must be present (or simulated) for the code development. However, the user can pop-up on the Assistant and ask for the front panel to be displayed. Then (after prompting) the code is converted into a VI and it can no longer be modified through Assistants. For DAQ the user will find that the code uses DAQmx, rather than the traditional DAQ VIs.

12.3

II

INSTRUMENT ASSISTANT So far we have discussed the operation of Data Acquisition Assistants, and the assistants for analysis. There is another major class of Assistant, namely, the Instrument Assistant. These are designed for easy handling of instruments. A very quick test shows that the potential productivity gains using Instrument Assistants are massive. Figure 12.9 shows the assistant-based VI (unconverted) for the NI Instrument Simulator connected through a GPIB board. What can be simpler than this? A single (albeit large icon) connected to two display icons (out of which the string display will normally be dispensed with!) doing everything, as against a dozen or so VIs strung together.

Fig. 12.9 VI Using Instrument Assistant

Figure 12.10 shows the Assistant palette. Here, the system has identified (apparently through *IDN?) that an instrument is available at GPIB:2, since the simulator is set at PAD2. All requirements of VISA programming are taken care of internally, as is data parsing, etc. Using just one Assistant and one operation, the query sour:func sin;sens:data? is sent to the device, and the response displayed on a graph while still inside the palette. Run this step facilitates testing

Interfacing with Assistants

139

out of code, and (almost) negates the use of MAX. The graphical display is activated by selecting Auto parse. The raw output string is available in Token and the parsed data in Token 2.

Fig. 12.10

Instrument Assistant

The Assistant Code if converted becomes (almost) normal VISA code, and part of the code is shown in Fig. 12.11. This shows the power of the Assistant concept. Once again, like DAQmx, there is now a stib-VI named IIOA, which takes the place of a lot of complex VIs.

Fig. 12.11

Part of Converted Code for Instrument I/O

140

Virtual Instrumentation Using LabVIEW

It is possible to code very rapidly using Assistants. However, one must bear in mind that using Assistants code is invariably bigger. Also, any person wishing to become a competent developer will do well to steer clear of this mode of programming. The very ease and power of Assistants tends to make a beginner very reluctant to learn to code using normal tools. Consequently, the skill levels developed becomes very poor. Even expert programmers on occasion use Assistants for ‘rough and ready’ code.

SUMMARY Coding using Assistants is a new concept in LabVIEW. Assistants and the associated tools made their appearance in LabVIEW 7, and have evolved with time. Based on past experience, one can make some observations. The concept is well thought out users may use the Instrument Assistants to their advantage, but complex applications may not be amenable to this concept. One can see some signs that the future developments are being thought about. For example, the DAQ Assistant gives the TaskID as an Output, with no direct application for this visible. It is quite likely that in future using either user-developed code or the Property node this may be used for multi-part code. The combination of acquisition and signal conditioning is again very handy. However, if one is acquiring mixed signals (say, a mixture of thermocouple, voltage, and strain all the signals (with appropriate gains) and then condition/process them separately.

its associated conditioning. It is claimed that the Assistant technique, is amenable to multiple process acquisition, and it is possible (and even probable) that the hardware timed loops were developed for just this type of a need. For a long time NI E-series boards (with STC timers) had a plethora of counter channels which were not used earlier, but may now be necessary for hardware-timed, multi-loop operations. apparent. Unless a lot of decision making is involved in acquisition, the advantages of using the Assistants are very evident. The paradigm of Assistants has evolved, and become stable It has become quite popular, especially amongst the non-specialist developers. It can be expected to further evolve as newer versions are released.

13 INTERFACING INSTRUMENTS: GPIB AND RS232 INTRODUCTION So far all the discussion has centred on the acquisition of signals directly from the user system. This is not always the case. Quite often existing instruments or systems have to be connected to the computer either singly or in ensembles. A common reason for connecting a standalone instrument is to provide data-transfer capabilities from or to the computer. Also, there may be cases where part of the system is connected using DAQ while the other part is on a standard interface. In cases of multiple instruments being connected these are mostly combined to form a more complex system. For example, a programmable voltage source, a voltmeter, and a current meter may be combined to form a curve tracer for devices. Alternatively, the function may be achieved using a system consisting of a waveform generator and an oscilloscope. These instruments are invariably connected to the computer through an interface. Traditionally, this interface was either the serial port (almost always RS232C) or the General Purpose Interface Bus (GPIB, also known as IEEE488). In future one can

expect more standards like Universal Serial Bus (USB), FireWire (IEEE1394) and Ethernet (particularly in the wireless forms) to join this group. However, these interfaces have severe limitations which will be mentioned towards the end. Also, with the near Universal Adaptation of SCPI (Standard Commands for Programmable Instruments) the software aspects are becoming increasingly platform independent. So whether the instrument is on RS232, or any other interface the commands remain the same. At present the interfaces of interest are the GPIB and RS232C (or its variants like RS485). Many instruments are available with one or both of these interfaces built in. In other situations one or the other can be ordered or added at nominal cost. Even though binary data transfers are possible in GPIB and RS232, ASCII is used almost invariably. handling of strings. This is also the reason why there is a massive array of functions available in the strings palette of LabVIEW.

142

13.1

Virtual Instrumentation Using LabVIEW

II

RS232C vs. GPIB Any instrument designed to be interfaced will invariably have one of these interfaces present. The following discussion focuses on the pros and cons of using them, and how does one select which interface to use. The RS232C interface is built-in in the computer (at least if one discounts the latest legacyfree laptops and desktops). On the other hand GPIB invariably demands the installation of additional hardware. Thus cost-wise RS232C is definitely advantageous. On the other hand, RS232C being a serial port has some major disadvantages. The RS232C port is good only for a one-to-one connection. Thus the number of instruments which can be connected is limited. RS485, a variant of RS232 does support up to 32 devices in a multi-drop configuration. GPIB on the other hand supports up to 16 devices on the bus. The serial connection, as the name implies sends one bit after the next, and hence the data transfer speed is limited to 19,200 bps, which corresponds to a data rate of ~ 2 kB/s. GPIB on the other hand is a parallel protocol (all bits in parallel over separate wires) and supports data rates of up to 3 MB/s (7 MB/s in the HS488 form). Over short distances RS232 can be extended up to even 150 kbps, but even this corresponds to only 15 kB/s. To take a realistic scenario, say one wishes to transfer data from a storage oscilloscope. There are 1k sampled channels, with the data having 4 significant digits. The volume of data is (1024 ¥ 6 = 6144) as the four significant digits contribute 6-bytes per sample (additional two bytes are for the decimal point and separator). An RS232C port at 9.6 kBps will take over 6 seconds to transfer the data, while even a slow (300 kBps) GPIB link will take just over 20 ms. The properties of GPIB, RS232 and RS485 are compared in Table 13.1. Table 13.1 Comparison table for properties of GPIB, RS232 and RS485 interfaces Property Bandwidth Max. cable length Connectors Termination Max. No. of Transmitters Max. No. of Receivers

GPIB

RS232

RS485

1-8 MB/s 20m Standard Built In 16 16 (T + R £ 16)

Notifier functions palette in the Diagram (Fig. 14.1). There are seven operations available: Obtain Notifier, Send Notification, Cancel Notification, Get Notifier Status, Release Notifer, Wait on Notification, and Wait on Notification from Multiple. Obtain and Release Notifier are Fig. 14.1 complementary functions, performing the tasks as named. The commonly used set comprises Obtain, Send, Wait on and Release. Obtain Notifier (Fig. 14.2) creates a notifier. If a name is specified, it is used to identify the notifier in multiple loops/processes. If only one notifier is used, name need not be specified (a default name is given), though this is not a good practice. Element Data type is the type of data being sent through the ‘notifier’. The other terminals are self-explanatory. It is permissible to create one notifier and then wire it into various loops, or alternatively the same name can be used at different places. Note the ‘Error In’ and ‘Error Out’ terminals for

Fig. 14.2

164

Virtual Instrumentation Using LabVIEW

normal error handling. At the end of the code, the notifer is cancelled with the Release Notifier command (Fig. 14.3). This is the opposite of Obtain command. If ‘force destroy’ is set true (very rare event), it kills the notifier even though some of the loops or VIs using the notifier may still be active.

Fig. 14.3

The operation of notifiers is in many ways very similar to the operations in the case of Intermediate VIs used for Data Acquisition. The Obtain and Release operations are carried out once in the code while Set and Get do the actual transmission. Once a notifier is created it is handled in various loops mostly through the Send Notification and Wait on Notification commands. As the name implies Send (Fig. 14.4) is used to effectively load and send the data on the notifier.

Fig. 14.4

While Wait on Notification (Fig. 14.5) is used to synchronise the daughter code and to send the data through the notifier.

Fig. 14.5

Figure 14.6 shows the diagram for generating a random number in one loop and displaying it in a second loop. As discussed earlier, the main Notifier

Advanced Topics in LabVIEW

165

functions, namely, Obtain, Send, Wait and Release VIs are used. A Notifier called Note 1 containing a real number is created. This is used by both the loops. A cluster containing the the value (Real) and a Boolean is defined as the data type for the Notifier. The ‘status’ from the Error Cluster is ORed with the Stop Button and transferred to the second loop. The Random Number is displayed while the Boolean controls the execution of the loop. The Notifier is ‘released’ from the second loop to ensure that its job is done before it is killed.

Fig. 14.6

The same code could have been developed using local variables. However, the complexity of the task would have been manifold, and the code would not be as efficient. Firstly, the local variable containing the random number (and possibly the refresh/use status) would have had to be read continuously. This would be inefficient. Then another local for the stop button status would have to be established to stop the daughter loop. Furthermore, as soon as a Local is created for a Boolean, latch action is not acceptable for the button, so a reset would also have to be provided. In Fig. 14.6, let us ignore the additional code required for the Error Cluster. One is simply transferring a cluster containing the random number and the Stop Button status through a cluster between the two loops in a transparent fashion, with the second loop executing only when fresh data is received. The software is taking full advantage of the multi-threaded environment of the computer. The other commands in the Notifier palette are Cancel Notification, Get Notifier Status, and Wait on Notification from Multiple. These commands are

166

Virtual Instrumentation Using LabVIEW

rarely used. Cancel Notification is used to cancel a notification, Get Status immediately returns the status, while Wait on Multiple accepts a set of Notifiers in an array, and acts as soon as any of the notifiers is received. It then returns the notification (containing the data) which has been received. It is apparent that using notifiers the data presentation can be easily separated from the data acquisition. Now if the display code is not placed inside the acquisition loop, but is put in a separate loop, then if required, the same code can be moved to another system (with practically no significant modification) for distributed applications. One thing to be borne in mind is that if a notification is not read by the slave process(es) before the next notification then the data in the old notification is lost. Thus, the notifier buffer can store only one event.

14.2

II

OTHER RELATED TOOLS

The use of Notifiers has been discussed in some detail. The other related tools, are Queue, Semaphore, Rendezvous, and Occurrence. Queue as the name suggests allows you to build up a queue of the data, and in case one set of data is not read before the next one arrives, it is put in the queue. The operations in a queue are very similar to those in Notifiers. Figure 14.7 shows the Obtain Queue command, which is very similar to the Obtain Notifier. The other commands are also very similar. You should be aware that there are two commands for putting data in a queue. En queue Element operates the puts data in the queue such that the new data goes to the back of the queue, and the queue then operates in a FIFO manner. On the other hand, En queue at Opposite End operates a LIFO queue. A notifier is identical to a queue with a single element.

Fig. 14.7 Obtain Queue

Semaphore VIs permit the user to operate a shared resource in an orderly fashion. If a resource is shared by multiple processes then one needs to allow only one process to access the resource at any given time, and bar other processes from being able to access it. Semaphores provide this tool. The Create, Acquire,

Advanced Topics in LabVIEW

167

Release and Destroy Semaphore VIs serve the obvious functions. Get Status and Not a Semaphore (checks for validity of a semaphore) are the other commands in this palette. Figure 14.8 shows the Create Semaphore VI. Once again the similarity with the Notifier or Queue VIs is obvious.

Fig. 14.8 Create Semaphore

Rendezvous VIs serve to synchronise code of multiple processes. For example, if a rendezvous, is created with three stage rendezvous, the code of three processes will only execute when all of them are ready. Create and Destroy Rendezvous VIs are used with Wait at Rendezvous (in sub-VIs) for the purpose. The Resize and Get Status functions are again used very rarely. The user should look at the example VIs to get more information. The final set in the family is for Occurences. Here there are three functions, Generate, Wait and Set Occurrence. Once the Occurrence has been created (using Generate) the Set and Wait functions serve the purpose of sending and reading the Occurrence. The same purpose could again have been served by global (or local) variables, except that in the polled mode the system overheads would be very high.

14.3

II

WAIT FOR FRONT PANEL ACTIVITY Continuing with the theme of moving over from polled to interrupt driven methods, for controlling code like State Machines two mechanisms have been developed—Event Structures, and Wait For Front Panel Activity. For mousedriven activity, the Event Structure is preferred while for in other cases the Panel Activity route is the one of choice. While the former can also be activated by a mouse operation the latter cannot. Event Structures were discussed in the chapter on State Machines. The Wait For Front Panel Activity (Fig. 14.9) command is on the Programming > Dialog & User Interface palette. In order to simulate a front panel activity an associated function, Generate Front Panel Activity (Fig. 14.10) is used. For example, if you want the user to input some data the code can be easily implemented using a while loop with waits. On the other hand, using Wait

168

Virtual Instrumentation Using LabVIEW

Fig. 14.9

for Front Panel Activity (Fig. 14.11) allows you to achieve the same in a far more efficient manner. The code allows the user to input the name and roll number, and goes into the outer loop only if the Done button Fig. 14.10 is pressed. The information is stored as arrays which are available for further processing outside the loops. The Stop button is used to end the data entry operation.

Fig. 14.11

14.4

II

DATA SOCKETS With increasing emphasis on networking and distributed controls and computing, it is but natural for LabVIEW to encompass these developments. While a modicum of support for TCP/IP was available in LabVIEW 4 with the

Advanced Topics in LabVIEW

169

appropriate toolkit, networking support really began with LabVIEW 5 when Data Sockets first made their appearance. Version 6 went all out for networking support, and was named LabVIEW 6i (I for Internet). The tool devised by NI for networked data acquisition is Data Sockets. Today Data Sockets enjoy approval from the US government. However, Data Sockets do not form part of the standard networking tools, and therefore in order to work in Data Sockets the user must start the Data Socket Server in the data socket network. In Windows this is done through Start > Program Files > National Instruments > Data Socket > Data Socket Server. There are many examples of Data Sockets in the examples/comm. directory under LabVIEW. Working with data sockets is not very different from working with Intermediate DAQ VIs and Notifiers. While the earliest implementation of Data Sockets used strings to transfer data, from Version 6 onwards data sockets have their own data type called Variant. However, any data type can be used, The DataSocket sub-palette (Fig. 14.12) is in the Data Communications menu, and there are five functions Read, Write, Select, Open and Close. The natural sequence of operations Fig. 14.12 Data Sockets sub-palette will be Open and Close (only once in each VI) and a series of Read or Write operations therein. Select works to allow the user to select the URL to use through a pop-up dialog box. The Variant submenu is used to handle data transfers to and from variants. Data Socket Open (Fig. 14.13) is very similar to AI Config or Open Notifier. The URL is the site for the connection (say dstp://localhost for the host system itself). Mode is an integer which defines the mode of connection (0-Read, 1-Write, 2-Read/Write, 3-Buffered Read and 4-Buffered Read/Write). The output is connection id (similar to TaskID), DataSocket Close (Fig. 14.14) is again very similar to the clear command for Intermediate DAQ or releasing a notifier.

Fig. 14.13 Data Socket open

170

Virtual Instrumentation Using LabVIEW

Fig. 14.14 Data Socket Close

The Data Socket Write command (Fig. 14.15) is again similar to Send Notifier. The connection can be defined either through a string or the connection id.

Fig. 14.15

Data Socket Write

The DataSocket Read command (Fig. 14.16) is again self-explanatory.

Fig. 14.16

Data Socket Read

The term Variant is all over the Data Socket VIs. It is a special data type created for Data Socket operations. Given the requirements of TCP/ IP, Variant has to be closely related to the String data type. The use of Variants takes care of all data types in Data Socket operations, and is hence very useful. One point which must be kept in mind when working with Variants is that any additional data loaded into the variant through attributes must be unloaded in the same way, as will be illustrated in the example. There are seven Variant handling commands—To Variant, Variant to Data, Get Variant Attribute, Set Variant Attribute, Delete Variant Attribute and two interchange VIs for String Variant inter-conversions). The latter pair are more

Advanced Topics in LabVIEW

171

for historical reasons, since the original implementation of Data Sockets used strings for all communications. To Variant (Fig. 14.17) simply converts whatever data you have to a Variant. After receipt of the data the Variant to Data command (Fig. 14.18) is used to get the data. Type is used to define the data type and must be connected.

Fig. 14.17 To Variant

Fig. 14.18

While the primary data (i.e., the first parameter) is loaded and unloaded as discussed, often more values have to be transmitted through the same Variant. This subsequent data is ‘loaded’ on to the variant through the Set Variant Attribute command (Fig. 14.19). This command can be used to either add data or to replace the named data in the variant. Therefore, any data which may need to be changed before transmission must be loaded through the Set Attribute command.

Fig. 14.19

Set Variant Attribute

However, any data put in through an attribute must be obtained using the Get Variant Attribute (Fig. 14.20) command. If name is omitted then all the attributes are extracted by this VI.

172

Virtual Instrumentation Using LabVIEW

Fig. 14.20

Get Variant Attribute

The simplest way of using a Data Socket connection to show data from one VI in another VI, which may be on another system to simply pop-up or right click on the variable to be transferred. In the example (Fig. 14.21) two VIs have been set up, one to read a number from another VI and to display it in a waveform graph, and also to transmit the Stop button information to the second VI. The second VI actually generates a random number every 100 ms and sends it to the first VI. Also, the Stop button on this VI is controlled by the Stop button on the first VI. To set this code up, one can use the inherent networking capabilities of LabVIEW. You proceed to set up this connection as follows. Create the two VIs as you normally would. Now on the Display and Control VI, pop-up on the Waveform Chart and select Properties > Data Binding to set up the connection (Fig. 14.22). Now simply type in the URL (in this case dstp://localhost/chitra) and set it to subscribe (as the waveform chart is to

Fig. 14.21

VIs to Transfer Random Number and Stop Button Status

Advanced Topics in LabVIEW

173

receive data). Similarly, for the Stop button another URL dstp://localhost/roko in the Publish mode was set up. The reverse was done in the second VI. The net connection is indicated by the presence of a small ‘LED’ next to the object on the front panel. In case the data was being moved across PCs the respective IP addresses would have replaced localhost.

Fig. 14.22

However, this type of connection is all very good for demonstrating Data Sockets, or very simple applications. For most real-life scenarios a somewhat more complex, and more versatile connection has to be set up. Figure 14.23 shows such a connection. There are two VIs, DS1 and DS2. S2 writes the random number as well as the Iteration and is controlled by the state of the Stop button in DS 1 which displays the two numbers sent by DS2. Note that the Variant Data Type has not been used in this example. Figure 14.24 shows the same problem solved using Variants. While the ‘roko’ code has been left untouched, the random number and Iteration are transferred using Variants. The random number is converted to a Variant, and then the Iteration is appended to it as an attribute ‘Iter’. This is then sent to DS Write. In DS 1 the Variant to Data command retrieves the random number. However, Iter is retrieved using the Get Attribute command. One can summarise this approach as follows. The first parameter is simply converted into a Variant. Subsequent parameters are added to this through a series of Set Attribute commands. In the reading section while the Variant to Attribute command gets the first parameter, the others are retrieved through a series of Get Attribute commands. Note that the names must be identical in both the VIs. The code does not show the Simple Error Handler VIs for clarity. Error Checking is done in both the VIs through the Unbundle by Name command on

174

Virtual Instrumentation Using LabVIEW

Fig. 14.23 VI Using Data Sockets without Variants

both the Data Socket variables. These along with the state of the Stop button are then logically ORed to control the loops. From version 8 onwards, LabVIEW introduced the new LabVIEW shared variable, which is a unified API for communicating data among VIs executing on the same local machine or across a network. Using the Shared Variable, you can share data between loops on a single diagram or between VIs across the network. In contrast to many existing data sharing methods in LabVIEW, such as UDP/TCP, LabVIEW queues, and Real-Time FIFOs, one typically configures the shared variable at edit time using property dialogs, and does not need to include configuration code in the application. More details on using Shared variables in LabVIEW programs may be obtained from the www. ni.com site.

Advanced Topics in LabVIEW

Fig. 14.24

175

VI Using Variants and Attributes

Occasionally, it is desirable to control a VI from a remote location. From LabVIEW 8.5 onwards web servers are easily configured. Using this approach one could run an experiment from a very remote location. Details of configuring the web server and web publishing are given in Chapter 16, under Lab Set 9, Exercise 5. Data Sockets have an advantage over Web Servers in that they allow for more control on the systems, and the data packets are smaller. However, Data Sockets not being a standard net protocol require that the data socket server is running on the system(s). In Data Sockets finer control on the client is available at the time of setting up the code. It should be noted that DataSockets uses the Variant data type. After the first packet is set up subsequent packets are ‘loaded’ onto the packet as attributes. At the time of data recovery the reverse is followed. While in Web Servers the Panel is exported’ in a data socket only data is exported. As a result, the data packets are smaller, and data can be easily extracted at the remote sites(s).

176

14.5

Virtual Instrumentation Using LabVIEW

II One problem faced by all programmers is: How do I print the front panel of my code? Newer versions of LabVIEW provide the Print Front Panel VI in the Programming > Report Generation > Easy Print VI Panel or Documentation palette (Fig. 14.25). Some earlier versions had an equivalent function in the Advanced palette. Layout options is a cluster which allows the user to select various parameters like page orientation, scaling, margins, colour/mono, etc. VI path specifies the location of the VI (normally left at default), contents can be used to select what parts of the VI are to be printed, etc. However, this method is not very convenient since quite often the printout format may defer significantly from the display format. For example, while a coloured background is desirable in the display, the background is mostly kept clear or white in prints for clarity as well as conservation of the printer ink. The font sizes are often different, especially if the printout is to be reduced.

Fig. 14.25

Furthermore, there is often a button to initiate printing, which the user normally wishes to conceal in the printout, often along with other controls, and indicators. Once the print option is selected these can be done by setting the Visible Attribute of various items to be hidden. The preferred options is somewhat different. It is often better and easier to create another sub-VI exclusively for printing purposes. This is formatted exactly as the printout required. This VI is then printed using either the Easy Print ... VI or through the VI set up. The VI can be easily set up not to display and print at the end of execution. This way the VI for printing only appears in the hard copy. For this you pop-up on the VI icon in the Panel and then Properties > Print Options lets you to set it up for printing at the end of execution.

15 DISTRIBUTED SYSTEMS INTRODUCTION Over the past few years, it has become obvious that computer-based instrumentation is evolving towards distributed systems. There are two reasons for this. One lies in software, namely, the ubiquitous Windows is not an operating system (inherent latency ~ ms) designed for real-time applications. Thus, obviously any action requiring a response faster that 1 ms is not practical. This is also acknowledged by the timers having a resolution of only 1 ms. The second reason is in hardware–access to computer internals (hardware) is becoming more restricted. As a result, interfacing hardware is running on USB or Ethernet. The latency is 1 ms in Ethernet and 200 μs in USB 2 (1 ms in USB 1.x). Thus, using a distributed system with some intelligence in the front-end modules is the way forward. These may then be interconnected using either of the two nearly universal interfaces. Given the shared nature of the medium, things may improve but not to a very large extent in wireless systems. In order to execute code with a faster timing, one has to recognise two possible scenarios. If the problem is only of acquisition and no (or slow) control, one can use the normal systems as long as large data buffers are employed. However, if closed-loop action is required with an interval of under a few ms then this route is not available. Therefore, one must have

some faster system for the purpose. Furthermore, if the ultimate function is to develop an embedded system then again specialised software and hardware are required. able, namely, normal (e.g., Windows), Real Time (RT), and Field Programmable Gate Array (FPGA), each with its own requirements. So far, the discussion has been ments of RT and FPGA coding will be discussed. One must keep the software architecture in mind. The depending on the requirements one can target:

To begin with, an operating system faster that Windows is required. An RTOS is fast, deterministic, small (often the CPUs and storage in RT are limited). Technically, one may say that the RTOS must have a

178

Virtual Instrumentation Using LabVIEW

in the innovative Hypervisor technology. Using this, it is possible to run normal, and RT processes at the same time on a multi-processor or multi-core system. Thus, one core (or processor) may be running a normal OS like Windows, while the other core(s) can be executing an RTOS. With rapid developments, FPGA techniques

15.1

II

are increasingly becoming the method of choice for embedded and stand-alone systems. It is not the endeavour to provide a comprehensive exposition in the use of RT and FPGA techniques, but rather to give the reader an exposure to these areas, and their place in the larger canvas of things.

BASICS Both RT and FPGA are add-on modules to the standard LabVIEW. The former is (by the looks of it) about same as the LabVIEW which the user is familiar with, along with the addition of some more functions geared towards faster timing, and data transfers between blocks of code. The RT system will be operating under a Real Time Operating System (RTOS). In the case of FPGA, the user interface is quite different. In the case of RT, the daughter system runs a Real Time Operating System (RTOS) and code is downloaded to the processor or resides on the daughter system itself. In FPGA, one uses LabVIEW to ultimately generate a bit stream to program the hardware. Certain tenets of data-flow programming will have to be discarded when one starts working in RT or FPGA. Looking at an RT code, the user will immediately observe the extensive use of sequence structures and very much reduced use of parallel code. This is done since in an RT application, a parallel code will produce a degree of jitter or indeterminacy. Say, there are three independent blocks of code, A, B and C, operating in parallel. The execution of the code in ABC and ACB sequence will introduce a degree of jitter which is best avoided or at least minimised. By placing A, B and C in a sequence structure, we can achieve this purpose. In the case of FPGA, one has to bear in mind that one is designing a hardware circuit through software so the judicious use of parallelism can actually speed up the execution. Even if data gets queued up for transfer, the jitter will only be one clock cycle, i.e., 5 ns for a 200-MHz clock! In RT, one sees the same functions palette as in normal LabVIEW. In addition, there is a Real-Time menu (Fig. 15.1) which has some additional functions grouped in four sub-palettes catering to FIFO operations (for data transfer across processes and processors), Timing (now timing drops to the μs regime), and miscellaneous utilities. On the other hand in FPGA, the Functions palette (Fig. 15.2) is heavily truncated with a very limited set of sub-menus. It should be borne in mind

Distributed Systems

179

Fig. 15.1 Real-Time palette

that while under normal LabVIEW one can code directly in VIs, in the case of RT (and especially, FPGA), the use of projects is almost mandatory. A lot of these restrictions arise from two major sources, firstly using logic gates, etc. Real arithmetic (floatingpoint) is not advisable. Secondly, since all code has to be developed to use gates, the number of which is far more limited than that of the memory, the scope is again drastically reduced. Also, one must now start thinking in terms of hardware rather that software, since at the end of the day the functionality will be interpreted in terms of a circuit implemented using gates.

Fig. 15.2

FPGA Functions palette

Timing The same options, namely, Tick Count, Wait, and Wait Until are available. The icons are somewhat different, but quite similar to those in regular LabVIEW. However, now the user has to define the clock interval in terms of Ticks, μsec or msec (Fig. 15.3). Ticks is a system-dependent parameter which is essentially the clock rate. Also, the size of the internal counter may have to be defined.

Fig. 15.3 Timing options

180

Virtual Instrumentation Using LabVIEW

Determinism, Critical Loops and Starvation The first requirement in a real-time process is determinism. This is best understood in terms of jitter. Assuming you wish your process to execute as fast as possible, a code not optimised for this will exhibit a certain variation in the time it takes to execute the same code repeatedly. Safe coding practice demands that the code covers the worst-case scenario. This can happen due to the multiple processes operating in the background. Some processes like DRAM refresh are always on in any system. How does one increase/improve determinism? 1. Avoid using parallel loops: Say, a process has three loops A, B and C which execute in parallel. Say, you are looking at how long does it take for C to start after A. There are two possibilities, A-B-C and A-C-B. Thus, the time taken for C to start will be different in both cases–jitter and poor determinism follow. One can immediately see that loops must be sequenced. In fact timing critical loops (as defined in priority) does not permit parallel processing. 2. Change the priority of the loop: LabVIEW allows the user to define some loops as timing critical (Fig. 15.4). A timing critical loop, as implied, has the highest priority in execution. Using while loops, the entire sub-VI can be assigned a priority but not individual elements. 3. Use timed loops: By using timed loops in place of while loops, it is possible to change the priority of individual loops and as well as assign them to specific processors in a multi-processor (or core) system. While changing the priority is often desirable, or even necessary, experience shows that the task scheduler of LabVIEW does an excellent job of Fig. 15.4 Timed loop options processor selection. 4. Pre-assign all arrays: Even though RT allows for dynamic array size, it is often not desirable. If an array grows beyond the size assigned to it then the manager has to go and find a large-enough contiguous space for the enlarged array, and then move the array there. The proper way (the only one under FPGA) is to initialise a large-enough array and then ‘Replace Array Element’ to update it. When working with critical loops, two specific points must be kept in mind. RT allows only one timing critical loop at any one time. The second point is to look out for starvation of code. If a critical loop does not periodically release the system (through a timing function–explicit or implicit) then the lower priority

Distributed Systems

181

loop(s) will never get access to the system resources. The simplest way is use Wait or Wait Until xx Multiple in the code, or allow enough time to the timed loop to go to sleep for some time.

15.2

II

PROGRAMMING IN FPGA As compared to real time, this is a totally different game. The palette is highly restricted; the user must watch resource usage very closely, etc. A typical project with three levels of VIs (Main in Normal LabVIEW, RT under RT and FPGA1 in FPGA) is shown in Fig. 15.5. It shows that the FPGA Target is populated with four modules (9201, 9263, 9423 and 9472) in slots 1 to 4 respectively. Also, notice the FIFO in the FPGA area which is used for transferring data from the FPGA to the RT code. This is set up for communication from target to host using DMA for the fastest communication. The FPGA code is shown in Fig. 15.5. It runs on a 500-μs loop. The outputs are the Chassis Temperature and Analog Input 1 from the 9201 in Slot 1. It also drives Analog Outputs AO2 and AO3 in Fig. 15.5 Project menu Module 2 (9263). While the data is sent to the RT code using a FIFO buffer, the analog values to be sent out are through normal variables. The two values which are to be sent to the RT code are loaded into a buffer, and then an interrupt is sent to indicate to the RT code that the data has been loaded. The operative part of the RT code, as far as FPGA is concerned is shown in Fig. 15.6. It first sets up communication with the FPGA module (RIO0). The FPGA buffer is configured for shared memory transfers (with DMA) and does the actual communication with the module. It uses the Interrupt as the interlock. The code waits for the Interrupt from the FPGA module. Then it reads both the elements from the FIFO, as an array which is then handled normally. The two AO values are transferred without the use of any buffers. Once the transfers are complete, the interrupt is acknowledged, which in turn releases the FPGA code and allows it to proceed. Outside the loop the communication channel is cleared,

182

Virtual Instrumentation Using LabVIEW

and an error handler is placed as usual. Strictly, the error status should have been ORed with the stop button, which is not done here for the sake of clarity.

Fig. 15.6 FPGA Code

The alert user may notice that AO2 is of the data type FXF. This is a new data type created primarily for the not-so-expert user. If the user looks at the properties then this data type occupies 20 bits, i.e., 4 bits longer than I16.

Fig. 15.7 RT code for above

Two things should be noted. Since the FPGA transfers are in the form of an array they must be of the same type. Secondly, in a very general sense, the structure of the open and close communication channel is the same as is done in the case of code for DAQ, etc.

Distributed Systems

183

One thing the user will often employ is the Data Manipulation sub-palette (Fig. 15.8) under the Numeric palette. Particular attention is drawn to the Join and Split Numbers functions. Since modern computers are intrinsically 32-bit (and increasingly 64-bit), it is efficient to combine multiple values into entities of that size. Fig. 15.8 Data Manipulation palette This is done through the ‘join’ and ‘split’ operations (Fig. 15.9). For example, using Join Numbers, two 16-bit values can be joined into a single 32-bit number. This 32-bit number is then transferred across. When required, using the Split Number function, the two 16-bit numbers are retrieved. The only restriction in using these functions is that the two numbers must be of the same length. This also shows why the authors are not too keen on the use of FXP to transfer numbers in FPGA coding. Fig. 15.9 Join and Split Looking at the operation of the code, it will be obvious that the FPGA code and its RT interface are to a very large degree not as universal as the normal LabVIEW code; the degree of customisation being far higher. In the example, the mechanism for the transfer of data from the RT code to the normal code is also not shown. The RT code can be controlled through various mechanisms. Depending on how tightly the RT and normal code are linked, various mechanisms like Data Sockets and Shared Variable are available. Shared Variable (Fig. 15.10) is often the fastest way of communication with a very tight binding between the target and the host. Data Sockets may be somewhat slower, more appropriate for frequent batch exchanges of information. If the RT code is stand-alone then the web server is often the preferred route to interact through the front panel. Often, systems are set up to operate and gather data into files in the RT platform. Here, many RT platforms have in-built ftp servers, which can then be Fig. 15.10 Shared variables used through a normal ftp operation (from within or outside) LabVIEW for communication.

184

15.3

Virtual Instrumentation Using LabVIEW

II

OPERATING IN A BATCH MODE The FPGA code has to be compiled, which is a batch operation. The code is translated by LabVIEW into VHDL. There a Xilinx compiler is invoked to generate the actual bit stream. The FPGA (and its associated RT code, if present) may be kept in the parent system running normal LabVIEW from which it is downloaded into the target(s). It can also be made self-starting and then permanently downloaded to the target. Here again, the advantage of LabVIEW is evident. The code can be developed using a high-level platform, and then made into a stand-alone application. This cuts down the development time and effort. Once complete, the user still has the capability of easily accessing and modifying the code if needed for removing bugs, or for upgradation.

15.4

II

WEB SERVER vs. DATA SOCKET Quite often there is need for a computer connected through Ethernet at the top end. This may be used only for monitoring, or may also be used for control. There are essentially two methods of setting up this link– web server and data sockets. These are discussed in Chapter 14. A web server replicates the front panel at the monitoring or managing site. Control capabilities may not necessarily be provided. Using the web server, the front panel (of the compiled program) is available through the standard http:// protocol (with or without control), and is relatively easy to set up. No code is required at the top end system. On the other hand, a data socket link requires that both the master system, and the system being addressed have some code resident in them. Data Socket Transfer Protocol (dstp://), though approved by the US Department of Defense, is not a standard TCP/IP protocol. Hence, the use of data sockets requires that the data socket server be started by the user. This protocol obviously has closer linkage between the two systems, permitting far more interaction–it is less verbose since the data rather than the front panel is transmitted.

SUMMARY

go into more details at this stage. therefore, somewhat beyond the scope of this book.

16 THE VI LAB INTRODUCTION As will be evident to the reader, the LabVIEW environment is a highly interactive one and a teaching laboratory will be a necessity. While some users of application, and would have the hardware (and users will be more interested in a general set-up. To learn LabVIEW, use the Learn LabVIEW with Activities section of the documentation. Users of newer versions will be able to locate equivalent material. However, a

One course (Postgraduates (PG) and 7th semester Undergraduates (UG)) is open only to Electrical Engineering students, while the second one (PG and 8th/6th semester UG) is open to all other disciplines. The courses comprise of one semester (14 teaching weeks) with two lectures (1 hour) and one laboratory (3 hours) every week. The last 1/3rd of the laboratory

and 3 are given out together so that the students can been evolved at IIT Kanpur over a number of years. These will be elucidated in this chapter. At IIT Kanpur, LabVIEW courses are available as electives to students from all disciplines. Two

16.1

and RS232 can be moved around with minor changes depending on convenience.

II All courses use the Virtual Instrumentation Laboratory which has a total of 10 workstations available to the students. All systems are Pentium class machines with 1GB RAM and 14” TFT and a few 17” CRT monitors, and Optical Mice. The systems are networked. In addition there is an instructor’s station, which is again a P-IV system to which an inkjet colour printer is attached. This is shared by all the student stations. While the 17” monitors are run on a

186

Virtual Instrumentation Using LabVIEW

1024 ¥ 768 resolution the 15” units run on 800 ¥ 600. The systems are running either Windows XP or Windows 2000. LabVIEW Full Development System (or Professional Development System) is loaded on all the workstations. Each workstation is equipped with one multi-function Data Acquisition Card (mostly PCI-6024Es; See—Fig. 16.1 Plate 2), and a DAQ Signal Accessory (being progressively replaced by the BNC2120; See—Fig. 16.2 Plate 2) for DAQ experiments. In addition each system also has a PCI-GPIB board along with an Instrument Simulator with both GPIB and RS232 cables. Single units of various other types of hardware—Motion, Fieldpoint, Image, fast DAQ, PXI, etc., are available in various laboratories and students may use some of these in their respective mini-projects, as required. The laboratory can have one or two users per workstation. Usually, having more than 10 workstations operating at the same time is not practical. Thus, the effective laboratory class size is restricted to 20. For larger groups of students, it is recommended that the number of laboratory groups be increased rather than the class size. If two laboratory sessions are run, then a class of 40 can be accommodated in two laboratory batches. It is advisable that the laboratory has some or all of the NI Instruction packages, since these are excellent reference works for the beginner. The mini-projects are mostly undertaken in different laboratories. This way the students get to work on real problems, and at the same time the institution benefits by having various small tasks solved. If the instructors’ in-charge of the mini-project have sufficient LabVIEW exposure it is often possible to split a relatively larger problem into a set of smaller projects, which can be combined into the full solution. Various problems solved this way at IIT Kanpur include Instrumentation of Flight Laboratory (three mini-projects), data collection from various sensor signals in the National Wind Tunnel Facility (at least a dozen), automation of DAQ from Instron Universal Testing Machine (one project), DAQ from X-ray diffractometer system (one project), etc. NI ELVIS (Educational Laboratory Virtual Instrumentation Suite) is currently being evaluated for the course. ELVIS (Fig. 16.3—See Plate 3) comprises a benchtop workstation which includes the expensive parts, namely, the power supplies, function generator, the I/O hardware for connecting the multifunction board, etc. The prototyping board sits on top of the workstation. It has I/O connections in the form of a main connector to the workstation for power, variable power supplies, variable function generator, along with virtual DMM and oscilloscope. Additional connections are provided through banana jacks, BNC connectors, a 9-pin sub-D connector, etc. There is a large prototyping area. This approach permits students to share the expensive resource (DAQ and Workstation) and have individual boards which can be plugged in for testing whenever required. While the utility of ELVIS for regular undergraduate and

The VI LAB

187

postgraduate projects is obvious the utility of the same for mini-projects has to be evaluated over a period of time. It should be useful in applications with a hardware bias in the field of electrical and electronics engineering. If procurement of the NI ELVIS is planned then it is advised that additional prototyping boards should be procured at the same time. A 2¥ or even 3¥ multiplexing should not be a problem. The exercises may have to be modified to make the best use of ELVIS of the DAQ Training Accessory is dispensed with.

16.2

II

LabVIEW VERSIONS LabVIEW is available in three different versions—Basic, Full Development, and Professional Development systems. In addition there is also LabVIEW RT for distributed applications. The base system is at the bottom of the ladder. It is a fully functional system but lacks the Advanced Analysis Library, which is useful in many disciplines. The Full Development System (FDS) is the workhorse for most educational applications. It includes the Advanced Analysis Library. Some of the exercises presented in this chapter may not be possible without this library. The Professional Development System (PDS) adds the Application Builder to the FDS. Using the Application Builder one can compile LabVIEW code into a stand-alone application. In addition, it also permits a few additional facilities, like permitting user VIs to be saved in a recursive mode. A recursive VI can have multiple copies running, each with its own set of parameters. LabVIEW RT came about for two reasons. Firstly, Windows is not a Real-Time Operating System (RTOS). Thus, tight timing cannot be guaranteed. Secondly, in distributed computing the hardware has its own processor (and memory), which runs on an RTOS kernel. This needs to be programmed. Under LabVIEW RT, the bulk of the code including the front panel resides on the host PC. The downstream processor is loaded with the minimum of code (under RTOS) for the actual execution of the application. This code running under RTOS makes use of hardware timing, etc., for tight execution of code with a minimum of latency. LabVIEW RT is only available in one version which is essentially the PDS with additional RT support. For student use, a low-cost version called the Student Edition (LabVIEW SE) is distributed by NI. This is an FDS with a few minor restrictions. For most users the only functional difference is the watermark of the student’s edition displayed whenever the SE is run. Also, SE does not support hardware drivers. There are versions of the LabVIEW for Personal Digital Assistants (PDAs) used for connecting to systems in remote locations.

188

Virtual Instrumentation Using LabVIEW

NI also distributes Software Solutions, which includes all tools including LabVIEW, LabVIEW RT, LabWindows CVI, Measurement Studio, DiaDem and all toolboxes, for various platforms on a departmental or institutional license for academic use. This is much cheaper than the components bought individually and may not be a bad option for heavy users.

16.3

II

LabVIEW TOOLBOXES LabVIEW (and LabWindows CVI) is supported by a vast selection of toolboxes for specialised applications. These are small collections of code specific to the application, and are used because they save a lot of development time. Some toolboxes available are the following: Signal Processing Toolkit: This is useful for time-frequency analysis and digital filter design. It includes support for wavelets, model based (super-resolution) spectral analysis and joint time-frequency analysis. Digital filter design permits the interactive design of finite and infinite impulse response filters. Sound and Vibration Toolset: Supports audio measurements, partial-octave analysis (standard way of measurement prior to extensive use of Fourier analysis), sound level measurements, frequency response, transient analysis, etc. In addition there are specialised toolkits for Order Analysis, Modulation, Spectral Measurements, etc. State Diagram Toolkit: This provides the basic tools for the interactive development and implementation of state machines. The Enterprise Connectivity Toolkit: It is also available separately in the Database Connectivity and SPC toolkits. These kits find use in large organisations for MIS functions. The VI Analyser Toolkit carries out a large number of standardised tests to ensure that a VI is robust, memory efficient, and are also used for report generation on the tests. The Internet Toolkit adds XML, CGI and FTP capabilities. The Report Generation Toolkit interfaces LabVIEW with MS Office (typically Excel and Word). The DSP Test Integration Toolkit, as the name suggests provides high-level tools for electronics design engineers. Math Interface Toolkit: Provides the seamless interface for LabVIEW developers to use MATLAB. Even though MATLAB can be invoked through ActiveX the various limitations of ActiveX apply when this approach is used.

The VI LAB

189

The Industrial Automations OPC Servers provide the necessary tools for Supervisory Control and also help integrate applications in LabVIEW, LabWindows CVI, Measurement Studio and Lookout. The PID Control Toolkit is invaluable for developing control applications using 1-, 2- or 3-term control. The Fuzzy Logic Toolkit which was a separate product in the very early days is now a part of this toolkit. The Simulation Interface Toolkit when used with Simulink (with Real Time Workshop) provides a seamless integration of the two. With increasing emphasis on simulation, this integration right at the development stage can considerably cut down the total time and effort for developing.

16.4

II

LABORATORY EXERCISES The Laboratory exercises are divided into a total of eight sets. These are more or less designed for a session each, though some are longer. The lab and lectures have to be run in synchronisation, and in the beginning of the course the instructor may have to occasionally use of a part of the lab time in lectures.

LAB SET 1: GET STARTED Purpose: Familiarisation with

(Note: Please do all your work in the directory, C:\LabVIEW\) Exercise 1: Creating a Simple VI 1. Go to the Panel and using the NUMERIC section of the CONTROLS palette place a DIGITAL CONTROL on the screen. Label it Input. 2. Now add a THERMOMETER from the same palette. Label it Output. 3. Go to the Diagram and wire the two together. Note the colour of the wire. It should be of type Real.

190

Virtual Instrumentation Using LabVIEW

4. Use the OPERATE tool and change the value of the input and observe the changes in the thermometer. You may wish to use the continuous run button. (Stop the operation if you are using the continuous run button). 5. Change the range of the Output to –50 Æ 250. This can be done in two ways by using either the OPERATE or LABELLING tools. Click on the number you wish to change with either tool. A single click enters the edit mode and a double-click the replace mode. Do likewise for the Input. You will see the scaling automatically adjust. 6. Save the VI. Ensure that you are in the correct directory and the file has the extension.vi. 7. You can try replacing the Digital Control by a KNOB. To replace an object you select the object, right click (or pop-up) on it, and then choose Replace. Exercise 2: Navigation and Editing Use Open VI to open Editing Exercise.vi in the course directory. Now follow the instructions as given in the supplementary sheets, and edit the VI. If you wish to save the exercise please use some other name. Please take your time since navigation and editing must be mastered in order to learn Lab VIEW. You also try and familiarise yourself with the Tools, Function and Control Palettes and their operation. (This is the Editing Exercise in LabVIEW Basics-I course of NI. If not available then a simple activity involving moving and resizing objects, handling free and owned labels, changing the colours and size of LEDs, can be designed.) Exercise 3: Developing a VI 1. Open the VI developed in Exercise 1. 2. Modify the VI to make a Degree C to Degree F converter. For this you take the input using the standard formula °F = (°C ¥ 9/5) + 32. To do this you have to break the wire from Exercise I, and then working with the diagram incorporate the MULTIPLY and ADD functions. 3. Test out as before and save. Exercise 4: Converting the VI into a Sub VI In this exercise we convert the code into a sub-VI. 1. Open the °C to °F converter. 2. In the Panel, right click on the ICON (top right hand side) and select Edit icon.

The VI LAB

191

3. Now modify the icon to whatever you like using the tools of the Icon Editor. 4. Now open the Select Connector as in step 2. The connector with two sections will be displayed. Now you associate the connectors with the Controls and Indicators. Click on the lh connector (colour changes from White to Black) then click on the Digital Control and then anywhere on the panel. The colour of the connector should change from black to the colour indicative of the type of data. This indicates that the connection has been made. Repeat for the Thermometer indicator and the rh connector. 5. Your VI is now ready. You should return the display to the Icon. If you see help then you will see the connection diagram of the VI with the terminals, etc. 6. Save the VI. You have just created your first VI capable of being used as a sub-VI. You can try to incorporate it into a VI as a module. 7. Now go back to and open the °C to °F converter. Just block the code for the converter leaving the Control and Indicator outside. Now going to the Edit Æ Create VI menu convert the blocked out text into a sub-VI. You may now change the icon, and also modify the wiring pattern. Exercise 5: Some Advanced Work This exercise is to expose you to some of the goodies to come. 1. Create a simple function say Random Number Generator (from the Functions- Numeric Palette which gives a 0-1 output), multiply by 100 and then connect to a display (digital/thermometer, etc., as you like it). 2. Now using the functions palette put a FOR LOOP around it. Click on the FOR LOOP and then POSITION and DRAG to encapsulate the earlier code. Wire a constant of 20 to the counter. (Note the blue colour for Integer). Add a delay (using wait until next ms multiple) of 200 ms from the Timing & Dialog section. Now you have a program that loops 20 times with a delay of 200 ms. 3. Operate and check the functioning. Save. Now we will add a graphical display. 4. Wire the ‘signal’ to a Waveform Chart. Keep the chart inside the loop. Use the pop-up to set both X and Y to Auto-scaling. Try moving the chart to outside the loop and see what happens. Now add averaging to the above. 5. Wire the ‘signal’ to the edge of the ‘For Loop’. You will see an icon or ‘tunnel’.

192

Virtual Instrumentation Using LabVIEW

6. From the Analysis set select the MEAN function (Statistics sub-palette). Position to the right of the tunnel. Wire the output of the tunnel to the Mean function. Note the ‘thicker wire’ as the For Loop ‘bundles’ the data automatically into an array. Now you add a display to the mean. Save.

LAB SETS 2 AND 3 Purpose: Familiarising with simple aspects of LabVIEW programming, including debugging, while loops, shift registers, local variables, etc. Arrays, Loops, Structures, Graphs 2.1 There is a logical error in the code. Use the debugging tools to trap and correct it. You should use the opportunity to familiarise yourself with the operation of the various debugging tools. Find the cause(s) of the broken wires and fix them. 2.2 As above. 2.3 Set up a while loop to execute EXACTLY the predefined number of iterations. For the test code place a shift register (initialized to 0) in the loop, increment the value by 1 and look at the value at the end of the loop. This test code is NOT to be used to control your loop. 2.4 This is a demonstration program, which introduces a few of the advanced functions from the signal-processing library. You should use this as a starting point for further experimentation. 2.5 Write a program to invert the state of a Boolean indicator twice a second, until the program is stopped by the user. The Boolean should initially be TRUE. You may wish to save this VI as it will be used in a later exercise. Solve the problem using two different methods: Shift Register, and Local Variables. 2.6 Write a program to count Modulus 32 and display the values in decimal, hexadecimal, octal and binary. The properties attribute is used to set the display type. Use a STOP button to stop your code programmatically. 2.7 Use local variables to stop a while loop and reset the Stop button in Problem 7. The action of the switch should be set to Switch When Pressed or Switch When Released. 2.8 Set up a temperature simulator as follows. Allow for a user-defined set point (you may place it inside the while loop). In the while loop add an error amounting to a maximum of ±10°C to the set point. Set up over- and under-temperature LEDs to light up whenever the deviation is >5°C. The loop should operate once every second.

The VI LAB

193

3.1 While Loop and Chart: Build a VI using the while loop that displays random numbers (0-5) into three Waveform Charts (strip, scope, sweep). Incorporate appropriate switching and delays. Using the Property Node modify your code to automatically reset the strip chart at the beginning of each run. For this you will have to reinitialise History at the beginning of each run. You will like/need to reset the strip chart in the majority of applications. 3.2 Shift Registers and Chart: Build a VI that displays two random plots on a single chart. These should be random numbers (0 < x < 10) and their five point moving average. The points should appear on your plot as points, while the trend line should be a solid line. 3.3 Square Root Problem: Develop a VI to check if a number is positive or negative. If yes then the VI should calculate and display the square root. Otherwise it should display a message and give a value of –99999.00 as output. Solve the problem using (a) Case Structure, (b) Select Function, and (c) Formula Node. You need not put up the display message for (b) and (c). 3.4 Case Structure: Build a Four-Function Calculator. Use a Menu Ring to select the function required. Add a Divide by Zero Trap to your code. 3.5 Timing, Arrays and Waveform Graphs: Write a VI to generate 150000 random numbers and display them in a continuous fashion on a Waveform Graph. This can be done in two ways: (a) add an element to the array in each iteration, and (b) initialise an array of sufficient length and then substitute one element every time. Develop both and then using Sequence Structures find the time taken in each case. Is the time uniform in both cases? Try and explain your observations. 3.6 Formula Node: Build a VI to compute and display the following equation (0 < x < 10) y1 = x3 – x2 + 5 y2 = mx + b 3.7 Global Variables: Set up two VIs as follows. One VI generates a reading of 80 ± 5 (error signal using a random number) every 500 ms, and has a Stop button. The second VI has a waveform chart, in a loop operating at the same time interval. Data is transferred from the first VI to the second through Global Variables. Run both the VIs at the same time, and try to understand the operation. Change the timing of either of the loops. What happens now?

194

Virtual Instrumentation Using LabVIEW

3.8 Temperature Monitor: Build a VI that continuously monitors the temperature (generated using Random Nos. 0 < T < 100) every 250 ms). There should be alarm limits, which can be set using panel controls. These limits along with the temperature should be displayed on a chart. Furthermore, an alarm should be lit up whenever the reading goes out of bounds. 3.9 Express VIs for Signal Processing: Using express VIs set up a simple signal simulation and processing system. Use the Express VIs for Simulate Signal, Spectral Measurements and Waveform Chart/Graph display for the code. Place your code inside a while loop which executes every 500 ms. You will need to adjust some parameters of the display to get meaningful results. Add noise to the sine wave, add filtering and display the power spectra, both before and after filtering. 3.10 Statistics with Express VIs: Set up a VI for computing a histogram. Generate 1000 random number with a pre selected range (it should be (– n1 < x < n2). Now use an Express VI to compute the histogram. Display the histogram in a Waveform Chart.

LAB SET 4 Exposure to

1. Simple Button Operation Write a VI to select and display between various button selections (say, Login, Configure, Acquire, Analyse and Exit). The code should display the option selected through a Single Button Dialog Box and execution should end only when the Exit button is pressed. Use Boolean Clusters. The mode of operation should be Latch when Released. Hint: In this and the next problem you get the selection through a cluster of Booleans. Then convert the cluster to an array. Now search for the occurrence of the ‘True’ state and connect to a case structure. A search of an array with no match returns-1. You may wish to examine the Radio Button programs in the sample programs provided by NI in ....\examples\general\controls\booleans\Using Buttons to

The VI LAB

195

Initiate Action, for both this and the next problem. The essential difference between the two is in that the mode of operation of the Boolean switches is different and the next problem also uses a Shift Register to ‘carry’ next STATE. Note that the best way to get identical buttons is to set up one button with the correct size, colour, operation, etc. Then replicate this to get the additional buttons. You can change the labels/captions of these additional buttons later. 2. State Machine Modify the code above into a full State Machine. On first running the VI the code should immediately ask for a Login. If configuration is selected then the VI should ask you if you wish to proceed to acquisition (use a two-button dialog box). On confirmation, the code should directly go into data acquisition, otherwise it should drop back to the main menu. On operating the Exit button it should ask for validation before stopping. The mode of operation of the buttons should be Switch When Released. You will have to provide appropriate ‘reset’ for the button(s). Modify and solve the problem using Event Structures. 3. Function Generator This VI can produce sine, square, triangle and sawtooth waveforms. Try changing the front panel controls and observe the signal on the display. You have to duplicate the front panel and develop the Diagram. Make sure you save your code since we will use this code later to form the basis of a real function generator*. 4. Binary Counter Set up a 8-bit binary counter and display your results graphically. The graph should have 8-traces corresponding to bits 0–7. For this you may like to do the following: Number to Boolean Array, Boolean to (0,1). (Hint: Initialise 8-numeric arrays. Then separate out each bit of the count and add to the appropriate array.) LAB SET 5 Instrument Simulator under RS 232C In this exercise you will use the National Instruments Instrument Simulator to carry out some Input Output on the Serial Port. The Instrument Simulator

196

Virtual Instrumentation Using LabVIEW

can simulate a DMM or a function generator under both GPIB (near 488.2) and RS232C. The data is identical in both except that under RS232C each communication from the Instrument is prefixed by seven bytes in the form nnnnn. These seven bytes have to be read first and then ‘nnnnn’ bytes read from the Serial Port. Problem 1: Write code to read and display the data from INSTROUT.TXT and then interpret and display it in a Waveform Graph. Make your data interpretation routine (Input—Data String, Output—Array of Real Numbers) into a sub-VI. You will use this sub-VI later. (Hint: Use the following VIs—Read characters from file, Match pattern, Scan from string, Spread sheet string to array) Problem 2: Check that your Instrument Simulator is set up for Serial Communication at 9600 bps, 8 data bits, 1 stop bit, and no parity. It uses the RTS/ CTS protocol by default. For this the DIP switch settings are SW1-Ø≠Ø≠≠≠Ø≠, SW2-≠≠≠≠≠≠≠≠. SW1 settings can be interpreted as follows: Ø≠Ø-9600 bps, ≠≠-no parity, ≠-one stop bit, Ø-8 data bits, ≠-serial mode. GPIB with Primary Address 2 will use ≠Ø≠≠≠≠≠Ø. NEVER CHANGE ANY DIP SETTINGS WHEN POWER TO THE SIMULATOR IS ON. You will use VIs from the InstrumentIO Æ Serial palette in this and subsequent exercises. Write a VI to – (i). configure the serial port for the settings you have. By default all handshakes are disabled. (ii). Send the appropriate command(s) to the simulator, (iii). Read the data packet length and the data packet from the simulator. You may wish to write your VI in the following format: (a) Configure the Serial Port. (b) Set up a while loop. (i) Send the command from the Panel after adding the terminator to the simulator whenever the SEND button is pressed. (ii) Read and display the string from the Simulator. Here, the read will be in two stages. First you read and interpret 7 bytes for the data stream length, and then read the rest of the data. (c) Watch the LED operation on the simulator while the transactions are taking place. (d) You may also perform the read and write using the terminator. In this case you will need to read twice, first to get the Byte count and then the actual data string. You do not use the byte count here.

The VI LAB

197

Problem 3: Write a VI to get the selected waveform from the simulator and display it graphically. You use the sub-VI from Problem 1. Try to do the solution using both Byte Count and Terminator methods. Problem 4: Write two VIs. The first should be an add-on to Problem 3 which writes the code to a spreadsheet file on demand. The data should be delimited with eight points per line with a three digit precision (use the e-format). The second should be a VI to read and display this file. LAB SET 6

GPIB Interfacing: In the previous exercise you have used the National Instruments Instrument Simulator to carry out some Input Output on the Serial Port. Now you will work with the unit under GPIB. The data is identical in both except that under GPIB the Byte Count of RS232C nnnnn does not appear in the output. Also, there is no terminator to be sent to the instrument in each command. The switch settings for GPIB with Primary Address 2 on SW1 are ≠Ø≠≠≠≠≠Ø). SW2 remains at ≠≠≠≠≠≠≠≠ as before. Problem 1 (no LabVIEW): Operate the Instrument Simulator under GPIB using the interactive controller of the Measurement and Automation Explorer. Examine the interface settings on the PC. Observe the operation of the various indicator lights. You might like to try the following communication methods, viz., Devicelevel and board-level. (a) Device-Level Communication devname IBWRT string to send (enclosed within double quotes) IBRD # of characters Example: IBFIND DEV2 , IBWRT “*IDN?” , IBRD 100 (b) Board-Level Communication IBFIND devname (specify the Board name, GPIB0) IBSIC (for clearing and initialising GPIB) IBSRE value (for controlling the REN line. a 0 value unasserts, a non-zero value asserts) IBCMD “list” (list is the list of characters used as Command messages to configure the GPIB) IBWRT string to send (enclosed within double quotes) IBRD # of characters

198

Virtual Instrumentation Using LabVIEW

Example: IBFIND GPIB0 , IBSIC , IBSRE 1 , IBCMD “@?\x22” , IBWRT “*IDN?” , IBCMD “? B” , IBRD 100 Please notice the space between ? and B in the IBCMD list. Note: “@” corresponds to My Talk Address 0, “?” is UNL, \x22 is My Listen Address 2, “ “ My Listen Address 0, “B” is My Talk Address 2. Problem 2: You have to set up a while loop to 1. Send the command from the Panel to the simulator whenever the SEND button is pressed 2. Send the command and then get the data from the Simulator whenever the READ button is pressed 3. Watch the LED operation on the simulator while the transactions are taking place 4. Do not carry out the commands more than once otherwise the unit will hang. Problem 3: Modify the code to be able to get the various types of the waveform from the simulator by selection from the front panel. For this you will need to use the appropriate String VI to select the part of the command selecting the waveform. Add an option to store the data to an ASCII file after reading. Try and solve the problem in both IEEE488.1 and 488.2. Problem 4: Use Express VI’s to solve part of Problem 3 (for a single waveform). Do you get all the data in the output array? Try and get all of it. Problem 5: Combine your code in Problem 3 with the one in the previous exercise (RS232C) so that by selecting a switch on the front panel, you can operate the simulator in either GPIB or RS232C. Be careful since you must switch off the power to the simulator before changing any switch setting. (This problem is optional.)

LAB SET 7 DAQmx and Express VIs Purpose:

Familiarisation with the operation of DAQmx and Express VIs.

The VI LAB

Exercise 1:

199

Simple exposure to DAQmx (no LabVIEW work)

1. Using Measurement and Automation Explorer (on the Windows Desktop) play with the DAQmx mode of operation. Familiarise yourself with the operation of the DAQ board under DAQmx. DO NOT GO TO THE OLD DAQ MODE OF OPERATION. Exercise 2: Digital Line Output 1. Load LabVIEW and write a small program using Express VIs to invert a Boolean every second. Display on the DAQ Training Accessory. It is pre-wired so you have bits 0 to 3 visible. Also, it is negative logic. 2. Run the VI and observe the behaviour of the LED’s. Exercise 3: Digital Byte Output 1. Create a VI using Express VIs to write an integer to Port 0 of Board 1. 2. Put it in a loop that executes every 200 ms, with a Stop button to end the run. 3. Write an integer (0–15) to this port through a control. Set up an indicator to display the binary value and compare with the LED pattern. Make sure they match. 4. Modify the code to count and display from 0 to 15 every second. Your program should automatically restart from 0 after counting to 15. You should be able to stop execution at will. Exercise 4: Multi-channel data acquisition and array operations DO NOT USE EXPRESS VIs. 1. Write a VI to acquire 500 points from channels 1 or 2 in a burst mode. 2. Display these on the waveform chart. Exercise 5: Multi-channel data acquisition and array operations DO NOT USE EXPRESS VIs. 1. Write a VI to continuously acquire 500 points each from channels 1 to 2. 2. Display these on the waveform chart. 3. Scale and offset the sine wave so that the two plots do not overlap. Depending on the availability of time you may wish to use an Express VIs to output a noisy signal produced using the Simulate VI, and then read it using a VI developed using DAQmx (Express or otherwise). Remember the maximum update rate on the AO in the 6024 is 10,000 ks/s.

200

Virtual Instrumentation Using LabVIEW

LAB SET 8 Data Acquisition I (Conventional DAQ) Note: When you close VIs LabVIEW may want to modify some Internal VIs. Please do not allow this. Answer No To All. Purpose: Familiarisation with MAX, Digital Output, Analog Input using simple VIs. You should ensure the following wiring on the DAQ Accessory Output of the sine wave generator to AI Channel 1 and the Square Wave to AI Channel 2. The room temperature sensor is internally connected to Channel 0. Exercise 1: Simple exposure to DAQ (no LabVIEW work) 1. Using Measurement and Automation Explorer (on the Windows Desktop) examine the settings of the hardware you are using. Note the Board Number. Make sure the connection is Differential. This will be required in subsequent exercises. Also, identify the board that is installed in your system. 2. Run the test panel in DAQ (not DAQmx) and see the signal in channel 0 (AI). This is the room temperature sensor of the Signal Accessory/BNC 2120 giving 10 mV/°C. 3. You may place your finger on the sensor to warm it up and observe. Also, change to gain settings and see how the resolution affects the observed signal. 4. Switch the noise generator on and off and observe the signal (not in 2120). 5. Run Test Panels in various modes for Channels 1 and 2. 6. Select DIO and under DO operate the DO line buttons. Observe the behaviour of the lights on the accessory. In practice you can use the DO lines to control various devices through relays. Please note that the Signal Accessory only shows the lower nybble, and that too in negative logic (BNC2120 has the full byte in normal logic). Play with the various options to get familiar with the DAQ hardware. Exercise 2: Digital Line Output 1. Write a small LV program using Simple VIs to invert a Boolean every second. 2. Run the VI and observe the behaviour of the LED’s.

The VI LAB

Exercise 3:

201

Digital Byte Output

1. Create a VI using to write an integer to Port 0 of Board 1. 2. Put it in a loop that executes every 100ms, with a Stop button to end the run. 3. Write an integer (0-15) to this port through a control. Set up an indicator to display the binary value and compare with the LED pattern. 4. Modify the code to count and display from 0 to 15 every second. Your program should automatically restart from 0 after counting to 15. You should be able to stop execution. PLEASE DO NOT USE THE WAVEFORM DATA TYPE OUTPUT IN THE NEXT 3 EXERCISES Exercise 4: Single point Analog Input 1. Use a single point measurement simple VI to measure Board 1, Channel 1. Put into a FOR Loop of 100 values and display the measurements on a Waveform Chart. 2. Try and find out the time taken for 100 measurements. This gives you some idea of the speed with which your system can carry out single measurements. 3. For a simple Digital Voltmeter will this type of measurement suffice? For acquiring a 1kHz wave form? Exercise 5: Simple Analog Input and Aliasing 1. Connect the sine wave generator to Analog Input Channel 1. 2. Keep the generator in the 100-Hz–10-kHz range. 3. Use Express VIs in the multipoint mode the system up for Channel 1, 500 samples at ~1000 samples/sec. 4. Connect the output to a Waveform Chart. Set the Y-axis to autoscaling, X-axis to 500 points. Open a second waveform chart to show only 50 points on the x-axis. Set up to reset the display at the beginning of every run. 5. Run the VI. Observe the envelope and waveform. 6. Slowly vary the frequency and repeat (May use ‘Run Continuous’ button). 7. Feed the data to the Power Spectrum VI and show output on a Waveform graph, setting the X-axis to the appropriate frequency. 8. Observe the power spectrum under various conditions of aliasing.

202

Virtual Instrumentation Using LabVIEW

Exercise 6:

Multi-channel data acquisition and array operations:

1. Write a VI to acquire 500 points each from Channels 1 to 2, in the ‘burst mode’. 2. Display these on the waveform chart. 3. Scale and offset the sine wave so that the two plots do not overlap. sockets).

LAB SET 9 Advanced Topics Purpose: Familiarising with use of Advanced Concepts (Notifiers and DataSockets). Exercise 1: Set up two while loops as follows. In the first loop generate a sinusoidal waveform a point at a time. You may multiply the Index by 0.01 and the take its sine. Also, put a Stop button in the loop and then run the loop once every 50 ms. In the second loop have a waveform chart to display some data. Set up a notifier to transfer both the data values (Sine and Stop) through a ‘notifier’ to the second loop where the values are separated and the Sine fed to the Waveform Chart, and the Boolean to control the loop. Now run the VI and observe notifier operation. Note that the second loop is synchronised even though there is no delay in it. Note: Good coding practice suggests that the notifier is destroyed from second loop. Why? Next try to use two notifiers one from Loop 1 to Loop 2 and the other from Loop 2 to Loop 1. Exercise 2: In this exercise you will set up a simple Data Socket operation. Modify the code of the previous exercise to use Data Sockets by splitting it into two VIs. One VI sends the data of the Sine to the second VI while the second VI sends the State of the Stop button to control the first. The Data Socket connections are set up by popping up on the indicators/controls as appropriate and using Data Operations Æ Data Socket Connection for the purpose. Once Data Socket is activated a small LED is created adjoining the object. Run the code and test. Remember to fire up the Data Socket server. You may use localhost on the same PC or test using two PCs. Exercise 3: Take the code from the pervious exercise. Disable the Data Socket operation, and then add proper data socket VIs to repeat Exercise 2.

The VI LAB

203

Exercise 4: Take the code of Exercise 3. You now have to send the value of the Iteration-terminal along with the Sine value to the second VI. For this use the Set and Get Variant Attribute functions. Join up with a pair of colleagues on another system and actually get DataSocket Operations to work on two systems. Exercise 5: Remote Control of a VI using Web Server/Web Publishing (i) Write a VI to acquire a sine wave continuously (or burst) from the BNC2120/DAQ Accessory on channel 1. Use DAQmx VIs. Display the signal on a waveform chart. (ii) (a) Configure Web server (Tools >> Options >> Web server: Configuration). Enable Web Server. Enter IP address of your machine as IP address of listener. Leave all defaults as they are. Press OK. (b) Configure Web Publishing Tool (Tools >> Web Publishing Tool ). On page 1 select your VI. Under Embedded, tick Request control….. Press Next. Type Document Title, Header and Footer, as required by you. Press Next. Edit file name of the html file (if required, else the existing VI name will be the name of the html file). Press Save to Disk. On the next window press ok. (iii) Keep the VI open. Launch Internet Explorer on your neighbour’s PC. Enter the URL of the html file correctly (eg. http://172.29.26.45/DAQ1.html). If everything goes fine, the Front Panel (with Title, header, and Footer) will be downloaded on the client PC. Run the code. Observe operations such as Request Control, Release Control.

17

LabVIEW RESOURCES INTRODUCTION

In the modern connected age, finding and using various resources is no problem at all. They may be available through the Internet, or in books etc. What is important is how to make best use of these resources. This chapter presents some resources which are useful and can be used fairly regularly in day-to-day

17.1

II

work. Articles on LabVIEW are readily available over the Internet. A recent search for LabVIEW on Google gave over three million references! Being able to locate useful information is thus of paramount importance to the user.

INTERNET RESOURCES

Learning Resources Beginners can find many LabVIEW tutorials on the web. Searching through National Instruments site (www.ni.com) can also uncover valuable information, both for beginners as well as experienced users. The section on Interactive Tutorials (http://www.ni.com/events/tutorials/campus.htm) has a lot of useful information available not only for LabVIEW (an interactive Web Tutorial ‘LabVIEW in Six Hours’ is currently located in the campus2 directory) but also many other aspects of Intelligent Instrumentation. Many other resources are available in the Learning Center of the NI Developer Zone. Exact URLs have not been given since they change frequently. The users should go into the areas specified and search for titles of interest. It should be noted that the very advantage of the Internet is also a handicap in putting a list into print, since sites may be added, dropped and changed so frequently.

LabVIEW Resources

205

Many universities are putting interactive tutorials on the web. However, the exact URLs change often, say once a year or so, so the user is better advised to do a search and then select the resource rather than list these here. NI keeps the support files for LabVIEW at http://www.ni.com/support/ labview/, with the toolkit support in the toolkits subdirectory. The academic page of NI at www.ni.com/academic also has a lot of useful information on academic applications, specially priced bundles, etc. Users may be well advised to browse in www.ni.com which is the corporate site of National Instruments. User Groups and Other Resources With the number of sites for LabVIEW reaching unmanageable levels, it is useful if a few well-tried and tested sites are identified by the user. The first place to look for information on LabVIEW is the site of National Instruments, www. ni.com. This is a well maintained and documented site with a lot of information, and support for LabVIEW. The user looking for information or the latest driver is well advised to start his/her search from here. The main user group for LabVIEW is Info-LabVIEW and is maintained independent of NI. It was set up in 1991 and managed for a long time by Tom Coradeschi. In mid-2004, the management of the email list was passed to Scott Hannahs at the National High Magnetic Field Laboratory, USA. The group correspondence is available in two forms—individual postings or a digest containing all the mails posted during the day. To subscribe to the former, send a mail to [email protected]fl.gov. For the digest, send a mail to [email protected]fl.gov. Info-LabVIEW does not permit the posting of VIs or binaries which the users may exchange through private mail. Further details are available from http://www.info-labview.org. An excellent source of information (and a very useful function library) is the VI Package Manager (Open G) library from www.jkisoft.com/vipm developed by Jim Kring. iLabVIEW is the primary user group for LabVIEW users in India. It was started in Bangalore in December 2002 during ‘NI Day 2002’ (the annual event organized by National Instruments, India). It is coordinated by Ganesh Devaraj of Soliton Technology (earlier Soliton Automation). Soliton is the oldest Alliance Partners of NI. It is hosted as a Yahoo Group. User group meetings have also been held in Bangalore where presentations were given on different LabVIEW topics. To subscribe, send an email to [email protected]. There is also a LabVIEW Technical resource (www.ltrpub.com) which is a paid service and highly spoken of.

206

Virtual Instrumentation Using LabVIEW

To sum up the current status of LabVIEW resources, one can do no worse than to quote a recent input from Scott Hannahs, the administrator of the LabVIEW User’s Forum. “To join or leave info-LabVIEW, the email addresses are now [email protected] and [email protected]. This can also be done through a web page at http://sthmac.magnet.fsu.edu/infolabview or at this more obscure address http://opsxserve.magnet.fsu.edu/mailman/listinfo/ info-labview (I may try to simplify the server at some point). There are a lot of other web resources out there these days. Here is a *partial* list off the top of my head blogs: ‘Eyes on Vis’ Christina Rogers http:// eyesonvis.blogspot.com/ ‘The MacView’ Marc Page http://themacview.blogspot.com/ of course! ‘Inside LabVIEW’ John Pasquarette http://pasquarette.wordpress. com/ ‘Thinking in G’ Jim Kring http://thinkinging.com/ ‘LabVIEW Mastery’ Ben Zimmer http://www.lvmastery.com/ ‘VI Shots’ Michael Aivaliotis http:// vishots.com/ ‘Expression Flow’ Tomi Maila http://expressionflow.com/ ‘Emerging Technologies for Virtual Instrumentaion’ Hall T Martin http://emertech.blogspot. com/ ‘LabVIEW Artisan’ Darren Nattinger http://labviewartisan.blogspot.com/ Web BBS ‘LabVIEW Advanced Virtual Architects’ http://lavag.org/ Code Repositories http://www.mooregoodideas.com/goodLabViewStuff.htm”

Thanks Scott for the inputs!

17.2

II

BOOKS With the increasing popularity of LabVIEW there has been a veritable explosion of books dealing with it. A web search on Amazon resulted in more than 2.7 million matches for LabVIEW. For specific applications, users should do likewise and find the appropriate text(s). The first authoritative book on LabVIEW was LabVIEW GraphicalProgramming by Gary W Johnson. Its fourth edition (by Gray W Johnson, Richard Jeninngs) was published by McGraw-Hill, New York, USA, in 2006. This book is an exhaustive reference and is targeted at the intermediate/advanced user. The majority of LabVIEW experts swear by (and occasionally at!) this book. For learning LabVIEW, the ‘official’ guide is authored by Robert Bishop and Published by Prentice Hall. This is also supported by NI. An excellent beginner’s text is LabVIEW for Everyone: 3rd Edition by Jeffrey Travis and Jim Kring (Prentice-Hall, 2006). One excellent book for serious users is The LabVIEW Style Book by Peter A Blume, published by Prentice Hall in 2007. This book is acquiring a status akin to that of Johnson’s book in the universe of experienced LabVIEW developers.

Glossary Active Controller ADC Aliasing Analog Ground Anti-alias Filter

Array Array Shell

ASCII

ATN Attenuation Autoindexing

Bandpass Filter Bandstop Filter Bandwidth

The device capable of taking over the bus. It has the capacity to send commands, configure talkers and listeners, etc. Analog-to-Digital Converter used to convert analog signals to digital form, as n-bit numbers. Most commercial ADCs have n = 12. Misrepresentation of a signal due to sampling at a rate lower than the Nyquist rate. Also, called signal ground and used as a reference for all analog signals. A low-pass filter added at the input of the sampler and ADC in order to ensure that no frequency component is greater than the Nyquist frequency. A homogenous collection of a number of data elements. A framework through which an array is created. The array becomes an array of whatever data element is placed in the shell. Array of arrays is not permitted. American Standard Code for Information Interchange. The de facto standard for storing and handling information as text in 8-bit format. ATtentioN—one of the bus management lines used in GPIB. The opposite of gain, i.e. the loss in the amplitude of a signal. A mechanism in LabVIEW whereby elements of arrays can be handle ‘automatically’. By default Autoindexing is On in FOR loops and Off in WHILE loops. A filter that passes a certain band of frequencies. A filter that stops a certain band of frequencies. Used to specify the band of signals the particular circuit/hardware can handle.

208

Glossary

Binary File

Breakpoint Bundle Bus

Case Structure

Cluster Cluster Order Cluster Shell Common Mode Signal Condition Terminal Control Conversion Rate Count Terminal CPU CTS Cursor

Cut-Off Frequency DAQ DAQ Assistant

DAQmx Data Sockets

A file where data is stored as binary numbers. This is the most efficient form of storage but is seldom used since these files cannot be edited in a normal way. Also, binary storage is system dependent. A flag in code where execution is stopped. Used in debugging. Grouping elements together into a cluster. An interconnection which allows many devices to be connected in a parallel (or sometimes serial) way to the same interface. These may be internal to computers (like UNIBUS, PCI, etc.) or external (like GPIB, CAN, MOD). Used for conditional execution of code. In dataflow all outputs must be available from all cases irrespective of whether they are used or not. A collection of data elements which need not be homogenous. Same as a data structure or construct in classical languages. The order in which the various elements of a cluster are placed. Important for accessing them. A framework which is used to group all the elements placed in it into a single cluster. Signals which appear at both the input terminals of an amplifier, which may be large. Inputs the value on which the ‘condition’ is tested in a case structure. Conditions could be in Boolean, Numeric or String. A LabVIEW front panel entity which takes an input to the code. Number of analog-to-digital conversions per second. The user defined number defining the number of time a FOR loop will iterate. Central Processing Unit. The ‘brains’ of a computer. Clear To Send—hand shake signal in RS232C. A marker placed on a graphical display. It is used to mark or collect information about the trace(s). This may include the index, x and y values, etc. The cut-off frequency of a filter is the frequency at the boundary between the pass and stopbands. Data Acquisition. A graphical interface for configuring measurement tasks, channels, and scales. One also can use the DAQ Assistant to generate DAQmx code from the task. The latest NI-DAQ driver with new VIs, functions, and development tools for controlling measurement devices. A TCP/IP tool developed by NI for networked data transfers.

Glossary

Dataflow Datalog File DAV DCE Debugging DI Diagram Differential Configuration Digital Frequency Digital Ground Direct Memory Access (DMA) Discrete Fourier Transform (DFT) Dither DSR DTE DTR Dumb Sensor EBCDIC EOI Error In Error Out Event Structures Fast Fourier Transform (FFT)

209

A programming environment whose operation is controlled totally by the flow of data (as in LabVIEW). A type of file (specific to LabVIEW) for data storage and access. DAta Valid handshake signal issued by the active Talker. Indicates that the byte on data lines is valid. Data Communication Equipment (RS232C). Finding and removing logical errors. Differential Input connection, where the amplifier input is configured as differential. Has excellent Common Mode Signal Rejection. The ‘backplane’ of a LabVIEW program where the actual code resides. Used in differential amplifiers to cancel out the noise that is common to both input lines. The ratio between the analog frequency and the sampling frequency, with units as cycles per sample. Also, called ‘normalized frequency’. Point to which all digital signals are referenced. Analog signals do not use this reference due to noise considerations. Direct transfer of blocks of data to (or from) the memory without involving the CPU. DMA transfers are faster than normal CPU based transfers. A frequency domain representation of a sampled signal. The addition of noise to the signal to gain some additional accuracy in the measurement using statistical means. Data Set Ready—handshake signal in RS232C. Data Terminal Equipment (RS232C). Data Terminal Ready—handshake signal in RS232C. A sensor with no on-board intelligence. Extended Binary Coded Data Interchange Code. An 8-bit coding scheme similar to ASCII developed by IBM. Now obsolete. End Or Identify. Used by the GPIB Talker to indicate end of block; also used by System Controller to obtain parallel poll reply. An error cluster control used commonly in data acquisition and instrument VIs. An error cluster indicator used commonly in data acquisition and instrument VIs. Implementation of detection of front panel events through Interrupt Driven route. This was originally developed to cater to mouse clicks. Algorithms used for fast computation of DFT.

210

Glossary

Feedback (In Loop) Filter Firmware

For Formula Node Fourier Analysis Free Label Front Panel G Gain-Bandwidth Product Global Variable

GPIB GPIB Analyzer GUI

Hardware Hex

Highlight Execution

Highpass Filter

Functionally identical to the shift register. Added in LabVIEW 7. May have repercussions in RT or FPGA applications. An electronic circuit which passes signals of a certain band of frequencies and attenuates all other frequencies (see specific types). Parts of a computer which lie in between hardware and software. The prime examples of firmware things like the BIOS which are stored in PROMs. Even though a PROM is a physical device and can be classified as hardware, its contents are more in the nature of software. A repetitive operation of code which iterates a preset number of times. A way of embedding small blocks of text-based code in LabVIEW. This could be in C or the Backus-Naur notation. Representation of a signal as a superposition of several sinusoidal signals. Text which is used for decoration of a panel or a diagram and has no linkage to the code. LabVIEW term for the user interaction interface. Graphical programming language (probably inspired by C). A figure of merit used for an amplifier, which is a constant, higher the gain, lower the bandwidth, and vice versa. A mechanism through which a variable can be accessed from multiple positions. The scope of a global variable can be across multiple VIs on the same system. The Global Variable(s) reside separately except that unlike a VI; a Global has a Panel but no Diagram associated with it. General Purpose Interface Bus; also called IEEE 488. A special purpose card/instrument used to record and analyze all GPIB bus activities for debugging purposes. Graphical User Interface which permits the user to interact graphically with the computer, most commonly through the use of a pointing device like a mouse. Computer parts which are physical components. Handling of numbers as hexadecimals. In hexadecimal the count is to the base of 16 - 0-9, A-F. Hex permits each byte to be treated as two 4-bit entities called nibbles. A debugging tool operated through the light bulb icon on the diagram tool bar. It shows the actual data flow and values therein. However, it does slow down the execution dramatically. A filter that passes frequencies above its cut-off frequency.

Glossary

IFC Indicator Instrument Assistant Inter-Channel Delay Interrupts(IRQ)

Iteration Terminal IVI Listener Local Variable Loop Timing

Low-Pass Filter LVDT Mainframe MAX Minicomputer Multiplexer (MUX)

NDAC Nybble NI-Spy Normalized Frequency Notifiers NRFD

211

InterFace Clear—One of the bus management signals which initialises GPIB interface. Takes over control of the system. A LabVIEW front panel entity which shows the output of the code. A software module which aids the user to configure and use his instruments in RS232C, GPIB, VISA, etc. without Coding. Delay between acquisition of data from successive channels. Arises due to MUX switching and conversion times. A way for a device to signal to the computer that it ‘needs service’. This results in efficient communication between devices, esp. when transfers do not take place at predetermined intervals. An integer value which shows how many times the loop has operated. It is of type I32 and starts at 0. Interchangeable Virtual Instrument. GPIB device which accepts data put out by the talker. A mechanism through which a variable can be accessed from multiple positions. The scope of a local variable is one VI. A software setting for the time duration for a loop. LabVIEW reprograms the internal clock on the PC to time in 1ms resolution (PC default in 54ms). A filter that passes the lower band of signals, i.e. signals from dc to up to the cut-off frequency. Linear Variable Differential Transformer. A large computer system. Measurement and Automation Explorer. A computer smaller than a mainframe, but not a PC. Mini computers were not exactly mix-n-match systems, as PCs are. Electronic hardware which selects one signal at a time, depending on the Control input at that instant. MUX is used to combine signals and thus share costly resources. Not Data ACcepted handshake signal issued by Listeners. Nonacceptance of data by all listeners. A nybble is a 4-bit number (i.e. two nibbles constitute an 8-bit word). A software tool used to record all GPIB bus activities for debugging purposes. The ratio between the analog frequency and the sampling frequency, with units as cycles per sample. Also, called ‘digital frequency’. A tool used in inter-process communication for notifying various processes in a loop of an event. Not Ready For Data handshake signal issued by Listeners. Nonavailability of listeners to accept further data.

212

Glossary

NRSE Signals Nyquist Frequency Object Occurrence Octal

One Third Octave Analyser Over-Sampling Owned Label Palette Parsing Passband Password Display Path Pop-Up Menu Power Spectrum

Pre-(And Post) Test Preamplifier Pretrigger Primary Addressing (PAD) Primary Y Axis Probe

Non-referenced single ended signals. Here, the Analog Sense not shorted with the Safety Ground. Half of the sampling frequency which is the maximum frequency that can be represented accurately, without aliasing. An entity in LabVIEW code. A tool used in inter-process communication to set up, send and read the ‘occurrence’ of an event. Representation of numbers as 3-bit blocks (0-7). Very popular in the 70’s. Hexadecimal display has almost totally replaced octal displays. Technique by which the power content is determined in one-third octave steps. Very popular prior to Fourier analysis. Choosing a sampling rate for a signal higher than twice the Nyquist frequency. A label which is associated with a function (or sub-VI). This is a characteristic of the function and works as its identifier. A collection of various function (or operations or properties) in LabVIEW used to for easy selection. Breaking up strings into various constituent sub-strings for analysis (and sometimes storage). The range of frequencies that is allowed to pass through a filter. A way of displaying characters as asterixes (*) in order to hide passwords from being displayed, hence, the name. The location of a file in the storage system. A menu accessed by ‘right clicking’ on an object which is used to select or change various properties related to it. The plot showing the power in each of the frequency components. Obtained by squaring the magnitude of the individual frequency component. Whether the condition in a conditional loop is tested at the beginning or at the end. A low-noise, precision amplifier used immediately after a sensor/ transducer. A technique whereby events and signals are stored in real-time before the actual trigger signal appears. Address used by GPIB devices. Address range 0 to 31. The main Y axis (normally placed on the left) in a waveform graph. A temporary indicator placed in the code to aid debugging. The probe is visible on both the panel and diagram.

Glossary

Programmable Gain Amplifier (PGA) PXI

Quantization Queue

REN Rendezvous Resolution (of ADC) Right-Clicking RSE Signals RTS RTSI

Safety Ground Sample And Hold Circuit Sampling Frequency Sampling Period Scan Rate Scope Chart

SCPI Secondary Addressing (SAD) Secondary Y-Axis

213

Gain stage used in Data acquisition boards which have software programmable gain settings. PCI eXtensions for Instrumentation—a high performance rackbased, modular instrumentation system used for robust industrial instrumentation applications. The process by which the sample of an analog signal is represented by an n-bit number. A tool used in inter-process communication to build up a queue of the data, and in case one set of data is not read before the next one arrives, it is put in the queue. Remote ENable. Locking out the front panel controls. Also called Local Lockout (LLO). Rendezvous is used to synchronise code of multiple processes. The voltage level corresponding to the least significant bit (or the smallest voltage the ADC can convert). Using the right mouse button for accessing the pop-up menu. Referenced single-ended signals. Here, the Signal Ground and Safety Ground are shorted together. Request to Send—handshake signal in RS-232C. Real-Time System Integration bus-the National Instruments timing bus that connects DAQ devices directly, by means of connectors on top of the devices, for precise synchronization of functions. Connected to the Ground of the mains, used as a safety line in equipment to prevent electrical shocks The first stage of an ADC which takes the analog voltage of the signal at the specified instant, and stores it for processing by the converter circuit. The rate at which a signal is sampled and digitized. The interval between the samples (or reciprocal of the sampling frequency). Number of times a second all the specified analog input (or output) channels are scanned by the DAQ hardware. A waveform chart data which function in a manner akin to an oscilloscope. The data is displayed from left-to-right and at the end of the trace the display is erased and again starts from the left. Standard Commands for Programmable Instruments. GPIB addressing scheme used to address sub-sections within a device. Additional Y-axis (or axes) usually placed on the right. Multiple Y-axes are required when there are major differences in the ranges of the various traces.

214

Glossary

Semaphore Sequence Local Sequence Structure Shift Register Sigma-Delta Converter

Signal Conditioning Signal Ground Signal Sense (Analog Reference) Lines Smart Sensor Software Spectral Leakage

Spreadsheet String

SRQ State Machine

Stopband String Strip Chart

Sweep Chart

Permits the user to operate a shared resource in an orderly fashion. Used to transfer data from one frame of a sequence structure to subsequent frames. Not used in Flat Sequences. Unique to dataflow programming. It forces code to operate in the defined sequence. A mechanism in FOR and WHILE loops which makes the result of an iteration available as an input to the next iteration. Used in high-end ADCs to achieve high resolution (> 16bits), analog-to-digital conversion. These can be often operated with variable resolution. In this mode speed and resolution can be traded off. Operations done (generally filtering and low-noise amplification) before a signal is given to a DAQ board. Reference point for all signals in the circuit/equipment. The reference to which all analogue signals are measured. Usually the same as the Analog (or Signal) Ground. Sensor with on-board intelligence. This may for calibration, identification, signal processing, etc. Computer programs, etc. which are not in the shape of physical devices or components. Smearing of the Fourier transform caused by sampling of noninteger number of cycles of a signal resulting in extra frequencies that were not present in the original signal. Formatting of data into strings with individual values separated by (normally) a and lines/records separated by an . In Windows an comprises a and a . Service ReQuest—issued by a device to the Active Controller. A very powerful way of coding in LabVIEW. It relies on the fact that a complex process progresses from one well defined ‘state’ to another, and this movement is not continuous or amorphous. The range of frequencies that is stopped by a filter. A sequence of displayable (or non-displayable) ASCII characters. The most common Waveform Chart where the display functions like a window on the data which is in the form of a scroll. Data is displayed from left-to-right and at the end the data rolls off from the left with the newest data all the time on the right. Similar to a scope chart, except that the trace is not erased at the end of the sweep. The display overwrites the data to the left of the cursor and the right is the old data. This is very useful for observing trends.

Glossary

Talker TCP/IP Thermocouple

Transducers Trigger Unbundle Unicode

URL USB Variant VISA VXI Waveform Chart Waveform Graph WHILE Windowing Xon-Xoff XY Graph Zero-Padding

215

The GPIB instrument which is currently configured to transmit data on the bus. Transport Control Protocol/Internet Protocol. A temperature sensor consisting of two dissimilar materials that are in thermal and electrical contact; used generally for high temperature applications. Electromechanical devices that convert a mechanical change, such as displacement, into an electrical signal or vice versa. An electronic signal, whose low-to-high or high-to-low transition is used to start DAQ operations. Opening out and separating one or more elements of a cluster. A 16-bit data encoding scheme. While ASCII caters only to Romanbased languages, Unicode covers most languages in a unified manner. Universal Resource Locator. Universal Serial Bus—a serial bus standard used to interface instruments/devices to a computer. A special data type for Data Socket operations. Virtual Instrumentation Software Architecture. VME eXtensions for Instrumentation—a high performance instrumentation bus standard based on the VME bus. The simplest graphing tool, used to graphically display data. It is the only graphing tool which permits direct input of scalar data. Used to display data having equal spacing along the x-axis. In case of multiple traces each trace may have its own Dx, and x0 values. A repetitive operation of code whose operation is terminated through a logical condition. Used to reduce the amplitude of the discontinuities at the boundaries of each period, thus reducing the spectral leakage. Start-Stop bytes used in a three-wire RS-232C system as software handshake. Graph used to display data where the data is not equally spaced along the x-axis. Adding zeroes to the end of the input sampled sequence so that the total number is equal to the next higher power of 2.

INDEX Symbols *IDN? 138 .lvm 70 .tdm 70

AUTOINDEXING 32

A

B

Auto parse 139

Add frame 37

BridgeVIEW 10 Aliasing 203 Analog ground 101 Analog-to-digital converter 98 Analog-to-digital converter 98

C

CASE STRUCTURE 38

Cold junction compensation 132 Computed GOTO 39

Index Concatenate 83 Concatenate strings 83

Connector 22

Express VIs 132

F FEEDBACK 32

D DasyLab 9 Data binding 172

Format specifier 73

Frame number 37

Data socket write 170

G Genie 9

Differential 101 Digital ground 100

Global variables 30 GLOBAL VARIABLES 30

E Edit icon 22 EISA 3

H EOLs 72

Highlight execution 20

217

218

Index

I Minicomputers 2

Indexing 71

INSTRUMENT ASSISTANT 138 Inter-channel delay 100 INTERLOOP COMMUNICATION 27

N

Non-referenced single ended (NRSE) 101

Notifiers 30 Interrupt 3 IRQ 3

O OBJECTS 18

L Over-sampling 99 LabWindows 10 Latch mode 29

P Paint 22

LOCAL VARIABLEs 29 LOOP TIMING 33 LVDTs 102

PARSING 91

PDP 2

M Mainframes 2

Polymorphic 72

MAX 139 Power Spectrum 203

Index Secondary

Send notifier 170 Sequence locals 37

Q Shared variable 183

R Race condition 29 SHIFT REGISTERS 31 Spectrum analysis 137 Referenced single ended (RSE) 101 Stacked structure 37

Ring controls 39

STRINGS 91

Sub-VI 21 Run icon 20

S

System resourc

S100 2 Safety ground 100

T

Scan from string 89

TCP/IP

Timed se

219

220

Index

W Wait until

U

UNIBUS 2

V

Write to VESA 3

X XON 1

Plate 1

Fig. 13.13

GPIB Cable (Note the Double Ended Connectors)

Plate 2

Fig. 16.1

NI PCI6024E and PCI-GPIB Boards

Fig. 16.2 BNC2 120, Signal Accessory and Instrument Simulator

Plate 3

Fig. 16.3 NI ELVIS (MkI and Mk II)

IT IS YOUR CHANCE TO WIN GREAT PRIZES Submit your applications developed using any of NI’s versatile instrumentation tools and win some fabulous prizes. So, hurry and send in your applications.

NI Systems (India) Private Limited 81/1 & 82/1, Salarpuria Softzone, Wing B, 5 th Floor, Block A, Bellandur, Varthur Hobli, Bangalore 560103, Karnataka Tel: 080-41190 000, Fax: 080-41190 010, email: [email protected]

Yes, I would like to avail my FREE copy of NI LabVIEW Evaluation Software. Yes, I would like an NI consultant to call me. First Name: ..................................................

Last Name: ..................................................

Designation – Student/Professional: ...................................................................................... College/Company: .......................................

Department: ................................................

Address: ................................................................................................................................ .....................................................................

City: ............................................................

State: ............................................................

Postal Code: ................................................

Tel: ..............................................................

Mobile: .......................................................

Fax: .............................................................

E-mail: ......................................................... Signatures:

Send in the enclosed Business Reply Card or email your contact details to [email protected] for a FREE Copy of NI LabVIEW Evaluation Software

NI LabVIEW NI LabVIEW is a powerful, industry-standard graphical development environment. Academic campuses worldwide use LabVIEW to deliver project-based learning LabVIEW offers unrivaled integration with thousands of hardware devices and provides hundreds of built-in libraries for advanced analysis and data visualization. With the intuitive nature of the graphical programming environment, students can: l Visualize and explore theoretical concepts through interactive simulations and realworld signals l Design projects in applications such as measurement, control, embedded, signal processing, and communication l Compute, simulate, and devise solutions to homework problems NI LabVIEW can be used across Electrical, Electronics, Communication, Computer Science, Mechanical, Civil, Telecom, Aerospace, Biomedical and many more disciplines for hands-on experiential teaching and learning.

NI Systems (India) Private Limited 81/1 & 82/1, Salarpuria Softzone, Wing B, 5 th Floor, Block A, Bellandur, Varthur Hobli Bangalore 560103 Karnataka Tel: 080-41190 000 Fax: 080-41190 010 email: [email protected]

AFFIX POSTAGE STAMP

BUSINESS REPLY CARD NI Systems (India) Private Limited, 81/1 & 82/1, Salarpuria Softzone, Wing B, 5th Floor, Block A, Bellandur, Varthur Hobli, Bangalore 560103 Karnataka Tel: 080-41190 000 Fax: 080-41190 010 email: [email protected]

ni.com/labview ni.com/academic ni.com/india