Vous êtes sur la page 1sur 350

LabWindows/CVI Basics I Course Manual

Course Software Version 3.0 January 1999 Edition Part Number 320803F-01

LabWindows/CVI Basics I Course Manual


Copyright Copyright 1998 by National Instruments Corporation, 11500 North Mopac Expressway, Austin, Texas 78759. Under the copyright laws, this publication may not be reproduced or transmitted in any form, electronic or mechanical, including photocopying, recording, storing in an information retrieval system, or translating, in whole or in part, without the prior written consent of National Instruments Corporation. Trademarks CVI, DAQCard-700, DAQPad-1200, NI-488.2, NI-DAQ, NI-VXI, and The Software is the Instrument are trademarks of National Instruments Corporation. Product and company names listed are trademarks or trade names of their respective companies.

Internet Support E-mail: support@natinst.com FTP Site: ftp.natinst.com Web Address: http://www.natinst.com Bulletin Board Support BBS United States: 512 794 5422 BBS United Kingdom: 01635 551422 BBS France: 01 48 65 15 59 Fax-on-Demand Support 512 418 1111 Telephone Support (USA) Tel: 512 795 8248 Fax: 512 794 5678 International Offices Australia 03 9879 5166, Austria 0662 45 79 90 0, Belgium 02 757 00 20, Brazil 011 288 3336, Canada (Ontario) 905 785 0085, Canada (Qubec) 514 694 8521, Denmark 45 76 26 00, Finland 09 725 725 11, France 01 48 14 24 24, Germany 089 741 31 30, Hong Kong 2645 3186, Israel 03 6120092, Italy 02 413091, Japan 03 5472 2970, Korea 02 596 7456, Mexico 5 520 2635, Netherlands 0348 433466, Norway 32 84 84 00, Singapore 2265886, Spain 91 640 0085, Sweden 08 730 49 70, Switzerland 056 200 51 51, Taiwan 02 377 1200, United Kingdom 01635 523545 National Instruments Corporate Headquarters 11500 North Mopac Austin, Texas 78759 USA Tel: 512 683 0100 Copyright 1998 National Instruments Corporation. All rights reserved.

Contents
Course Slides and Text
Introduction................................................................................................................. 1 Lesson 1Introduction to LabWindows/CVI............................................................ 11 Lesson 2Creating a Graphical User Interface......................................................... 46 Lesson 3Data Acquisition....................................................................................... 95 Lesson 4Formatting and Scanning.......................................................................... 129 Lesson 5General-Purpose Interface Bus................................................................. 143 Lesson 6Serial Communication.............................................................................. 172 Lesson 7Instrument Drivers.................................................................................... 183 Lesson 8Standalone Executables............................................................................ 209

Lesson 1 Exercises
Exercise 1-1 ................................................................................................................ 1-1 Exercise 1-2 ................................................................................................................ 1-4 Exercise 1-3 ................................................................................................................ 1-8 Exercise 1-4 ................................................................................................................ 1-12 Exercise 1-5 ................................................................................................................ 1-19 Exercise 1-6 ................................................................................................................ 1-20 Exercise 1-7 ................................................................................................................ 1-24

Lesson 2 Exercises
Exercise 2-1 ................................................................................................................ 2-1 Exercise 2-2 ................................................................................................................ 2-2 Exercise 2-3 ................................................................................................................ 2-6 Exercise 2-4 ................................................................................................................ 2-10 Exercise 2-5 ................................................................................................................ 2-12 Exercise 2-6 ................................................................................................................ 2-13 Exercise 2-7 ................................................................................................................ 2-15 Exercise 2-8 (Additional Challenge Exercise) ........................................................... 2-18

National Instruments Corporation

iii

LabWindows/CVI Basics I Course Manual

Contents

Lesson 3 Exercises
Exercise 3-1 ................................................................................................................3-1 Exercise 3-2 ................................................................................................................3-3 Exercise 3-3 ................................................................................................................3-5 Exercise 3-4 ................................................................................................................3-7 Exercise 3-5 ................................................................................................................3-11 Exercise 3-6 ................................................................................................................3-12 Exercise 3-7 ................................................................................................................3-18 Exercise 3-8 ................................................................................................................3-19

Lesson 4 Exercises
Exercise 4-1 ................................................................................................................4-1

Lesson 5 Exercises
Exercise 5-1 ................................................................................................................5-1 Exercise 5-2 ................................................................................................................5-6 Exercise 5-3 ................................................................................................................5-9 Exercise 5-4 ................................................................................................................5-11

Lesson 6 Exercises
Exercise 6-1 ................................................................................................................6-1 Exercise 6-2 ................................................................................................................6-3

Lesson 7 Exercises
Exercise 7-1 ................................................................................................................7-1 Exercise 7-2 ................................................................................................................7-10 Exercise 7-3 ................................................................................................................7-17

Lesson 8 Exercises
Exercise 8-1 ................................................................................................................8-1

Appendix
A. File I/O ...................................................................................................................A-2 B. Formatting and Scanning Modifiers.......................................................................A-6

LabWindows/CVI Basics I Course Manual

iv

National Instruments Corporation

LabWindows/CVI Basics I
National Instruments 11500B MoPac Expressway Austin, TX 78759 (512) 794-0100

LabWindows/CVI Basics I Course Manual

National Instruments Corporation

Evolution of Instrumentation
Flexibility

PC TV Radio
25

50

75

10

Clock Time PC-based virtual instrumentation has become the new methodology for instrumentation

Instrumentation helps science and technology progress. Scientists and engineers around the world use instruments to observe, control, and understand the physical universe. Our quality of life depends on the future of instrumentation from basic research in life sciences and medicine to design, test and manufacturing of electronics, to machine and process control in countless industries. The slide above shows the evolution of instrumentation over the last 100 or so years. It is important that instruments have always leveraged off widely-used technology. In the 19th century, the jeweled movement of the clock was first used to build analog meters. In the 1930s, the variable capacitor, the variable resistor, and the vacuum tube from radios were used to build the first electronic instruments. Display technology from the television has contributed to modern oscilloscopes and analyzers. And finally, modern personal computers contribute highperformance computation and display capabilities. In the past, data acquisition devices have been traditionally reserved for the standalone instrument. Also, advancements in the personal computer area have shifted data acquisition to the personal computer, which offers greater flexibility, ease of use, and cost-effective analysis.

LabWindows/CVI Basics I Course Manual

National Instruments Corporation

Instrumentation
Standard Instrumentation
M RO
P
AY PL D OL DISAN TR N CO th Ma P

Virtual Instrumentation

PR

OC E

MO ME
BU S

RY T OR 8P 48
Pre

Te

mp

era

tur e

SS OR

Flo

w Co ntr ol

Pa

ne

ssu

A/D D/A O Co nd DI/ O itio TI/ nin g

Tim

re

Ala

rm

Co

ing

nd

itio

ns

ST

OP

Vendor Defined

User Defined

Instruments have evolved in terms of both flexibility and the degree to which they integrate into systems. The first-generation instruments were analog instruments manually controlled from their front panels. Measurements from these instruments had to be recorded by hand. The users had no flexibility in user interface design, measurement capabilities, or computational features. With the invention of the GPIB and digital instruments, users could control systems both programmatically and manually. Each GPIB instrument was designed for a specific measurement, and users racked and stacked a number of instruments to create a complete measurement system. Now millions of scientists and engineers around the world use PCs to automate their research, design, and manufacturing tasks. Increased performance and capabilities of PCs now rival those of sophisticated workstations at a fraction of the cost. Easy-to-use but powerful software and application development environments allow you to develop more capable applications faster. With the advent of the PC, a new term has become popular in the instrumentation community. The term virtual instrument describes the combination of programmable instruments with general-purpose PCs. Historically, architectural limitations have resulted in hard boundaries between vendor-defined instruments and user-defined functionality in an instrumentation system. The PC revolution has equipped users with powerful processing and display capabilities of their own. If you enhance the fixed capabilities of a traditional instrument with flexible user-defined capabilities of a computer, you have a virtual instrument.

LabWindows/CVI Basics I Course Manual

National Instruments Corporation

The Virtual Instrument


PC or Workstation
SCXI-1 001
SCXI 1140 SCXI 1140 SCXI 1140

Tem per atu re

Flo

w Con trol Pan

Pre

ssu

el

re

Ala

rm

Con ditio ns

STO P

SCXI 1140

SCXI 1100

SCXI
MAINFRAME

Application Software

DAQ Products

Process

Serial Instruments GPIB Instruments


NATIONA INSTRUM L ENTS

bus

Unit Under Test

Modular Instruments (VXI, PXI, CAMAC)

With virtual instrumentation, you can build your own instrumentation systems with standard computers and cost-effective hardware. These software-centered systems leverage off the computational, display, and connectivity capabilities of popular computers to give you the power and flexibility to build each of your instrumentation functions. You can mix and match your choice of data acquisition and instrument control hardware, including all of your existing instruments, to create virtual instrumentation systems that exactly meet your needs. Virtual instrumentation saves you time and money because you can build user-defined systems in a fraction of the time it takes with traditional approaches. By combining a computer with standard data acquisition and instrument control devices (such as DAQ products and serial, GPIB, or VXI instruments), you can create virtual instruments and use them in many applications. Unlike traditional instruments, which are limited by the design of the manufacturer, a virtual instrument can operate a variety of devices, such as a temperature monitor, voltmeter, strip chart recorder, digitizer, and signal analyzer.

LabWindows/CVI Basics I Course Manual

National Instruments Corporation

Key Elements of Virtual Instruments

Acquisition
INSTRUMENT

Analysis
Calculate

Presentation
User Interface File I/O Interprocess Communication

Signal Routing and Conditioning

IEEE488 (GPIB) DAQ Boards VXI RS-232

Format Trigger Control

Networking

...

A virtual instrument consists of three key elements: acquisition, analysis, and presentation. Acquisition is the means by which physical signals (such as voltage, current, pressure, and temperature) are converted into digital formats and brought into the computer. Analysis, such as a frequency response, is performed by specifically optimized software routines available in a wide selection of development environments. The presentation of the acquired and analyzed signal is accomplished using graphical display methods common on computers today. The four popular methods for acquiring data are plug-in data acquisition boards, GPIB instruments, VXI instruments, and RS-232 instruments. Data analysis transforms raw data into meaningful information. Data presentation is the means for communicating with your system in an intuitive, meaningful format. The components listed are but a few examples of the data presentation tools available. National Instruments has products available for all of the elements of a virtual instrument.

LabWindows/CVI Basics I Course Manual

National Instruments Corporation

What Does National Instruments Provide?


Acquisition
IEEE 488.2 controllers Plug-in data acquisition boards VXI controllers Software for RS-232 instruments

Analysis
Signal generation Digital filters Smoothing windows Statistics DSP hardware

Presentation
GUI Strip charts Graphs Hardcopy File I/O

HiQ (Post analysis and report generation) LabWindows/CVI, LabVIEW, and ComponentWorks

National Instruments is the leading vendor for GPIB control products worldwide. Our GPIB ASICs represent the leading edge of GPIB control technology. We manufacture products for a wide variety of powerful industry-standard computer buses, including PCI, PXI, ISA, PCMCIA, and Solaris Bus (SB). We have a wide selection of plug-in data acquisition boards, from high-performance analog input boards to low-cost multifunction boards, for all PC platforms. National Instruments leads the VXI control market with a complete line of VXI controllers and operating systems. We also invented the MXIbus, a high-speed cable standard, to give desktop computers control of VXI systems with the same power and speed as embedded VXI controllers. The foundation for the instrumentation system is the software LabWindows/CVI, ComponentWorks, and LabVIEW. Each software package accommodates all aspects of measurement and instrumentation, including data acquisition and control, data analysis, and data presentation. LabWindows/CVI, LabVIEW, and ComponentWorks are designed to simplify the construction of measurement and instrumentation systems. HiQ is a tool for analyzing, displaying data, and generating professional reports. National Instruments is driven by a vision for the future. We are changing the world by changing the way the world uses instrumentation. By taking advantage of high-performance industry-standard computers, we are leading a revolution in which scientists and engineers will use these computers running powerful new software to build their own virtual instruments. These modular instruments are more cost effective, more flexible, and adapt more readily to changing needs than the instruments of the past. We are leading the way to the future of instrumentation, a future in which The Software is the Instrument.
LabWindows/CVI Basics I Course Manual 6 National Instruments Corporation

LabWindows/CVI
Standard ANSI C Language Built-In Instrumentation Libraries Productivity Tools for Faster Development

Standard Language IMAQ, etc) Compiler Network Editor Interactive Debugger GUI TCP Open System Execution

I/O Code (GPIB, VXI, ANSI C Serial, Generation Tools Analysis DAQ,

OLE

LabWindows/CVI addresses all of the challenges of an integrated ANSI C development environment. It includes a 32-bit compiler and linker with advanced editing and debugging tools. Best of all its open! You can incorporate the best of other peoples development efforts and produce DLLs for other environments. LabWindows/CVI has a comprehensive suite of libraries targeted at instrumentation applications, from instrument control to data analysis and graphing all you need is right there at your fingertips. For rapid application development, LabWindows/CVI includes CodeBuilder and interactive Function Panels. These two powerful code generation tools mean you can develop your application with the bare minimum of programming. Its like having your own personal C guru helping you with your application!

LabWindows/CVI Basics I Course Manual

National Instruments Corporation

Software Architecture
Ap So

ic ftw atio ar n e

pl

LabWindows/CVI
Acquisition Analysis Presentation

Dr i So ver ftw ar e

Instrument Drivers

NI-488.2

NI-VXI

NI-DAQ

Serial

GPIB

VXI

Computer Bus

RS-232 RS-485

To account for the varying needs of measurement and instrumentation applications, software must integrate all of the elements in a manner that delivers ease of use, power, and flexibility. National Instruments software architecture combines low-level device drivers for our hardware and high-level application development software. With this combination, you have a scalable development system with the flexibility to handle a very wide range of measurement and instrumentation applications. To build virtual instruments, you need software that easily integrates any or all of the four hardware instrumentation options in a single system. At the lowest level, with standardized driver software packages you can control the four acquisition hardware options. The driver packages include function libraries for programming your hardware. Our NI-488.2 driver is the industry standard for programming GPIB. NI-VXI is our driver software for programming VXI. NI-DAQ is our driver software for programming our plug-in data acquisition boards. Most computers include RS-232 driver software. Our driver software packages are standardized across all popular computers and a wide variety of operating systems. You can use our stand-alone driver software and program using the language and operating system of your choice. If you need assistance with programming, our application software is the answer. With our application software, LabWindows/CVI, you can build your own instruments. LabWindows/CVI works with all aspects of an instrumentation system, including data acquisition and control, data analysis, and data presentation. LabWindows/CVI also features modular, reusable, high-level instrument drivers for specific instruments and applications that dramatically reduce your software development task. By using our application software packages, you are free to choose the components necessary to meet your application cost and performance requirements. You now have the opportunity to build your own instruments to exactly meet your particular application needs.
LabWindows/CVI Basics I Course Manual 8 National Instruments Corporation

LabWindows/CVI A History of Innovation


May 1998 May 1996 July 1995 March 1994 April 1991 January 1989

LabWindows/CVI 5.0
New instrument driver technologies

LabWindows/CVI 4.0
External C/C++ compiler support

LabWindows/CVI 3.1

Automatic program generation

LabWindows/CVI 3.0

Multiplatform for Windows and Sun

LabWindows for DOS 2.0


GUI tools and memory extender

LabWindows for DOS 1.0


Introduction

LabWindows first emerged as a set of libraries and a development environment for creating instrumentation systems using QuickBasic and Microsoft C under DOS. As DOS memory extenders became available, it was enhanced to include a user interface library and editor with the introduction of version 2.0. Version 3.0 saw a move to Microsoft Windows and the Sun platform as the environment focused on C as its fundamental development tool (hence the addition of CVI to the name C for Virtual Instrumentation). Version 3.1 added the capability to automatically generate code from a user interface, and version 4.0 brought compatibility with compilers from Microsoft, Borland, Symantec, and Watcom. LabWindows/CVI 5.0 brings many new features particularly aimed at production tests, such as high-performance instrument drivers and additions of current technologies like ActiveX Automation and OpenGL for 3D visualization. This timeline represents a commitment to innovation and development that has allowed our customers to develop applications secure in the knowledge of a migration path to future environments.

LabWindows/CVI Basics I Course Manual

National Instruments Corporation

Course Outline
Day 1 Introduction to LabWindows/CVI Graphical User Interface Day 2 Data Acquisition (DAQ) Formatting and Scanning IEEE 488 (GPIB) Day 3 Serial Communication Instrument Drivers Creating and Distributing Standalone Executables

LabWindows/CVI Basics I Course Manual

10

National Instruments Corporation

Lesson 1
Introduction to LabWindows/CVI

Objectives: Learn what LabWindows/CVI is Learn about LabWindows/CVI windows Learn about the LabWindows/CVI menus and toolbars Learn about function panels and the Interactive Execution Window (IEW) Learn about LabWindows/CVI data structures and their scope Learn how to use the LabWindows/CVI debugging tools

This lesson introduces the LabWindows/CVI environment and the tools it provides for application development.

LabWindows/CVI Basics I Course Manual

11

National Instruments Corporation

Timesaving Features of LabWindows/CVI


Function Panel concept Automatic skeleton code generation Tight integration between compiler and linker Run-time error checking Interactive execution of library functions Instrumentation libraries Compatibility and portability Availability of add-on packages

LabWindows/CVI was designed to minimize the development effort required to create engineering and scientific instrumentation applications and includes numerous features to ensure your success. Function Panel Concept Function panels are the key to making programming with LabWindows/CVI easy. You no longer need to remember how many parameters are in a function call or what order they are in LabWindows/CVI takes care of them for you! Automatic Skeleton Code Generation Minimizes the development effort placed into developing applications by creating skeleton code to help you begin your program Tight Integration between Compiler and Linker LabWindows/CVI is intelligent enough to automatically include header files required for its internal libraries. Run-Time Error Checking LabWindows/CVI prevents you from overwriting memory locations and will catch errors that other environments may not. Interactive Execution of Library Functions Allows developers to test code functionality without having to write a complete program. Instrumentation Libraries Instrument Driver, Data Acquisition, GPIB, VXI, and Analysis Libraries are all built in. Compatibility and Portability LabWindows/CVI supports ANSI C and is available on several platforms. In addition, any code written today will be supported on all future versions of LabWindows/CVI, and code developed on the Windows 95/98 and NT (Win32) environments can be accessed from other Win32 development environments. LabWindows/CVI can access third-party DLLs and libraries on these platforms as well. On Solaris operating systems, LabWindows/CVI can access external libraries as well. Availability of Add-On Packages Test Executive, Structured Query Language (SQL), Image Processing, Statistical Process Control (SPC), PID control, and more!

LabWindows/CVI Basics I Course Manual

12

National Instruments Corporation

LabWindows/CVI Libraries
LabWindows/CVI ships with several different function libraries. These libraries are available to make your programming easier.

Standard and Optional Libraries for LabWindows/CVI User Interface Functions for complete control of menus, controls, graphs, strip charts, etc. Analysis Functions to do mathematical and array operations. Advanced Analysis Included with the Full Development System (FDS), it takes the place of the analysis library. Adds functions for time/frequency transforms, integration/differentiation, digital filters, solution of linear equations, curve fitting, and advanced statistics. Easy I/O for DAQ Functions for controlling National Instruments plug-in DAQ boards and SCXI hardware using simplified functions. Data Acquisition Functions for controlling National Instruments plug-in DAQ boards and SCXI hardware. VXI Included with the FDS, it is used for controlling a VXI system using National Instruments VXI controllers. GPIB/GPIB 488.2 Functions for controlling National Instruments GPIB boards. RS-232 Functions for serial port I/O. VISA Functions used to create interface-independent instrument drivers. IVI Intelligent Virtual Instruments, the next generation of instrument drivers. TCP Functions for network communications using Transmission Control Protocol. DDE (Windows Only) Functions for Dynamic Data Exchange. ActiveX Automation Functions for controlling an ActiveX server. Formatting and I/O Functions to format data and perform file/screen I/O. Utility Functions for timing, date/time, keyboard, file utilities, directory utilities, and external module access. ANSI C ANSI specified libraries (stdio, stdlib, and so on).
LabWindows/CVI Basics I Course Manual 13 National Instruments Corporation

LabWindows/CVI Windows
Project Window

There are seven icons used in the Project window. They are described below: The file is currently closed. Double-click on this icon to open the files. The file is currently open. Double-click on this icon to close the files. File has not yet been compiled or has been modified since the last time it was compiled. Double-click on this icon to compile the file. This icon in the applies only to source (.c) files and indicates that you enabled the Compile into Object option. If this option is enabled when you compile the source file, LabWindows/CVI creates an object (.obj) file on disk that contains nondebuggable code rather than generating debuggable code in memory. Doubleclick on this icon to toggle the option. The file has been modified since the last time it was saved. Double-click on this icon to save the file. The file is the source program of an instrument driver. The file is associated with a loaded instrument driver. LabWindows/CVI uses standard file name conventions and defines a few new ones. The following conventions are used for filenames: .c C source files .h C header files .obj Object files (compiled C files) .lib Static and Import Library files .uir User Interface files .fp Instrument Driver Function Panel files
LabWindows/CVI Basics I Course Manual 14 National Instruments Corporation

LabWindows/CVI Windows
Source Editor Window
Split Window Tags

The Source Editor window behaves like a standard source code editor but adds many useful features, such as the ability to insert commonly used C constructs (for loops, case statements, etc.), color-coding, split windows, and tags. Split windows offers the ability to view two portions of your code simultaneously. To access this feature, pull down the double bar at the top of the source window (just underneath the toolbar). Tags offer an easy way to mark selected lines of code. Press <Shift-F2> to set a tag and press <F2> or <Ctrl-F2> to jump between tags (forward and backward, respectively). You may use multiple source windows simultaneously. Each window can contain up to one million lines of code (254 characters per line).

LabWindows/CVI Basics I Course Manual

15

National Instruments Corporation

LabWindows/CVI Windows
Standard Input/Output Window

The Standard Input/Output window is used for simple input and output. This window can contain up to one million lines of code and 254 characters per line. The contents of this window can be saved to a text file for analysis at a later time. You can clear the Standard I/O window by selecting Edit Clear Window or by using the Cls() function in your program. If you use the Cls function, you need to add the #include <utility.h> preprocessor statement (or you can let LabWindows/CVI do it for you!). The LabWindows/CVI Standard I/O window is equivalent to a DOS console I/O window.

LabWindows/CVI Basics I Course Manual

16

National Instruments Corporation

LabWindows/CVI Windows
User Interface Editor Window
Discussed in Lesson 2, this window is used to design your graphical user interface (GUI)

Applications can have multiple graphical panels (windows) associated with them and can even have nested panels (panels within other panels). The User Interface Editor window will be discussed in Lesson 2.

LabWindows/CVI Basics I Course Manual

17

National Instruments Corporation

Exercise 1-1

Objective: To open and run an application inside the LabWindows/CVI environment.

LabWindows/CVI Basics I Course Manual

18

National Instruments Corporation

Exercise 1-2

Objective: To examine features of the LabWindows/CVI Source Editor.

LabWindows/CVI Basics I Course Manual

19

National Instruments Corporation

LabWindows/CVI Menus

The project window contains the following menus: The File menu includes the standard commands for loading and saving project files. The Edit menu includes commands for adding and deleting files from a Project window. The View menu includes commands to alter the Project window display (for example, show the full pathname of the file or just the filename). The Build menu commands are for compiling files and building projects (compiling all files and linking). The Run menu commands are for running and terminating projects. The Instrument menu includes commands to access the files from the Instrument Library, which contains instrument-specific control functions for various instruments. The Library menu includes functions that assist you in writing application programs. The Advanced Analysis Library, when installed, replaces the regular Analysis Library. For this course, the Advanced Analysis Library has been installed on your computer. The Tools menu contains wizards to assist with developing ActiveX and IVI instrument drivers. It also contains the DAQ channel wizard when the NI-DAQ drivers are installed, and anything else you specify. The Window menu contains commands for arranging and displaying various windows. The Options menu contains commands for setting up preferences in the LabWindows/CVI environment and executing various utilities. Different options include Run Options and Compiler Options. The Help menu contains commands to invoke the online help.

LabWindows/CVI Basics I Course Manual

20

National Instruments Corporation

LabWindows/CVI Toolbars

You can use toolbars for quick access to selected commands from menus without having to pull down any menus. Use the VIEW Toolbar command to display or hide the toolbar. To customize the toolbar (that is, rearrage, add, or remove items), select Options Toolbar. To identify the corresponding command for a toolbar icon, drag the mouse pointer over the icon, and a yellow tag strip describing the icon will pop up.

LabWindows/CVI Basics I Course Manual

21

National Instruments Corporation

LabWindows/CVI Options

The project workspace can be customized via the project Options menu. This menu allows the developer to add directions to the LabWindows/CVI search path, change the debugging level, change colors, etc.

LabWindows/CVI Basics I Course Manual

22

National Instruments Corporation

Exercise 1-3

Objective: To examine various LabWindows/CVI project options.

LabWindows/CVI Basics I Course Manual

23

National Instruments Corporation

Function Panels

Go to the Library menu and select the library you want to search. Navigate through the function tree until you find the function you want to operate. Select it and its function panel appears, representing the function with a control for each parameter. By manipulating the controls, you construct the function call. You can view the tree of functions in the instrument driver in several ways. Function Names: This checkbox allows you to view the ANSI C name of the functions. Alphabetize: This checkbox displays the list the functions in alphabetical order. Flatten: This checkbox removes the submenu hierarchy. Instead of displaying all names organized into groups, all functions are listed under one menu. This is very useful (with Alphabetize) if you know the name of the function you are looking for.

LabWindows/CVI Basics I Course Manual

24

National Instruments Corporation

Function Panels

Function panels are screen-oriented interfaces to the LabWindows/CVI library functions. You can use function panels for the interactive execution of library functions. Function panels are also capable of generating code for inclusion in a program. A function panel is a graphical method of calling a subroutine in a program. You simply select and execute the desired function panel. The function panel, in turn, calls code in memory that is associated with the panel. You can use the instrument driver function panel in two key ways: To execute a particular function interactively. To generate function calls that can be included in an application program. To execute a function interactively, fill in the function parameters, go to the Code menu, select Run Function Panel, and press the icon on the toolbar or <Shift-F5>. To generate function calls that can be included in your application program, enter the function parameters on the function panel and insert the function call into your code. To do this, select Code Insert Function Call and press the icon on the toolbar, or press <Ctrl-I>. The function call will be placed in your code at the current cursor position. Note: Function panels save you from having to remember the syntax or order of parameters associated with any particular function.

LabWindows/CVI Basics I Course Manual

25

National Instruments Corporation

Function Panels - Online Help

Every LabWindows/CVI library function has an associated function panel associated with online documentation that describes the function in addition to each of the input and output parameters. Online documentation for a function panel can be accessed simply by right-clicking on an empty area of the function panel, pressing <Shift-F1>, or selecting Help Function Help. You can access information about the input and output parameters by placing the cursor within the control and either right-clicking, pressing <F1>, or selecting Help Control Help. Notice that the function documentation includes a prototype of the function, and the control documentation reflects the expected data type.

LabWindows/CVI Basics I Course Manual

26

National Instruments Corporation

Function Panels - Variables

Pressing <Ctrl-D> allows you to declare variables from a function panel interactively.

Function panels speed development time because they allow you to make variable declarations as you develop your program and insert these variable declarations into the Interactive Execution Window and/or your source code. To declare variables interactively, place the cursor in the area of the function panel corresponding to the parameter you want to declare a variable for, and select Code Declare Variable. Alternately, you can press <Ctrl-D> or press the Declare Variable Toolbar icon Three options affect how and where the variable is placed. These are summarized in the table below. Option Execute declaration Add declaration to top of target file Description Declares the variable in the Interactive Execution Window Places the variable declaration at the beginning of the currently selected target file. To set the target file press the Set Target File button. Places the variable declarations at the top of the current set of braces{ }.

Add declaration to current block

LabWindows/CVI Basics I Course Manual

27

National Instruments Corporation

Interactive Execution Window


The Interactive Execution window allows you to execute portions of code. You do not need to have a complete program in the window. The code shown will execute although there is no main!

The main use of the Interactive Execution Window (IEW) is to execute functions directly from a function panel. To execute a function from a function panel, just Run it. To run a function panel, select Code Run Function Panel, press the icon in the toolbar, or press <Shift-F5>. When you execute a function from a function panel, LabWindows/CVI inserts the function call into the IEW, where it executes. In this way, the IEW keeps a record of the functions you have executed from function panels. When LabWindows/CVI copies a function call from a function panel to the IEW, it inserts the code after all pre-existing lines. LabWindows/CVI also copies the header file associated with the function to the IEW if it is not already included. When you execute a function call from a function panel, all previous lines in the IEW are automatically excluded. In addition, all variables declared from function panels with the Execute Declaration option selected are copied to the IEW, so that other function panels that you use will have access to them. Interactive Execution statements can be cleared by selecting Edit Clear Window. Note: It is recommended that you clear the IEW every time you open a new project in LabWindows/CVI. This clears the variables list available in a function panel and prevents you from accidentally using variables defined in the IEW only.

LabWindows/CVI Basics I Course Manual

28

National Instruments Corporation

Exercise 1-4

Objective: To create a LabWindows/CVI project using function panels.

LabWindows/CVI Basics I Course Manual

29

National Instruments Corporation

Exercise 1-5

Objective: To plot a random number array and find the mean of the array.

LabWindows/CVI Basics I Course Manual

30

National Instruments Corporation

LabWindows/CVI Data Structures


Assignments short int long int unsigned short int unsigned long int char float double Alternative Assignment short long or int unsigned short unsigned long or unsigned int Description integer (2-byte) variable integer (4-byte) variable unsigned integer (2-byte) variable unsigned integer (4-byte) variable character variable (1-byte) single precision (4-byte) floating point double precision (8-byte) floating point

LabWindows/CVI supports standard ANSI C variables and assignments.

Note: LabWindows/CVI is a 32-bit compiler regardless of operating system. Hence, an integer is 4 bytes.

Reminder: C variables are case sensitive. The variable Status is different than the variable status. Arrays can be declared statically in the same fashion as they would be in any other ANSI C compiler. For example, int waveform[100]; char stringFromInstrument [200]; /* 100-element array of 4-byte integers */ /* 200-element array of characters (string) */

LabWindows/CVI Basics I Course Manual

31

National Instruments Corporation

Scope of Variables
Describes the accessibility of variables within different program modules
Global variables Module-global variables Local variables

When using variables in a program, you must decide what level of accessibility, or scope, is required for each variable and declare it accordingly. Global Variables When you declare a variable as global, it can be accessed anywhere by any module that is part of the project. You must declare all global variables outside any functions or main, (typically at the beginning of a source file below the #include statements). Other modules in the project can access the global variable by redeclaring the variable and prefacing the declaration with the keyword extern. Module-Global Variables When you declare a variable as global to a module, it can be accessed anywhere in the module you declare it; however, it cannot be access in any other module. You must declare any module global variables outside any function or main and precede all variable declarations with the keyword static. Local Variables When you declare a variable as local, it can be accessed only in the subprogram (set of opening and closing curly braces { } ) in which you declare it. Local variables cannot be accessed in any other subprogram or module. Note: Local variable can be declared with or without the keyword static. Local variables not declared static are kept on the stack. If you declare huge arrays as local variables without specifying them as static, you could get stack overflows. The maximum stack size in a Win16 environment is approximately 16 KB with debugging on and 64 KB with debugging turned off. In a Win32 environment, the stack size can be up to 1 MB.

LabWindows/CVI Basics I Course Manual

32

National Instruments Corporation

Scope of Variables
Module1.c
int x; // global to all modules static int y; // global to module1 main() { int z; // local to main x = 1; y = 2; z = 3; foo1(); foo2(); printf ("main x=%d,y=%d,z=%d\n",x,y,z); } void foo1() { static int z; // local to foo1 z = 100; printf ("foo1 x=%d,y=%d,z=%d\n",x,y,z); }

Module2.c
extern int x; // defined in module1 static int y; // global to module2 void foo2() { static int z; // local to foo2 x = 1000; y = 2000; z = 3000; printf ("foo2 x=%d,y=%d,z=%d\n",x,y,z); }

Output: foo1 x=1, y=2, z=100 foo2 x=1000, y=2000, z=3000 main x=100, y=2, z=3

To understand how to access variables in different modules, consider a project with two modules, source1.c and source2.c. Because x is defined as a global, it is accessible in both modules. Therefore, the value of x was overwritten in the function foo2. Because y is defined as a static variable, its value was preserved between function calls. (The variable y is global to each modules because it is defined outside of any functions or main). Therefore, the output is: foo1 x=1,y=2,z=100 foo2 x=1000,y=2000,z=3000 main x=1000,y=2,z=3 You will look at this program in detail in Exercise 1-6. The scope of variables also extends into the Interactive Execution Window. You can think of the variables defined in the IEW as if they were defined in another module. The IEW can access global variables defined in other modules (make sure to put the extern keyword in front of the definition), but the IEW cannot define global variables for other modules to use.

LabWindows/CVI Basics I Course Manual

33

National Instruments Corporation

Debugging
Compiling Excluding lines Breakpoints/conditional breakpoints Single-stepping Variables window Watch window

Debugging LabWindows/CVI offers many different debugging options to assist you in creating usable code. Among the options are: Compiling Allows you to check for syntax errors as CVI converts your code into machine code. Excluding Lines Allows a simple and efficient method of commenting out code that you do not want to be compiled with your project. Breakpoints/Conditional Breakpoints Allows you to halt the execution of your program at various points in your code to view variable values, etc. Single-Stepping Allows you to run your program line-by-line to determine the effect your code has on your variables and eliminate errors. Variables Window Shows all variables used in your code. Watch Window Allows you to select variables and expressions to display. This is similar to the variables window.

LabWindows/CVI Basics I Course Manual

34

National Instruments Corporation

Compiling Files
Compiling your file checks for syntax errors!

Compiling Files By selecting Build Compile File <Ctrl-K>, LabWindows/CVI will compile the selected file for you. Alternately, you can compile the file by double-clicking on the C that appears next to the filename (in the project menu) or by clicking on the icon in the source window. When you run the project, the file is automatically compiled and linked prior to the execution of your program. Compiling and linking errors are displayed in the Build Errors window. Double-clicking on the error displays and highlights the portion of code generation the error if the error is a compilation error. Common errors that you may come across include: Trying to compile a C++ program in LabWindows/CVI. LabWindows/CVI is a C compiler and will not understand C++ code. Attempting to compile a program that was developed on a different environment. These programs often have function calls which are specific to that environment. Forgetting that ANSI C is a case-sensitive language. If you are using a function called GetCtrlVal and you spell it getctrlval, the compiler will not recognize your function call. Forgetting that all statements must be terminated with a semicolon (;). Many errors can be fixed by looking for a missing semicolon on the line preceding the error.
LabWindows/CVI Basics I Course Manual 35 National Instruments Corporation

Excluding Lines
Excluding lines <Ctrl-E> is a fast way of commenting out lines of code.

Exclude/Include Lines For debugging purposes, LabWindows/CVI features a quick and easy method for excluding line of code that you do not want to execute. You can exclude lines by placing the text cursor on the desired line and selecting Edit Toggle Exclusion (<Ctrl-E>). When you exclude a line, its color changes and it behaves as if it is commented out. You can include previously excluded code by following the same procedure. Another option you have is to select Edit Resolve all Excluded Lines. This will give you the option to resolve (that is, comment out, delete, or include) line by line all currently excluded lines. You can also exclude/include a line by right-clicking on it and selecting Toggle Exclusion from the pop-up menu. Excluding lines is a very easy way to comment out large blocks of code that you believe are causing problems. You can also exclude an entire file from being built into the project by selecting Edit Exclude File from Build (<Ctrl-E>). This is useful if you have two versions of the file that you want to keep in the same project. Note: You cannot save a file with excluded lines. LabWindows/CVI will prompt you to resolve the excluded lines.

LabWindows/CVI Basics I Course Manual

36

National Instruments Corporation

Breakpoints

Breakpoints provide a convenient method of pausing your program at specified points.

Breakpoints You can pause the program execution without aborting it altogether by parking breakpoints in your code. You can also use the Breakpoint function to pause the execution of a program. To temporarily suspend program execution on a user-interaction basis, press <Ctrl-F12> while the program is running. When a program reaches a breakpoint, LabWindows/CVI positions the keyboard cursor at the program statement to be executed and outlines the statement. You cannot edit the source code in the window while the breakpoint is in effect. However, you can look at other windows, change the state of breakpoints, and modify the value of variables. Note: The Debugging Level (Project Menu Options Run Options) must be set to No run-time checking, Standard, or Extended to use breakpoints. Here are some common ways to set and clear breakpoints: If you activate View Line Icons, you should see a column to the left of your program code. You can left-click in this line icon area to set or clear a breakpoint. Move the cursor to the line of code where you want to set or clear a breakpoint. Select Run Toggle Breakpoint (<F9>). Select Run Break at First Statement. This will cause LabWindows/CVI to break automatically on the first executable statement in the project. You can set breakpoints in your source code by using the Breakpoint function.

LabWindows/CVI Basics I Course Manual

37

National Instruments Corporation

Conditional Breakpoints

LabWindows/CVI allows you to set conditional breakpoints.

Conditional Breakpoints LabWindows/CVI also allows you to establish conditional breakpoints. This feature is extremely useful when debugging large programs, because it allows you to break only when certain conditions are met (for example, when a variable equals some value). Conditional breakpoints can be created by inserting a breakpoint at the line you want to place a breakpoint. Next, select Run Breakpoints (<F9>) or right-click on the breakpoint icon and select Breakpoints from the pop-up menu. This brings up the dialog box shown in the slide above. Note: Breakpoints that are programmatically included are not listed. Highlight the breakpoint you want to modify and select Add/Edit Item. This allows you to establish various conditions for the breakpoint, including a pass count (the number of times a condition must be true for the breakpoint to be valid).

LabWindows/CVI Basics I Course Manual

38

National Instruments Corporation

Single-Stepping

LabWindows/CVI allows you to single-step through your code.

Single Stepping To resume execution after a breakpoint, you have several options under the Run menu that control the program flow. You can also execute these options by pressing the corresponding icon on the toolbar or by pressing the appropriate keyboard short cut. Continue (<F5>) resumes the program execution until the next breakpoint. Go to Cursor (<F7>) continues program execution until the program reaches the line on which you have placed the text cursor, where it enters another breakpoint state. Step Over (<F10>) executes an outline statement while in a breakpoint state. Step Over executes the entire function and breakpoints on the statement following the function call. Step Into (<F8>) enters the function and suspends execution at the first statement in the function. Trying to step into a library function will actually step over the function. Finish Function (<Ctrl-F10>) resumes execution through the end of the current function and breakpoints on the next statement after the current function. Terminate Execution (<Ctrl-F12>) terminates a program suspended at a breakpoint. Activate panels when resuming (under the Run menu) allows you to view updates on the user interface while stepping through the code. By combining breakpoints with program tracing, you can normally execute parts of the program that are operating correctly and use the trace and step features to manually step through parts of the program you are attempting to debug.

LabWindows/CVI Basics I Course Manual

39

National Instruments Corporation

Variables Window
LabWindows/CVI keeps track of the variables you have in your program in the Variables window.

You use the Variables window to inspect and modify the values of program variables. The names and types of all variables, including arrays and strings, are shown in the Variables window. The current value of numeric scalars, values and contents of pointers, and string contents are also shown in the Variables window. Variables in this window are updated at each breakpoint. To view the Variables window, select Window Variables. Several icons appear to the left of certain variables. Two of the icons are discussed below. Character arrays (strings) are not displayed beyond the first NULL byte, because strings are terminated by a NULL character in ANSI C. If you need to see the entire buffer, you can double-click on the buffer to display it, then go to the Options menu and select Display Entire Buffer. The variable on this line is the starting pointer to a block of defined data such as an array, string, or structure. The value next to the icon is the memory offset corresponding to the memory location of the variable. Clicking on this icon or selecting View Expand Variable expands the variable so that you can see each element or member. The variable on this line is the starting pointer to a block of defined data currently being viewed in expanded form. Clicking on this icon or selecting View Close Variable closes the variable so that you see only the starting pointer. Tip: During the debugging process, it is also possible to monitor the value of any particular variable quickly by right-clicking on the top of the name in the source window and selecting View Variable Value from the pop-up menu.
LabWindows/CVI Basics I Course Manual 40 National Instruments Corporation

Watch Window

The Watch Window allows you to select your own set of variables and expressions to view

Watch Window The Watch window is similar in nature to the Variables windows, except that you can select your own set of variables and expressions to view in the Watch window. By default, variables and expressions in the Watch window are updated at each breakpoint, but you can also set them to update continuously and cause a breakpoint when their values change. To activate the Watch window, select Window Watch. Select Watch window variables and expressions from the Variables by selecting Edit Add Watch Expression. Some controls in the Add/Edit Watch Expression dialog box are used as follows: Variable/Expression contains the variable or expression to be placed into the Watch window. Scope corresponds to whether the variable or expression is global to the project, global to a file, local to a function, or global to the Interactive Execution windows. File corresponds to the file where the variable or expression is defined if its scope is global to a file or local to a function. Function corresponds to the function where the variable or expression is defined if its scope is local to a function. Replace replaces the existing attributes of the current variable or expression of the same name in the Watch window with the current attributes in the dialog box. Replace is available only when the dialog box is invoked from the Watch window. Add inserts the variable or expression to the Watch window.

LabWindows/CVI Basics I Course Manual

41

National Instruments Corporation

Exercise 1-6

Objective: To use the Variables window to view the scope of variables.

LabWindows/CVI Basics I Course Manual

42

National Instruments Corporation

Exercise 1-7

Objective: To examine the source code stepping and debugging tools in LabWindows/CVI.

LabWindows/CVI Basics I Course Manual

43

National Instruments Corporation

Summary Lesson 1
Integrated environment Project, source, standard I/O windows Function panels Scope of variables Debugging tools
Exclude lines Breakpoint/conditional breakpoints Single stepping Variables and Watch Windows

LabWindows/CVI is an integrated C programming environment. We learned about four of the different windows that LabWindows/CVI uses. They are the Project window, the Source window, the Standard I/O window, and the Interactive Execution window. You use the Project window to open, edit, build, run, and save files for your LabWindows/CVI application. The Source window is where the program is actually coded. You can type code directly in the Source window, or you can use the LabWindows/CVI code builder (discussed in Lesson 2) and function panels to generate the code in the Source window or the IEW. Function panels are a graphical method of calling subroutines in a program. Function panel controls specify the parameters in a function call. The scope of a variable is its accessibility within its own module and to external modules. A module is simply a file. You can declare variables as global, module-global, or local. The scope of variables extends to the IEW, which can be thought of as a separate module. The different debugging options are very useful in determining what your program is doing.

LabWindows/CVI Basics I Course Manual

44

National Instruments Corporation

Tips and Shortcuts


Common Keyboard Shortcuts
Menu Item Compile File Build Project Run Project Halt Execution Toggle Exclusion Balance Find Find Next Go to Definition Recall Function Panel Find Function Panel Toggle Tag Next Tag Previous Tag Keyboard Shortcut Ctrl-K Ctrl-M Shift-F5 Ctrl-F12 Ctrl-E Ctrl-B Shift-F3 F3 Ctrl-I Ctrl-P Ctrl-Shift-P Shift-F2 F2 Ctrl-F2
Menu Item Declare Variable Select Variable Close Window Insert Code Select User Interface Constant Keyboard Shortcut Ctrl-D Ctrl-A Ctrl-W Ctrl-I Enter

Common Function Panel Shortcuts

There are many shortcuts available to speed up your development! Pop-up menus and toolbar shortcuts are also available.

LabWindows/CVI Basics I Course Manual

45

National Instruments Corporation

Lesson 2
Creating a Graphical User Interface
Objectives: Learn about the User Interface Editor Learn how to create a graphical user interface (GUI) Learn about commonly used controls Learn about the User Interface Library Learn about event-driven programming Learn how to use the LabWindows/CVI Code Builder Learn about timers and timer events Learn about multiple panels and pop-ups

LabWindows/CVI Basics I Course Manual

46

National Instruments Corporation

Graphical User Interface


LED Decoration Numeric Indicator Panel Strip Chart

Command Button

Knob

A LabWindows/CVI graphical user interface (GUI) can consist of panels, command buttons, pull-down menus, graphs, strip charts, knobs, meters, and many other controls and indicators. In the next few pages, you will learn different techniques to create a GUI, as well as how create an application that has an associated GUI.

LabWindows/CVI Basics I Course Manual

47

National Instruments Corporation

User Interface Editor


The User Interface Editor is used to create a GUI.

The User Interface Editor is the starting point for designing the layout of your graphical program interface. To invoke the User Interface Editor, go to the File menu and select New User Interface. From this window, you can create and edit panels, controls, indicators, and menu bars. Use the tool bar beneath the menu bar for high-level editing with the mouse. When you click on a particular tool, the mouse cursor changes to reflect the new editing mode. Toolbar Commands Use the Operating tool to operate objects. When you are in operate mode, events display on the right side of the toolbar. You can select, position, and size objects using the Editing tool. You can modify text associated with objects using the Labeling tool. You can change the color of objects using the Coloring tool. Clicking the right mouse button displays a color palette from which you can choose a color. Clicking with the left mouse button automatically colors the object with the current color of the coloring tool. You can pick up a color from and existing object or colored area by holding down the <Ctrl> key (the tool changes to an eyedropper icon, ) and clicking on the object. Menu Bar Commands All of the functionality in the User Interface Editor is found in the User Interface Editor Menu commands. We will be reviewing these commands as we progress through this lesson. There are commands to create panels, create controls, arrange controls, generate code, etc. By the time you finish with this lesson, you will be familiar with these commands.
LabWindows/CVI Basics I Course Manual 48 National Instruments Corporation

Creating a GUI
Panel Numeric Input Command Buttons

Graph

Above is an example of a simple GUI. This GUI consists of a panel, a numeric control, three command buttons, and a graph.

The GUI is the interface to your program that your users will see. Any functions in your program that you want to be accessible to the user should have an associated GUI control. Implementing a GUI is a two-step process. First, you graphically create the GUI with the User Interface Editor. LabWindows/CVI saves the user interface as a .uir file. Then, you use the commands in the User Interface Library to load the .uir file and process the GUI controls and indicators.

LabWindows/CVI Basics I Course Manual

49

National Instruments Corporation

Creating a Panel

Creating a Panel A panel in the User Interface Editor is a rectangular area that may contain a variety of graphical controls. To create a panel, select Create Panel (alternately, you can right-click in an area of the editor where there is no panel and select Panel from the pop-up menu).

LabWindows/CVI Basics I Course Manual

50

National Instruments Corporation

Panel Properties

Double-Click

Double-click on a panel to bring up its property page

Panel Properties The property page of the panel has four main sections. The top section is the Source Code Connection. You use the Source Code Connection section to link the panel to your source code.
The two options available in the Source Code Connection are defined as follows. These will make more sense as you start to program with them. Constant Name The constant name (also called the Resource ID) for the panel. You pass this ID to the LoadPanel function to load the panel into memory. The Constant Name is defined in the .h file when you Save the .uir file. Callback Function type the name of the function to be called when an event is generated on the panel. (Events and callback functions will be discussed shortly.)

Use the other three sections to set the panel size and appearance. After creating the panel, you can create the other objects by selecting the appropriate options from the Create menu. Note: A UIR file can have multiple panels associated with it, provided that each panel has a unique Constant Name.

LabWindows/CVI Basics I Course Manual

51

National Instruments Corporation

Creating Controls

To create a control, select the desired control from the Create menu. LabWindows/CVI will place the control on the panel. Alternately, you can right-click on any panel, and the same menu will appear. You can position the control using the mouse or arrow keys.

LabWindows/CVI Basics I Course Manual

52

National Instruments Corporation

Control Properties

Double-Click

Control Properties Like a panel, you can edit a control by double-clicking on it. Depending on the control being edited, the Edit Control dialog box usually has six sections, titled Source Code Connection, Control Settings, Shortcut Key, Control Appearance, Quick Edit Windows, and Label Appearance. (On some controls, the Shortcut Key section will not appear.) Use the Source Code Connection section to link the control to your source code. You use the other sections to set the different control attributes. Constant Name The User Interface Editor appends the constant name of the control to the constant name of the panel to create the Resource ID for the control. The Resource ID identifies the control in any control-specific function such as GetCtrlVal (discussed shortly). The Resource ID is defined in the .h file when you save the .uir file. For example, the Resource ID for the control on this slide would be PANEL_GENERATE if it were placed on the panel of the previous slide (the constant name of the panel is PANEL and the constant name of the control is GENERATE). The _ separates the panel constant name and the control constant name. Callback Function Type the name of the function to be called when an event is generated on the control. (Events and callback functions will be discussed shortly.)

After creating the GUI, save it by selecting File Save or Save As. LabWindows/CVI will save the user interface as a .uir file.

LabWindows/CVI Basics I Course Manual

53

National Instruments Corporation

Control Labels, Shortcut Keys


The underline in Quit is created by placing a double underscore in the Label field. When a control has an underlined character, press <Alt-Char> to access it.

When you create a control such as a command button, you can create special keys as shortcuts to the control. This can be done in two ways. One is to type a double underscore before any letter in the label. When you do this, LabWindows/CVI underlines the character immediately following the double underscore. If you do this, the user can select the control by pressing <Alt> and the underlined letter, provided no menu bar is accessible. This feature helps you access controls on pop-up panels. For example, notice the underlined Q in the Quit button on the slide. To create this, place a double underscore before the Q in the Label field. You can also set up shortcut keys for the control. You do this by setting up the Shortcut Key section of the Edit Control dialog box. In the above example, when the user presses <Shift-F3>, the command button behaves as if it were clicked with the mouse.

LabWindows/CVI Basics I Course Manual

54

National Instruments Corporation

Tab Order

From the UIR Editor Window, select Edit Edit Tab Order

Each control on a panel has a position in the tab order. The tab order determines which control becomes the next active control when the user presses <Tab> or <Shift-Tab>. Usually, you will set the tab order to help maintain a logical flow for your program. When you create a control, it is added to the end of the tab order. When you copy and paste a control, the new control sits immediately before the source control in the tab order. To put the panel into tab order edit mode, select Edit Tab Order. Click on a control (with the special pointer cursor), to change the tab position of a control to the number in the Click to set to box. You can change the cursor to the special eyedropper cursor by holding down the <Ctrl> key. This eyedropper cursor changes the number in the Click to set to box to the current tab position associated with that control. The new tabbing order will appear in the black box on the right side of the control, while the original tab order will appear in the white box. Clicking on sets the new tab order. Clicking on keeps the original tab order.

LabWindows/CVI Basics I Course Manual

55

National Instruments Corporation

Graph Control Zooming


Checkbox to enable zooming

The LabWindows/CVI Graph Control has built-in zooming and panning. Double-click on the graph control to set the Enable Zooming option.

Zooming and Panning on Graphs You can use zooming, the ability to expand or contract the viewport around a particular point in the graph control. When you zoom in, the area of the graph shown in the viewpoint gets smaller, thereby showing the area with higher resolution. When you zoom out, the viewport shows a wider area. You can also use panning, which is the ability to shift the viewport left, right, up, or down. By default, however, zooming and panning are disabled. You must explicitly enable them programmatically or in the User Interface Editor. Also, a graph control must be in Hot mode if zooming and panning are to be used. (Hot mode will be described later in this lesson.) To start zooming in on a point, press the <Ctrl> key and press the left mouse button with the cursor over the point to zoom in around. The resolution of the viewport is continuously increased until you release the mouse. (You do not need to keep pressing the <Ctrl> key.) If you drag the mouse, the zooming continues, but does so over the new point under the mouse. The zooming stops when you release the left mouse button or click on the right mouse button. You zoom out just like you zoom in, except that you use the right mouse button instead of the left mouse button. To start panning, press <Ctrl-Shift> and the left mouse button with the cursor over a point on the viewport. Drag the mouse to another point. The graph viewport is scrolled so that the original point now appears under the new mouse cursor location. You can drag the mouse anywhere on the screen. To restore the viewport to its original state after zooming or panning, press <Ctrl-Spacebar>. If you are using autoscaling in the graph, the autoscaling should be temporarily disabled while zooming or panning. If any plotting occurs while the end user is zooming or panning, the zooming or panning is terminated and the new data is shown using autoscaling.
LabWindows/CVI Basics I Course Manual 56 National Instruments Corporation

User Interface Header File

The User Interface Header File is the link between the UIR and the application program.

Once you save the .uir file, LabWindows/CVI automatically generates a header file (.h). The file contains the user-defined, unique Resource IDs identifying the controls (along with the corresponding values assigned by LabWindows/CVI.). The header file is the link between the .uir file (which contains the GUI) and the program (which contains the User Interface Library functions). For this reason, you must include the .h file at the beginning of the application program.

LabWindows/CVI Basics I Course Manual

57

National Instruments Corporation

Exercise 2-1 (5 min.)

Objective: To view and run an application program containing a GUI.

LabWindows/CVI Basics I Course Manual

58

National Instruments Corporation

Exercise 2-2 (15 min.)

Objective: To play with some of the features of a GUI.

LabWindows/CVI Basics I Course Manual

59

National Instruments Corporation

Commonly Used Controls - I


String Controls

Text Message

Numeric Controls Text Box Controls

Command Button Controls

Numeric Controls Numeric controls are used to input or display numeric values. A typical use of these controls might be to input or display a voltage value. Numeric controls have many different graphical representations, including knobs, meters, thermometers, gauges, and dials. To operate a numeric control with the mouse: Click on the up/down arrows of the digital display to change the value of the control. Click on and drag the needle (for circular controls like knobs) or the slider (for slide controls) to change the value of the control. Click on the scale labels to set the control to the value of the label. String Controls String controls are used to input or view a string of characters. You can use these controls to input user or instrument information. Text Message Text messages are indicators used to programmatically display strings of text. You cannot operate them using the keyboard, but you can assign callback functions to them so that they respond to mouse-click events. Text Box Controls Text box controls are large string controls that feature line, word, and character wrap modes as well as scroll bars to facilitate displaying large amounts of text. As with the string control, you can interactively enter text into the text boxes and you can control the text box programmatically. Command Button Controls Command buttons are used to trigger an action, which is indicated by the label on the button. To operate a push button with the mouse, click on the button. The button remains depressed until the user releases the mouse button or moves it off the button.
LabWindows/CVI Basics I Course Manual 60 National Instruments Corporation

Commonly Used Controls - II

LED Controls Binary Switch Controls Toggle Button Controls

Ring Controls

Toggle Button Controls Toggle button controls allow you to select between two different states. A toggle button has two positions: pressed or unpressed. When the button is pressed, its value is 1; when it is not pressed, its value is 0. To operate a toggle button with the mouse, click on the toggle button to change its state. LED Controls LEDs (Light Emitting Diodes) indicate an on/off state. When the LED is on, its value is 1 and it displays its ON color. When the LED is off, its value is 0 and it displays its OFF color. LED controls operate like toggle button controls. Binary Switch Controls Binary switch controls, like toggle buttons, allow you to select between two states: on or off. You can also associate a value with each state of a binary switch. Binary switch controls operate like toggle button controls Ring Controls You use ring controls to select from a group of items. Many of the ring controls look like numeric controls, but ring controls have a finite set of label/value pairs. Ring controls with arrows can be operated in a pop-up format by clicking in the text area of the control. This will display all ring items in a linear list.

LabWindows/CVI Basics I Course Manual

61

National Instruments Corporation

Commonly Used Controls - III

List Box

Decorations

Picture Strip Chart

List Box Controls List box controls are used to select an item from a list. They can also be used as an intelligent text box because they accept escape codes that allow you to change the color of individual characters as well as create columns. Decorations Decorations are used to enhance the visual appeal of the GUI. They do not contain data (they can, however, contain bitmaps), but they can be assigned callback functions so that they can respond to mouse clicks. Strip Chart Controls Strip chart controls display graphical data in real time. A strip chart consists of one or more traces that are updated simultaneously. Picture Controls A picture control allows you to place images on panels, such as logos and diagrams. For example, you can use a picture control to place a schematic that instructs the user how to hook up a unit for testing. When you want to place images on a command button, toggle button, or on a ring control, LabWindows/CVI frees you from programming the simple Picture control. Separate command, toggle buttons, and ring controls exist for pictures. The image formats that work with all types of picture controls appear below. Image Format PCX BMP, DIB, RLE, ICO XWD WMF, EMF
LabWindows/CVI Basics I Course Manual

Platform Windows and UNIX Windows only UNIX only Windows 95 and NT only
62 National Instruments Corporation

Commonly Used Controls - IV

Graph

Timer

Canvas

Graph Controls Graph controls display graphical data as one or more plots. A plot consists of a curve, point, geometric shape, or text string. Graph controls can have one or more cursors associated with them. With cursors, you can select a point or region of the graph for further processing or analysis. Operate a graph with cursors using the mouse as follows. Drag a cursor to move it. If the cursor is in snap-to-point mode, the cursor tracks the mouse until the user releases the mouse button and then it snaps to the nearest data point. If the cursor is in free-form mode, the cursor tracks the mouse until the user releases the mouse button and then stays at the new position. Move the active cursor left and right by dragging the active cursor marker at the top or bottom edge of the plot area. Likewise, you can move the active cursor up and down by dragging the active cursor marker at the left or right edge of the plot area. Timer Controls Use timer controls to trigger actions at specific time intervals. The timer control schedules these actions so that you do not have to schedule them. Timer controls repeat a given action at a specified time interval for an indefinite period of time, which makes them useful programming tools when a repeated action is required. You can specify a function to be called at the end of each interval. LabWindows/CVI has functions to suspend and reset the timer controls. Timer controls are not visible during program execution. They are visible only in the User Interface Editor. Timer controls will be discussed in greater detail later in this lesson. Canvas Controls Use canvas controls as an arbitrary drawing surface. You can draw text, shapes, and bitmap images. An offscreen bitmap is maintained so the appearance of the canvas can be restored when the region is exposed. If you want to display images that are not rectangular or that have holes in them, you can use bitmaps that have a transparent background.

LabWindows/CVI Basics I Course Manual

63

National Instruments Corporation

Exercise 2-3 (15 min.)

Objective: To build a graphical user interface.

LabWindows/CVI Basics I Course Manual

64

National Instruments Corporation

User Interface Library


Panels Load Panel Display Panel Pop-up Panels Message Popup LoadPanel DisplayPanel

MessagePopup

Controls/Graphs/Strip Charts: General Functions Set Control Value SetCtrlVal Get Control Value GetCtrlVal User Interface Management Run User Interface RunUserInterface Quit User Interface QuitUserInterface

The User Interface Library contains many functions for programming the menus, panels, and controls in the .uir file. Among these functions are loading and displaying menu bars and panels, controlling strip charts, graphs, push buttons and LEDs, and receiving user input from the objects in the .uir file. The tables on this and the next page list the User Interface Library functions discussed in this lesson. The table is fashioned after the LabWindows/CVI User Interface Library menu.

LabWindows/CVI Basics I Course Manual

65

National Instruments Corporation

User Interface Library


Controls/Graphs/Strip Charts: Graphs and Strip Charts: Graph Plotting and Deleting Plot Y PlotY Delete Graph Plot DeleteGraphPlot Controls/Graphs/Strip Charts: Graphs and Strip Charts: Strip Chart Traces Plot Strip Chart PlotStripChart Clear Strip Chart ClearStripChart

LabWindows/CVI Basics I Course Manual

66

National Instruments Corporation

User Interface Library


Functions in the User Interface Library are used to: Load panels Display panels Manipulate controls

Controlling a Graphical User Interface After you build your GUI, you must develop a C program to process the events generated from the user interface and to control the flow of your program. LabWindows/CVI features two basic methods for designing your programs: callback functions and event loops. You can use either method in your program or combine methods for added flexibility. This course covers only callback functions. The User Interface Library contains many functions for programming the menus, panels, and controls in the .uir file. Among these are functions for loading and displaying menu bars and panels, controlling strip charts, graphs, command buttons, and retrieving user input from objects on the GUI. Note: All User Interface Library functions return an integer code containing the call result. If the code is negative, an error occurred. Otherwise, the function completed successfully. Loading a Panel To load a panel into memory, use the LoadPanel function. LoadPanel returns a handle used to reference the panel in subsequent operations. (Think of a handle as a reference number.) int panelHandle = LoadPanel (int parentPanelHandle, char filename [],int panelResourceID); panelHandle: The unique specifier that defines a particular panel in a particular file. This is the value you must use in subsequent function calls to specify this panel. If you want this panel to appear inside of another panel, you specify the panelHandle of the panel in which you want to display this panel. The name of the .uir file in which the panel is saved. The constant name that was given to this panel in the User Interface Editor.

parentPanelHandle:

filename: panelResourceID:

LabWindows/CVI Basics I Course Manual

67

National Instruments Corporation

User Interface Library Continued

Displaying a Panel Loading a panel does not automatically display it. Use the DisplayPanel function to display a panel. int status = DisplayPanel (int panelHandle); The panelHandle parameter is the value returned from LoadPanel and determines which panel to display. Notes LabWindows/CVI uses the defined constant name assigned to the panel (PANEL in the source code on the previous page) to reference the panel only when loading it from the resource file. After the panel loads, you must use the panel handle (panelHandle in this case). LabWindows/CVI automatically breaks on run-time errors if you set the Debugging Level to Standard or Extended. To change the Debugging Level, go to the Project Windows, and from the menu bar select Options Run Options. If you set the Debugging Level to NONE (or No Run Time Checking), your program executes faster; however, you will need to check for errors as shown in the example on the previous page.

LabWindows/CVI Basics I Course Manual

68

National Instruments Corporation

Set Control Value


SetCtrlVal is used to update the value of a control on the user interface

Setting Control Values You use the SetCtrlVal function to set the value of a panel control. The value can be an integer, a floating point, a string, and so on. It must match the data type of the control being modified. int status = SetCtrlVal (int panelHandle, int controlID, void value); panelHandle controlID value the value returned from LoadPanel the Resource ID of the control to modify the value the control on the GUI will display

The code fragment in the slide shows how you can set the value of two different controls. The first SetCtrlVal function displays the value of buffer (Hello) in the string indicator PANEL_STROUT. The second SetCtrlVal function displays the value of number (1.23) in the numeric indicator PANEL_NUMOUT. Note that the variable, number, and control object, Numeric Output, are both associated with the data type of double. Run-time errors result when the datatype of the variable and the control object to do not match.

LabWindows/CVI Basics I Course Manual

69

National Instruments Corporation

Get Control Value


GetCtrlVal is used to retrieve the value of a control on the user interface

Getting Control Values You use the GetCtrlVal function to get the value from a panel control. The value can be an integer, a floating point, a string, and so on. It must match the data type of the control being queried. int status = GetCtrlVal (int panelHandle, int controlID, void *value); panelHandle ControlID value The value returned from LoadPanel. The Resource ID of the control to query. The value of the control on the GUI.

The code fragment in the slide shows how you can get the value of two different controls. The first GetCtrlVal function queries the string indicator PANEL_STRIN for its value and stores the result in buffer (you can see the results of buffer in the variables window). The second GetCtrlVal function queries the numeric indicator PANEL_NUMIN for its value and stores the result in number. Notice that you must pass the address of number because its value is modified in the function call.

LabWindows/CVI Basics I Course Manual

70

National Instruments Corporation

Set Control Attribute


Attributes define the characteristics of an object

Setting Control Attributes In LabWindows/CVI, all user interface objects have attributes such as color, visibility, position, and size. Some objects have specific attributes. For example, a graph has attributes for its left and right axes, plot color, grid lines, and so on. Many of these attributes can be set in the UIR editor. Using SetCtrlAttribute, you can change the current value of an attribute programmatically. int status = SetCtrlAttribute (int panelHandle, int controlID, int controlAttribute, ...); panelHandle ControlID ControlAttribute ... The value returned from LoadPanel. The Resource ID of the control to modify. The attribute you wish to modify. The new setting for that attribute. This can be of any data type and can have a variable number of parameters; therefore, it is defined as a variable size parameter.

The code fragment in the slide shows how you can set the attributes of a control. The first SetCtrlAttribute function sets the color of the command button to BLUE. The second SetCtrlAttribute function sets the top of the command button to be at pixel 20.

LabWindows/CVI Basics I Course Manual

71

National Instruments Corporation

SetCtrlAttribute Function Panel

Click

There are defined constants for each attribute that can be set. Remembering all of these constants is not necessary (or likely). LabWindows/CVI has special function panels that assist you in finding the attributes you want to set. By left-clicking on the Control Attribute parameter in the function panel, you get a special dialog box that lists all the possible attributes organized in a hierarchical fashion. The dialog also presents the attributes in an easily understandable format with help on each attribute. You can filter attributes for the particular control type you are working on by changing the Control Type ring control. Once the desired attribute has been selected, select OK to get back to the function panel.

LabWindows/CVI Basics I Course Manual

72

National Instruments Corporation

SetCtrlAttribute Function Panel

Press Enter

Once the desired attribute has been selected, the user can press OK. Certain attributes, such as color, have predefined discrete values associated with them. These values can be selected from a dialog box by pressing <Enter> in the Attribute Value parameter of the function panel. Other attributes, such as height, can have a range of values associated with them and require the developer to enter the attribute value manually.

LabWindows/CVI Basics I Course Manual

73

National Instruments Corporation

Get Control Attribute


Attributes define the characteristics of an object

Getting Control Attributes Not only can you set the specific attributes of a control, you can also retrieve them programmatically. The function you use is called GetCtrlAttribute. int status = GetCtrlAttribute(int panelHandle, int controlID, int controlAttribute, void *attributeValue); panelHandle ControlID ControlAttribute AttributeValue The value returned from LoadPanel. The Resource ID of the control to modify. The attribute you want to query. The memory location (that is, the address of the variable) that will store the value of the attribute

The code fragment in the slide shows how you can get the value of two different attributes of a control. The first GetCtrlAttribute queries the control for the pixel location of the top edge, while the second GetCtrlAttribute queries the control to determine whether or not it is visible.

LabWindows/CVI Basics I Course Manual

74

National Instruments Corporation

Panel Attributes

Panel Attributes Panels also have attributes associated with them. The functions used for setting or retrieving them are called SetPanelAttribute and GetPanelAttribute. int status = SetPanelAttribute(int panelHandle, int panelAttribute, ...); panelHandle PanelAttribute ... The value returned from LoadPanel. The attribute you want to query. The new setting for that attribute. This variable must match the data type of the attribute you want to set.

int status = GetPanelAttribute(int panelHandle, int panelAttribute, void *attributeValue); panelHandle PanelAttribute AttributeValue The value returned from LoadPanel. The attribute you want to query. The location to store the value of the attribute.

The code fragment in the slide shows how you can set an attribute of the panel (add scrollbars) and then retrieve the attribute from a panel (query the panel for its title).

LabWindows/CVI Basics I Course Manual

75

National Instruments Corporation

Event Driven Programming

When you program with LabWindows/CVI, you are generating event-driven code. When you are using event-driven code, you are physically linking an object on the user interface (for example, a command button) with a function in your code. Every time you perform an action on the UIR control, an event is generated. LabWindows/CVI determines which control the event occurred on, and if you have a callback function associated with the control, the function is invoked. The slide above shows that an event on GENERATE calls the function GenerateWfm. Likewise, DEL PLOTS calls DeletePlots, and QUIT calls Quit. Not every control on a panel requires a callback function. The Num Cycles has no callback function associated with it. For example, to pass information to and from the Num Cycles control, use SetCtrlVal and GetCtrlVal. Every callback function in LabWindows/CVI has the exact same prototype. The first parameter is the handle (not Constant name!) of the panel on which the control is located. The second parameter is the Contstant ID of the control that generated the event. The third parameter is which event was generated that caused the callback function to be invoked. The fourth parameter is callback data, which is used to pass data between callback functions. This can be of any user-defined data type and is not discussed in this course. The fifth and sixth parameters are data generated with the event and are different for each event. We will discuss events and eventData1 and 2 shortly.

LabWindows/CVI Basics I Course Manual

76

National Instruments Corporation

Viewing Run-Time Events


You can use the operator tool from the toolbar to view the different runtime events that are generated

The LabWindows/CVI graphical user interface editor has a convenient tool that allows the programmer to see what type of events are generated by certain actions on the GUI he or she creates. Once you finish creating the panel and all controls, you can select the operator tool from the toolbar and perform run-time type actions (clicking buttons, etc.) around the panel. As you click around on the panels and controls, you will see in the upper-right corner all the events you are generating. These are obviously slowed down so that they can be seen, but the events you are looking for in your code are all shown. At the heart of every GUI program written in LabWindows/CVI, there is a function called RunUserInterface. This function is generally called once in main after the first panel is loaded and displayed. RunUserInterface is the function that continually monitors the UIR for events and makes sure that these events are passed on to the proper callback function. RunUserInterface not only detects and reports which events occur, but also the control and panel on which the events occur. This is important, because chances are you do not want a left-click on the Acquire Data button to do the same thing as a left-click on the Exit Test button. By using the information of what event was generated and on what object it was generated, the CVI programmer has a lot of versatility in how he or she controls the execution of the final application.

LabWindows/CVI Basics I Course Manual

77

National Instruments Corporation

LabWindows/CVI Events
Event Type Control and Menu Events Control Event Control and Panel Event Event EVENT_COMMIT panel control eventData1 p c eventData2 EVENT_VAL_CHANGED EVENT_LEFT_CLICK EVENT_LEFT_DOUBLE_CLICK EVENT_RIGHT_CLICK EVENT_RIGHT_DOUBLE_CLICK EVENT_KEYPRESS EVENT_GOT_FOCUS EVENT_LOST_FOCUS p p p p p p p p p p p ptr to time ptr to time since last tick event c c c c c c c c x x x x key code y y y y ptr to key code

EVENT_CLOSE EVENT_PANEL_SIZE EVENT_PANEL_MOVE Continuous EVENT_TIMER_TICK Event Panel Event

x = x coordinate of the mouse relative to the control or panel y = y coordinate of the mouse relative to the control or panel

Applications written in LabWindows/CVI that take advantage of a GUI operate on a principle called event-driven programming. This simply means that unlike other text-based programs, which execute top to bottom, LabWindows/CVI executes segments of code (called callback functions) in response to events that occur on the user interface. These events can occur on any object on the panel or on the panel itself. The basic events that CVI looks for are events such as left-clicks, right-clicks, left and right double-clicks, and so on. In future lessons in this course and the LabWindows/CVI Basics II course, you will see that CVI can respond to events other than the simple ones discussed here. For example, you can have a serial port generate an event when a certain number of bytes have been received, or if your application is set up to run as a TCP/IP server, an event is generated when a client connects. A table of all the basic events that your user interface monitors is shown in the slide above. A few of the less self-explanatory events are given below: EVENT_COMMIT A control generates a commit event when you click on a control with the left mouse button and release the mouse button while still on top of the control, or if you select a control and press <Enter>. This is valid only if the control mode is set to Hot or Validate. EVENT_GOT_FOCUS and EVENT_LOST_FOCUS A control generates a got focus event when it is made the active control. To make the control the active control, you can either perform a mouse click on the control or use the <Tab> key to tab to the control. The control that loses the input focus (the control that was previously the active control) generates a lost focus event. To help get an understanding of events, load and run \CVI\BASICS1\EVENTS.PRJ. This project is an example of the different events that you will be able to see on a typical user interface.
LabWindows/CVI Basics I Course Manual 78 National Instruments Corporation

Control Modes

Control Modes Controls in LabWindows/CVI have four different control modes. Normal specifies that the user can operate the control and that it can be changed programmatically. Hot is identical to normal except that the control generates a commit event when acted on by the user. Normally, a hot control generates a commit event when its state is changed. For example, if you move a binary switch from off to on, a commit event is generated. Validate is identical to hot except that, before the commit event is generated, the program validates all numeric controls on the panel that have their range-checking attribute set to Notify. LabWindows/CVI checks the control value against a predefined range. If it finds an invalid condition, LabWindows/CVI activates the control, causing a notification box to display. The validate control cannot generate a commit event until the user enters a new valid value into all controls that are out of range. This process ensures that all numeric/scalar controls are valid before the commit event is reported to your application program. Indicator specifies that you can change the control programmatically, but users cannot generate commit or value-changed events. Strip chart and text message controls are always indicators.

LabWindows/CVI Basics I Course Manual

79

National Instruments Corporation

Processing Events
RunUserInterface QuitUserInterface ProcessSystemEvents

When programming, it is not sufficient just to make applications that are functional. A good programmer always makes sure that his or her program is also well behaved. When developing applications in LabWindows/CVI, it is very important to understand the way the workhorse functions operate. The three functions we will discuss in this section are RunUserInterface, QuitUserInterface, and ProcessSystemEvents. As we have just discussed and demonstrated, a callback function is called when an event occurs on an object. What happens if an event occurs while the program is busy executing another callback function? Does the event get lost? When does the event get handled? Well, the event does not get lost, but when it gets handled depends on the currently executing callback function. What happens is that this new event is queued up, and its callback function executes when the application hits RunUserInterface again (that is, when execution returns from the currently executing function). This is generally not a problem, unless the callback the program is currently in takes a long time to execute. It could be a matter of seconds or even tens of seconds before the program responds to the queued event (depending on the length of the current callback). Earlier in this lesson, it was stated that RunUserInterface is at the heart of every GUI application in CVI. At the heart of RunUserInterface however, is the function ProcessSystemEvents. ProcessSystemEvents is actually the function that monitors and updates the user interface. RunUserInterface is really little more than ProcessSystemEvents in a while loop. At any point in the program, the programmer can make an explicit call to ProcessSystemEvents, even inside a callback function. This can come in handy when you know that a particular callback will take a long time to execute and you want to make sure that other events are being handled. When the code hits ProcessSystemEvents, it goes out and executes any callbacks that may have been queued up and then returns to continue where it left off.

LabWindows/CVI Basics I Course Manual

80

National Instruments Corporation

Relationship of Run/QuitUserInterface

General relationship between RunUserInterface and QuitUserInterface

So, how does QuitUserInterface tie into all of this? QuitUserInterface disables RunUserInterface. It is important to understand that QuitUserInterface does NOT quit the application. The applications we have looked at so far quit because RunUserInterface is the last function in main. QuitUserInterface just allows execution of the main to return from RunUserInterface and continue on like a normal C-based application. The code in the slide shows how to envision the relationship between the two functions.

LabWindows/CVI Basics I Course Manual

81

National Instruments Corporation

Exercise 2-4 (20-25 min.)

Objective: To take a look at different events and to write a program that takes advantage of events.

LabWindows/CVI Basics I Course Manual

82

National Instruments Corporation

Code Builder
The CVI Code Builder makes the development of your application easier and faster.

To make the development of your application easier and faster, LabWindows/CVI has a built-in code builder engine. The code builder automatically generates skeleton code based on the layout of the user interface and the user-defined preferences set in the Code Preferences menu of the User Interface Editor. You then make modifications to the skeleton code that allows for a very quick and structured development. The skeleton code generated is syntactically correct and runs without any modifications, but serves no function until you add in the functional code. To generate code, select Code Generate All Code. Code builder will ask you to select a function that will be the quit function because applications generally have at least one callback that calls QuitUserInterface. Code builder creates the main function for you and generates a callback function for each object you specified as needing a callback function from the User Interface editor. In the main function, any panels you select from the code builder menu are loaded and displayed if you select this as an option when generating the code.

LabWindows/CVI Basics I Course Manual

83

National Instruments Corporation

Code Builder
Select Code Preferences Default Control Events

Skeleton code is created from the preferences selected

You can select the different Default events that are monitored in your program by selecting Code Preferences Default Control/Panel Events. The screen shot above shows the screen for Default Control Events. Notice that you can select many of the events discussed previously for each control. In this screen, we have checked EVENT_COMMIT and EVENT_RIGHT_CLICK. When we select Generate All Code, a skeleton code (as shown in the slide above) is created. Notice that the events we chose in our preferences are generated in the C code.

LabWindows/CVI Basics I Course Manual

84

National Instruments Corporation

Exercise 2-5 (10 min.)

Objective: To use the code builder to create the same application that was created in Exercise 2-3.

LabWindows/CVI Basics I Course Manual

85

National Instruments Corporation

Exercise 2-6 (10 min.)

Objective: To understand how to develop well behaved applications in LabWindows/CVI.

LabWindows/CVI Basics I Course Manual

86

National Instruments Corporation

Pop-Up Panels

MessagePopup ("LabWindows/CVI, "CVI Rocks"); ConfirmPopup ("This is a ConfirmPopup, "Press Yes or No");

PromptPopup ("Prompt Me, "Please Enter Your Login Name Below", login, 10);

LabWindows/CVI has a number of high-level pop-up panels that can be called. These panels will simply pop up and wait for the user to address them before the program continues. The simplest of these is MessagePopup. MessagePopup takes two parameters; the first determines the text of the title bar, and the second determines the text of the message itself. MessagePopup is generally used for online help and to display status information. ConfirmPopup is similar, but instead of offering only one button for the user to press, there are two buttons. One button is labeled Yes; the other is labeled No. The function returns which button was pressed. Another convenient pop-up panel is PromptPopup. This function will pop up a message that prompts the user for a response string before moving on. The parameters are like the MessagePopup parameters, but include variables to store the response and an integer to limit the length of the response. These pop-up panels and many others can be found in the User Interface Library under the Pop-Up Panels subclass.

LabWindows/CVI Basics I Course Manual

87

National Instruments Corporation

Timer Control
Use a timer to carry out periodic tasks. When a timer tick occurs, the timer callback function is invoked.

So far, all the events we have been working with have been events generated by the users actions. As was mentioned earlier in the chapter, things other than the user can cause events to occur. One of the most common of these is a timer. A timer is a special type of control that the programmer can place on the user interface that continuously generates an event (EVENT_TIMER_TICK) at a periodic interval throughout the duration of the application. This event can be used to periodically call a segment of code. A common application of this may be when you need to monitor temperature or pressure in a tank. Because it is unlikely that these values will change rapidly, the application can probably get by just checking these values once per second. A timer could be set up so that once per second, it jumps into its callback routine that performs these operations. To get a timer control in your application, start by dropping a timer on your panel in the User Interface Editor. This timer will not appear at runtime, so you can place it anywhere. By double-clicking on the timer object, you will pop up the Edit Timer screen. The callback function in the Source Code Connection block determines which function is called every time the timer goes off. The Interval input controls how often the timer goes off. The unit is seconds and the resolution is 1 ms (0.001 s). Notice in the code that the event the callback is looking for is an EVENT_TIMER_TICK. The code placed in this case statement is executed once per interval. Just as you can programmatically perform functions on other controls in the user interface, there are functions that can be called to regulate the behavior of timers. For example, a call can be made to SuspendTimerCallbacks to temporarily suspend all timers, and ResumeTimerCallbacks can re-enable them. ResetTimer can be used to reset the interval start time for a timer. Just like all other controls, you can use SetCtrlAttribute to modify the specific attributes for a given timer, such as its interval and whether or not it is active.

LabWindows/CVI Basics I Course Manual

88

National Instruments Corporation

Strip Charts
Strip charts are used to display continuously acquired data.

You use the PlotStripChart function to plot points on a strip chart. int status = PlotStripchart (int panelHandle, int controlID, void *yArray, int numberOfPoints, int startingIndex, int skipCount, int yDataType); Using the PlotStripChart function can be confusing at first, because you must pass the point in an array. Although this passing may appear awkward at first, you can use it to plot multiple traces on a strip chart. Assuming one point is plotted per trace, each element in the array contains the point for each trace. The entire trace would be plotted by calling the PlotStripChart function in a looping structure such as a For Loop. yArray contains the points to be plotted. For example, yArray[0] = value for trace 1 yArray[1] = value for trace 2 yArray[n-1] = value for trace n numberOfPoints is the number of points to be added to the strip chart. If you are adding only one point per trace, numberOfPoints is equal to the number of traces. startingIndex is the starting index in yArray where the first point begins. In most cases, startingIndex is zero, and skipCount is also zero. yDataType specifies the data type for the yArray. The example in the slide shows a strip chart with one trace. Timers are often used to collect data and display it on a strip chart.
LabWindows/CVI Basics I Course Manual 89 National Instruments Corporation

Strip Charts
You can display more than one trace at a time.

The code fragment above shows how two traces of 10 random points are plotted on a strip chart. When plotting two traces, you must configure the strip chart to expect two traces. You do this by double-clicking on the strip chart in the GUI editor and selecting Traces. If you plot twice to a strip chart, the new data will be appended to the end of the previous data. If you want to clear the strip chart, you can use the function ClearStripChart. int status = ClearStripChart (int panelHandle, int controlID); panelHandle controlID The handle returned from LoadPanel for the panel that the strip chart is on. The Resource ID of the strip chart to clear.

LabWindows/CVI Basics I Course Manual

90

National Instruments Corporation

Strip Charts

To plot two traces on a strip chart, you must first configure the strip chart control in the User Interface Editor to plot two traces. To configure the strip chart, double-click on the control and select Traces.

LabWindows/CVI Basics I Course Manual

91

National Instruments Corporation

Exercise 2-7 (25 min.)

Objective: To create an application that displays three plots on a strip chart.

LabWindows/CVI Basics I Course Manual

92

National Instruments Corporation

Exercise 2-8 (30 min.)


(Challenge/Optional)

Objective: To modify Exercise 2-5 to cause the counter to continually increment/decrement if the mouse button is held down.

LabWindows/CVI Basics I Course Manual

93

National Instruments Corporation

Summary Lesson 2
Created and used GUIs The GUI editor is used to create the panels Common user interface controls Panels are controlled with the User Interface Library routines Event-driven programming The Code Builder creates a program shell from the GUI Timer controls are used for continuous, timed events Strip charts are used to display data as it is obtained Keyboard events Pop-up panels allow you to use predefined panels for simple actions

LabWindows/CVI Basics I Course Manual

94

National Instruments Corporation

Lesson 3
Data Acquisition
Objectives: Learn about data acquisition basics: analog-to-digital theory, signal processing, system configuration, board considerations, etc. Learn about DAQ ECHO controls and how to build a DAQ application quickly Learn about the Easy I/O Library Learn how to create an analog input application Learn how to create an analog output application Learn how to create a digital I/O application Learn additional information about DAQ application programming

This lesson introduces the use of plug-in data acquisition (DAQ) boards and the associated LabWindows/CVI functions. The LabWindows/CVI Data Acquisition Library contains functions to perform a wide range of acquisition and control operations. The supported interface buses span the spectrum of ISA, EISA, PCMCIA, PCI, Sbus, NuBus, PXI, USB, and parallel. LabWindows/CVI provides three levels of DAQ functionality: DAQ ECHO controls, the Easy I/O Library, and the Data Acquisition Library. In this course, we will focus on DAQ ECHO controls and the Easy I/O Library, which are easy to use and provide the flexibility necessary for most DAQ applications.

LabWindows/CVI Basics I Course Manual

95

National Instruments Corporation

DAQ Designer
- Reduces the complexity of building a data acquisition (DAQ) system - Saves you time by guiding you through the selection process and making recommendations - Ensures that you select all the products and components you need

With the growing power and flexibility of computers and workstations, you can now create virtual instruments whose capabilities were formerly restricted to vendor-defined, standalone instruments. The advent of plug-in DAQ boards paves the way to user-defined virtual instruments, where acquisition, analysis, and presentation capabilities are now merged into one system. National Instruments data acquisition boards can provide a variety of functions analog-to-digital (A/D) conversions, digital-to-analog (D/A) conversions, digital input/output (DIO), and counter/timer operations. The selection of the proper board depends on the signal sources, physical environment, financial resources, computer system limitations, grounding schemes, data acquisition components, performance requirements, and much more. To simplify the data acquisition selection process, you can use National Instruments DAQ Designer. This software application serves as a decision aid when it comes to selecting the proper board for your application. DAQ Designer is available for free from National Instruments and will quickly help you identify the necessary system components and accessories best suited for your data acquisition solution. You can obtain a copy of DAQ Designer from our web site, request a DAQ Designer CD from our sales department, or use it interactively via our web page. Your instrumentation solution can now include multifunction I/O boards, dynamic signal acquisition hardware, digital I/O, computer-based instruments (such as oscilloscopes, arbitrary waveform generators, etc.), signal conditioning modules, and motion control. As a computer-aided selection tool, DAQ Designer will help you navigate through the National Instruments product line and help reduce your decision-making time.

LabWindows/CVI Basics I Course Manual

96

National Instruments Corporation

Exercise 3-1 (15 min.)

Objective: To explore the functionality of DAQ Designer.

LabWindows/CVI Basics I Course Manual

97

National Instruments Corporation

DAQ System Components


B - Laptop computer with a PCMCIA-DAQ

A A - Desktop PC with a plug-in DAQ board B

The fundamental task of a DAQ system is the measurement or generation of real-world physical signals, where a signal is a physical phenomenon whose magnitude varies with time. Often, the plug-in DAQ board is considered to be the entire DAQ system; however, the board is only one of the system components. Before the signal can even be processed by a computer-based system, there are several factors that must be taken into consideration: the signal measurement system, signal conversion, and signal conditioning. This signal measurement system involves understanding the importance of ground, different types of signal sources, and how one implements measurements. The method by which one measures system or chassis ground throughout the instrumentation system may lead to the pickup of unwanted noise, such as common-mode noise, which must be taken into account. Whether the signal source is left floating or referenced may also influence the quality of data obtained, because the integrity of acquired data depends on the entire analog or digital signal path. Depending on the signal source chosen, this will determine the type of measurement system needed (single ended, nonreferenced single ended, and differential). Signal conversion is necessary because physical signals may not be in a format that is desirable for the instrumentation system. More often than not, the format of choice is either current or voltage. Therefore, physical signals such as strain, pressure, temperature, etc., must be converted to electrical signals through a device called a transducer. Examples of transducers include thermocouples, RTDs (Resistive Thermal Devices), strain gauges, photoelectric cells, piezoelectric crystals, and many others.

LabWindows/CVI Basics I Course Manual

98

National Instruments Corporation

DAQ System Components Continued

In addition, unlike most standalone instruments, sometimes you may not be able to connect a converted signal to a data acquisition board directly. Before the signal can be connected to a DAQ board, you might need to insert a signal-conditioning accessory, such as a National Instruments SCXI module, to modify the incoming electrical signal. Factors that may need to be taken under consideration can be remembered through the acronym FILTA (filter). FILTA stands for Filtering (removing unwanted frequency components), Isolation (separating high voltages), Linearization (handling nonlinear conversion), Transducer excitation (energy source for transducer performance), and Amplification (creating a detectable signal). An in-depth study of these factors is outside the scope of this course, but they are important enough to mention when you are designing a data acquisition system. Once the signal measurement system, signal conversion, and signal conditioning have been integrated into the total system, you can take subsequent steps to build the DAQ application.

LabWindows/CVI Basics I Course Manual

99

National Instruments Corporation

DAQ Software Architecture Windows 95


Win95 Device Manager LabWindows/CVI

NI-DAQ Configuration Utility

DAQ Import Library

nidaq32.dll for Win95 Win95 Registry


DAQ-STC

DAQ Board

Hardware configuration of a data acquisition board will depend on whether a board is plug and play (PnP) or not. National Instruments E-Series boards are plug and play; therefore, the operating system assigns the necessary hardware resources. Legacy boards contain dip-switches and jumpers for the three primary resources: base I/O address, interrupts (IRQ), and direct memory access (DMA). These resources must be selected in a manner so that they do not conflict with the settings of other boards in the system. Regardless of whether or not the board is PnP, the DAQ board must be configured through software using the NI-DAQ driver software. For this class, the boards have been configured already. The following section presents highlights of DAQ board setup for the Windows 95 platform. The LabWindows/CVI setup program, in combination with the NI-DAQ installation, copies the required files for LabWindows/CVI DAQ onto your computer. LabWindows/CVI for Windows 95 DAQ functions use an import library, dataacq.lib, to access the National Instruments standard NI-DAQ for Windows 95 32-bit dynamic link library (DLL). The NI-DAQ setup program installs the NIDAQ32.DLL in the windows\system directory. NI-DAQ for Windows 95 supports all National Instruments DAQ Boards and SCXI modules. The NIDAQ32.DLL file, the high-level interface to your board, is loaded in the Windows 95 System directory. The NIDAQ32.DLL file then interfaces with the Windows 95 Registry to obtain the configuration parameters defined by the NI-DAQ Configuration Utility. The Windows 95 Configuration Manager keeps track of all the hardware installed in your system, including National Instruments DAQ boards. If you have a plug and play board, the Windows 95 Configuration Manager automatically detects and configures your board. If you have a non-PnP board (known as a legacy device) you must configure the board manually using the Windows 95 Add New Hardware option under the Control Panel.
LabWindows/CVI Basics I Course Manual 100 National Instruments Corporation

DAQ Software Architecture


Use the NI-DAQ Configuration Utility to configure your DAQ cards Information is stored in the Windows 95 Registry and niconfig.daq Start Programs CVI NI-DAQ Configuration Utility

You can check the Windows 95 Configuration by accessing the Device Manager (Start Settings Control Panel System). You will find Data Acquisition Devices, which lists all DAQ boards installed in your computer. Highlight a DAQ board and select Properties or double-click on the board, and you will see a dialog window with two tabbed pages (General and Resources). The General tab displays overall information regarding the board. You use the Resources tab to specify the system resources to the board such as interrupt levels, DMA, and base address for software configurable boards. NI-DAQ for Windows 95 installs the NI-DAQ Configuration Utility, which establishes all board configuration parameters. After installing a DAQ board in your computer and configuring the board with the Device Manager as described above, you must run this configuration utility. The utility reads the information that the device manager records in the Windows 95 registry and assigns a logical device number to each DAQ board. You use the device number to refer to the board in LabWindows/CVI. You access the configuration utility by selecting Start Programs CVI NI-DAQ Configuration Utility. The figure above shows the primary NI-DAQ Configuration Utility window. The NI-DAQ Configuration Utility is also the means for SCXI configuration. The board parameters that you can set using the configuration utility depend on the board. The configuration utility saves the logical device number and configuration parameters in the Windows 95 registry.

LabWindows/CVI Basics I Course Manual

101

National Instruments Corporation

Exercise 3-2 (10 min.)

Objective: To open the NI-DAQ Configuration Utility and study the current setup. You will also test the board interactively with the utility.

LabWindows/CVI Basics I Course Manual

102

National Instruments Corporation

DAQ ECHO Controls


Extended Code Hierarchy Object Easily output and acquire signals from your DAQ hardware with very little programming Right-click configuration at run time daq_num.fp daqchart.fp

DAQ ECHO (Extended Code Hierarchy Object) controls are CVI User Interface controls that have been extended to have DAQ capabilities. Currently, there are two types of DAQ ECHO controls available: DAQ Numerics and DAQ Charts. A DAQ Numeric is simply a user interface display such as a tank, thermometer, or knob that is automatically tied to an analog channel. You can set a DAQ Numeric to any input or output channel, including SCXI channels. A DAQ Chart is a strip chart that can be tied to one or more analog input channels, and it features display, alarm, and data logging capabilities. LabWindows/CVI provides two instrument drivers (daq_num.fp and daqchart.fp) in the \cvi\toolslib\custctrl directory that allow you to quickly build simple DAQ applications (in a later lesson, you will learn more about creating and using instrument drivers). You can use the daq_num.fp driver to create and configure DAQ-based numeric controls and the daqchart.fp driver to create and configure DAQ-based charts. With DAQ ECHO controls, you can output and acquire signals from your National Instruments data acquisition hardware with very little programming. You can customize the operation of DAQ controls at run-time by simply right-clicking on the control and changing the user-configurable properties. For more information regarding DAQ ECHO controls, select Help Search for Help on. Type ECHO in the query box. Select Display to display more information on DAQ ECHO controls. DAQ Numeric Controls A DAQ Numeric control can be in input mode or output mode. When the control is in output mode, the value is tied to an associated analog channel. When the control is in input mode, its value is periodically updated by reading the voltage from its associated analog input channel at the rate specified by the refresh frequency. DAQ Chart Controls A DAQ Chart control is a strip chart that automatically reads and plots data from its associated input channels. DAQ Charts maintain a history buffer containing the acquired data and can be configured to watch for alarm conditions and log data to disk. The input channels, data acquisition rate, and so on can be configured programmatically or interactively.
LabWindows/CVI Basics I Course Manual 103 National Instruments Corporation

Exercise 3-3 (15 min.)

Objective: To build a DAQ application quickly using ECHO controls.

LabWindows/CVI Basics I Course Manual

104

National Instruments Corporation

Easy I/O Library


The Easy I/O for DAQ Library makes it easier to write DAQ programs You will use the Easy I/O for DAQ Library in this course Easy I/O functions are listed in the course manual All Easy I/O functions return a status code 0 indicates no error Nonzero values indicate an error

Easy I/O Library The Easy I/O for DAQ Library makes it easier to write simple DAQ programs than if you just used the Data Acquisition Library. The Easy I/O for DAQ Library implements a subset of the Data Acquisition Library functionality, but it does not use the same functions. The table on the next page lists the Easy I/O for DAQ functions. Handling Easy I/O Errors All Easy I/O for DAQ Library functions return a value of zero if they complete successfully. If there is a problem during function execution, the function returns a nonzero value. You can find a list of error codes for an Easy I/O for DAQ function by right-clicking on the Error control in its function panel. Also, you can call the GetDAQErrorString function for a description of the numeric error codes returned by function calls in the Easy I/O for DAQ Library. char *GetDAQErrorString (short errorNumber);

LabWindows/CVI Basics I Course Manual

105

National Instruments Corporation

Easy I/O Library Functions

Easy I/O for DAQ Function Names: Analog Input AISampleChannel AISampleChannels AIAcquireWaveforms AIAcquireTriggeredWaveforms Asynchronous Acquisition AIStartAcquisition AICheckAcquisition AIReadAcquisition AIClearAcquisition PlotLastAIWaveformsPopup Analog Output AOUpdateChannel AOUpdateChannels AOGenerateWaveforms AOClearWaveforms Digital Input/Output ReadFromDigitalLine ReadFromDigitalPort WriteToDigitalLine WriteToDigitalPort CounterRead CounterStop ICounterControl Miscellaneous GetDAQErrorString GetNumChannels GetChannelIndices GetChannelNameFromIndex GetAILimitsOfChannel GroupByChannel SetEasyIOMultitaskingMode

LabWindows/CVI Basics I Course Manual

106

National Instruments Corporation

Analog Input Considerations


Single-Ended vs. Differential Resolution Range Gain

Analog Input The most common use for data acquisition systems is the sampling of data channels. However, when measuring analog signals with a DAQ board, you must consider the following factors that affect the digitized signal quality: single-ended and differential inputs, resolution, range, sampling rate, and noise. Analog Input Considerations Single-ended vs. Differential: In a differential system, inputs are not connected to a fixed reference, but are measured via the difference between two terminals. By measuring the difference in voltage, the noise that each channel acquires can effectively be subtracted from the end measurement. The drawback is that in differential mode, only half the number of channels are available, as compared to single-ended mode. Therefore, if the number of channels is critical, the voltage levels are high (>1 V), and the distance is relatively short (<15 ft.), single-ended mode may be the preferred configuration. For the best accuracy and good noise immunity, the desired input mode is differential. Resolution: Resolution is the number of bits that the analog-digital converter (ADC) used to represent the analog signal. The higher the resolution, the higher the number of divisions into which the range is divided, and therefore, the smaller the detectable voltage change. The figure in the slide shows a sine wave and its corresponding digital image that a 3-bit ADC obtains. A 3-bit converter (which is seldom used but makes a convenient example) divides the range into 23 or eight divisions. A binary code between 000 and 111 represents each division. The digital signal is not a good representation of the original signal because information is lost in the conversion. By increasing the resolution to 16 bits, however, the ADCs number of codes increases from eight to 65, 536 (216), and it can obtain an extremely accurate representation of the analog signal.
LabWindows/CVI Basics I Course Manual 107 National Instruments Corporation

Analog Input Considerations

Range: Range refers to the minimum and maximum voltage levels that the ADC can quantize. DAQ boards offer selectable ranges (typically 0 to 10 V or 10 to 10 V) to match the signal range to that of the ADC and to take advantage of the resolution available to accurately measure the signal. Gain: Gain refers to any amplification or attenuation of a signal that may occur before the signal is digitized. By applying gain to a signal, you can effectively decrease the input range of an ADC and thus allow the ADC to use as many of the available digital divisions as possible to represent the signal. For example, using a 3-bit ADC and a range setting of 0 to 10 V, the figure in the slide shows the effects of applying gain to a signal that fluctuates between 0 and 5 V. With no gain applied, or gain = 1, the ADC uses only four of the eight divisions in the conversion. By amplifying the signal with a gain of two before digitizing, the ADC now uses all eight digital divisions, and the digital representation is much more accurate. Effectively, the board now has an allowable input range of 0 to 5 V, because any signal above 5 V when amplified by a factor of two makes the input to the ADC greater than 10 V. If you specify the voltage limits in your function calls, the NI-DAQ driver software will automatically supply the correct gain for the analog-to-digital converter. Note: This gain is used only for precision in the analog-to-digital conversion. The voltage level measured with the NI-DAQ driver will be readjusted to the correct level after the signal has been digitized.

LabWindows/CVI Basics I Course Manual

108

National Instruments Corporation

Analog Input Considerations


Code Width
range gain * 2
resolution in bits

10 1 * 2 16 = 0.15 mV

Sampling Rate
Adequately Sampled

Aliased due to undersampling

Noise

Code Width: The range, resolution, and gain available on a DAQ board determine the smallest detectable change in the input voltage. This change in voltage represents one least significant bit (LSB) of the digital value and is often called the code width. The smallest detectable change is calculated as:

code width =

range gain 2 resolution in bits

Sampling Rate: Sampling rate determines how often the conversions take place. A fast sampling rate acquires more points in a given time and therefore can often form a better representation of the original signal than a slow sampling rate. All input signals must be sampled at a sufficiently fast rate to faithfully reproduce the analog signal. According to the Nyquist Sampling Theorem, you must sample at least twice the rate of the maximum frequency component you want to detect in order to properly digitize the signal. For example, audio signals converted to electrical signals often have a frequency components up to 20 kHz; therefore, you need a board with a sampling rate greater than 40 kHz to properly acquire the signal. On the other hand, temperature transducers usually do not require a high sampling rate because temperature does not change rapidly in most applications. Therefore, a board with a slower sampling rate can acquire temperature signals properly. Noise: Unwanted noise distorts the analog signal before it is converted to a digital signal. The source of this noise may be external or internal to the computer. You can limit external noise by using proper signal conditioning and/or differential input mode. You can also minimize the effects of this noise by over-sampling the signal and then averaging the over-sampled points. The reduction in noise is linearly proportional to:

1/ number of points averaged


For example, if you average 100 points, the effect of the noise is the signal is reduced to 10% of the original noise. Note: The individual and accumulative effects of these factors require that preplanning and understanding of the entire data acquisition system be taken into consideration.

LabWindows/CVI Basics I Course Manual

109

National Instruments Corporation

Sampling Analog Channels - I


Acquiring a single voltage from a single input channel short AISampleChannel (short device, char singleChannel[], double highLimitVolts, double lowLimitVolts, double *voltage); Parameters device: board ID from the NI-DAQ configuration utility singleChannel[]: string representing the single channel highLimitVolts: maximum voltage to measure lowLimitVolts: minimum voltage to measure voltage: measured voltage

You will find the functions used for performing analog sampling in the Easy I/O for DAQ: Analog Input menu. We will break our discussion into three different segments: Acquiring a single voltage from a single channel Acquiring a single voltage from multiple channels Acquiring multiple voltages from single/multiple channels

In all of the functions, there are parameters for highLimitVolts and lowLimitVolts. These parameters are used internally by NI-DAQ to specify the gain. By using the best values of highLimitVolts and lowLimitVolts, you will get the most accurate digital representation possible.

LabWindows/CVI Basics I Course Manual

110

National Instruments Corporation

Sampling Analog Channels - II


Acquiring a single voltage from multiple channels short AISampleChannels (short device, char channelString[], double highLimitVolts, double lowLimitVolts, double voltageArray[]); Parameters device: board ID from the NI-DAQ configuration utility channelString[]: string representing the set of input channels highLimitVolts: maximum voltage to measure lowLimitVolts: minimum voltage to measure voltageArray: array containing the measured channel voltages

LabWindows/CVI Basics I Course Manual

111

National Instruments Corporation

Sampling Analog Channels - III


Acquiring multiple voltages from multiple channels
short AIAcquireWaveforms (short device, char channelString[], double numberOfScans, double scanSecond, double highLimitVolts, double lowLimitVolts, double *actualScanRate, short fillMode, double waveforms[]);

Parameters numberOfScans: number of scans to acquire scanSecond: number of scans to perform per second (timed by the DAQ hardware) actualScanRate: actual scan rate at which the acquisition took place fill mode: group by scan or group by channel waveforms: array containing the scanned data

AIAcquireWaveforms performs a timed acquisition of voltage data from the analog channels specified by channelString[]. A Scan is defined as one sample from every channel. The parameter scanSecond is the number of scans to perform every second. This parameter is analogous to the sample rate because one scan is the equivalent of one sample from every channel. Because the actual scan rate can vary from the requested scan rate (due to hardware limitations or other external factors), the actualScanRate is used in calculations to make the data accurate.

LabWindows/CVI Basics I Course Manual

112

National Instruments Corporation

Different Fill Modes


Group-By-Scan
Ch 1 Pt 0 Ch 2 Pt 0 Ch 1 Pt 1 Ch 2 Pt 1 Ch 1 Pt 998 Ch 2 Pt 998 Ch 1 Pt 999 Ch 2 Pt 999

1996 1997 1998 1999

Group-By-Channel
Ch 1 Pt 0 Ch 1 Pt 1 Ch 1 Pt 999 Ch 2 Pt 0 Ch 2 Pt 1 Ch 2 Pt 999

1 Channel 1 data

999

1000 1001 Channel 2 data

1999

If you are acquiring data from channels 1 and 2 and placing it into an array called buffer, the group-by-scan mode places the data in the buffer in the following manner (depicted in the top picture of the slide). Data is collected in scans (which you will recall is a data point from every channel). The hardware will read a voltage from channel one and then a voltage from channel 2. This will alternate until all of the data is collected. The data is placed into the array in the order it was received. In the group-by-channel mode, the data is placed in the buffer in the following manner (depicted in the bottom picture of the slide). Data is collected the same way, but instead of writing data to the array in the order it was received, it is placed in the array as if you collected all the data from channel 1 and then all of the data from channel 2. Therefore, the first data point collected (from channel 1) will go into the first entry into the array. Then, the second data point collected (the first point from channel 2) will be placed into the array at the point after where all of channel 1s data will be placed (for two channels, this will be the number of scans plus one). When performing the acquisition of waveforms from multiple channels, LabWindows/CVI acquires the samples at a uniform sampling rate, so they are equally spaced in the time domain. The DAQ board has special circuitry to ensure that the sampling rate is uniform and independent of the computer you are using.

LabWindows/CVI Basics I Course Manual

113

National Instruments Corporation

Sampling Analog Channels - IV


Quickly displaying timed analog data
short PlotLastAIWaveformsPopup (short device, double waveformsBuffer[]);

Parameters device: board ID specified by the NI-DAQ Configuration Utility waveformsBuffer: array containing the scanned data Data must be grouped by channel! Convert an array of group-by-scan to group-by-channel short GroupByChannel (double Array[], long Number_of_Scans, unsigned long Number_of_Channels);

If you are interested in quickly examining the timed analog data that was acquired by AIAcquireWaveforms, you can use the Easy I/O for DAQ Library function PlotLastAIWaveformsPopup. PlotLastAIWaveformsPopup plots the last waveform that was acquired from the function AIAcquireWaveforms. The data must be grouped by channel mode before it is passed to this function. If you acquired the data in group-by-scan mode, you can call GroupbyChannel (Easy I/O for DAQ: Miscellaneous) before calling PlotLastAIWaveformsPopup.

LabWindows/CVI Basics I Course Manual

114

National Instruments Corporation

The DAQ Signal Accessory

The exercises in this lesson use the DAQ Signal Accessory. Here are some of the highlights of this box.
The 5 V line from the DAQ board supplies power to the DAQ Signal Accessory. Analog input channels 1 and 2 are available at the quick connect terminal located in

the lower central portion of the top panel. The IC temperature sensor is hard-wired to AI channel 0 and is located in the lower-right corner of the top panel. The temperature sensor will return a voltage between 0 V and 1 V, corresponding to 0 C and 100 C, respectively.
Analog output channels 0 and 1 are available at the quick connect terminal located at

the lower central portion of the top panel.


The function generator is located in the lower central portion of the top panel. It

produces a sine wave and a square wave. Use the Frequency Range selector switch to select a frequency range and then use the Frequency Adjust knob next to it to further adjust the frequency.
There is a row of four LEDs in the middle of the DAQ Signal Accessory that

correspond to Lines 0 to 3 on Port 0 of the MIO board. The four LEDs use inverted logic.

LabWindows/CVI Basics I Course Manual

115

National Instruments Corporation

Exercise 3-4 (30 min.)

Objectives: I) To measure temperature using a DAQ board and plot it on a strip chart. II) To acquire waveforms from multiple channels.

LabWindows/CVI Basics I Course Manual

116

National Instruments Corporation

Asynchronous Acquisition
Returns immediately while board handles acquisition Data is stored in a circular buffer Flowchart demonstrates continuous, asynchronous acquisition
N

Start Start Acquisition Check Acquisition

Buffer 1/2 Full?


Y

Read Acquisition

Complete?
Y

Clear Acquisition Stop

When you are not concerned with time in your DAQ applications, the aforementioned Easy I/O functions serve their purpose well. However, if time is critical, the previously mentioned functions are synchronous, meaning that all the functions do not return control to your program until the DAQ board acquires all of the data points. If the acquisition takes a long time (for example, acquiring many points at a very slow sample rate), the computer cannot perform other tasks if you use synchronous calls. The LabWindows/CVI Easy I/O for DAQ Library contains functions that you can use to collect data in the background, allowing other parts of your program to run simultaneously. You can find these functions in the Easy I/O for DAQ : Analog Input : Asynchronous Acquisition menu. There are four functions that we will discuss: AIStartAcquisition AICheckAcquisition AIReadAcquision AIClearAcquisition

LabWindows/CVI Basics I Course Manual

117

National Instruments Corporation

Asynchronous Acquisition Functions


Allow you to perform other tasks while the DAQ board acquires data Use four functions: AIStartAcquisition AICheckAcquisition AIReadAcquisition AIClearAcquisition

Starting the Acquisition: short AIStartAcquisition (short device, char channelString[], int bufferSize, double scanSecond, double highLimitVolts, double lowLimitVolts, double *actualScanRate, unsigned long *taskID); device: channelString[]: bufferSize: scanSecond: highLimitVolts: lowLimitVolts: actualScanRate: taskID: board ID from the NI-DAQ configuration utility string representing the set of input channels size of the circular buffer in scans. This must be an even number number of scans to acquire per second maximum voltage to measure minimum voltage to measure actual rate at which the data was scanned identifier for the asynchronous acquisition which will be passed to all other asynchronous calls.

Checking the Acquisition: short AICheckAcquisition (unsigned long taskID, unsigned long *scanBacklog); taskID: scanBacklog: identifier for the asynchronous acquisition that was returned by AIStartAcquisition number of scans that have been acquired into the circular buffer but have not been read using AIReadAcquisition

LabWindows/CVI Basics I Course Manual

118

National Instruments Corporation

Asynchronous Acquisition Continued

Reading the Acquisition: short AIReadAcquisition (unsigned long taskID, long scansToRead, unsigned short readMode, unsigned long *scanBacklog, short fillMode, double waveforms[]); taskID: scansToRead: readMode: scanBacklog: fillmode: waveforms: identifier for the asynchronous acquisition that was returned by AIStartAcquisition number of scans that will be read from the internal circular buffer specifies whether to read the circular buffer starting from the last scan that was read or to read the most recently acquired data number of scans that have been acquired into the circular buffer but have not been read using AIReadAcquisition group-by-scan or group-by-channel contains the voltages acquired

Clearing the Acquisition: short AIClearAcquisition (unsigned long taskID, unsigned long *scanBacklog); taskID: scanBacklog: identifier for the asynchronous acquisition that was returned by AIStartAcquisition. number of scans that have been acquired into the circular buffer but have not been read using AIReadAcquisition

LabWindows/CVI Basics I Course Manual

119

National Instruments Corporation

Exercise 3-5 (20 min.)

Objectives: To perform asynchronous timed analog input using callback functions.

LabWindows/CVI Basics I Course Manual

120

National Instruments Corporation

Analog Output
Similar to analog input Used when you need to generate analog voltages Factors to consider are similar to analog input Range Resolution Monotonicity Linearity Settling Time Slew Rate

Analog Output Though analog input is the most common type of data acquisition, there are times when you need to generate analog voltages for purposes such as waveform generation, power sources, excitation, etc. National Instruments multifunction DAQ boards contain digital-to-analog (DAC) converters that can generate required output voltages. Factors Range: The range refers to the output range of the DAC in volts. DACs can be either unipolar or bipolar. Resolution: An n-bit DAC should be able to produce 2n distinct output voltages corresponding to its 2n possible digital values. Analog output accuracy is similar to analog input accuracy the higher the DAC resolution, the higher the number of digital levels, and hence, the higher the accuracy. Also, as the DAC range increases, the DAC accuracy decreases. Monotonicity: A DAC is monotonic if its analog output increases as the digital input increases. Linearity: The maximum deviation of the DAC transfer curve from an ideal straight line. Settling Time: This is the time required for the output to settle to the specified accuracy. The settling time is usually specified for a full-range change in voltage. Slew Rate: The slew rate is the maximum rate of change the DAC can achieve in the output signal. The slew rate is calculated as the desired change in DAC output voltage, V, divided by the time in which the change occurs, T. The slew rate is usually specified for a full-range change in voltage. Settling time and slew rate work together in determining how fast the DAC can change the output signal level. A DAC with a small settling time and a high slew rate can generate high frequency signals because little time is needed to accurately change the output to a new voltage level.
LabWindows/CVI Basics I Course Manual 121 National Instruments Corporation

Analog Output Functions


Allow you to output voltages from your DAQ board Uses three functions: AOUpdateChannel AOUpdateChannels AOGenerateWaveforms

Single Point to a Channel: short AOUpdateChannel (short device, char singleChannel[], double voltage); device: singleChannel[]: voltage: board ID from the NI-DAQ configuration utility analog channel where the voltage will be applied value that will be output to the analog channel

Single Point to Multiple Channels: short AOUpdateChannels (short device, char channelString[], double voltageArray[]); channelString[]: voltageArray[]: analog channel where the voltage will be applied values to be output to each analog channel

Generating a Waveform(s) to Multiple Channels: short AOGenerateWaveforms (short device, char channelString[], double updatesPerSecond, int updatesPerChannel, int iterations, double waveforms[], unsigned long *TaskID); updatesPerSecond: updatesPerChannel: iterations: taskID: how often a voltage will be applied per channel how many voltage values are stored in the array for each channel how many times to output the waveform. Pass a 0 for continuous generation. handle for the waveform. This is used if you set iterations to 0. You need to pass the taskID to AOClearWaveforms

LabWindows/CVI Basics I Course Manual

122

National Instruments Corporation

Exercise 3-6 (25 min.)

Objectives: To perform a single-point analog output operation.

LabWindows/CVI Basics I Course Manual

123

National Instruments Corporation

Digital Input/Output
Digital lines are grouped as ports For the AT-MIO-16E-2, there are eight lines to a port Uses TTL logic 0 V to 0.8 V is logic low 2.0 V to 5.5 V is logic high Can be used as either input or output

Digital Input/Output Features of the digital input and output functions vary depending on the type of DAQ board, but a few features remain constant for all types of DAQ boards. The Easy I/O for DAQ library takes advantage of these common features and includes some board-independent functions. Several digital I/O lines are grouped in a port (eight lines comprise a digital port on the MIO board used in this class). The digital I/O functions can write to and read from an entire port or a single digital line within a port. To write to an entire port, the functions write a binary pattern to the port to generate a digital output. To read from a port, the function return a byte of data as a digital input pattern. The mapping of the byte value to the digital I/O lines follows the line numbering. (For example, line 0 is the least significant bit and line 7 is the most significant bit for an 8-bit port.) When a port is configured as an input port, reading that port returns the value of the digital lines. In this case, external devices connected to and driving digital lines determine the state of those lines. If no external device is driving the lines, the lines float to some indeterminate state and can be read in either state 0 or state 1. If a port is configured as an output port, writing to the port sets each digital line in the port to a digital logic high or low, depending on the data written. In this way, you can use these digital lines to drive an external device. Reading and writing from an individual line is even simpler. You specify which port to read from and which line within that port you want to retrieve the value from. The resultant answer is either a one (logical high) or a zero (logical low). To write to a line, you specify the port and line that you want to change the state of and write a one (TTL high) or a zero (TTL low) to the port.

LabWindows/CVI Basics I Course Manual

124

National Instruments Corporation

Digital Input/Output Functions


Port I/O ReadFromDigitalPort WriteToDigitalPort

Reading from a Digital Port: short ReadFromDigitalPort (short device, char portNumber[], short portWidth, long configure, unsigned long *pattern); device: portNumber[]: portWidth: configure: the board ID specified in the NI-DAQ Configuration Utility which port to read the pattern from total width of the port in bits specifies whether to configure the digital port before reading. When calling ReadFromDigitalPort in a loop, you can increase performance by configuring the digital port only on the first iteration passed by reference, this variable contains the data read from the port

pattern:

Writing to a Digital Port: short WriteToDigitalPort (short device, char portNumber[], short portWidth, long configure, unsigned long pattern); device: portNumber[]: portWidth: configure: pattern: the board ID specified in the NI-DAQ Configuration Utility which port to write the pattern to total width of the port in bits specifies whether to configure the digital port before writing this variable specifies the new state of the lines in the port

LabWindows/CVI Basics I Course Manual

125

National Instruments Corporation

Digital Input/Output Functions


Line I/O ReadFromDigitalLine WriteToDigitalLine

Reading from a Digital Line: short ReadFromDigitalLine (short device, char portNumber[], short line, short portWidth, long configure, unsigned long *lineState); device: portNumber[]: line: portWidth: configure: lineState: the board ID specified in the NI-DAQ Configuration Utility which port to read the pattern from the individual bit or line within the port used for I/O total width of the port in bits specifies whether to configure the digital port before reading contains the state of the line. lineState can be either a zero (logical low) or a one (logical high)

Writing to a Digital Line: short WriteToDigitalLine (short device, char portNumber[], short line, short portWidth, long configure, unsigned long lineState); device: portNumber[]: line: portWidth: configure: lineState: the board ID specified in the NI-DAQ Configuration Utility which port to write to the individual bit or line within the port used for I/O total width of the port in bits specifies whether to configure the digital port before reading specifies the new state of the digital line. lineState can be either a zero (TTL low) or a one (TTL high)
126 National Instruments Corporation

LabWindows/CVI Basics I Course Manual

Exercise 3-7 (15 min.)

Objectives: To set or clear a digital I/O line.

LabWindows/CVI Basics I Course Manual

127

National Instruments Corporation

Summary Lesson 3
The DAQ ECHO controls allow you to quickly create a DAQ application. You can use the EASY I/O for DAQ Library to control plug-in DAQ boards. You can use the Easy I/O for DAQ Library functions to sample either a single channel or multiple channels. The Easy I/O for DAQ Library also features timed analog input capabilities. You can use the Easy I/O for DAQ Library function to output analog voltages and perform digital I/O operations. The User Interface and Analysis Libraries include functions to view and analyze the data acquired with the Easy I/O for DAQ Library. LabWindows/CVI uses the asynchronous functions from the Easy I/O for DAQ Library to collect data in the background. This feature is very useful if you are performing other tasks during the data acquisition.

LabWindows/CVI Basics I Course Manual

128

National Instruments Corporation

Lesson 4
Formatting and Scanning

Objectives: Reinforce the basic concepts of data conversion in C Explain the rules for building formatting strings Demonstrate the use of a few selected modifiers

LabWindows/CVI Basics I Course Manual

129

National Instruments Corporation

Data Conversion
Binary Value 0100 0001 0011 0100 0011 0101 Decimal 65 54 53 ASCII A 6 5

Decimal 65 stored differently than ASCII 65 Use data conversion to convert from ASCII to decimal and vice-versa To send a decimal 65 across a bus (i.e., GPIB, serial, network), you need to send the characters 6 and 5 Formatting and scanning automatically convert decimal 65 to the characters 6 and 5 (65)

Data Representation and Conversion In the world of computers, there are many ways to store data. If you look at the data found on contemporary machines, you can notice that it ranges from ordinary ASCII files (in human-readable form), to binary stored integer and floating-point numbers, to encrypted data. Different computers also have different ways of looking into this data when it is presented to them in the binary form (for example, Big Endian and Little Endian machines differ in byte order). The programmer needs to resolve and take care of all these issues and the programmer is you! The LabWindows/CVI compiler is an ANSI C compliant compiler. This means the user has access to formatted input and output functions from the standard library such as printf, scanf, etc. Those functions, in conjunction with getchar, putchar, atoi, atof and similar, are sufficient for any data manipulation, whether we talk about strings and characters, long and short integers, or single- and double-precision floating-point numbers.

LabWindows/CVI Basics I Course Manual

130

National Instruments Corporation

LabWindows/CVI vs. ANSI

In addition to these, LabWindows/CVI offers its own Formatting and I/O library. Functions from this library provide more powerful tools for putting together and breaking down your data structures, whether we are talking about strings of characters, arrays of floating-point numbers, or any combination of basic data types. All that in one function call! Naturally, to get such a power, you need to give up the simplicity of the formatting strings of ANSI C functions. For example, printing the famous Hello, world! with ANSI C printf function would look like this: printf ( %s\n , Hello, world! ); And using CVIs FmtOut function would look like this: FmtOut ( %s\n , Hello, world! ); As you can see, there is no difference between these functions when used for everyday outputs to the standard I/O screen. When dealing with more complex structures of data, formatting strings will increase in size and complexity. However, careful study of basic rules for drafting this formatting string will make even the most complicated conversions easy. Let us introduce the main functions that are covered in this chapter. Depending on your output target or input source (memory, file, or Standard I/O window), you have three formatting and scanning options to choose from. As with their ANSI siblings, these functions also take a variable number of arguments and format the output according to the given formatting string.

LabWindows/CVI Basics I Course Manual

131

National Instruments Corporation

Formatting Functions
Formatting:
Fmt (target, formatString, source1, source2, );

Target is created from source(s) Rules are applied based on the formatString target_spec < source_specs and literals < points to the target! Fmt, FmtFile, FmtOut

Formatting and Scanning Functions These functions allow you to convert datatypes. The Fmt, FmtFile, and FmtOut functions differ only in the target (a variable, a file, or the Standard I/O window, respectively). Similarly, the Scan, ScanFile, and ScanIn differ in the same respect. int Fmt (void *target, char formatString[], ...); int FmtFile (int fileHandle, char formatString[], ...); int FmtOut (char formatString[], ...); int Scan (void *source, char formatString[], ...); int ScanFile (int fileHandle, char formatString[], ...); int ScanIn (char formatString[], ...); Format Strings The formatting and scanning functions use format strings to determine how to convert the source argument(s) into the target argument(s). The format string is actually a mini-program that tells the formatting/scanning function exactly what operations to perform. The general syntax of the format string is as follows: "target_spec < source_specs and literals" (Formatting) source_spec > target_specs and literals (Scanning) Notice that because the format string is a string constant, it must be enclosed in quotes. The < and > symbols are a graphical reminder that the formatting direction is FROM the source(s) TO the target(s). The syntax shows that formatting functions build a single target from multiple sources and scanning functions break a single source into multiple targets.
LabWindows/CVI Basics I Course Manual 132 National Instruments Corporation

Scanning Functions
Scanning:
Scan (source, formatString, target1, target2, );

Divides the source into multiple targets Rules are applied based on the formatString source_spec > target_specs and literals > still points to the target(s)! Scan, ScanFile, ScanIn

LabWindows/CVI Basics I Course Manual

133

National Instruments Corporation

Format Codes
%s %100f %i[b2u]

% repetitions

format code

[modifiers]

Always preceded by a % Three components - repetitions, format code, and format modifier Common format codes - s, i, d, x, f, c

Format String Specifiers The specifiers on both sides of the < or > have the same general format: % repetitions formatcode [modifiers] The format symbol % always introduces format specifiers. The next string item is a repetition code. If the code is omitted, a one (1) is implied. This parameter indicates how many times the Fmt or Scan function should apply the particular format specifier. This parameter is useful when formatting arrays of numeric data. Repcodes are not allowed when the format code is a string (s). formatcode indicates the nature or type of data element. The commonly used types are: s string data i,d integer data x integer data in hexadecimal format f real number c character A few commonly used modifiers are: bn The b modifier specifies the length of the integer argument in bytes pn The p modifier specifies to what precision to convert a floating-point number x The x modifier tells a scanning function to discard the terminator tn The t modifier tells a scanning function to terminate on a particular character u The u modifier tells a scanning function to treat an integer as unsigned

LabWindows/CVI Basics I Course Manual

134

National Instruments Corporation

Array Formatting Example

Equivalent

For most of the examples on the next few pages, we will provide you with both the LabWindows/CVI method of data conversion and the ANSI C method of data conversion for comparison. We will start with a simple task of outputting the members of a double-precision array on the screen. To display an array of five double-precision numbers on the standard I/O windows with ANSI C functions, it takes a loop and a printf statement. With the Formatting function, it takes only one statement. Notice that the output of each of these functions is the same. Because both methods produce the same result, you can use either method in your program. As we start to discuss more complex formatting, you will see that the LabWindows/CVI functions are simpler, faster, and easier to use. In this example, we are using a repetition code of 5, specifying that we have five elements in the array. We are also using two modifiers, [p2] and [w5]. The [p2] modifier specifies the precision of the floating-point values (the number of decimal places to store) and the [w5] modifier says to use five characters to store the data. Therefore, you will notice that each number took exactly five characters in the Standard I/O window (four for the number and one for the space in between the numbers).

LabWindows/CVI Basics I Course Manual

135

National Instruments Corporation

Array Scanning Example

Similarly, the task of converting the string output of an instrument into a data array may be simplified by using Scan functions. Assuming that the instrument returns a string with comma delimited single-precision numbers, the conversion may be done with the ANSI sscanf function. Using the LabWindows/CVI Scan function, you can avoid having to list all the arguments. In the Scan function, the [b4] modifier designates the size of the floating datatype. Normally, LabWindows/CVI, as a 32-bit compiler, defaults to 32-bit integers and 64-bit floating-point numbers. Accordingly, the %d and the %f formatting codes assume 32-bit integers and 64-bit floats respectively. Therefore it is necessary to place the [b4] modifier for single-precision numbers in formatting strings and the [b2] modifier for short integers. The [x] modifier indicates that the numbers in the original string are delimited by a character, and we want to remove it from the final result.

LabWindows/CVI Basics I Course Manual

136

National Instruments Corporation

Removing Headers

Note: There is no variable for the header; the [d] modifier automatically removes it.

Sometimes you do not want or do not care what the header of the instrument string is. To ignore a part of the string, ANSI formatting strings use an asterisk. The Scan function uses the [d] modifier for discarding the data. It indicates that there is no target argument for this part of the original source buffer. Note that the %d format code indicates a decimal number. This is very different from the [d] modifier, which is used to discard the data.

LabWindows/CVI Basics I Course Manual

137

National Instruments Corporation

Modifying Byte Order

Note: This operation can be executed in place - it does not require a new or different buffer.

As mentioned before, different computers store binary information in different ways. If you are a PC (Little Endian) or Sun (Big Endian) user, you may not need to worry about this if your project is limited to your computer only and does not involve any external hardware that may have been built using different chips. However, if your application will establish some kind of binary connection with other hardware (or software), you must take care of your data format. Lets assume that your application must pass some binary data (for example, an array of 32 short (16-bit) integers) to another software component. (It is OK to assume software component here because even in the case of communication with hardware, CVI talks to the device driver, which is essentially a software component.) Lets further assume that this component accepts only binary data and that it accepts it in the Big Endian format, meaning high (most significant) byte first and low (least significant) byte second. If you are on the Sun platform, you are fine with sending the plain array to this component, because the Sun CPU stores the data the same way. If, however, you are on a PC, you must do some data conversion first before sending it out. The solution can be a simple loop that goes through all the numbers in the array and swaps the array elements. This solution is good, but it is also platform dependent. It will work on a PC platform, but if you use the same source code on the Sun platform, swapping is unnecessary and wrong in that case. LabWindows/CVI offers the modifier that solves this problem in one line (no unnecessary looping and swapping) and the solution is platform independent your array will always be of the desired order. The [b2] modifier in the example tells the Scan function that the data is a short, 2-byte integer. The [o10] modifier tells the Scan function that the byte order [o] is [10] (or a descending order of precedence) as compared to [01], which would be an ascending order of precedence.

LabWindows/CVI Basics I Course Manual

138

National Instruments Corporation

Discarding Unwanted Data

Sometimes you are particularly interested in a character in the string: something either begins with it or ends when that character is encountered. This example shows how to extract the information from the string that you need, discarding the rest. The chosen character of interest is @, which is typically found in an e-mail address. We are interested in dividing the email address around the @ to create separate strings with the user name and the domain name. The [tn] modifier indicates the character on which scanning should terminate. The ASCII code for @ is 64; thus, [t64] indicates that we should terminate the first %s when we see the @ symbol. The [x] modifier instructs LabWindows/CVI to skip over the @ character itself and not store it with either of the strings. If [x] was not used, the domain name string would have included the @ character. Note that if you didnt want to save the user name, you could have added the [d] modifier, and the Scan function would have discarded the user name.

LabWindows/CVI Basics I Course Manual

139

National Instruments Corporation

Formatting Examples

This page has multiple formatting examples showing different combinations of modifiers. The comments after each line indicate the value buffer contains. For a complete list of modifiers, refer to the Formatting and Scanning Modifiers section in the appendix.

LabWindows/CVI Basics I Course Manual

140

National Instruments Corporation

Exercise 4-1 (15 min.)

Objective: To use a Scanning function to parse a data string.

LabWindows/CVI Basics I Course Manual

141

National Instruments Corporation

Summary Lesson 4
Data conversion ANSI C compiler ANSI C conversion tools LabWindows/CVI conversion tools
Fmt makes (target from sources) Scan breaks (source to targets)

Data is often in a format which is unusable. Data conversion is used to convert the data from an unusable form to a usable form. Example: If you have a string of numeric data from an instrument, you need to convert the data from its string format to its decimal format to be able to manipulate it. Example: If you have an array of numeric data and you need to save it to disk, you may want to convert it to a string format so the data in the file is readable. LabWindows/CVI is an ANSI C compiler. Therefore, you have access to standard ANSI C conversion functions such as sprintf, sscanf, etc. LabWindows/CVI has powerful additional conversion functions that are easier to use and faster than the ANSI C counterpoints.

LabWindows/CVI Basics I Course Manual

142

National Instruments Corporation

Lesson 5
General-Purpose Interface Bus

Objectives: Learn about the IEEE 488 (GPIB) bus Learn about GPIB global variables Learn about basic GPIB communication Learn about GPIB service requests Learn how to troubleshoot common GPIB problems

The LabWindows/CVI General-Purpose Interface Bus (GPIB) Library contains a set of highlevel and low-level functions for communicating across the GPIB. High-level functions automatically execute sequences of commands that handle all necessary bus management operations while writing to or reading from a device. Low-level functions perform fundamental bus management operations and require knowledge of the GPIB protocol. This lesson introduces you to the GPIB Library. It explains how to establish communication with a device using a combination of high-level and low-level GPIB functions.

LabWindows/CVI Basics I Course Manual

143

National Instruments Corporation

GPIB Overview
International Standard GPIB = IEEE 488 = HP-IB 15 devices (usually 14 instruments and computer)

What is GPIB? Hewlett-Packard developed GPIB in the late 1960s and early 1970s. The Institute of Electrical and Electronic Engineers, Inc. (IEEE) standardized the GPIB bus in 1975 as IEEE 488. The terms GPIB, HP-IB, and IEEE 488 are all synonymous. The original purpose of GPIB was to allow computer control of test and measurement instruments; however, given that GPIB is quite versatile, applications also include computer-to-computer communication and control of scanners and film recorders. Because the original IEEE 488 document contained no guidelines for preferred syntax and format conventions, work continued on the specification to enhance system compatibility and configurability among test systems. This work resulted in a supplemental standard IEEE 488.2, Codes, Formats, Protocols, and Common Commands that you use with IEEE 488 (which was renamed to IEEE 488.1).

LabWindows/CVI Basics I Course Manual

144

National Instruments Corporation

GPIB Overview
24-pin cable Eight data lines Five bus management lines ATN, EOI, IFC, REN, SRQ Three handshake lines DAV, NFRD, NDAC Eight ground Three termination methods EOI Line Assertion EOS Character Byte Count (default)

The GPIB is a digital, 24-line parallel bus. It is made up of eight data lines, five bus management lines (ATN, EOI, IFC, REN, and SRQ), three handshaking lines (DAV, NRFD, and NDAC), and eight ground lines. GPIB communication uses an 8-bit parallel data transfer scheme. With this data transfer scheme, whole bytes are sequentially handshaked across the bus at a speed determined by the slowest participant in the transfer (that is, the slowest device). Because the unit of data across the GPIB bus is a byte (8 bits), the messages transferred are frequently encoded as ASCII character strings. There are three ways to signal the end of a data transfer. In the preferred method, GPIB provides a separate hardware line (EOI) that can be asserted with the last data byte. Alternately, a specific end-of-string (EOS) character can be sent at the end of (or in addition to) the EOI line assertion. Finally, the listener(s) can count the number of bytes handshaked and stop reading when a byte count limit is reached. The byte count method is most often used as a default terminator because the transfer stops on the logical OR of EOI, EOS (if used), and byte count. Thus, you typically set the byte count equal to or (slightly) larger than the expected number of bytes to read.

LabWindows/CVI Basics I Course Manual

145

National Instruments Corporation

GPIB Common Terms

Primary Address System Controller Controller-in-Charge

Talker/Listener Commands Data

Primary Address Every device, including the computer interface card, must have a unique primary GPIB address between 0 and 30. Primary address 0 is normally assigned to the GPIB interface board. The instruments on the GPIB can use addresses 1-30. System Controller The GPIB bus can have only one System Controller (usually your computer) that performs all the necessary addressing on the bus. The system controller is responsible for driving (asserting) the REN and the IFC lines. The controller in charge is responsible for driving the ATN line. You can have multiple instruments capable of being a controller, but you can have only one active controller (controller in charge) at any given time. Talkers and Listeners The GPIB allows the bus to have one talker and one or more listeners. A talker is the device that is sourcing data bytes, while a listener is a device that is receiving the data. Commands and Data To transfer instrument commands and data on the bus, the controller in charge addresses one Talker and one or more Listeners. To perform addressing, the controller sends commands. Commands are ASCII bytes that are sent with the ATN line active. Once everybody is addressed, the ATN line is dropped and data begins to be transferred from the talker to the listener(s). The high-level LabWindows/CVI GPIB functions automatically address talkers and listeners.

LabWindows/CVI Basics I Course Manual

146

National Instruments Corporation

GPIB Global Variables - ibsta


Mnemonic Bit Hex Type Description
ERR 15 8000 dev, brd GPIB error TIMO 14 4000 dev, brd Time limit exceeded END 13 2000 dev, brd END or EOS detected SRQI 12 1000 brd SRQ interrupt received RQS 11 800 dev Device requesting service CMPL 8 100 dev, brd I/O completed LOK 7 80 brd Lockout State REM 6 40 brd Remote State CIC 5 20 brd Controller-In-Charge ATN 4 10 brd Attention is asserted TACS 3 8 brd Talker LACS 2 4 brd Listener DTAS 1 2 brd Device Trigger State DCAS 0 1 brd Device Clear State 1998 National Instruments Corporation. All Rights Reserved.

The GPIB Library has three global integer variables: ibsta, iberr, and ibcntl. These variables contain the values of the GPIB status (ibsta), error (iberr), and byte count (ibcntl). ibsta updates after every function, ibcntl updates after I/O operation, and iberr updates when a GPIB error occurs. These three variables are very useful for debugging GPIB programs and are defined in the GPIB header file (gpib.h). In addition, you can examine their contents using the Variables window. GPIB Status ibsta All GPIB functions return a status word (16 bits) containing specific information about the state of the GPIB bus. If the most significant bit is set, a GPIB error has occurred. The table on the slide lists each valid status bit and its meaning. The most common status values that you will see are: ERR : This informs you that an error occurred during the last GPIB function. TIMO : This means that the last operation timed out. This is usually accompanied by the ERR bit. END : This means that the END signal (EOI or EOS) was detected. CMPL : This means that the last operation completed. CIC : This means that you are the controller in charge. ATN : This means that the ATN (bus management) line is asserted.

LabWindows/CVI Basics I Course Manual

147

National Instruments Corporation

GPIB Global Variables - iberr


Mnemonic Value Meaning
EDVR 0 System error ECIC 1 Function requires GPIB board to be CIC ENOL 2 No Listeners on the GPIB EADR 3 GPIB board not addressed correctly EARG 4 Invalid argument to function call ESAC 5 GPIB board not System Controller as required EABO 6 I/O operation aborted (timeout) ENEB 7 Nonexistent GPIB board EDMA 8 DMA error EOIP 10 Asynchronous I/O in progress ECAP 11 No capability for operation EFSO 12 File system error EBUS 14 GPIB bus error ESTB 15 Serial poll status byte queue overflow ESRQ 16 SRQ stuck in ON position ETAB 20 Table problem 1998 National Instruments Corporation. All Rights Reserved.

GPIB Error iberr iberr will indicate which GPIB error occurred. If the ERR bit of ibsta is not set, the value of iberr can be ignored. The table on the slide lists each error bit and its meaning. The most common errors that you will see are: EDVR: This is a driver error. This could mean that your driver is not installed correctly or you are trying to access a device that doesnt exist. ENOL: This means that there are no listeners at the address you are trying to communicate to. Verify the Primary Address of the instrument. EADR: This means that there is an addressing error. This is usually caused by having the primary address of the GPIB board set to the same address as the instrument you are trying to communicate with. EABO: This means that driver aborted the operation. This is usually seen on a GPIB read and is an indication that you wrote a command to the instrument that it didnt understand. Either verify spelling or look in the user manual of the instrument for valid commands. EBUS: This is a bus error. It usually means that there are no instruments connected to your computer or that all of the instruments are turned off. GPIB Count ibcnt The count variable contains the number of bytes transferred to or from the GPIB through the interface card. This is also used when you get an EDVR error to indicate which driver error occurred. A listing of the most common EDVR error codes are listed in the NI-488.2M (NI-488.2 for Windows 3.x) User Manual.
LabWindows/CVI Basics I Course Manual 148 National Instruments Corporation

GPIB Communication
Open/Close Find Board/Device Find Unused Device Online/Offline Configuration Change Config Parameter Bus Control Send Interface Clear Set/Clear Remote Enable I/O Write Read ibfind ibdev ibonl ibconfig ibsic ibsre ibwrt ibrd

There are two different protocols for communicating with GPIB devices, 488.1 and 488.2. All 488.1 function calls begin with the letters ib. Another feature of the 488.1 protocol is the philosophy of device handles. Usually, at the beginning of your program you will open a session to the GPIB board and/or your GPIB instruments. At the end of your program, you will usually close all sessions. When you open a session, you will have a handle to be used in subsequent function calls to refer to that particular session. The 488.1 commands can either be board level or device level. If the handle passed to the function is that of a board, it is known as a board-level function; if the handle that is passed to the function is that of a device, it is known as a device-level function. When you use a board-level function, you must manually perform low-level bus addressing. However, the device-level functions automatically address the device whose handle you pass. The 488.2 routines, on the other hand, do not use handles; instead, they have a parameter for the primary address of the device(s) to talk to. We will use the 488.1 functions in this course. The functions we will use are listed on the slide above.

LabWindows/CVI Basics I Course Manual

149

National Instruments Corporation

Opening/Closing Devices - I
Open a device ibfind - open session to board/device ibdev - open session to device Both return a handle which is used in subsequent calls Close a device ibonl - close session to board or device

Opening and Closing Devices Before using a LabWindows/CVI GPIB function (488.1 only) to communicate with an instrument, you must open a handle to the device with either the ibfind or ibdev function. When you open a session to a device using either function, it returns an integer value called the unit descriptor. To communicate to a particular device in all subsequent operations, such as ibwrt or ibrd, you reference the device using the unit descriptor. Find Board/Device ibfind opens a session to a GPIB board or to a preconfigured device that is configured in the device template. ibfind returns a unit descriptor used in all references to that board or device in subsequent GPIB functions. If ibfind cannot get a valid descriptor, 1 is returned. int board/device = ibfind (char *board/deviceName); board/deviceName: This is a string containing a default or preconfigured device or board name. The device strings are assigned in the device template, which can be found in the Device Manager, GPIB Control Panel, or ibconf (depending on your particular OS). The board names can be found in the configuration utility for the particular board (also found in the Device Manager, GPIB Control Panel, or ibconf).

LabWindows/CVI Basics I Course Manual

150

National Instruments Corporation

Opening/Closing Devices - I
General Programming Flow: Open and configure all devices Communicate with all devices Close all sessions to devices

Find Unused Device ibdev provides a more robust method of opening devices than using ibfind. When using ibdev, you can programmatically specify most of the information that is stored within the device template (that is, Primary Address, Board Index, Timeout Value). By using ibdev, you make your code more portable across computers by not relying on a specific device template. ibdev returns a unit descriptor used in all references to that device in subsequent GPIB functions. If ibdev cannot get a valid descriptor, a 1 is returned. int device = ibdev (int boardIndex, int primaryAddress, int secondaryAddress, int timeoutValue, int ENDMessage, int EOSCharacter); boardIndex: A number specifying which GPIB board to which the instrument is connected. primaryAddress: The Primary Address of the device. secondaryAddress: The Secondary Address of the instrument. Pass a 0 if secondary addressing is not used. timeoutValue: The time the driver will wait for the transfer to complete before aborting the transfer. This value does not have a direct decimal equivalent. You can look up the valid values in your NI-488.2(M) Function Reference Manual or in the header file gpib.h. (For a 10-second timeout, you can use either the number 13 or the macro T10s.) ENDMessage: Determines whether you will assert the EOI line when transferring the last byte (1 is yes/0 is no) for write operations. EOSCharacter: Used to configure the driver to stop transmitting data when you send a particular EOS character and/or terminate its read when it detects the particular EOS character. For valid values, refer to the NI-488.2(M) Function Reference Manual or look at the function panel help.

LabWindows/CVI Basics I Course Manual

151

National Instruments Corporation

Opening/Closing Devices - II

Example using ibfind, ibdev, and ibonl

Online/Offline When you use either ibdev or ibfind, you are creating an entry into a table created by the driver. Because this table has only a finite number of entries available to store unit descriptors, you should close all unit descriptors when you are finished with them. The function call used to close a device is called ibonl. This function either takes a device offline or restores a device to its default configuration (that is, the parameters in the ibdev call or the device attributes in the internal tables if using ibfind). int status = ibonl (int board/device, int operationMode); board/device: The unit descriptor returned by ibfind or ibdev operationMode: Determines whether the device should be placed offline (0) or reset to its original configuration (1)

LabWindows/CVI Basics I Course Manual

152

National Instruments Corporation

Configuration

ibconfig allows you to programmatically change the attributes of a given instrument.

Configuration The GPIB Library allows you to modify the configuration of your GPIB interface programmatically. This allows you the flexibility to reconfigure your board/device whenever necessary. Change Config Paramerter ibconfig modifies the settings of a particular board or device. There are two sets of options, board and device. When the first parameter is a valid board descriptor, the board options are in use. When the first parameter is a valid device descriptor, the device options are in use. int Status = ibconfig (int board/device, int option, int value); board/device: The unit descriptor returned by ibfind or ibdev option: A number or macro specifying which configurable item you want to change. For a list of options, see your NI-488.2(M) Function Reference Manual or check the ibconfig function panel. value: The value to which you want to set the particular option

LabWindows/CVI Basics I Course Manual

153

National Instruments Corporation

Bus Control

Using ibsic and ibsre allows you to set the bus into a known state.
Bus Control The GPIB Library offers a variety of functions to handle bus configuration. The two functions discussed in this section are ibsic and ibsre. Send Interface Clear This function causes the GPIB board to assert the Interface Clear (IFC) signal for at least 100 S provided the GPIB board has System Controller Capability. This places all devices on the GPIB bus into a known quiescent state and makes the interface board Controller-in-Charge. This action must initially be done to establish Controller status. It is a good habit always to use this action at the beginning of your code. int status = ibsic (int board); board: The unit descriptor returned by ibfind Set/Clear Remote Enable This function (ibsre) turns the Remote Enable (REN) signal on and off. Devices use the REN line to select between local and remote mode. Many older devices require this line to be asserted before you can control them via GPIB. It is a good habit to always use this at the beginning of your code. int status = ibsre (int board, int lineStatus); board: The unit descriptor returned by ibfind operationMode: Specifies whether to assert (1) or unassert (0) the REN line

LabWindows/CVI Basics I Course Manual

154

National Instruments Corporation

Input/Output

ibwrt and ibrd allow you to send data to and receive data from your instrument.

Input/Output The GPIB Library contains many functions that handle all aspects of GPIB communication. The most important and most frequently used functions are the write and read functions. These two functions are discussed below. Write This function will write data from your computer to a device. int status = ibwrt (short board/device, void *dataBuffer, unsigned long byteCount); Board/device: The unit descriptor returned by ibfind or ibdev dataBuffer: Contains the data to be sent over the GPIB byteCount: Specifies the number of bytes to be written. It is usually the string length of dataBuffer. Read This function will read data from the device and store it in computer memory. int status = ibrd (short board/device, void *dataBuffer, unsigned long byteCount); Board/device: The unit descriptor returned by ibfind or ibdev dataBuffer: The variable where the data that is read from the GPIB will be stored byteCount: Specifies the maximum number of bytes to be read.

LabWindows/CVI Basics I Course Manual

155

National Instruments Corporation

Exercise 5-1 (25 min)

Objective: To establish communication with a GPIB instrument.

LabWindows/CVI Basics I Course Manual

156

National Instruments Corporation

Exercise 5-2 (30 min)

Objective: To continuously obtain data from the device simulator using GPIB.

LabWindows/CVI Basics I Course Manual

157

National Instruments Corporation

GPIB Service Requests


Callbacks Install Synchronous Callback Install Asynchronous Callback Device Control Get Serial Poll Byte ibInstallCallback ibnotify

ibrsp

In GPIB communication, the controller dictates when tasks are performed. No device can communicate unless it is addressed to talk. A device may, however, need to communicate with the controller before the controller tells it to talk. To do this, any device can assert the SRQ line, which is separate from the data lines, to inform the controller that it needs attention. Consider a situation in which an instrument generates a large amount of data, or takes a long time to collect a data point. You want the instrument to send that data to the controller as soon as the data is acquired. The controller could perform a read and wait until the device sends data. This will cause your program to hang while waiting for the device to send you data with a potential for timeout errors if the device does not respond before the timeout period ends. An alternate method is to have the device assert the SRQ line when it has finished collecting data so that the controller can then start reading it. The controller will acknowledge the service request by polling to determine which instrument needs service. Once the controller finds the correct instrument, it will interpret the status byte and act appropriately. By using service requests, you can allow your system to do other work while your instrument is collecting data.

LabWindows/CVI Basics I Course Manual

158

National Instruments Corporation

Serial Polling
SRQ line indicates an instrument needs service Serial poll instruments to determine who requested service Automatic Serial Poll Manual Serial Poll Serial Poll Status Byte determines if and why the instrument requested service Bit 6 of the byte determines if the instrument requested service All other bits are instrument defined

The purpose of the SRQ line is to signal the controller that a device needs service. When the SRQ line is asserted, it is the responsibility of the Controller to determine who requested service by checking all devices individually. A serial poll obtains specific information from a device. When you serial poll a device, you are asking it to return its serial poll status byte. The serial poll status byte is different for each instrument with the exception of one bit. Bit 6 (hex 40) of any serial poll status byte indicates whether a device requested service by asserting the SRQ line. The device uses the other seven bits of the status byte to specify why it needs attention. Automatic Serial Polling By default, whenever the SRQ line is asserted, our GPIB driver will conduct a serial poll of every instrument connected to the bus and determine which instruments asserted the SRQ line. The driver informs you as to which instrument asserted the line by setting the RQS bit of the instruments ibsta (you can get the ibsta value for any instrument by calling ibwait with the unit descriptor of the instrument as the first parameter). This phenomenon is known as AutoSerialPolling and can be turned on in the configuration utility or programmatically using ibconfig. Alternately, you can conduct the serial polls manually by turning off AutoSerialPolling. This allows you to look for the SRQI bit in the ibsta of the GPIB board (again, use ibwait but use the unit descriptor of the GPIB board). The SRQI bit will inform you that at least one instrument is requesting service. You must then serial poll all the instruments to determine which instrument(s) is requesting service.

LabWindows/CVI Basics I Course Manual

159

National Instruments Corporation

488.2 Service Request Model

488.2 Status Model While the 488.1 status model defines bit 6 to be whether or not the instrument is requesting service, the 488.2 specification adds two bits (ESB, MAV) and a mask register (Service Request Enable). ESB indicates that a standard event has occurred. A standard event is determined by a different register and is beyond the scope of this course. If you are interested in learning more about standard events, please refer to your NI-488.2(M) User Manual. MAV indicates that the instrument has a message available (data in its output buffer). The Service Request Enable (SRE) register is a mask that determines whether or not a particular bit that is set in the Status Byte Register will generate an SRQ. For example, if you write a 0x10 (decimal 16) to the SRE register, that will instruct the instrument to generate an SRQ when it has a message available. Get Serial Poll Status Byte ibrsp serially polls a device and returns its status response. The response consists of a single byte in which bit 6 (hex 50) is set if the device is requesting service and asserting the Service Request (SRQ) line. The instrument vendor defines all other bits. This is specified via the IEEE 488.1 standard. In the IEEE 488.2 standard (see slide), bits 4 and 5 are also reserved. int status = ibrsp (int device, char *serialPollResponse); device: serialPollResponse: The unit descriptor returned from ibdev or ibfind The value containing the response of the specified device to a serial poll. If bit 6 of the response byte is set, the device is requesting service.

LabWindows/CVI Basics I Course Manual

160

National Instruments Corporation

GPIB Service Requests

GPIB Example The example on the slide shows how you would serial poll an instrument. There are a few things that may need clarification. Notice that the ibfind, ibsic, and ibsre calls were left off due to space constraints. Normally, you should include these calls. The Wait for SRQ section has been left off (options will be discussed in the next section) and is up to the programmer. A simple method would be to use a while loop similar to the one below: while (!done) { ibwait (board, 0); // update the status if (ibsta & SRQI) // check for the SRQ line done = 1; } The string *SRE 0x10; *IDN? causes the instrument to assert the SRQ line whenever it has finished generating its identification. It does this by writing a 0x10 (which sets the MAV mask) to the SRE register. This causes the instrument to assert the SRQ whenever it has a message available. The *IDN? is going to cause the instrument to generate a message. With serial polling, first check to see whether or not bit 6 is asserted. This will let you know whether or not the instrument is asserting the SRQ line. Then, check to see whether or not the instrument is requesting service because of MAV (we could have many different if/case statements checking for other device-dependent bits).

LabWindows/CVI Basics I Course Manual

161

National Instruments Corporation

Service Request Callbacks


Using ibInstallCallback
Prototype the Callback Function Install the callback using ibInstallCallback Callback occurs synchronously upon occurrence of event specified in eventMask

ibInstallCallBack (int board/device, int eventMask, GPIBCallbackPtr CallbackFunction, void *callbackData);

Up to now, you have learned how to serial poll a device and interpret its serial poll status byte. Now you need a way to detect the SRQ line being asserted to begin the serial poll process. Keeping with its callback structure, LabWindows/CVI provides two unique functions that will notify the application when an SRQ occurs. These two functions are ibInstallCallback and ibnotify. ibInstallCallback (synchronous) int ibInstallCallback (int board/device, int eventMask, GPIBCallbackPtr callbackFunction, void *callbackData); The unit descriptor returned from ibfind or ibdev The event(s) that cause the callback function to be invoked (usually you will have an eventMask of 0x1000 to indicate the SRQ line (see ibsta)) callbackFunction: The function that will be invoked when the specified event occurs callbackData: A void pointer to be used to pass data between callback functions board/device: eventMask: This function allows you to install a synchronous callback function for a specified board or device.

LabWindows/CVI Basics I Course Manual

162

National Instruments Corporation

Service Request Callbacks

The callback function is called when any GPIB event specified in the eventMask parameter has occurred on the specified board or device. Because this callback function is synchronous, it will be called only when the system is free to process events. The system can process events when you call ProcessSystemEvents or have called RunUserInterface and none of your callback functions is currently active. The callbacks are termed synchronous because they cannot be invoked while other processes (for example, other callbacks) are active. Asynchronous processes, on the other hand, may be invoked at any time, interrupting any active process. Unlike asynchronous callbacks (discussed next), there are no restrictions on what you can do in a synchronous callback. However, the latency between the occurrence of a GPIB event and the invocation of the callback function is greater with synchronous callbacks than with asynchronous callbacks. Only one callback function can apply for each board or device. Each call to this function for the same board or device supersedes the previous call. To disable callbacks for a board or device, pass 0 as the eventMask parameter.

LabWindows/CVI Basics I Course Manual

163

National Instruments Corporation

Service Request Callbacks


Using ibnotify
Prototype the Callback Function Install the callback using ibnotify Callback occurs asynchronously upon occurrence of event specified in eventMask Restrictions on operations in asynchronous callbacks Refer to the course manual for more information.
Note: the callback function has a different prototype in ibnotify than it did in ibInstallCallback (see following example).

ibnotify (asynchronous) int ibnotify (int board/device, int eventMask, GPIBNotifyCallback_t callbackFunction, void *callbackData); Note: All parameters are identical to the parameters for ibInstallCallback. This function allows you to install an asynchronous callback function for a particular board or device. To install a synchronous callback, use the ibInstallCallback function instead. The callback function is called when any of the GPIB events specified in the eventMask parameter has occurred on the specified board or device. Unlike the synchronous call, this function will be invoked immediately upon the arrival of the event. If you are currently in a callback function, CVI will jump to the callbackFunction, complete it, and return to your original callback function (see note below). Just like the synchronous version, only one callback function can apply for each board or device. Each call to this function for the same board or device supersedes the previous call. To disable callbacks for a board or device, pass a 0 for the eventMask parameter.

LabWindows/CVI Basics I Course Manual

164

National Instruments Corporation

Service Request Callbacks

Asynchronous Callback Limitations Asynchronous callbacks can be called anytime while the system is running. You do not need to allow the system to process events. This means that you are restricted in what you can do inside the asynchronous callback. Things that you can do inside an asynchronous callback are: Call PostDeferredCall (schedules a different callback to be called synchronously) Call any GPIB function, except ibnotify or ibInstallCallback Manipulate Global variables (be careful!) Call ANSI C functions such as strcpy and sprintf, which affect only the arguments (that is, have no side effects). You cannot call printf or perform file I/O. Call malloc, calloc, realloc, or free

For more information about the restrictions, see the LabWindows/CVI Standard Libraries Reference Manual. Note: ibnotify is supported on only the Windows 95 and Windows NT platforms. To use ibnotify, you must be running version 1.1 or greater of the NI-488.2M software for Windows 95 or version 1.2 or greater of the NI-488.2M software for Windows NT.

LabWindows/CVI Basics I Course Manual

165

National Instruments Corporation

Exercise 5-3 (15 min.)

Objective: To use ibInstallCallback in a program to respond to an SRQ.

LabWindows/CVI Basics I Course Manual

166

National Instruments Corporation

Troubleshooting GPIB Problems

National Instruments offers many ways to troubleshoot GPIB problems. The first step in troubleshooting GPIB problems is to run the appropriate diagnostic utility (Diagnostics in Win95/NT, Hardware diagnostics and Software diagnostics in Windows 3.x, and ibtsta in Solaris). This is a good way to verify that your hardware and software are correctly installed. If they are not, please see your user manual on proper installation or contact technical support. Once you have verified that your GPIB board and its driver are correctly installed, the next step is to determine whether or not your instrument is working. The easiest way to verify that your instrument is working is to attempt communication. National Instruments provides an interactive control program called ibic (on Windows platforms, it is called the Win16/32 Interactive Control). This program allows you to communicate directly with the driver. By forgoing your application software, you can verify communication with your instrument. Another advantage of the Win32 Interactive Control is the ability to verify your programming philosophy. By interactively writing and reading from your instrument, you can determine whether the command sequence you are using in your program is valid.

LabWindows/CVI Basics I Course Manual

167

National Instruments Corporation

Troubleshooting : NI Spy

Once you have verified that your installation is successful and you can talk to your instrument, you need to determine why your application may not be working. Shipping with the Windows drivers (Win 3.x, Win95, and WinNT) is a utility called NI Spy or GPIB Spy. This utility captures all calls made into the appropriate DLL (gpib.dll for Win 3.x, gpib-32.dll for Win95/NT) and reports the status of each call (ibsta, iberr, and ibcntl). By determining which calls are made into the driver, you can determine if the code you are writing is logically correct.

LabWindows/CVI Basics I Course Manual

168

National Instruments Corporation

Troubleshooting : GPIB Analyzer

If NI-Spy does not supply you with enough information, you may have a hardware problem. National Instruments has a GPIB Analyzer product that allows you to monitor activities on the GPIB. Whenever any of the five bus management lines or the three handshake lines change state, all 16 hardware lines (24 total minus eight ground) are logged. With this knowledge, you can determine whether a device is not handshaking correctly or whether the data you are sending to or receiving from the instrument is the data you expect. With an analyzer, you can accurately determine whether any problem exists on the GPIB. Note: The GPIB Analyzer software requires special hardware only found on the plus boards, AT-GPIB/TNT+, PCI-GPIB+, and PCMCIA-GPIB+. It does not capture events if you do not have one of these three boards.

LabWindows/CVI Basics I Course Manual

169

National Instruments Corporation

Exercise 5-4 (15 min.)

Objective: To become familiar with some of the GPIB troubleshooting options available.

LabWindows/CVI Basics I Course Manual

170

National Instruments Corporation

Summary Lesson 5
The GPIB Library contains all functions necessary for GPIB communication The GPIB Library has three global integer variables: ibsta, iberr, and ibcntl. These variables are very useful for debugging GPIB programs Open up a session to the GPIB board using ibfind. Then call ibsic and ibsre to make sure the interface is reset to a known state Open up a session to a device with ibdev. The ibdev function returns an integer unit descriptor used in subsequent GPIB operations The read (ibrd) and write (ibwrt) functions are widely used in GPIB communication. Close the board and device using the ibonl function GPIB service requests can be handled by a callback function after calling ibInstallCallback or ibnotify There are many ways to troubleshoot GPIB problems Interactive Control (ibic) GPIB Spy/NI Spy GPIB Bus Analyzer

LabWindows/CVI Basics I Course Manual

171

National Instruments Corporation

Lesson 6
Serial Communication

Objectives: Learn about serial communication Learn about InstallComCallback Learn how to troubleshoot common serial problems

With the advent of GPIB, devices can now communicate over a bus at high speeds and with greater versatility. However, GPIB requires hardware that does not come standard with the computer. Another very common protocol for device communication that comes standard on just about every PC is serial communication. Most computers include one or two RS-232-based serial ports. Serial is a common communication protocol used by many devices for instrumentation. Numerous GPIB-compatible devices also come with an RS-232 port. It can also be used for data acquisition in conjunction with a remote sampling device. In this section, we will discuss the fundamentals of serial communication, establish serial communication using LabWindows/CVI, use the LabWindows/CVI InstallComCallback function to obtain data from serial devices, and provide methods for debugging serial communication problems.

LabWindows/CVI Basics I Course Manual

172

National Instruments Corporation

Serial Protocols
RS-232 One-to-one communication 50 ft. (15 m) range Signal reference to ground RS-485 Multidrop (up to 32 devices) User-defined addressing for multidrop 4000 ft. (1220 m) range Differential Signal RS-422 Electrically a subset of RS-485 Multidrop (up to 11 devices)

There are three main protocols for serial communication, RS-232, RS-485, and RS422. From a programming standpoint, there is no difference between any of the available serial protocols. We will not go into detail about all of the available serial port communication protocols such as RS-485 and RS-422, because these are less common, require extra hardware, and differ from RS-232 only electrically. The above slide illustrates some of the similarities and differences between RS-232, RS-485, and RS-422.

LabWindows/CVI Basics I Course Manual

173

National Instruments Corporation

Serial Communication Lines


RS-232 RS-232 data lines (single-ended) TXD RXD GND RS-485 data lines (differential) TXD+, TXD RXD+, RXDPin 1 2 3 4 5 6 7 8 9 DCD RXD TXD DTR GND DSR RTS CTS RI DTE DCE Input Output I O O I O I I O O I I O I O

The concept of serial communication is simple. The serial port sends and receives bytes of information one bit at a time. Although this is slower than parallel communication, which could send an entire byte at once, it is simpler and can be used over longer distances. For example, the IEEE 488 specifications state that the cabling between equipment can be no more than 20 meters total, with no more than 2 meters between any two devices; however, serial can extend as many as 1220 meters. Typically, serial is used to transmit ASCII data. RS-232 communication is completed using three transmission lines: (1) Transmit, (2) Receive, and (3) Ground. To communicate, connect the transmit line of one device to the receive line of another. Devices can have two different connectors, DTE and DCE. If you are connecting a DTE to a DCE, all you need to do is wire all of the pins straight through (pin 1 to pin 1, pin 2 to pin 2, etc.), but if you are wiring a DTE to a DTE or a DCE to a DCE, you need to swap transmit and receive lines, because they have the same connector. This can be done easily with a NULL-Modem cable, which automatically swaps the transmit and receive lines on opposite ends of the cable.

LabWindows/CVI Basics I Course Manual

174

National Instruments Corporation

Handshaking Options
Hardware handshaking CTS - Clear To Send RTS - Ready To Send Software handshaking (XON/XOFF) XOFF - ASCII - Hex 13 XON - ASCII - Hex 11 No handshaking

The method used by RS-232 for communication allows for a simple connection of three lines: Transmit, Receive, and Ground. Although this method is sufficient for most applications, it is limited in being able to respond to problems such as the receiver being overloaded. This is where serial handshaking can help. You have three handshaking options regarding the transfer of data over a serial connection: hardware handshaking, software handshaking, and no handshaking. Hardware handshaking requires that two addition lines be connected, CTS and RTS. When a receiver is ready for data, it asserts the RTS line, indicating it is ready to receive data. The sender sees this input as CTS because, in a null modem cable, the CTS and RTS lines are crossed. When the senders CTS line is asserted, it responds by writing to the port. Software handshaking does not require the use of two additional lines. If during data transfers, the receiver is unable to read additional information, it will send the XOFF character to the sender via the transmit line. The sender will then stop transfers until it sees the XON character at its receive line. With no handshaking, the sender transmits all information without verifying that the receiver can handle the data. If data is sent faster than the receiver can read, information is lost.

LabWindows/CVI Basics I Course Manual

175

National Instruments Corporation

Serial Configuration
Baud Rate Data Bits Stop Bits Parity - Speed of communication (bits/sec) - Number of bits used for data in a frame - Signal end of frame transfer - Bit used for error checking

The important serial characteristics are baud rate, data bits, stop bits, and parity. For two ports to communicate, these parameters must match. The baud rate determines the number of bit transferred per second. The data bits parameter determines how many of the actual bits in a frame are used for data. A frame is defined as the number of bits sent to transfer one data byte. When the computer sends a frame of information, the amount of actual data may not be 8 bits. Standard values for the data bits parameter are 5, 7, and 8. Which setting you choose depends on the type of information you are transferring. For example, standard ASCII has values from 0 to 127 (7 bits). Extended ASCII uses 0 to 255 (8 bits). The stop bits are used to signal the end of a frame. Parity is a simple form of error checking used in serial communication. If you add the value of all of the data bits in the communication (logic high equals one, logic low equals zero), it will be either an odd number or an even number. The parity bit added to sum of the data bits creates either an even or odd number.

LabWindows/CVI Basics I Course Manual

176

National Instruments Corporation

Programming Methodology
Open and configure serial port Write to port Read from port Close port

Before using a serial function to communicate with your instrument, you must open a session to your COM port using the OpenComConfig function. This function will open a COM port and allow you to specify the baud rate, data bits, stop bits, and parity. LabWindows/CVI also allows you to specify a buffer in memory to store the contents of the input and output queues. Use the CloseCom function to release computer resources used by your serial port session. To guarantee that all bytes were written before closing the port, monitor the output queue with the GetOutQLen function. When the queue length equals zero, it is safe to close the port. ComWrt writes data from memory to the serial output queue of the specified COM Port. The count specifies the number of bytes to write. strlen (ANCI C Library) determines the size of a buffer. The value returned from strlen is often used to specify the number of bytes to be written. ComRd reads a specified number of bytes from the determined COM Port. Use the function GetInQLen to obtain the number of bytes present at the serial input queue. Use this value to determine the number of bytes to read.

LabWindows/CVI Basics I Course Manual

177

National Instruments Corporation

Exercise 6-1 (25 min.)

Objective: To establish communication with a serial instrument.

LabWindows/CVI Basics I Course Manual

178

National Instruments Corporation

InstallComCallback
Monitors port while using little processor time Callback function associated with serial port eventMask determines criteria for callback
int InstallComCallback (int COM_Port, int eventMask,int notifyCount, int eventCharacter,ComCallbackPtr callbackFunction, void *callbackData);

Commonly used eventMasks:


Any character received Received certain character Notify count bytes in inqueue LWRS_RXCHAR LWRS_RXFLAG LWRS_RECEIVE

Consider a situation in which an instrument generates a large amount of data, or takes a long time to obtain a data point. The instrument needs to send data to the computer as soon as the data is acquired. Because you do not want to tie up computer resources waiting for ComRd to complete and you do not want to make the serial input buffer extremely large, you must be notified when data is present at the port. This prevents you from waiting on data and enables you to read from the port periodically. InstallComCallback allows you to install a callback function for a particular COM port. The callback function is called whenever any of the events specified in the EventMask parameter occur on the COM port. Some of the common COM port events are LWRS_RXCHAR, LWRS_RXFLAG, and LWRS_RECEIVE. LWRS_RXCHAR occurs when any byte is received at the COM port. LWRS_RXFLAG occurs when a specific byte is received at the COM port. For example, if we set the eventCharacter to the value Z and we receive a Z at the COM port, the LWRS_RXFLAG will be generated. LWRS_RECEIVE will be generated when the number of bytes received at the COM port equals notifyCount.

LabWindows/CVI Basics I Course Manual

179

National Instruments Corporation

Exercise 6-2 (20 min.)

Objective: Use InstallComCallback to retrieve waveforms from a serial instrument.

LabWindows/CVI Basics I Course Manual

180

National Instruments Corporation

Debugging Methods
Verify settings match device Perform a loopback test Use HyperTerminal - Microsoft serial application Start Programs Applications HyperTerminal Connect transmit to receive RS-232 - Connect pins 2 to 3 RS-485 - Connect pins 4 to 8 and 5 to 9 Keyboard data is sent out of the serial port Typed data is looped back and displayed on screen Use LabWindows/CVI serial example

When trying to establish communication via serial ports, problems sometimes exist. The data you receive may not be what you expected, or it may not receive data at all. First, check the configuration setting of the port. Verify that all settings, such as baud rate, parity, and stop bits, match those of the connecting port. One way to verify the port is functional is to perform a loopback test. In a loopback test, you connect the transmit and receive lines together. When attempting to write to the serial port, data travels out of the transmit line and into the receive line. You are then able to read all the data written to the port. A number of applications may be used to implement a loopback test. One method of performing a loopback test is using the Windows HyperTerminal program, located under the Accessories folder. Another method is using the LabWindows/CVI serial example \CVI\SAMPLES\RS232\ SERIAL.PRJ.

LabWindows/CVI Basics I Course Manual

181

National Instruments Corporation

Summary Lesson 6
Serial protocol includes RS-232, RS-485, and RS-422. RS-485 and RS-422 support multidrop communication. RS-232 communication requires only three lines: TXD, RXD, and GND RS-232 hardware handshaking requires two additional lines: CTS and RTS Three handshaking options: CTS/RTS, XON/XOFF, none. Serial parameters: Baud Rate, Data Bits, Stop Bits, Parity Information travels in frames (typically containing 1 byte of data). Use HyperTerminal to verify functionality of port.

LabWindows/CVI Basics I Course Manual

182

National Instruments Corporation

Lesson 7
Instrument Drivers

Objectives: Multiple modules within one project Learn about instrument drivers Learn how to create an instrument driver Learn about VISA API

LabWindows/CVI Basics I Course Manual

183

National Instruments Corporation

Multiple Modules

Calling functions from other Modules You can call functions from other modules by simply adding a .c file to your LabWindows/CVI project that contains the functions you want to call. To make the function calls, simply pass the necessary parameters to the functions that are defined in the other module. Also, make sure that the file calling the function in the other module contains the necessary #include statements. Notice that in the example above, the functions displayName and storeName are defined in the names.c module. The phonbook.c module (which contains main) has the statement #include name.h because the functions need to be prototyped before they can be used within phonbook.c. When accessing variables in different modules, you must pay a particular attention when defining the variables. Lesson 1 contains a section that covers in detail the scope of variables in LabWindows/CVI.

LabWindows/CVI Basics I Course Manual

184

National Instruments Corporation

What Is an Instrument Driver?


Collection of functions Organized as a separate module .c .lib .obj .dll Function Panel (.fp) front end.

What is an Instrument Driver? From the discussion on the previous page, you can have multiple .c files in one project. Many times, you may want to separate the functions in your project to reside in multiple files to organize the functions logically. An instrument driver is just a collection of functions, organized in a .c, .lib, .obj, or .dll file, with a function panel front end. This is almost identical to the multiple modules model discussed on the previous slide. An instrument driver simply defines function panels, which you have been using throughout this course when you used the LabWindows/CVI library functions, to map to functions in your own .c files. On the next few pages, you will learn how to create an instrument driver as a library of functions. Then, under this same framework, you will learn how instrument drivers in LabWindows/CVI help simplify instrumentation control.

LabWindows/CVI Basics I Course Manual

185

National Instruments Corporation

Instrument Driver Files


Source Code .c Include File .h Function Panels .fp Attribute File .sub Files must reside in the same directory

Instrument Driver
INCLUDE FILE

INSTNAME.H
FUNCTION PANELS

SOURCE CODE
Attach

INSTNAME.C
(INSTNAME.OBJ) (INSTNAME.DLL)

INSTNAME.FP INSTNAME.SUB

There are four file types associated with LabWindows/CVI instrument drivers: The instrument driver program, which can be a .c, .obj, .dll, or a .lib file. The instrument driver include file (.h), which contains function prototypes and constant declarations. The instrument function panel file (.fp), which contains information that defines the Function Tree, the function panels, and the help text. An ASCII text file (.doc), which contains documentation for the instrument driver. A .sub file, which defines all attributes available for the instrument when using IVI instrument drivers.

LabWindows/CVI Basics I Course Manual

186

National Instruments Corporation

Loading an Instrument Driver

To use an instrument driver in LabWindows/CVI, select Instrument Load. From the dialog box, find the instrument driver you want to load. Once the instrument driver is loaded, its name appears under the Instrument menu option.

LabWindows/CVI Basics I Course Manual

187

National Instruments Corporation

Instrument Driver Function Tree

You use the instrument driver exactly as you use the standard LabWindows/CVI library functions. Navigate through the function tree until you find the function you want to operate. Select it and its function panel appears, representing the instrument driver function with a control for each parameter. By manipulating the controls, you can construct a specific function call that you can either interactively execute or paste into a program.

LabWindows/CVI Basics I Course Manual

188

National Instruments Corporation

Creating an Instrument Driver


Steps: 1) Create function tree (.fp file) 2) Create function panels for functions 3) Create documentation directly from Function Tree Editor 4) Create header file and source code skeleton directly from Function Tree Editor 5) Complete all function definitions in source code skeleton

Creating an Instrument Driver To create an instrument driver, you must first create the function tree in the function panel file (.fp). The function tree contains all the function names categorized in different classes. Once you create the function tree, you create a function panel for each function. Fill in the online help as you create your functions. Once you have the function panel help written for all the functions in your function tree, you can automatically create a .doc file that contains all the help information documented on each function. LabWindows/CVI 5.0 can automatically create a source code skeleton and header file that contains the function prototypes of all the functions in the function panel file. Once you have created the source skeleton code and the header file, add all the necessary code to create working functions. The next pages describe in detail each step required to create an instrument driver.

LabWindows/CVI Basics I Course Manual

189

National Instruments Corporation

Creating .fp File

You can create a new instrument driver by selecting File New Function Tree (*.fp). The Function Tree Editor window will appear. This window allows you to define all the functions in the instrument driver.

LabWindows/CVI Basics I Course Manual

190

National Instruments Corporation

Creating Instruments

Name the instrument by selecting Create Instrument from the menubar. Enter the Name and Prefix of the instrument driver. The name of the instrument is the name that will display under the Instrument menu after it is loaded. The prefix of the instrument is prepended to each function to create the function name. This is useful in your code to help determine which instrument driver each function call originated from.

LabWindows/CVI Basics I Course Manual

191

National Instruments Corporation

Creating Classes

Your instrument driver is made up of different functions, which can be categorized into classes. To create a class, select Create Class from the Function Tree Editor menubar. Classes are very useful in organizing your functions into logical groups.

LabWindows/CVI Basics I Course Manual

192

National Instruments Corporation

Creating Function Trees

You create functions by selecting Create Function Panel Window from the menubar. Fill in the Create Function Panel Window Node dialog box. The Name field defines the name of the Function Panel window, which appears while searching through the instrument driver function tree. The Function Name field defines the actual name of the function that performs a given operation (which will then be preceded by the instrument prefix once you paste it in the source code). The Function Name field must follow ANSI C rules of naming a function (that is, no spaces, etc). An example of the prefix with the function name is: Prefix: names Function Name: displayName Function Name in source code: names_displayName

LabWindows/CVI Basics I Course Manual

193

National Instruments Corporation

Creating Function Panels

Creating a Function Panel To create a function panel, double-click on the name of the desired function defined in the Function Tree or highlight the function and select Edit Edit Function Panel Window from the menubar. This opens an empty function panel. You can place input controls, slide controls, binary controls, ring controls, or a numeric control. All the input controls are the input parameters of the function. You can also place output controls, which represent the output parameters of the function. In addition, you also can specify a return value for the function. You can place input controls, output controls, and a return value by selecting the desired object from the Create menu in menu bar or by clicking on one of the following icons on the toolbar of the function panel window: Creates an input control Creates a slide control Creates a binary control Creates a ring control Selecting a control brings up a dialog box where you can fill in the parameters for each particular control. This dialog box is discussed on the next slide. Creates a numeric control Creates an output Creates a return value

LabWindows/CVI Basics I Course Manual

194

National Instruments Corporation

Creating Function Panels

When creating an input, output, or a return value, a dialog box will appear requesting the following information: Control Label: The label of the control to place on the function panel. Parameter Position: The position of the parameter in the function call. Data Type: The data type of the parameter. You can toggle between data types by clicking on the arrows of the Data Type control or by clicking once on the Data Type control and selecting the data type from the pop-up menu. To add user-defined data types to the list, select Options Data Types from the function panel menu bar. Default Value: The default value of the function parameter. Control Width: The width of the control in pixels. Display Format (if output): The format of numeric data to be displayed in the output control in the function panel. Binary, slide, ring or numeric controls require control-specific information that you define the in the same way as in the graphical user interface editor. You can also place global variable indicators on the function panel. These variables are updated as a result of an operation performed within the function. To do this, select Create Global Variable from the function panel window or click on the icon. You can also place text on the function panel by selecting Create Message from the menu bar or by clicking on the icon.

LabWindows/CVI Basics I Course Manual

195

National Instruments Corporation

Documenting Instruments

Documenting the Instrument Driver You can document a function directly from the function panel editor. You create a help window for the function by right-clicking on an open area of the function panel. Type in all the help information pertaining to the function. You can also document the function parameters. To do this, right-click on the function parameter and type in all the necessary help information for the parameter. LabWindows/CVI automatically adds the prototype of the function to the function help and the data type to the parameter help. You can view this additional information when the function panel is operational (not in edit mode). As mentioned before, another file type associated with an instrument driver is an ASCII text file (.doc), which contains documentation for the instrument driver. LabWindows/CVI can create this file automatically based on the help text entered on the function panels. This document provides information such as the function tree layout, the data types associated with each function parameter, and the information entered on the help windows of each function panel. In addition, LabWindows/CVI also automatically adds general instrument driver information and it can document the functions in Visual Basic or in C format. To have LabWindows/CVI generate a .doc file automatically, select Options Generate Documentation from the menubar. A dialog box appears, in which you can specify the type and format of the information to place in the document.

LabWindows/CVI Basics I Course Manual

196

National Instruments Corporation

Generating Source Code and Header

Generating the Header File and the Source Code Skeleton LabWindows/CVI can automatically generate a header file (.h) containing the function prototypes of the functions defined in the Function Tree as well as a source skeleton code (.c) to simplify the coding of your functions. To generate these files automatically, select Tools Generate New Source For Function Tree.

LabWindows/CVI Basics I Course Manual

197

National Instruments Corporation

Skeleton Code Files

Header File and the Source Code Skeleton The figure above shows an example of the resulting source skeleton code and the header file. Observe that the functions contain a CVIFUNC define at the beginning of the function. This is the _stdcall calling convention defined in the file cvidef.h. For the source code to compile, you must add the #include <cvidef.h> line in the instrument driver header file. You can now begin coding all the functions of your instrument driver by filling in the blanks!

LabWindows/CVI Basics I Course Manual

198

National Instruments Corporation

Editing an Instrument Driver


Select Instrument Edit and select the instrument driver you want to edit

Editing Instrument Driver Files When working with instrument drivers, you use the Edit command from the Instrument menu to either invoke the Function Panel Editor or to modify the relationship between the function panel file (.fp) and its associated program file. Show Info - displays the names of the current function panel file and the attached program file. Attach and Edit Source - searches the directory that contains the function panel for a filename that has the same prefix as the function panel file and a .c extension and opens the .c file for editing. Detach Program - detaches the program file from the function panel. Reattach Program - attaches a program file to a function panel. It searches the directory that contains the function panel for a program file that has the same prefix as the function panel file and a .lib, .obj, .dll, or.c extension. Edit Function Tree - invokes the Function Tree Editor.

LabWindows/CVI Basics I Course Manual

199

National Instruments Corporation

Exercise 7-1 (30 min.)

Objective: To create an instrument driver and use it as a library.

LabWindows/CVI Basics I Course Manual

200

National Instruments Corporation

Instrument Control with an Instrument Driver


Handles low-level interface operations (GPIB, Serial, VXI, PXI) Command set for instrument preprogrammed into driver National Instruments instrument drivers come with source code Add functionality to driver Convert an existing driver to work with instruments that do not have a driver More than 650 instrument drivers available from National Instruments

Advantages of Using an Instrument Driver So far, you have seen how instrument drivers are used as a library of functions. How does this fit into actual instruments? Consider a power supply that can interface to a computer through the GPIB bus. To generate a voltage, it could take several GPIB calls, which involve passing configuration parameters to the power supply before the actual voltage generation. With an instrument driver, this could take a single function call because the driver acts as a high-level translator for communicating with your instrument. When you use an instrument driver, you can bypass time-consuming instrument programming tasks, such as: Learning the command set for your instrument. Building command strings. Learning how to send strings back and forth over the GPIB, VXI, or serial interfaces. Parsing data strings returned from the instrument.

By using an instrument driver, you can concentrate on your application and not worry about the low-level details. LabWindows/CVI has a growing list of more than 650 instrument drivers available for GPIB, VXI, and serial interfaces. Each driver is designed for a specific instrument and comes with source code. You can change, optimize, or add functionality to the driver source code to meet the needs of your application.
LabWindows/CVI Basics I Course Manual 201 National Instruments Corporation

VXIpnp Instrument Drivers

VXIpnp Instrument Driver An alliance called the VXIplug&play System Alliance (VXIpnp) designed a model for instrument drivers that is generally used among companies. This alliance defines certain aspects of an instrument driver, the most important being the organization of functions. The function tree shown above is the Fluke 45 instrument driver. This driver conforms to the VXIpnp standard. As you can see, the instrument driver is a high-level library, broken down into functions for initializing, configuring, and measuring data from your instrument. All VXIpnp instrument drivers follow the same Initialize-Configure-Action/Status-Data-Utility-Close format. Initialize Function Initializes the software connection to the instrument. The initialize function can optionally perform an instrument identification query as well as a reset operation. In addition, it can perform any necessary actions to place the instrument in its default power-on state or other specific state. Configuration Functions A collection of software routines that configure the instrument to perform the desired operation. There may be numerous configuration functions, depending on the particular instrument. Action/Status functions This category contains two types of functions. Action functions cause the instrument to initiate or terminate test and measurement operations. Status functions obtain the current status of the instrument or the status of pending operations. The specific routines in this category and the actual operations performed by those routines are left up to the instrument driver developer.

LabWindows/CVI Basics I Course Manual

202

National Instruments Corporation

Example of an Instrument Driver

Data Functions Functions that transfer data to or from the instruments. Examples include functions for reading a measured value or waveform form a measurement instrument, functions for downloading waveforms or digital patterns to a source instrument, and so on. The specific routines in this category and the actual operations performed by those routines are left up to the instrument driver developer. Utility Functions Perform a variety of operations. Some utility functions are required, such as reset, self-test, error query, error message, and revision query; others are defined by the developer. Close Function All LabWindows/CVI instrument drivers have a close function that terminates the software connection to the instrument and deallocates system resources.

The function panel shown illustrates the FL45_init function for the Fluke 45 instrument driver. As in any other LabWindows/CVI function panel, you enter values in the controls, and LabWindows/CVI automatically builds the function call at the bottom of the screen. The Initialize function queries the instrument for its identification, verifies that the response matches the expected response and then performs a reset of the Fluke 45. The driver handles all lowlevel GPIB, VXI, and serial interface operations. If you want to pass variables for the Boolean switches instead of using the true/false options, you can select Options Toggle Control Style <Ctrl-T>.

LabWindows/CVI Basics I Course Manual

203

National Instruments Corporation

VISA Overview
Virtual Instrument System Architecture (VISA) Interface for GPIB, Serial, VXI, and PXI
Uses VISA Driver Instrument Descriptor contains interface information Interface GPIB Serial VXI GPIB-VXI PXI Resource Name Grammar GPIB[board]::primary address[::INSTR] ASRL[board][::INSTR] VXI[board]::VXI logical address[::INSTR] GPIB-VXI[board][::GPIB-VXI primary address] ::VXI logical address[::INSTR] PXI[bus]::deviceNumber[::functionNumber] [::INSTR]

What is VISA? Instrument drivers have become increasingly popular over the last several years, and both users and vendors have taken advantage of the technology. Increased use of instrument drivers has fueled a continuous improvement process, resulting in high-quality instrument drivers. To address customers needs for reusable, interoperable software, National Instruments helped develop the Virtual Instrument System Architecture (VISA) specification. It is a standard endorsed by the VXIplug&play Systems Alliance, which includes more than 35 of the largest instrumentation companies in the industry. The VISA standard unifies the industry to make software interoperable and reusable over time and regardless of the instrument I/O option. VISA is a single interface library for controlling GPIB, Serial, VXI, and PXI instruments on all LabWindows/CVI platforms. To establish communication with a specified device, you need to open a session to the device specifying an instrument descriptor, which contains information on the type of I/O interface and device address. For example, based on the table above, the instrument descriptor required to open a session to a GPIB instrument with a GPIB address of 2 and connected to your GPIB0 interface board would be GPIB0::2::INSTR. The next page illustrates an example of how to open a session to a GPIB instrument and perform an I/O operation.

LabWindows/CVI Basics I Course Manual

204

National Instruments Corporation

Communicating with VISA

VISA Example The example above shows how to perform an I/O operation using VISA function calls. The viOpenDefaultRM function must be called before any VISA operations can be invoked. The call to this function initializes the VISA system, including the Default Resource Manager resource (please refer to the VISA reference manual for more details), and returns a handle to that resource. The viOpen function opens a session to the instrument and returns a handle that will be used in any subsequent VISA I/O operations performed with the instrument. Notice that you pass the instrument descriptor GPIB0::2::INSTR to this function. The viWrite function sends the *idn? command to the instrument to query its identification. The viRead function reads the response back from the instrument and stores it in the array buffer. The viWrite and viRead functions know which instrument to communicate with by means of the handle (instrHandle) returned by the viOpen function. When all the I/O operations have been completed, you close the VISA sessions returned by both viOpenDefaultRM and viOpen functions using the viClose function. The VISA specification defines a set of variable declarations, which are contained in the header file visa.h. For example, the variables defaultRM and instrHandle sessions are of the type ViSession, which is defined as an integer in visa.h.

LabWindows/CVI Basics I Course Manual

205

National Instruments Corporation

Exercise 7-2 (15 min.)

Objective: To interactively use an instrument driver to control the device simulator.

LabWindows/CVI Basics I Course Manual

206

National Instruments Corporation

Exercise 7-3 (25 min.)

Objective: To use the device simulator instrument driver to create a working program.

LabWindows/CVI Basics I Course Manual

207

National Instruments Corporation

Summary Lesson 7
LabWindows/CVI instrument drivers consist of four files: the instrument driver program (.c, .lib, .obj, or .dll), a header file (.h), the instrument function panel file (.fp), and an ASCII text file (.doc). A function tree defines all the functions of the instrument driver. You can categorize the functions under different classes through the Function Tree Editor. A function panel is a graphical representation of a function. You can add inputs, outputs, return values, etc. LabWindows/CVI automatically generates a header file, a source skeleton code, and a document file containing all the help text entered on the function panels. An instrument driver can be used to handle all low-level operations of a particular instrument. VISA is a specification that provides a single set of function calls to interface with GPIB, Serial, VXI, and PXI devices.

LabWindows/CVI Basics I Course Manual

208

National Instruments Corporation

Lesson 8
Standalone Executables

Objectives: Learn how to create a standalone executable Learn about the LabWindows/CVI run-time engine Learn how to distribute a standalone executable

LabWindows/CVI Basics I Course Manual

209

National Instruments Corporation

Standalone Executables
Run-Time Engine RTE is a DLL on Win95 Must be present on target machine Only needs to be installed once Error Checking Debugging is disabled in standalone executables Check the return value from every function for errors

Run-Time Engine The Run-Time Engine contains all of the built-in library, memory, and program execution tools present in the LabWindows/CVI environment without all of the program development tools such as the Source Editor, compiler, debugger, and User Interface Editor. The Run-Time Engine is smaller than the LabWindows/CVI environment, so it loads faster and consumes less memory. It must be present on any target computer on which you want to run your executable program and you only need one copy of the Run-Time Engine on each target machine, even though you may have several executables. You receive the Run-Time Engine with your purchase of LabWindows/CVI. You can either bundle the Run-Time Engine with your executable when you create your distribution kit (discussed later in the lesson), or you can distribute it separately. Error Checking When you develop applications in LabWindows/CVI, you typically have debugging set to either standard or extended and the Break on Library Errors option checked. With these utilities enabled, LabWindows/CVI identifies and reports programming errors in your source code, so you may be relaxed in your own error checking. However, in compiled modules and standalone executables, debugging and Break on Library Errors are disabled. This results in smaller and faster code, but you must perform your own error checking or unpredictable results may occur. You should remember that many problems could occur in compiled modules and standalone executables even if the program works inside the environment. It is important to check for errors that can occur due to external factors beyond the control of your program. Examples include running out of memory or trying to read from a file that does not exist. malloc, fopen, and LoadPanel are examples of functions that can encounter such errors. You must do your own error checking for these types of functions. Other functions return errors only if your program is incorrect.
LabWindows/CVI Basics I Course Manual 210 National Instruments Corporation

Creating Executables

From the Project window select Build Create Standalone Executable

Creating a standalone executable is very simple. Go to the Project window and select Build Create Standalone Executable. You should get a message that indicates that the debugging level will be changed to None. Recall that standalone executables run without the debugger, and you must have your own error checking. Next, you should get a dialog box similar to the one depicted in the slide above. Usually, you can just press OK, and your executable will be made. You can add files to the executable (that is, instrument drivers that are referenced by modules that you load at run-time by calling LoadExternalModule). You can also add version information to your executable that can be retrieved by certain Windows SDK functions. Once you have created your standalone executable, you are ready to take your program to the target machine. The next two slides will tell you what files you need to transfer to the target machine and how to use LabWindows/CVIs automated distribution kit to make it easier.

LabWindows/CVI Basics I Course Manual

211

National Instruments Corporation

Necessary Files
Executable
Startup code Compiled Source Code Instrument Driver Code .obj or .o .lib or .a Name and Icon

LW/CVI Run-Time Engine


Program Execution Support Memory Management Built-in CVI Libraries

.UIR

.DLL

External

External

.lib

.obj

Other files

Necessary Files For your executable to run successfully on a target computer, any files that are required by the executable must be accessible. If you create your distribution kit (discussed next) properly, the final distribution kit should contain all the necessary files for installing your LabWindows/CVI executable program on a target machine. Some of the files that you may need to consider are: Executable This file contains a compiled, linked version of your LabWindows/CVI project and any instrument driver program files that are statically linked to your project. It also contains the application name and icon resource to be registered to the operating system. The executable has an associated icon on which you can double-click to start the application. When the executable is started, it loads and starts the Run-Time Engine. .uir Files These files contain the user interface panels that are used by your application program. They must be included separately because they are actually loaded by the executable using LoadPanel. .dll Files You need to include any Windows dynamic link library (DLL) files that are used by your application program. External .lib Files Any 32-bit .lib files loaded by LoadExternalModule and are not listed in the project. External .obj Files Any 32-bit .obj files loaded by LoadExternalModule and are not listed in the project. Other Files Any additional files used by your program including, but not limited to, bitmap files, files opened in your code using fopen or OpenFile, and .ini files used for configuration.

LabWindows/CVI Basics I Course Manual

212

National Instruments Corporation

Distributing Executables

Build Create Distribution Kit

After you create an executable, you can easily distribute it by making a set of disks from which you can install your executable program on a target machine. You use the Build Create Distribution Kit command from the Project window to create the set of disks. The Create Distribution Kit command automatically includes all the files necessary to run your executable program on a target computer except for DLLs for National Instruments hardware and files that are loaded using LoadExternalModule. DLLs for National Instruments hardware should not be part of your distribution kit. These DLLs must be installed by the end-user from the hardware installation disks supplied by National Instruments. For example, if your application uses a GPIB board, you must install the DLLs using the NI-488.2 software installation disks that came with your GPIB board. Similarly, if your application uses a plug-in DAQ board, you must install the DLLs using the NI-DAQ software installation disks that came with your DAQ board. For help with the Create Distribution Kit dialog box, choose Search for Help on... from the Help menu. Type Create Distribution Kit... (Windows only) in the query box. Select Display. Scroll down to the Create Distribution Kit dialog box and move your mouse over the image. The mouse cursor will turn into a hand over items on which you can get further help. Click with the left mouse button to access this additional information.

LabWindows/CVI Basics I Course Manual

213

National Instruments Corporation

Exercise 8-1

Objective: 1) To create an executable out of a project. 2) To create a distribution kit with the executable.

LabWindows/CVI Basics I Course Manual

214

National Instruments Corporation

Summary Lesson 8
A standalone executable is a program that you can run outside the LabWindows/CVI environment The LabWindows/CVI run-time engine contains all the library code required for the executable to run

LabWindows/CVI Basics I Course Manual

215

National Instruments Corporation

Lesson 1 Exercises
Exercise 1-1
Objective: To open and run an application inside the LabWindows/CVI environment. 1. Start LabWindows/CVI by selecting the shortcut to it from the Start menu (Start Programs Cvi Cvi). 2. Select File Open Project. In the Open File dialog box, browse to the CVI directory and go to the BASICS1 subdirectory. Select the file TEMPSYS.PRJ and click on the Load button.

The Project window lists all files that make up a particular project or program. Projects that you build with LabWindows/CVI can consist of multiple files of many different types. You can add C source files, object modules, DLL import libraries, C libraries, user interface files, and instrument drivers by selecting Edit Add Files To Project. The Project window displays status information for the files listed in the project list, as shown below.

National Instruments Corporation

1-1

LabWindows/CVI Basics I Course Manual

Lesson 1 Exercises

The TEMPSYS.PRJ project consists of three files: TEMPSYS.C, TEMPSYS.H, and TEMPSYS.UIR. The .c file is the source file, the .h file is the header file containing constants for the user interface, and the .uir file is the user interface file.
Run Project toolbar icon

3. Close any untitled windows and run the project by selecting Run Run Project (<Shift-F5>) or by pressing the Running Man icon. LabWindows/CVI automatically compiles the source file in the project list (notice that the C indicator disappears from the project list), links the project with the libraries used, and executes the compiled code.

This project simulates the operation of a temperature monitor system. The temperature is displayed in the thermometer indicator and plotted on the strip chart. A graph displays a histogram of the temperature measurements. The knob controls set the high and low limits for the alarm condition, which the LEDs display. The bar indicators display the mean and standard deviation of the last 10 temperature measurements.

LabWindows/CVI Basics I Course Manual

1-2

National Instruments Corporation

Lesson 1 Exercises

4. Click on the Quit button to stop execution and return to the Project window. 5. Examine each file in the Project window by double-clicking on the filename. Double-clicking on a file opens the respective editor window. Text files (.c or .h) are opened in the Source window, and User Interface Resource files (.uir) are opened in the User Interface Editor window. After you finish, close each file by selecting File Close. Do not save any changes you make.

End of Exercise 1-1

National Instruments Corporation

1-3

LabWindows/CVI Basics I Course Manual

Lesson 1 Exercises

Exercise 1-2
Objective: To examine the features of the LabWindows/CVI Source Editor. 1. Close any open windows, open the file C:\exercises\ CVI Basics 1\events.prj, and build the project by selecting Build Build Project. This project demonstrates some of the events, key clicks, mouse movements, mouse button clicks, and so on that you can access in LabWindows/CVI. (The next lesson discusses events.) 2. Open EVENTS.C by double-clicking on it. 3. Examine the following Source window menus used while developing your application. Edit menu: standard Cut, Copy, Paste, Find, and Replace Build menu: project building commands for compiling and linking Run menu: source code stepping tools 4. Turn on line numbers by selecting View Line Numbers. 5. Select Edit Find or press <Shift-f3>. You can enter regular expressions in the Find dialog box for your search (the Regular Expressions checkbox must be checked). For example, {if}|{else} will search for all occurrences of the words if or else (there are no spaces between }|{). You can use the Multiple Files checkbox to include other source files from the project in the search. Cancel out of the Find dialog box. 6. Because your projects involve multiple files (source files, header files, UIR files, and so on), you may need to refer to these files during development. Move the cursor to the filename USERINT.H at the top of the Source window and select Open Quoted Text (<Ctrl-U>) from the File menu to automatically open the file for viewing in another Source window. Close the window. 7. If you are working with a particularly large file, you may need to refer to certain areas of the source code many times. Drag down the double line at the top of the source window by clicking the left mouse button on the line and then scrolling the mouse while pressing the mouse button. This process will create two subwindows: two different views of the same source file that you can scroll separately. Note that you cannot edit two different files at the same time from within one source editor window. Multiple source windows must be used to edit multiple files.

LabWindows/CVI Basics I Course Manual

1-4

National Instruments Corporation

Lesson 1 Exercises

8. You can also set tags anywhere in your source file so that you can easily jump to a line at any time. Place the cursor on a line and select Toggle Tag (<Shift-F2>) from the View menu. A green box should appear on the line in the left column. Repeat this procedure on several lines. Press <F2> to jump between tags. Tags can be used as virtual bookmarks and are especially useful when working with other developers or when working on a large project.

Toggle tags using <Shift-F2> Move between tags using F2

National Instruments Corporation

1-5

LabWindows/CVI Basics I Course Manual

Lesson 1 Exercises

9. If your source code has a function call that you are not familiar with, you can highlight the function call and select Go To Definition (<Ctrl-I>) from the Edit menu. LabWindows/CVI will take you to the place in the source code where the function is defined. Highlight the Keycheck function call on line 49 in EVENTS.C and press <Ctrl-I>. LabWindows/CVI will bring up another Source window with the KEYCHECK.C file open at the Keycheck function. Close the window. (If you get a No Definition Found error, you forgot to build the project as described in step 1.) 10. If the function call is a LabWindows/CVI function, place your mouse on the function call and select Recall Function Panel (<Ctrl-P>) from the View menu to recall the function panel. Do this step with the SetCtrlVal function in the ProcessEvents callback function. (Use Find from the Edit menu to find the function.)
Tip

You can easily implement steps 5, 8, and 9 by right-clicking on a line of code in the source window and selecting the appropriate action from the pop-up menu. 11. LabWindows/CVI can track differences in source files. Select File Open Source. Open the file \CVI\BASICS1\EVENTS2.C. Select Edit Diff Diff With. If you have more than two source files open, you will need to specify which file you want to compare with the one currently in use. Once the files have been selected, any differences can be highlighted by selecting Diff Synchronize at Top and then repeatedly use Diff Find Next Difference. Perform this operation and close EVENTS2.C when finished. 12. LabWindows/CVI has several ways of highlighting code in the editor. Click on the Highlighting icon at the bottom center of the Source window to change modes. Highlight some code in each mode to see the difference.

Highlighting icon

LabWindows/CVI Basics I Course Manual

1-6

National Instruments Corporation

Lesson 1 Exercises

13. Repeatedly use Undo (<Ctrl-Z>) from the Edit menu to return the source file to its original state. You can configure the number of undos using Editor Preferences from the Options menu.

End of Exercise 1-2

National Instruments Corporation

1-7

LabWindows/CVI Basics I Course Manual

Lesson 1 Exercises

Exercise 1-3
Objective: To examine LabWindows/CVI Project window options. The Project window has various options that you can use to configure the LabWindows/CVI environment. Explanations for some options are in this manual; however, the LabWindows/CVI User Manual describes all options in detail.
Note

Do not change any options. They are set correctly for this course. 1. Load C:\exercises\CVI Basics 1\TEMPSYS.PRJ. From the Project window, select Options Compiler Options. Use this dialog box to set the different compiler options.

LabWindows/CVI Basics I Course Manual

1-8

National Instruments Corporation

Lesson 1 Exercises

Compatibility with displays the programming environment that can create binary code compatible with LabWindows/CVI. The compatibility mode was selected during the installation of LabWindows/CVI and defaults to Visual C++. It can be changed only by running the setup installation program. Default calling convention specifies the method used when calling a DLL function. Calling convention affects how function parameters are stored on the stack. Maximum number of compile errors sets an upper limit on the number of compiler errors listed in the Build Errors window. Require function prototypes requires a full prototype declaration to precede all function references. A full prototype is one that includes the function return type as well as the types of each parameter. If a function has no parameters, a full prototype must have the void keyword to indicate this case. Require return values for nonvoid functions generates compile warnings for nonvoid functions (except main) that do not end with a return statement returning a value. For example, the following code produces a compile-time warning and a run-time error when (g == 6) is not true.

National Instruments Corporation

1-9

LabWindows/CVI Basics I Course Manual

Lesson 1 Exercises

int MyFunction (void) { if (g == 6) return 20; g = 7; }

Display status dialog during build displays a status box during the build, showing the name of the file being compiled, the number of errors and warnings encountered, and a percent complete value. Disabling this feature speeds up compiling. 2. Select Run Options from the Options menu. With this dialog box, you can select the maximum stack size, the level of debugging, and whether to hide the windows when you run a program.

Maximum stack size (bytes) The stack is for passing function parameters and storing automatic local variables. By setting a stack limit, LabWindows/CVI can catch runaway recursive functions and report a stack overflow. Debugging Level NoneSource modules execute faster without debugging, but you sacrifice the ability to set breakpoints or use the Variable Display window. Also, there is no user protection to check for using bad pointers, overindexing arrays, invalid array sizes, and so on. No run-time checkingIn this mode, you can set breakpoints and use the Variable Display window, but you have no user protection. StandardIn this mode, you can set breakpoints and use the Variable Display window and have user protection. ExtendedThis mode has the same benefits as Standard mode, with added user protection that validates every attempt to free

LabWindows/CVI Basics I Course Manual

1-10

National Instruments Corporation

Lesson 1 Exercises

dynamically allocated memory by verifying that the address passed is actually the beginning of an allocated block. 3. Select Options Library Options. You can select which libraries can be accessed from the Libraries menu and also install your own libraries. Once installed, the libraries are loaded automatically and appear at the bottom of the Library menu each time you launch LabWindows/CVI.

Note

The libraries added as user libraries must have function panel files associated with them so that they can be used via graphical function panels (discussed later in the course). Third-party library files generally do not have function panel files associated with them and are not integrated into the environment via the library options menu. Integrating external libraries is beyond the scope of this course manual and is discussed in greater detail in the Programmers Reference manual, as well as application notes and higher-level CVI course manuals.

End of Exercise 1-3

National Instruments Corporation

1-11

LabWindows/CVI Basics I Course Manual

Lesson 1 Exercises

Exercise 1-4
Objective: To create a LabWindows/CVI project. In Part A of this exercise, you enter code directly inside the Source window to create a program that generates a sine waveform and plots it on a graph. In Part B, you will use LabWindows/CVI function panels and the Insert Construct command from the Edit menu to create the same program.

Part A

1. Open a new project by selecting File New Project. Select Yes in the dialog box asking you if you want to unload the current project. Verify that every item in the Transfer Project Options dialog box has a check mark next to it and click on OK. (After you configure options such as compiler options, include paths, run options, and so on, you can transfer them from one project to another.) 2. Select Save As from the File menu. Name the project C:\exercises\CVI Basics 1\SINE.PRJ. 3. Select File New Source and enter the code shown below into the Source window. (If line numbers are not enabled, enable line numbers by selecting View Line Numbers.)
#include <userint.h> #include <analysis.h> double sine[1000]; void main() { SinePattern (1000, 1.0, 0.0, 1.0, sine); YGraphPopup ("Sine Plot",sine, 1000, VAL_DOUBLE); }

Note

Variable and function names are case sensitive in C.

LabWindows/CVI Basics I Course Manual

1-12

National Instruments Corporation

Lesson 1 Exercises

This program uses functions from the LabWindows/CVI Library menu to generate a sine pattern and plot it on a pop-up graph. At this time, do not worry about the different parameters. You will soon see how function panels describe the different parameters and simplify entering function calls in your application. 4. Add the file to the project by selecting File Add File To Project. Click Yes when asked if you want to name the file now and type C:\exercises\CVI Basics 1\SINE.C when LabWindows/CVI prompts you for the filename. After you are finished, close the file by choosing File Close (<Ctrl-W>). 5. Run the project by selecting Run Run Project (<Shift-F5>). After the program displays the sine plot graph, click on OK to return to the Project window.

Part B
LabWindows/CVI function panels simplify the development of a program. Now you will use the function panels to create the same program. When using function panels, you do not need to remember the order or data type of the various parameters associated with a function. 1. Double-click on the SINE.C filename in the Project window to open the file. 2. Highlight all text inside the window and choose Edit Delete (or press <Delete>). 3. Select Edit Insert Construct and choose Main. 4. Place the cursor on the line below the "return (-1)" statement. 5. From the Library menu, select the (Advanced Analysis : Signal Generation) Sine Pattern function.

National Instruments Corporation

1-13

LabWindows/CVI Basics I Course Manual

Lesson 1 Exercises

6. LabWindows/CVI has built-in help on all function panels. To display the panel help, select Help Function, <Shift-F1>, or right-click on the background. On the box that appears, you can use the Class Help button for help on the corresponding class of functions.

You can also get help on any control by clicking on the control and choosing Help Control, pressing <F1>, or right-clicking on the control. On the box that appears, you can use the Function Help button for help on the corresponding function for the selected control.

LabWindows/CVI Basics I Course Manual

1-14

National Instruments Corporation

Lesson 1 Exercises

7. Fill in the function panel as shown below. Notice how the parameters are inserted in the function displayed in the text box at the bottom of the window.

Declare Variable toolbar icon

8. With the cursor in the Sine Pattern box, select Code Declare Variable or press <Ctrl-D>. (You can also select the Declare Variable icon from the toolbar.) Fill in the dialog box as shown and click on OK.

National Instruments Corporation

1-15

LabWindows/CVI Basics I Course Manual

Lesson 1 Exercises

This action will declare the sine variable array and paste it in the Interactive Execution Window and at the top of the target file SINE.C. If your project has multiple source files, you can select the target file in which you want to declare the variable using the Set Target File button. 9. Select Code Insert Function Call (<Ctrl-I>) to paste the SinePattern function into the Source window. (You can also select Insert Function Call the Insert Function Call icon from the toolbar.) If your project has toolbar icon multiple source files, you can select the target file in which you want to insert the function call by using Code Set Target File (or by pressing the Set Target icon on the toolbar).
Set Target toolbar icon

10. Select Close (<Ctrl-W>) to close the function panel and return to the Source window. Notice the array declaration and the call to the SinePattern function with the parameters you specified.

Select Variable toolbar icon

11. Use View Find Function Panel (<Ctrl-Shift-P>) to find the YGraph Popup function. You need to type in only part of the function name; CVI finds all functions that match. The YGraphPopup function plots an array against its indices along the X axis. Recall that if you do not remember the names of previously declared variables, you can choose Code Select Variable (<Ctrl-A>) or press the Select Variable toolbar icon. A dialog box will appear from which you can select variables that have the same data type as the control. Fill in the Y Array parameter by selecting sine from the variable list.

LabWindows/CVI Basics I Course Manual

1-16

National Instruments Corporation

Lesson 1 Exercises

12. Select Code Insert Function Call (<Ctrl-I>) to paste the YGraphPopup function into the Source window. Close the function panel to return to the Source window. 13. Select Build Compile File. LabWindows/CVI can automatically determine which header files are required for a program when the Require Function Prototypes option is enabled in the Compiler Options for the project. (Recall that Require Function Prototypes can be found in the Project window under Options Compiler Options.)
Note

You still must remember to include header files that are not a part of the development environment or the libraries supplied with it. Any header files you create yourself must be manually included with a #include compiler directive.

National Instruments Corporation

1-17

LabWindows/CVI Basics I Course Manual

Lesson 1 Exercises

14. Make sure your program looks like the one shown below.

15. Save the program and the project by selecting File Save All. This action saves all files in the project.
Run Project toolbar icon

16. Run the program by selecting Run Run Project (you can also press <Shift-F5> or select the Run Project toolbar icon). It should work identically to the program you developed earlier.

End of Exercise 1-4

LabWindows/CVI Basics I Course Manual

1-18

National Instruments Corporation

Lesson 1 Exercises

Exercise 1-5
Objective: To plot a random number array and to find the mean of the array. Starting with a new project, write a program that generates a 100-element array containing a white noise pattern, plots it on a pop-up graph, calculates the mean (average) of the noise array, and prints the mean in the Standard I/O window. To create the program, use function panels and the Insert Construct command from the Edit menu. Use the (Advanced Analysis : Signal Generation) White Noise function to generate the array and the (Advanced Analysis : Statistics : Basics) Mean function. Use the ANSI C printf function to print the mean. Remember that even standard ANSI C functions have function panels. You access them the same way you access any other function panel from the Library menu. Also, to print a floating-point number, you must use the %f specifier in your printf function (for example, printf (number = %f\n, number);).
Note

Use Find Function Panel in the Source window View menu to bring up the function panel for the function (<Ctrl-Shift-P>). If you know only part of the function name, type in the part of the name that you know, and click Find. For example, if you want to find the PlotOval function, you could type in Plot or Oval to find the function. Save the project as C:\exercises\CVI Basics 1\NOISE.PRJ and the source file as C:\exercises\CVI Basics 1\NOISE.C. Dont forget to add the files to the project.

End of Exercise 1-5


Note

In the Mean function, the returned mean value is passed by reference. Therefore, you need to pass the address of the variable that you use for the Mean parameter. The & operator returns the address of the variable it precedes. For example,
double my_mean; . . Mean (my_inputArray, my_numPoints, &my_mean);

National Instruments Corporation

1-19

LabWindows/CVI Basics I Course Manual

Lesson 1 Exercises

Exercise 1-6
Objective: To use the Variables window to view the scope of variables. You will load and run a program that has global, module-global, and local variables. Using the Variables window, you will view the scope of the variables at successive breakpoints in the program. 1. Select File Open Project and open the project C:\exercises\CVI Basics 1\SCOPEVAR.PRJ. 2. Double-click on each filename and examine the contents of each file. The red diamonds are breakpoints.

3. Run the project. When execution stops at a breakpoint, choose Window Variables. Notice the global variable x, the two module-global variables y, and the local variable z.

LabWindows/CVI Basics I Course Manual

1-20

National Instruments Corporation

Lesson 1 Exercises

4. Continue program execution by selecting Run Continue (or press <F5> or the GO icon on the toolbar). 5. Look at the Variables window once again. Notice that when the program stops at the breakpoint inside the subroutine foo1, the Variables window displays a new local variable, z. This variable is different from the variable z defined in main.

6. Continue program execution. 7. Look at the Variables window once again. Notice that when the program stops at the breakpoint inside the subroutine foo2 (inside a different module SCOPVAR2.C), the Variables window displays a new local variable, z. The variable z is the one in module foo2, as opposed to the variable z in foo1 as in step 5. The variable z in foo2 is also different from the variable z defined in main.

National Instruments Corporation

1-21

LabWindows/CVI Basics I Course Manual

Lesson 1 Exercises

8. Continue program execution. 9. When the program completes, the Standard I/O window displays values of the different variables. Notice that the subroutine foo2 changed the original value of x and foo1 changed the original value of y. However, z was not changed; both subroutines temporarily defined the variable z. foo1 changed y because the original y was global only to SCOPVAR1.C; a new y was defined in SCOPVAR2.C.

10. Look at the Variables window again. Notice that when the program completes, the variable z (the one defined in main) is no longer present. It is discarded after the program completes. However, the global variable x and the module-global variables y (both of them) are still present.
Note

The Interactive Execution Window cannot be used to declare module global variables. However, module global variables (such as x in this example) can be accessed from the IEW by declaring the same variable in the IEW with keyword extern. 11. Insert a breakpoint in the main subroutine on the line containing the second printf call. Remove all other breakpoints by left-clicking on the breakpoint symbols in the margin.

LabWindows/CVI Basics I Course Manual

1-22

National Instruments Corporation

Lesson 1 Exercises

12. Run the program again and type the following code segment in the interactive execution window when you reach the breakpoint.
extern int x; printf(x = %i ,x);

13. Run the interactive statements entered in the IEW and then continue normal program execution.

End of Exercise 1-6

National Instruments Corporation

1-23

LabWindows/CVI Basics I Course Manual

Lesson 1 Exercises

Exercise 1-7
Objective: To examine the source code stepping and debugging tools in LabWindows/CVI. Rather than show all the different ways you can step through code and view variables, you will look at a simple example that illustrates key concepts involved in debugging and monitoring project execution. You will configure LabWindows/CVI for a conditional breakpoint to stop the program whenever a user-defined condition is met a specified number of times. 1. Open the project C:\exercises\CVI Basics 1\WATCHDBG.PRJ and run the project. After running the project, examine the source code. Notice that it generates random numbers between 0 and 32,767 and checks to see whether the number is greater than 16,383. Depending on the outcome of the comparison, the project counts the random number as a head or a tail. Two hundred tosses (random numbers) are generated, and a tally of heads and tails is kept and updated after each toss. At the end, the program outputs the number of heads and tails that occurred to the Standard I/O window. 2. Now, you will observe the processing steps taken by the program to go through a single toss. Run the program again and, while it is running (indicated by the word <<Running>> in the upper left corner of the Project window), manually halt the program by pressing <Ctrl-F12>. 3. Place a breakpoint on line 15 (RandTest (arr[i]);) in the source file WATCHDBG.C. To place a breakpoint on the line, left-click in the line icon column of the Source window. (A red diamond should appear, indicating a breakpoint.)

LabWindows/CVI Basics I Course Manual

1-24

National Instruments Corporation

Lesson 1 Exercises

4. Continue the program execution by selecting Run Continue (or pressing <F5>). The program should break at line 15. Examine the values of the various variables by selecting the Variables window from the Window menu. Hide the window after reviewing the variables by selecting File Hide or pressing <Ctrl-W>. 5. Step into the RandTest function by selecting Run Step Into (or pressing <F8> or the Step Into toolbar icon shortcut). A new window should display the RandTest function. Because the RandTest function is in a separate source file, RANDTEST.C, LabWindows/CVI simply opens a new window.

Go to Cursor toolbar icon

6. Step through the RandTest source code by pressing <F8>. Notice that the function first executes a large for loop. Single stepping through this loop takes too much time. However, you do not want to skip through the whole function; you just want to execute the for loop to get to the code after the loop. You can do this easily by clicking the mouse to the left of the last closing curly bracket in the function and selecting Run Go To Cursor (or by left-clicking on the Go to Cursor icon in the toolbar). 7. Select Window Variables to examine the updated tally for heads and tails. Select File Hide (<Ctrl-W>) to close the window. 8. Select Run Continue (or press <F5> or the Go toolbar icon) to continue program execution. Again, examine the variables to see the effects of the last toss. 9. Select Run Terminate Execution (or press <Ctrl-F12> or the Stop toolbar icon) to terminate program execution. 10. Remove the breakpoint from line 15 by left-clicking on the red diamond.

Go toolbar icon

Stop toolbar icon

National Instruments Corporation

1-25

LabWindows/CVI Basics I Course Manual

Lesson 1 Exercises

Now, you will set conditional breakpoints to investigate how many tosses are required to get 50 heads. 11. Select the Watch window from the Window menu. Select Edit Add Watch Expression. Fill in the dialog box as shown below and select Add.

12. Repeat step 11 to add tails and the expression heads+tails to the Watch window. Use the same values as shown above in the dialog box. 13. Now, you will add variables for the conditional operation. Again, select Edit Add Watch Expression. Fill in the dialog box as shown below and select Add.

14. Repeat step 13 to add arr[i] to the Watch window. Use the same values as shown above in the dialog box. The Watch window should resemble the one shown below.

LabWindows/CVI Basics I Course Manual

1-26

National Instruments Corporation

Lesson 1 Exercises

15. Except for the Project window, close all open windows. Run the project again to see how you can monitor selected expressions in the Watch window during project execution. 16. Place a breakpoint on line 16 (Delay (.05)) in the source file WATCHDBG.C. Right-click on the red diamond and select Breakpoints in the dialog box. Highlight the line with the breakpoint information and select Add/Edit Item. Fill in the dialog box as shown below.

With this setup, the project execution breaks whenever (arr[i] > 16383). However, you want the program to halt only when this condition has occurred 50 times. Therefore, you set the Pass Count field to 50. Click on Replace and select OK. Save the project. Close all the windows except the Project window. 17. Run the project again and examine the contents of the Watch window as the execution continues. Observe how many tosses it takes to reach 50 heads.
Stop toolbar icon

18. Press <Ctrl-F12> or the Stop icon in the toolbar to terminate execution.

End of Exercise 1-7


Note

LabWindows/CVI saves breakpoints and watch expressions in the .prj file, and not in the source file.

National Instruments Corporation

1-27

LabWindows/CVI Basics I Course Manual

Lesson 1 Exercises

Notes

LabWindows/CVI Basics I Course Manual

1-28

National Instruments Corporation

Lesson 2 Exercises
Exercise 2-1
Objective: To view and run an application program containing a GUI.

19. Open and run C:\exercises\CVI Basics 1\UILDEMO.PRJ. 20. The program plots a sine waveform on a graph when you press the GENERATE button. 21. You can clear the graph using the DEL PLOTS button and specify the number of cycles using the Num Cycles input. 22. Use the QUIT button to terminate the application.

End of Exercise 2-1

National Instruments Corporation

2-1

LabWindows/CVI Basics I Course Manual

Lesson 2 Exercises

Exercise 2-2
Objective: To play with some of the features of a GUI. 1. Open C:\exercises\CVI Basics 1\graphs.prj.

2. This is the same program you looked at in Exercise 2-1. You will explore some of the features of graphs and GUIs, including panning, zooming, tab order, and shortcut keys. 3. The first thing you will look at is panning. Run the program and generate a plot on the screen. To pan (move the image on the screen) the graph image, press <Ctrl-Shift-Left Mouse Button> and move the mouse. The point that you clicked on will move with the mouse. To undo any panning, press <Ctrl-Spacebar> to restore the graph to its original state. 4. Try to zoom in and out on the graph. To zoom in (enlarge the graph), press <Ctrl-Left Mouse Button> and you will see the graph zoom in on the cursor location. If you move the mouse, zooming will continue over the new cursor location. To zoom out, press <Ctrl-Right Mouse Button>. Again, you can press <Ctrl-Spacebar> to restore the graph to its original state. 5. Quit the program and double-click on graphs.uir to bring up the User Interface Editor. Edit each button and add a double underscore (__) to a letter in each command button. Notice that it becomes underlined. Windows automatically assigns the shortcut key <Alt-Underlined Letter> to the control. Run the project again. Press the shortcut keys and notice that the associated control generates an EVENT_COMMIT.

LabWindows/CVI Basics I Course Manual

2-2

National Instruments Corporation

Lesson 2 Exercises

6. Notice the Tab Order of the controls. When you press the tab button, watch the focus change among the controls. Is this the logical order of things? Normally, you would want the user to select the number of cycles, graph the sine wave, delete the sine wave, and quit the program. Quit the program and bring up the User Interface Editor. Select Edit Tab Order and change the tab order of the controls to make them follow the program logic. Run the program and notice how you can just press <Tab> (the spacebar will generate an EVENT_COMMIT when a command button has focus) to logically traverse your controls. 7. Quit the program. Save all changes.

End of Exercise 2-2

National Instruments Corporation

2-3

LabWindows/CVI Basics I Course Manual

Lesson 2 Exercises

Exercise 2-3
Objective: To build a GUI.

Creating the Panel


1. Start a new project by selecting File New Project. Save the project as C:\exercises\CVI Basics 1\INCDEC.PRJ. 2. Open a new UIR file by selecting File New User Interface. 3. Before creating any controls, you must first create a panel. To do this, select Create Panel. Enlarge the panel by dragging any corner. 4. Edit the Panel dialog box by double-clicking on the panel (or right-click on the User Interface Editor window background and select panel). Fill in the dialog box as indicated below: Constant Name Panel Title PANEL Increment/Decrement

The Constant Name specifies the prefix of all defined controls associated with this panel in the applications program. You will use the prefix in your program when specifying this panel.
Coloring tool

5. If you want, modify the panel color using the Coloring tool in the Quick Edit Window. (Right-click on the panel to display the color palette from which you can choose a color.) When you have finished, select OK.

Creating the Numeric


6. To create the Count numeric, select Create Numeric Numeric (or right-click on the panel and select Numeric Numeric). Double-click on the numeric and fill in the Edit Numeric dialog box as indicated below. If you want, modify the numeric color using the Coloring tool in the Quick Edit Window or modify the numeric text using the Control Appearance section. When you finish, select OK. Position the numeric indicator by dragging it with the mouse (or using the arrow keys). Constant Name Default Value Data Types Minimum Maximum Inc Value Range Checking Control Mode Label COUNT 0 int -2147483648 2147483647 1 Notify Indicator Count

LabWindows/CVI Basics I Course Manual

2-4

National Instruments Corporation

Lesson 2 Exercises

Note

The Constant Name is COUNT. When you develop your application, PANEL_COUNT refers to the numeric on this panel. PANEL is the prefix for all controls on the panel, while each object is labeled with unique constants. To move an object one pixel at a time, press <Shift> while using the arrow keys. You can also access the Create menu by clicking on a panel using the right mouse button.

Tip

Creating the Command Buttons


7. To create the four command buttons, select Create Command Button Square Command Button. Double-click on the button and fill in the dialog box as indicated below. If you want, modify the button color using the Quick Edit Window and the label color using the Label Appearance section. When you have finished, select OK. Position each button by dragging it with the mouse (or using the arrow keys). Button Name Constant Name Callback Function Control Mode Label
Note

INCREMENT AddOne Hot __Increment

DECREMENT SubtractOne Hot __Decrement

RESET SetToZero Hot __Reset

QUIT QuitProgram Hot __Quit

You can use Copy and Paste from the Edit menu to create the second and third buttons. Resize the button by dragging a corner. 8. Your panel should look similar to the one shown below. If it does not, position the objects on your panel to match those shown below.

National Instruments Corporation

2-5

LabWindows/CVI Basics I Course Manual

Lesson 2 Exercises

9. Add the file to the project by selecting File Add File To Project. Enter C:\exercises\CVI Basics 1\INCDEC.UIR when prompted for the filename and save the file. This file is a User Interface Resource (.uir) file, which contains the panel and controls.

The .h File
10. When you save the GUI, LabWindows/CVI automatically generates an include file (.h) containing all user-defined constants. To view the contents of the include file, select View Preview User Interface Header File. Close the .h file and the .uir file and save the project.
/**************************************************************************/ /* LabWindows/CVI User Interface Resource (UIR) Include File */ /* Copyright (c) National Instruments 1997. All Rights Reserved. */ /* */ /* WARNING: Do not add to, delete from, or otherwise modify the contents */ /* of this include file. */ /**************************************************************************/ #include <userint.h> #ifdef __cplusplus extern "C" { #endif /* Panels and Controls: */ #define #define #define #define #define #define PANEL PANEL_COUNT PANEL_INCREMENT PANEL_DECREMENT PANEL_RESET PANEL_QUIT 1 2 3 4 5 6

/* /* /* /*

callback callback callback callback

function: function: function: function:

AddOne */ SubractOne */ SetToZero */ QuitProgram */

/* Menu Bars, Menus, and Menu Items: */ /* (no menu bars in the resource file) */ /* Callback Prototypes: */ int CVICALLBACK AddOne(int panel, int control, int event, void *callbackData, int eventData1, int eventData2); int CVICALLBACK QuitProgram(int panel, int control, int event, void *callbackData, int eventData1, int eventData2); int CVICALLBACK SetToZero(int panel, int control, int event, void *callbackData, int eventData1, int eventData2); int CVICALLBACK SubtractOne(int panel, int control, int event, void *callbackData, int eventData1, int eventData2); #ifdef __cplusplus } #endif

LabWindows/CVI Basics I Course Manual

2-6

National Instruments Corporation

Lesson 2 Exercises

The constant PANEL refers to the panel in the INCDEC.UIR file. The constant PANEL_COUNT refers to the numeric indicator, the constant PANEL_INCREMENT refers to the Increment button, the constant PANEL_DECREMENT refers to the Decrement button, the constant PANEL _QUIT refers to the Quit button, and the constant PANEL_RESET refers to the Reset Button. To use these constants in your program, you must include the .h file at the beginning of the application program. To include the file, use the following statement:
#include "incdec.h"

Note

Do not use this statement in the .h file. You will add this statement to your application program in Exercise 2-4.

End of Exercise 2-3

National Instruments Corporation

2-7

LabWindows/CVI Basics I Course Manual

Lesson 2 Exercises

Exercise 2-4
Objectives: To look at the different events and understand how they are generated by looking at the User Interface Editor Event Watcher. To use the User Interface created in the last exercise to create a working program that operates on the Event Driven Program principle. The final program will increment and decrement the value in a user interface control in response to a users selection. At any point, the user should be able to reset the value to zero and continue.

Understanding Events
1. Open INCDEC.PRJ. Double-click on INCDEC.UIR to open the user Interface Editor. 2. From the toolbar in the User Interface Editor, select the Operating toolbar icon.
Operating toolbar icon

3. Spend a few minutes clicking around the window and selecting different objects. What happens when you double-click on an object? What happens when you click on one object and then another? What happens if you click on an object and move the cursor before releasing the mouse button? 4. Once you feel you have a good idea about the events and how they are generated, think about what kinds of events would be used in this application.

Making the Program Work


1. Open a new source code window by selecting File New Source. 2. Type in the following source code, paying attention to the code structure. (Tip: Make good use of copy, paste, and Find Function Panel (<Ctrl-Shift-P>). Notice the similarity of each int CVICALLBACK portion of the code).
#include <userint.h> #include "incdec.h" static int panelHandle, i; int main (int argc, char *argv[]) { panelHandle = LoadPanel (0, "incdec.uir", PANEL); DisplayPanel (panelHandle); RunUserInterface (); return 0; } int CVICALLBACK AddOne (int panel, int control, int event, void *callbackData, int eventData1, int eventData2) {

LabWindows/CVI Basics I Course Manual

2-8

National Instruments Corporation

Lesson 2 Exercises

switch (event) { case EVENT_COMMIT: SetCtrlVal (panelHandle, PANEL_COUNT, ++i); break; } return 0; } int CVICALLBACK SubtractOne (int panel, int control, int event, void *callbackData, int eventData1, int eventData2) { switch (event) { case EVENT_COMMIT: SetCtrlVal (panelHandle, PANEL_COUNT, --i); break; } return 0; } int CVICALLBACK SetToZero (int panel, int control, int event, void *callbackData, int eventData1, int eventData2) { switch (event) { case EVENT_COMMIT: i=0; SetCtrlVal (panelHandle, PANEL_COUNT, i); break; } return 0; } int CVICALLBACK QuitProgram (int panel, int control, int event, void *callbackData, int eventData1, int eventData2) { switch (event) { case EVENT_COMMIT: QuitUserInterface (0); break; } return 0; }

Run Project toolbar icon

3. Save the code as INCDEC.C, add the file to the project (File Add File to Project), and run the code by selecting Run Run Project <Shift-F5> (or pressing the Run Project icon).

National Instruments Corporation

2-9

LabWindows/CVI Basics I Course Manual

Lesson 2 Exercises

4. Test the functionality of the program. When you finish, press the Quit button.

Understanding Event-Driven Programming


Now that youre back at the code window, examine what you have written. Notice that the main function consists of only three lines of code. After the panel is loaded and displayed, the code hits RunUserInterface. Most of the time, the code is in this RunUserInterface function. When this function detects that an event has occurred on a particular object on the user interface, it calls the callback function associated with that object. If you remember, when you created each object in the User Interface Editor, this callback function was determined in the Source Code Connection section of the Edit Object window. In the callback function in the source code, the programmer checks to see which event was generated (with the case statement) and executes a portion of code in response to that event. Once that particular segment of code finishes execution, execution returns to RunUserInterface until another event occurs. It is not until a call to QuitUserInterface is made (as in the QuitProgram callback in this exercise) that execution returns from RunUserInterface and continues with the next line of code in the main function if there is one. It is important to realize that with this structure of programming, the segments of code below the main function are executed only in response to events that occur on the user interface. It is possible for a particular callback not to be used at all during execution of a program. For example, in the previous exercise, if the user never presses the Reset button, the lines of code associated with that button never execute. To demonstrate this structure, run through the procedure shown below.

LabWindows/CVI Basics I Course Manual

2-10

National Instruments Corporation

Lesson 2 Exercises

1. Place a breakpoint on the line that makes the call to SetCtrlVal in the SubtractOne callback function. 2. Run the program. 3. This time, press the Increment and Reset buttons repeatedly. Notice what happens when you press the Decrement button.

End of Exercise 2-4

National Instruments Corporation

2-11

LabWindows/CVI Basics I Course Manual

Lesson 2 Exercises

Exercise 2-5
Objective: To use the LabWindows/CVI CodeBuilder to load and display programmatically a GUI created earlier in this lesson. 1. Open the project C:\exercises\CVI Basics 1\INCDEC.PRJ and save it as INCDEC2.PRJ. Because you will use the CodeBuilder to generate your source file, remove the current source file INCDEC.C and INCDEC.H (if you added the header file) from the project by highlighting them and selecting Edit Remove File. 2. Double-click on incdec.uir to open it. Select Save As to save INCDEC.UIR as INCDEC2.UIR. Now you need to select the events for the switch construct of the control callback functions that the CodeBuilder will generate. Select Code Preferences Default Control Events. Check EVENT_COMMIT and EVENT_RIGHT_CLICK. Make sure that everything else is unchecked. Click on OK. 3. Select Code Preferences again and make sure that Always Append Code to End is checked. This will cause the callback functions to be appended at the end instead of where the cursor currently resides. 4. Now, you are ready to generate code to control the GUI. Select Code Generate All Code. The Generate All Code dialog box should appear. Make sure that the panel, PANEL, is checked. Next, type panelHandle (or a different variable if you so desire) in the Panel Variable Name box. This refers to the name of the variable that contains the panel handle. Finally, place a checkmark next to QuitProgram. This tells LabWindows/CVI which callback function you want to contain the function QuitUserInterface. Click on OK. 5. A new Source window, containing the newly generated main, as well as AddOne, SubtractOne, SetToZero, and QuitProgram, should open. Observe the generated code. Notice that the LabWindows/CVI CodeBuilder has inserted three include statements. Also, notice that the variable name that you chose for the panel handle has been declared and is used in the LoadPanel function. Further, the EVENT_COMMIT and EVENT_RIGHT_CLICK cases have been incorporated in the switch construct for all callback functions. You selected these cases as default control events in step 2. Finally, notice that the QuitUserInterface function has been incorporated into the QuitProgram callback function. Save the file as INCDEC2.C and select File Add File To Project. 6. Remember that the CodeBuilder produces only the skeleton code, and you need to change it to perform customized tasks. Declare a module global variable called number to keep track of the number to display. (See Lesson 1 for more information on module globals.)

LabWindows/CVI Basics I Course Manual

2-12

National Instruments Corporation

Lesson 2 Exercises

7. Customize the AddOne function. Add code to increment the counter by one in the EVENT_COMMIT case in AddOne and use MessagePopup to add online help in the EVENT_RIGHT_CLICK section. 8. Make similar additions to the SubtractOne and SetToZero callback functions. 9. Make sure that all the source code is functionally equivalent to that shown in the code listing for Exercise 2-3. Save the source code file. 10. Run the project again. It should execute as it did before. 11. Choose Project Save All.

End of Exercise 2-5

National Instruments Corporation

2-13

LabWindows/CVI Basics I Course Manual

Lesson 2 Exercises

Exercise 2-6
Objectives: To understand how to develop well behaved applications in LabWindows/CVI. To understand the functionality of RunUserInterface, QuitUserInterface, and ProcessSystemEvents.

Procedure
1. Open C:\exercises\CVI Basics 1\BEHAVE.PRJ. This application has no functional value but will have instructional value. 2. Examine the code. Notice that the callback Start does nothing but count off 10 seconds and update the screen with these values. Additionally, if the user presses the Pop Up Message button, a message will pop up acknowledging this event. 3. Run the application and press the Start Counting button. 4. While the application is counting off the seconds, press the Pop Up Message button. When do you see the message? Click on the Quit button to quit. 5. Open Behave.c. On line 50 of the code, make the call to ProcessSystemEvents no longer commented out. 6. Repeat step 3 and notice how this call has affected things. Repeat this action a few times and notice that the message always pops up in one of two placesafter you have counted 5 or 10, depending on when the button was pressed. 7. What happens when you press the Quit button? Run the program again and press the Quit button during the first five seconds of the test. What happens on the screen? What happens to the application? Is this how you want your application to behave? 8. Add the following line starting on line 27, right after QuitUserInterface:
quitFlag = 1;

(quitflag is already declared) 9. Add the following lines to line 51, right after ProcessSystemEvents:
if (quitFlag) break;

10. Run the application and see how the behavior is different.

End of Exercise 2-6

LabWindows/CVI Basics I Course Manual

2-14

National Instruments Corporation

Lesson 2 Exercises

Exercise 2-7
Objective: To use a timer control to continuously plot data on a strip chart. You will load an incomplete project and add the necessary functions to the program to continuously plot the numbers on the strip chart. 1. Open the project C:\exercises\CVI Basics 1\PLOTCHRT.PRJ. This project is incomplete.

Adding the Strip Chart


2. Double-click on the file PLOTCHRT.UIR to enter the User Interface Editor. The GUI already defines two buttons, QUIT and PLOT. The callback functions Quit and PlotData are already assigned to the respective buttons. 3. To create the strip chart, select Create Graph Strip Chart. Double-click on the chart and fill in the Edit Strip Chart dialog box as indicated below. If you want, modify the chart color using the tool in the Quick Edit Window or the grid color using the Control Appearance section. When you have finished, select OK. Size and position the strip chart. Constant Name Points per Screen Scroll Mode Y-axis... Axis Name Minimum Maximum Divisions Precision Label
Random Numbers 0.00 100.00 5 1 Random Number Chart CHART 100 Continuous

Adding the Timer Control


4. Select Create Timer. Double-click on the timer and fill in the Edit Timer dialog box as shown below. Remember that timer controls are visible only on the User Interface Editor panel. They do not appear when the panel is displayed programmatically. Notice that the timer interval is specified in seconds. You have specified it to be 0.100 seconds. Constant Name Callback Function Interval (seconds) Label
TIMER TimerCB 0.100 Timer

National Instruments Corporation

2-15

LabWindows/CVI Basics I Course Manual

Lesson 2 Exercises

5. Close and save your GUI.

Modifying the Source File


6. Double-click on the file PLOTCHRT.C to edit the source file. Examine the source file. TimerCB is the timer control callback function. You will add code to this function shortly. PlotData, assigned to the PLOT button, sets the variable plotFlag to TRUE when the PLOT button is committed. Quit, assigned to the QUIT button, quits the user interface when the QUIT button is committed. 7. Press <F2> or select View Next Tag to go to the tag (green square). The file was saved with a tag to mark where you will insert additional code. 8. Select Edit Insert Construct and choose If.... For the condition of the If construct, type plotFlag == TRUE in the If dialog box. 9. From the Library menu, select the following function and fill in the function panel as shown below. After you have finished, select Code Insert Function Call (<Ctrl-I>). Plot Strip Chart (User Interface : Controls/Graphs/Strip Charts : Graphs and Strip Charts : Strip Chart Traces) Panel Handle Control ID YArray Number of Points Starting Index Skip Count Y Data Type Status
panelHandle PANEL_CHART dataPoints 1 0 0 double precision

Leave blank

10. Insert the following line before the PlotStripChart line.


dataPoints[0] = rand()/32767.0 * 100.0;

11. Run the project. When you left-click on the PLOT button, the program should plot random numbers on the strip chart. 12. Modify the program to do the following: Plot three traces on the strip chart. One trace should be the random number, and the other two traces should be constants at 30.0 and 70.0. Disable the PLOT button after the user left-clicks on the button.

LabWindows/CVI Basics I Course Manual

2-16

National Instruments Corporation

Lesson 2 Exercises

Note

You will need to edit the strip chart control for three traces, modify the dataPoints array for three elements, set elements 1 and 2 to 30.0 and 70.0, respectively, and update PlotStripChart for three traces. Use the SetCtrlAttribute function to disable the PLOT button. Use the attribute ATTR_DIMMED. This is very useful in preventing you from selecting a button out of the logical order. 13. Save all your work when finished.

End of Exercise 2-7

National Instruments Corporation

2-17

LabWindows/CVI Basics I Course Manual

Lesson 2 Exercises

Exercise 2-8 (Additional Challenge Exercise)


Modify INCDEC2.PRJ created in Exercise 2-5 so that clicking and holding on up or down buttons increments or decrements the number continuously. While pressing the up or down buttons, the number should increment or decrement every half-second.
Note

You will need to add a timer control to INCDEC.UIR. In addition, you may consider using the GetRelativeMouseState, SetCtrlAttribute, and GetCtrlAttribute functions. If you are unfamiliar with these functions, please look up their function panels and read the online help. There are many different implementations of this program. Depending on your view of the ideal behavior, it may be programmed in many different ways. The solution is just one implementation. Save your files as: Project File GUI File Source File
C:\exercises\CVI Basics 1\INCDEC2.PRJ C:\exercises\CVI Basics 1\INCDEC2.UIR C:\exercises\CVI Basics 1\INCDEC2.C

Note

End of Exercise 2-8

LabWindows/CVI Basics I Course Manual

2-18

National Instruments Corporation

Lesson 3 Exercises
Exercise 3-1
Objective: To explore the functionality of DAQ Designer. DAQ Designer is a software utility that helps you during the system configuration stage. DAQ Designer acts as an advisor and steps you through the various phases of designing a total data acquisition system: obtaining information about your application, signal types, system requirements, signal conditioning, software needs, and product selection. Through an interactive wizard method, you are prompted for information regarding your data acquisition needs and constraints.

National Instruments Corporation

3 -1

LabWindows/CVI Basics I Course Manual

Lesson 3

Exercises

1. Run DAQ Designer by selecting Start Programs DAQ Designer. 2. This exercise is not intended to answer all your data acquisition application questions, but to familiarize you with a powerful configuration tool that is available for your use. Go through the various steps of configuring a data acquisition system and learn about the assortment of design considerations that may need to be considered during the design stage. Some of the data acquisition concepts mentioned in DAQ Designer will be explained in a later section of this chapter. 3. When you reach the last window, step 12 of 12, you will get a product listing for the system you configured. Make sure that you deselect the option to transmit a request to National Instruments via the Internet.

4. Quit the application after you have finished browsing through the features available in DAQ Designer.

End of Exercise 3-1

LabWindows/CVI Basics I Course Manual

3 -2

National Instruments Corporation

Lesson 3

Exercises

Exercise 3-2
Objective: To open the NI-DAQ Configuration Utility and study the current setup. You will also test the board interactively with the utility. Explain the features and capabilities of the DAQ Signal Accessory.
Instructors Note Note

Please do not alter any of the setup parameters. The hardware has been correctly configured for the course. 1. Start the NI-DAQ Configuration Utility by selecting Start Programs CVI NI-DAQ Configuration Utility.

2. You should see the DAQ board configured with a device number. When you install the board for the first time, you can arbitrarily assign any device number to your board. This device number is an important parameter used in DAQ function calls. 3. Select the Configure button and you will see another window that lists the hardware parameters assigned to the board.

National Instruments Corporation

3 -3

LabWindows/CVI Basics I Course Manual

Lesson 3

Exercises

These parameters should match those listed for the board in the Device Manager. 4. Use the Test Resources button to verify the hardware settings of the DAQ board. You should use the Run Test Panels routine to verify hardware operation before attempting to use the LabWindows/CVI DAQ functions. 5. Verify that the analog input, analog output, and digital I/O functionality is working properly. 6. Close all the NI-DAQ windows when you are finished.

End of Exercise 3-2

LabWindows/CVI Basics I Course Manual

3 -4

National Instruments Corporation

Lesson 3

Exercises

Exercise 3-3
Objective: To quickly build a DAQ application using ECHO controls. 1. Open the project C:\exercises\CVI Basics 1\ECHO.PRJ. The project is incomplete. 2. Run the project and you will see a strip chart and a quit button. This is the basic template for using a DAQ ECHO control. 3. Quit the application. 4. Double-click on the file ECHO.C to edit the source file. 5. Press <F2> or select View Next Tag to go to the tag (green square). 6. The rest of the source file was automatically generated from Code Builder. All you will add is the following function call at the tag location:
DAQ_Chart_ConvertFromStripChart (panelHandle, PANEL_STRIPCHART, 0); where panel = panelHandle (this is the handle returned from LoadPanel); Strip Chart to Convert = PANEL_STRIPCHART (strip chart on UIR); and Configuration Name = 0

7. Save your changes and run the project. 8. The program will look the same, but the voltage from Channel 0 (Temp Sensor on the DAQ Signal Accessory) should now be plotted (temperature reading) on the strip chart. The DAQ Chart ties an analog input channel to the strip chart. 9. To configure the properties of the DAQ Chart, right-click on the strip chart itself. A Properties button will appear. 10. By selecting the Properties option, you will get a selection of tabbed pages in which you can manipulate the DAQ properties of the chart.

National Instruments Corporation

3 -5

LabWindows/CVI Basics I Course Manual

Lesson 3

Exercises

11. Set up an alarm condition by selecting the Alarms tab. Within this tab, you will get a list of the various alarm conditions that you have set. To create an alarm condition, choose the New Alarm control. For this exercise, change the value of the Limit control and make sure the Plot Alarm control is enabled. When you are finished, press the Done command button and you will see the alarm condition plotted against the data. 12. After you are finished exploring the capabilities of the DAQ Chart Properties sheets, select the Done command button and quit the application.
Note

The instrument driver for this functionality, DAQCHART.FP, was already loaded in the project. The driver will be discussed later in this course.

End of Exercise 3-3

LabWindows/CVI Basics I Course Manual

3 -6

National Instruments Corporation

Lesson 3

Exercises

Exercise 3-4
Objective: Part A: To measure temperature using a DAQ board and plot it on a strip chart. Part B: To acquire waveforms from multiple channels.

Part A
In this exercise, you will load a partially completed program and modify it to measure temperature using the temperature sensor on the DAQ Signal Accessory. The temperature sensor generates a voltage directly proportional to the ambient temperature. The sensor is hard wired to Channel 0 of the DAQ board. The GUI (already created for you) is shown below.

When you select the Start button, the program should: Continuously measure the temperature sensor voltage Convert the voltage to degrees Celsius Plot both the measurement along and the value of the MAX control Use the voltage conversion formula C = voltage * 100 (as the temperature sensor is reading 0.01 V per degree Celsius)

Use the project C:\exercises\CVI Basics 1\TMON.PRJ to get started and bear in mind that the strip chart has been configured for two traces.
Note Note

Recall how PlotStripChart handles multiple traces. Save your work when finished, because you will modify this project in a later exercise. The behavior of the LED will be modified at that point.

National Instruments Corporation

3 -7

LabWindows/CVI Basics I Course Manual

Lesson 3

Exercises

Part B
You will complete a program that uses the AIAcquireWaveforms function to acquire two signals and plot both signals on a graph. To set up the DAQ Signal Accessory for this exercise, connect analog input channels 1 and 2 to two different function generators (such as the sine and square wave) using wire provided by the instructor. 1. Open the project C:\exercises\CVI Basics 1\SCAN.PRJ. The program is incomplete. You will add code to scan Channels 1 and 2 and plot the waveforms. 2. Examine the program. The program loads and displays a GUI that contains a graph, a command button to start the multiple-channel acquisition, a numeric input control to specify the scan rate, and a command button to terminate the program. The GUI (SCAN.UIR) is already built.
Panel Constant Name: PANEL Panel Title: Acquire and Plot Waveform Constant Name: GRAPH Graph Title: Waveform Y-axis Name: Voltage X-axis Name: sec X-axis precision: 2

Constant Name: QUIT Callback Function: Quit Constant Name: RATE Data Type: Double Minimum: 100 Maximum: 40000 Range Checking: Notify Control Mode: Validate Constant Name: ACQUIRE Callback Function: Acquire

3. Open the SCAN.C file by double-clicking on the filename. Press <F2> to move to the first tag and add the declaration code shown below.
static double waveforms[2000];

The array, waveforms, stores the data that AIAcquireWaveforms returns. The program acquires a total of 2,000 points1,000 points from Channel 1 and 1,000 points from Channel 2. 4. Press <F2> to move to the tag inside the Acquire callback function.

LabWindows/CVI Basics I Course Manual

3 -8

National Instruments Corporation

Lesson 3

Exercises

5. From the Library menu, select the following function and fill in the function panel as shown below. After you have finished, select Code Insert Function Call (or press <Ctrl-I>). AI Acquire Waveforms (Easy I/O for DAQ : Analog Input) Device Channel String Number of Scans Scans/Second High Limit (volts) Low Limit (volts) Actual Scan Rate Fill Mode Waveform(s) Error
1 "1:2" 1000 scan_rate +5.0 -5.0 &act_scan_rate Group by Channel waveforms easyErr

6. Your Acquire callback function should look similar to that shown below.
int CVICALLBACK Acquire(int panel, int event, void *callbackData, int eventData1, int eventData2) { switch (event) { case EVENT_COMMIT: GetCtrlVal (pnl_handle, PNL_RATE, &scan_rate); easyErr = AIAcquireWaveforms (1, "1:2", 1000, scan_rate, 5.0, -5.0, &act_scan_rate, waveforms); DeleteGraphPlot (pnl_handle, PNL_GRAPH, -1, 1); PlotWaveform (pnl_handle, PNL_GRAPH, waveforms,1000, VAL_DOUBLE, 1.0, 0.0, 0.0, (1/act_scan_rate)/2, VAL_THIN_LINE, VAL_EMPTY_SQUARE, VAL_SOLID, 1, VAL_RED); PlotWaveform (pnl_handle, PNL_GRAPH, waveforms+1000, 1000, VAL_DOUBLE, 1.0, 0.0, 0.0,(1/act_scan_rate)/2, VAL_THIN_LINE, VAL_EMPTY_SQUARE, VAL_SOLID, 1, VAL_DK_BLUE); break; } return (0); }

Selecting the ACQUIRE button starts the two-channel scanned acquisition. GetCtrlVal gets the value of Scanning Rate and assigns it to the variable scan_rate. The program uses this value to start the multiple-channel

National Instruments Corporation

3 -9

LabWindows/CVI Basics I Course Manual

Lesson 3

Exercises

acquisition. After AIAcquireWaveforms returns, the data is in a demuxed mode in the array waveforms. The first call to PlotWaveform plots the data from Channel 1, which forms the first 1,000 elements of the array waveforms. The second call to PlotWaveform plots the 1,000 points from Channel 2, which forms the next 1,000 elements of waveforms. 7. Save and run your project. The number placed into the Scan Rate control specifies the scanning rate per channel. AIAcquireWaveforms uses pseudo-simultaneous scanning, which means that the interchannel delay is automatically set to the smallest value accepted by your hardware. The program should plot two waveforms to the screen. Run the project several times, varying the sampling rate and observing the data on the screen. 8. After you have finished, select QUIT to return to the Project window.

End of Exercise 3-4

LabWindows/CVI Basics I Course Manual

3 -10

National Instruments Corporation

Lesson 3

Exercises

Exercise 3-5
Objective: To perform asynchronous analog input using callback functions. You will complete a program that uses the asynchronous functions to acquire data in the background. While the acquisition is in progress, the program updates a display showing the current scan backlog as well as a graph showing the acquired data. 1. Open the project C:\exercises\CVI Basics 1\DAQASYNC.PRJ. The project is incomplete. You will add code to asynchronously acquire data from Channel 1 and display it on a graph. 2. Open the DAQASYNC.C source file and examine the program. The program loads and displays a GUI that contains a graph, a command button to start the asynchronous acquisition, a numeric input control to specify the scan rate, a numeric indicator to display the current scan backlog, and a command button to terminate the program. The GUI (DAQASYNC.UIR) is already built. Notice the use of the timer callback function (ProcessLoop) in this program. The variable start is set to TRUE (in the Acquire callback function) when you commit the ACQUIRE button. When start is TRUE, the ProcessLoop function checks the number of points in the unread data acquisition buffer. If the number of points exceeds 500, the data is read and plotted on the graph. This process continues until an error occurs or the QUIT button is pressed. You will add code to the Acquire callback function to start the acquisition and to the ProcessLoop callback function to check the acquisition and acquire data. The GUI for this program is shown below.

National Instruments Corporation

3 -11

LabWindows/CVI Basics I Course Manual

Lesson 3

Exercises

Panel Constant Name: PANEL Panel Title: Asynchronous Data Acquisition Constant Name: GRAPH Graph Title: Waveform Y-axis Name: Voltage X-axis Name: sec X-Axis Precision: 2

Constant Name: QUIT Callback Function: Quit

Constant Name: RATE Constant Name: ACQUIRE Data Type: Double Callback Function: Acquire Constant Name: BACKLOG Minimum: 100 Maximum: 1000 Data Type: unsigned int Range Checking: Notify Control Mode: Indicator Control Mode: Validate Constant Name: TIMER Callback Function: ProcessLoop Interval: 0.00

3. Press <F2> until your cursor is on the tagged line inside the Acquire function. 4. From the Library menu, select the following function and fill in the function panel as shown below. After you have finished, select Code Insert Function Call. AI Start Acquisition (Easy I/O for DAQ : Analog Input : Asynchronous Acquisition) Device 1 Channel String "1" Buffer Size 5000 Scan/Second scan_rate High Limit (volts) +5.0 Low Limit (volts) -5.0 Actual Scan Rate &actual_scan_rate Task ID &task Error Leave blank

LabWindows/CVI Basics I Course Manual

3 -12

National Instruments Corporation

Lesson 3

Exercises

5. Press <F2> until your cursor is on the first tagged line inside the ProcessLoop function. 6. From the Library menu, select the following function and fill in the function panel as shown below. After you have finished, select Code Insert Function Call. AI Check Acquisition (Easy I/O for DAQ : Analog Input : Asynchronous Acquisition) Task ID Scans Backlog Error
task &scans_acquired

Leave blank

7. Press <F2> until your cursor is on the second tagged line inside the ProcessLoop function. 8. From the Library menu, select the following function and fill in the function panel as shown below. After you have finished, select Code Insert Function Call. AI Read Acquisition (Easy I/O for DAQ : Analog Input : Asynchronous Acquisition) Task ID Scans to Read Read Mode Scans Backlog Fill Mode Waveforms Error
task 500 Consecutive &scans_remaining Group by Channel waveform

Leave blank

9. Press <F2> until your cursor is on the tagged line inside the Quit function. 10. From the Library menu, select the following function and fill in the function panel as shown below. After you have finished, select Code Insert Function Call. AI Clear Acquisition (Easy I/O for DAQ : Analog Input : Asynchronous Acquisition) Task ID Error
task

Leave blank

National Instruments Corporation

3 -13

LabWindows/CVI Basics I Course Manual

Lesson 3

Exercises

11. Make sure your code looks functionally equivalent to the code shown below.
#include "easyio.h" #include <userint.h> #include <cvirte.h> otherwise */ #include "daqasync.h" #define TRUE #define FALSE 1 0 /* Needed if linking in external compiler; harmless

static double waveform[500]; unsigned long task, scans_acquired, scans_remaining; int panelHandle, start = FALSE; double scan_rate, actual_scan_rate; int main (int argc, char *argv[]) { if (InitCVIRTE (0, argv, 0) == 0) /* Needed if linking in external compiler; harmless otherwise */ return -1; /* out of memory */ panelHandle = LoadPanel (0, "daqasync.uir", PANEL); DisplayPanel (panelHandle); RunUserInterface (); return 0; } int CVICALLBACK ProcessLoop (int panel, int control, int event, void *callbackData, int eventData1, int eventData2) { switch (event) { case EVENT_TIMER_TICK: if(start==TRUE) { AICheckAcquisition (task, &scans_acquired); SetCtrlVal (panelHandle, PANEL_BACKLOG, scans_acquired); if(scans_acquired>500) { AIReadAcquisition (task, 500, CONSECUTIVE_MODE, &scans_remaining, GROUP_BY_CHANNEL, waveform); DeleteGraphPlot (panelHandle, PANEL_GRAPH, -1, 1); PlotWaveform (panelHandle, PANEL_GRAPH, waveform, 500, VAL_DOUBLE, 1.0, 0.0, 0.0, 1/actual_scan_rate, VAL_THIN_LINE, VAL_EMPTY_SQUARE, VAL_SOLID, 1, VAL_GREEN); } }

LabWindows/CVI Basics I Course Manual

3 -14

National Instruments Corporation

Lesson 3

Exercises

break; } return (0); }

int CVICALLBACK Acquire(int panel, int control, int event, void *callbackData, int eventData1, int eventData2) { switch (event) { case EVENT_COMMIT: /* disable the Acquire and Scan Rate controls */ SetInputMode (panelHandle, PANEL_ACQUIRE, 0); SetInputMode (panelHandle, PANEL_RATE, 0); start = TRUE; GetCtrlVal (panelHandle, PANEL_RATE, &scan_rate); AIStartAcquisition (1, "1", 5000, scan_rate, 10.0, 0.0, &actual_scan_rate, &task); break; } return(0); } int CVICALLBACK Quit(int panel, int control, int event, void *callbackData, int eventData1, int eventData2) { switch (event) { case EVENT_COMMIT: start=FALSE; AIClearAcquisition (task); QuitUserInterface (0); break; } return (0); }

12. When you press the ACQUIRE button, SetInputMode disables the ACQUIRE and Scan Rate controls. GetCtrlVal gets the value from the Scan Rate input control and assigns it to the variable scan_rate. AIStartAcquisition starts the asynchronous data acquisition and returns immediately. Because start is set to TRUE in the Acquire function, the ProcessLoop function calls AICheckAcquisition to check the status of the acquisition. If the number of points acquired since the last buffer read exceeds 500, AIReadAcquisition will be called.

National Instruments Corporation

3 -15

LabWindows/CVI Basics I Course Manual

Lesson 3

Exercises

AIReadAcquisition transfers 500 data points from the acquisition buffer to the array waveform. It also moves the buffer read mark to the

end of the data points transferred (in consecutive mode). Next, the current waveform graph is deleted and the graph is updated with the new data. This process continues until an error occurs or you press the QUIT button. When you press the QUIT button, AIClearAcquisition stops the data acquisition process and frees the data acquisition buffer. 13. Save and run your project. 14. Try running this project with successively higher scan rates. When you exceed a particular rate, your Scan Backlog will begin to climb. When it reaches a certain scan rate, you will get an overwrite error. Overwrite errors occur when the system is not able to move data out of the transfer buffer fast enough before new data arrives. The time in which this overwrite error occurs will depend on the speed of the computer system and how quickly it can extract the data from the data acquisition boards FIFO buffer.

End of Exercise 3-5

LabWindows/CVI Basics I Course Manual

3 -16

National Instruments Corporation

Lesson 3

Exercises

Exercise 3-6
Objective: To perform a single-point analog output operation. You will complete a program that outputs a voltage to be read by a User Interface voltmeter. You will need to connect analog output channel 0 of the DAQ Signal Accessory to analog input channel 1 to read the voltage. Make sure the range values for your controls stay within the input/output ranges of the DAQ board (normally, this is 10 to +10 V). One possible design for the user interface is the following GUI:

1. Create a new project. 2. Design a program that possesses the following features: When you manipulate the knob control, the voltmeter should change accordingly. When you press the Start button, it should become disabled. The voltmeter reading should be periodically updated via a timer callback and be reading an actual voltage from the DAQ Signal Accessory.

3. Save your application as OUTPUT.PRJ, run the project, and verify that the program behaves as expected. 4. Quit the application when you are finished.

End of Exercise 3-6

National Instruments Corporation

3 -17

LabWindows/CVI Basics I Course Manual

Lesson 3

Exercises

Exercise 3-7
Objective: To set or clear a digital I/O line The group of four LEDs on the DAQ Signal Accessory is connected to a digital I/O port on the DAQ board. Remember that the LEDs use negative logic, which is the logic scheme used for TTL operations. That is, writing a 0 to the line turns on the LED, and writing a 1 to the line turns off the LED. In this exercise, you will modify an earlier exercise to turn on an LED on the DAQ Signal Accessory if a temperature value exceeds a specified limit. 1. Open the project C:\exercises\CVI Basics 1\TMON.PRJ that you saved in an earlier exercise. 2. Modify your program to have the following behavior: Turn on the LED on the DAQ Signal Accessory when the temperature exceeds the value set in MAX value; otherwise, turn off the LED. Turn on the LED on the User Interface if the temperature exceeds the value set in MAX; otherwise, turn off the LED.

3. Save your application as TMON2.PRJ. (Hint: Using WriteToDigitalPort, you should first initialize the port as an output port and write a value to the port to turn off the LEDs. (If you are using an E-series card, make sure to use a port width of 8 and write a value of 255 to the port.) As your program acquires and plots temperature data, compare the current temperature with the value specified in the MAX control. If the current temperature exceeds the MAX value, use WriteToDigitalLine to turn on the LED.

End of Exercise 3-7

LabWindows/CVI Basics I Course Manual

3 -18

National Instruments Corporation

Lesson 4 Exercises
Exercise 4-1
Objective: To use a scanning function to parse a data string. Open the project C:\exercises\CVI Basics 1\FmtScan.prj. Double-click on the file fmtscan.UIR to view the user interface file. Notice that there is a data string with a header and 18 numbers separated by commas. Double-click on the file fmtscan.c to edit the source file. Press <F2> to go to the tag in the Go callback function. Add the necessary code (notice that the variables are already declared) to convert the string to an array and plot it on the graph. If you are unsure of what format codes and modifiers to use, consult Appendix A in the back of the manual.

End of Exercise 4-1

National Instruments Corporation

4-1

LabWindows/CVI Basics I Course Manual

Lesson 4 Exercises

Notes

LabWindows/CVI Basics I Course Manual

4-2

National Instruments Corporation

Lesson 5 Exercises
Exercise 5-1
Objective: To establish communication with a GPIB instrument. You will complete a program that writes a string to an instrument or reads a string from an instrument. You will display the commands and the strings in a User Interface panel.

Setup: Confirm that the GPIB cable is connected to the GPIB board in the computer and to the NI Instrument Simulator. For this exercise, make sure

National Instruments Corporation

5-1

LabWindows/CVI Basics I Course Manual

Lesson 5 Exercises

the NI Instrument Simulator is properly set to GPIB mode with a primary address of 2. To configure the simulator, change the dip switches (if necessary) to match the pattern below and power cycle the simulator.

1. Open the project C:\exercises\CVI Basics 1\GPIBRW.PRJ. 2. Double-click on the filename GPIBRW.UIR to examine the user interface. GPIB function specifies whether to write a string to the instrument or read a string from the instrument. String to Write specifies the string to send to the instrument. Bytes to Read specifies the maximum number of bytes to read from the instrument (recall that if the instrument asserts the EOI line, the transfer may terminate before the specified number of bytes). String from Instrument displays the string returned from the instrument. GO performs the requested GPIB function, and QUIT exits the program. The three global variables are displayed on the bottom of the screen for you to monitor. Close the file when finished. 3. Double-click on the filename GPIBRW.C to examine the source code. Note that the board setup has been written for you. The program is incomplete. You will add code to send commands to the Simulator and read Simulator output.
Note

If you feel comfortable with GPIB syntax or want a challenge, complete steps 4-7; otherwise, complete steps 8-11. After you finish, skip to step 12. If you feel you need additional help, turn the page for the instructions to complete these steps. 4. Press <F2> to go to the tag inside main. Add code to open up a session to the Instrument Simulator. 5. Press <F2> to go to the tag inside of the WRITE case. Add code to write data from the buffer to the Simulator. 6. Press <F2> to go to the tag inside of the READ case. Add code to read data from the Simulator.

LabWindows/CVI Basics I Course Manual

5-2

National Instruments Corporation

Lesson 5 Exercises

7. Press <F2> to go to the tag inside of Quit. Add code to close the session to the Simulator. 8. Press <F2> to go to the tag inside main. From the Library menu, select the following function and fill in the function panel as shown below. Declare the variable simulator at the top of your code. After you finish, select Code Insert Function Call. ibdev (GPIB/GPIB 488.2 : Open/Close) Board Index Primary Address Secondary Address Timeout End Message EOS Character Device
0 2 NO SAD (or 0) 10 Sec Enable 0 simulator

This function will open a session to the device located at primary address 2 connected to GPIB0. It will configure the device to have a 10-second timeout and assert the EOI line when it writes the last byte out to the GPIB bus. Simulator will contain the unit descriptor used in subsequent GPIB operations. 9. Press <F2> to go to the tag inside the WRITE case in the Go callback function. The Go callback function gets the function selected in the Function menu ring. In the WRITE case, it reads the string in the String to Write control and assigns it to WriteBuffer. This string is used as an input to the GPIB write function. From the Library menu, select the following function and fill in the function panel as shown below. After you finish, select Code Insert Function Call. ibwrt (GPIB/GPIB 488.2 : I/O) Board/Device Data Buffer Byte Count Status Returned
simulator writeBuffer strlen (writeBuffer)

Leave blank

10. Press <F2> to go to the tag inside the READ case in the Go callback function. In the READ case of the Go callback function, the number of bytes to read from the Simulator is obtained from the Bytes to Read control. This information is used as an input to the GPIB read function.

National Instruments Corporation

5-3

LabWindows/CVI Basics I Course Manual

Lesson 5 Exercises

From the Library menu, select the following function and fill in the function panel as shown below. After you finish, select Code Insert Function Call. ibrd (GPIB/GPIB 488.2 : I/O) Board/Device Data Buffer Byte Count Status Returned
simulator readBuffer count

Leave blank

11. Press <F2> to go to the tag inside the Quit callback function. From the Library menu, select the following function and fill in the function panel as shown below. After you have finished, select Code Insert Function Call. ibonl (GPIB/GPIB 488.2 : Open/Close) Board/Device Operation Mode
simulator offline

12. Run the project. Type *IDN? in the String to Write control and press the GO button. The string "*IDN?" queries the instrument for its identification. 13. Set the Function control to Read, type 100 inside the Bytes to Read control, and press the GO button. The Simulator returns its identification string, which String from Instrument displays. 14. Try sending other commands to the Simulator. First, write one of the commands below to the Simulator, then read the waveform data. (The Simulator is programmed to take about 10 seconds to generate a chirp wave. If you have the simulator generate a chirp wave, wait about 10 seconds before reading the data.) You will need to read at least 1,200 bytes for each waveform. For a complete list of commands, refer to Appendix B.
SOUR:FUNC SIN;SENS:DATA? SOUR:FUNC SQU;SENS:DATA? SOUR:FUNC NOIS;SENS:DATA? SOUR:FUNC RAND;SENS:DATA? SOUR:FUNC PCH;SENS:DATA?

Output sine waveform Output square waveform Output noisy sine waveform Output random noise waveform Output chirp waveform

LabWindows/CVI Basics I Course Manual

5-4

National Instruments Corporation

Lesson 5 Exercises

Examining Errors
15. Return to the Source window, enter a value of 3 for the Primary Address parameter in the ibdev function, and run the project again. Select a function for the device, enter it in String to Write, and press the GO button. If debugging is on, the program should display a dialog box showing error code 2. Error code 2 means there is no listener at the address with which you are trying to communicate.
Note

To find the description of a status code quickly without using the manual, select any function panel from the GPIB/GPIB 488.2 Library and highlight the Status control. Press <F1> (or right-click) to display a dialog box that lists brief descriptions of all GPIB status codes. If, and only if, the status is greater than hex 8000, the code returned in the error control is valid. You can obtain a description of the error code by highlighting the Error control and pressing <F1>. 16. Change the address back to 2 and save the program.

End of Exercise 5-1

National Instruments Corporation

5-5

LabWindows/CVI Basics I Course Manual

Lesson 5 Exercises

Exercise 5-2
Objective: To obtain data continuously from the device simulator using GPIB. Write a program that displays a GUI with a strip chart, a START button, and a QUIT button. When you push the START button, the program should repeatedly send the command MEAS:DC? to the Simulator to generate a random value, read the ASCII value, convert it to a double-precision number, plot the number on a strip chart, and display it in an indicator. The program should terminate when you select the QUIT button. Disable the START button after you select it. To help you get started, the GUI and the program shell have been created already. The files are in C:\exercises\CVI Basics 1\ GPIBRAND.PRJ. Save your program after you have finished. If you need additional help, you can refer to the program listing on the following page.
Note

Use the Scan or the Fmt function.

End of Exercise 5-2

LabWindows/CVI Basics I Course Manual

5-6

National Instruments Corporation

Lesson 5 Exercises

Exercise 5-2 Program Listing


#include #include #include #include #include <ansi_c.h> <formatio.h> <gpib.h> <userint.h> <cvirte.h> /* Needed if linking in external compiler; harmless otherwise */ #include "gpibrand.h" #define TRUE 1 #define FALSE 0 static static static static int int int int panelHandle; device; board; startFlag = FALSE;

int main (int argc, char *argv[]) { if (InitCVIRTE (0, argv, 0) == 0)

/* Needed if linking in external compiler; harmless otherwise */ return -1; /* out of memory */ if ((panelHandle = LoadPanel (0, "gpibrand.uir", PANEL)) < 0) return -1; board = ibfind (GPIB0); ibsic(board); ibsre (board, 1); device = ibdev (0, 2, 0, T10s, 1, 0); DisplayPanel (panelHandle); RunUserInterface (); return 0;

} int CVICALLBACK Acquire (int panel, int control, int event, void *callbackData, int eventData1, int eventData2) { static char writeBuffer[10], reading[10]; static double chartBuffer[1]; switch (event) { case EVENT_TIMER_TICK: if (startFlag == TRUE) { Fmt (writeBuffer, "%s", "MEAS:DC?"); ibwrt (device, writeBuffer, strlen(writeBuffer)); ibrd (device, reading, 10L); Scan (reading, "%s>%f", &chartBuffer[0]); SetCtrlVal (panelHandle, PANEL_MEAS, chartBuffer[0]);

National Instruments Corporation

5-7

LabWindows/CVI Basics I Course Manual

Lesson 5 Exercises

PlotStripChart (panelHandle, PANEL_CHART, chartBuffer, 1, 0, 0,VAL_DOUBLE); } break; } return (0); } int CVICALLBACK Start (int panel, int control, int event, void *callbackData, int eventData1, int eventData2) { switch (event) { case EVENT_COMMIT: startFlag = TRUE; SetInputMode (panelHandle, PANEL_START, 0); break; } return(0); } int CVICALLBACK Quit (int panel, int control, int event, void *callbackData, int eventData1, int eventData2) { switch (event) { case EVENT_COMMIT: startFlag = FALSE; ibonl (device, 0); ibonl (board, 0); QuitUserInterface (0); break; } return(0); }

LabWindows/CVI Basics I Course Manual

5-8

National Instruments Corporation

Lesson 5 Exercises

Exercise 5-3
Objective: To use ibInstallCallback in a program to respond to an SRQ. You will finish a program that displays a GUI with a graph, acquire button, quit button, and a menu ring to allow you to select the type of function to generate. When you run the application, the ibInstallCallback function should be called to install the WaveCallback function. The WaveCallback function will be called on the assertion of the SRQ line. When you select the acquire button, the program should command the instrument to generate a waveform and assert the SRQ line on completion. In addition, the application should read the waveform and plot it to a graph.

1. Open the project C:\exercises\CVI Basics 1\GPIBSRQ.PRJ. 2. Double-click on the file name GPIBSRQ.UIR to examine the user interface. The Select Waveform menu ring specifies the type of waveform to generate. The Acquire button commands the instrument to generate the specified waveform. The Quit button exits the program. Close the file when finished. 3. Double-click on the filename GPIBSRQ.C to examine the source code. The program is incomplete. You will add code to install a callback function. 4. Press <F2> to go to the tag inside main.

National Instruments Corporation

5-9

LabWindows/CVI Basics I Course Manual

Lesson 5 Exercises

5. From the Library menu, select the following function and fill in the function panel as shown below. Install Synchronous Callback (GPIB/GPIB 488.2 : Callbacks) Board/Device Event Mask Callback Function Callback Data Status Returned
board 0x1000 WaveCallback 0

Leave blank

6. After you have finished, select Code Insert Function Call.


Note

The WaveCallback function has already been prototyped for you at the top of the source file. The event mask (0x1000) causes the callback to occur when the SRQI bit is set. 7. Scroll through the code to view the commands sent to the Simulator. Inside the main function, auto serial polling is disabled and the WaveCallback function is installed. In the AcquireWaveform function, the instrument is commanded to generate a waveform and assert the SRQ line when complete. In the WaveCallback function, the Simulator is serial-polled and then asked to send the data back to be graphed.

Note

If auto serial polling is enabled (default), once the SRQ line is asserted, the driver automatically serial polls all instruments on the bus. Because you want to handle service requests in code, you need to disable this action. 8. Save and run the application. Select a waveform and click on the Acquire button. Notice that it takes a few seconds to generate the waveform. Once complete, the Simulator asserts the SRQ line, as the LED on the front of the device indicates, and then transfers the data back to the application. Try some different waveforms.

End of Exercise 5-3

LabWindows/CVI Basics I Course Manual

5-10

National Instruments Corporation

Lesson 5 Exercises

Exercise 5-4
Objective: To become familiar with some of the GPIB troubleshooting options available. This exercise is designed to help you become familiar with using ibic and NI-Spy. First, load NI Spy (Start Programs NI-488.2M Software for Windows 95 NI Spy). You should see a screen that looks like the following.

Recall that NI Spy allows you to capture calls that are made into the GPIB driver. To begin capturing events, press the blue arrow. The title bar will change to NI Spy - [capture on]. After you press the arrow, NI Spy is ready.
Note

If you are using an older driver, you may have GPIB Spy installed on your machine. If you do, once you load GPIB Spy, it is automatically set to capture events. No other interaction is necessary. To turn off the capture, press the stoplight.

National Instruments Corporation

5-11

LabWindows/CVI Basics I Course Manual

Lesson 5 Exercises

Now, load the Win32 Interactive Control (ibic) (Start Programs NI-488.2M Software for Windows 95 Win32 Interactive Control). After you load the control, you should see a window that looks like the following.

The colon is the initial prompt. From here, you can type in GPIB commands to be executed interactively. Once you use ibfind or ibdev, the prompt will change to indicate which board/instrument with which you are communicating. The syntax of ibic is different from C syntax. Type in the following commands (notice how ibic returns the status):
ibfind gpib0 ibsic ibsre 1 ibdev 0 2 0 13 1 0 ibwrt "*idn?" ibrd 100

Note

After every function call, you can press <Enter> to be prompted for each input value. You should see the identification appear on the screen. On the left half of the screen, the data will appear in hexadecimal format; on the right half, it will appear in ASCII text. Now, type in two more commands:
ibwrt "hello" ibrd 100

LabWindows/CVI Basics I Course Manual

5-12

National Instruments Corporation

Lesson 5 Exercises

This ibrd will hang for about 10 to 15 seconds and return an error. This error is caused because you wrote something to the Simulator that was not understood. Therefore, when you tried to read, the Simulator had nothing to send. Because the driver was expecting data and there was none, a timeout error occurs. View the NI Spy output. The last line should be in red to indicate an error. ibsta equals 0xC100 indicating an error (0x8000) and a timeout (0x4000) as well as a complete (0x100), because the operation finished, even if it finished abnormally. iberr equals 6 (EABO) indicating that the driver timed out and aborted the I/O. Feel free to run any of the three CVI programs you have written in this lesson with NI Spy running in the background.

End of Exercise 5-4

National Instruments Corporation

5-13

LabWindows/CVI Basics I Course Manual

Lesson 5 Exercises

Notes

LabWindows/CVI Basics I Course Manual

5-14

National Instruments Corporation

Lesson 6 Exercises
Exercise 6-1
Objective: To establish communication with a serial instrument. You will complete a program that writes a string to an instrument or reads a string from an instrument.

Setup
Confirm that the serial instrument is connected to the computers COM1. Set the NI Instrument Simulator switches to the following locations:

OFF

ON

NI Instrument Simulator Switch Settings

1. Open the project C:\exercises\CVI Basics 1\Serialrw.prj. 2. Double-click on Serialrw.c. 3. Press <F2> to go to the tag inside main. 4. From the Library menu, select the following function from RS-232 Open/Close and fill in the function panel as shown below. After you finish, select Insert function Call from the Code menu.
OpenComConfig (1, "", 9600, 0, 8, 1, 512, 512)

National Instruments Corporation

6-1

LabWindows/CVI Basics I Course Manual

Lesson 6 Exercises

5. You want to enable hardware handshaking. This will prevent data loss on transfers larger than the buffer specified in OpenComConfig. From the Library menu, select the following function from the RS-232 Control menu item and fill in the function panel as shown below. After you have finished, select Insert function Call from the Code menu.
SetCTSMode (1, LWRS_HWHANDSHAKE_CTS_RTS);

6. Press <F2> to go to the tag inside the write case within the Go callback. 7. The Go callback gets the state of the SERIAL_FUNC binary switch. If the state is TRUE, write the string to send to the instrument. From the Library menu, select the following function from the RS-232 menu item and fill in the function panel as shown below. After you have finished, select Insert function Call from the Code menu.
ComWrt (1, message,strlen (message) );

8. Press <F2>. If the state of the SERIAL_FUNC binary switch is FALSE, read the first seven bytes from the serial port. These seven bytes are the header. The header provides information about the data transfer. In this case, the value of the header is the total number of bytes in the data transfer minus the header.
ComRd (1, serialRead, 7);

9. Press <F2>. Read the remaining bytes from the data transfer.
ComRd (1, serialReadMessage, numToRead);

10. Run your project and verify your programs functionality. The simulator will respond to the same commands given in the GPIB section.

End of Exercise 6-1

LabWindows/CVI Basics I Course Manual

6-2

National Instruments Corporation

Lesson 6 Exercises

Exercise 6-2
Objective: You will complete a program that requests data from an instrument. You will use InstallComCallback to implement a serial callback to read the data from the instrument when it arrives. In the InstallComCallback function, specify the mask to look for seven bytes at the serial port. These seven bytes are a header. The header specifies the total amount of data in the transfer minus the header. Read the data transfer and display it to a GUI. 1. Open the project C:\exercises\CVI Basics 1\SerialCB.prj. 2. Double-click on the SerialCB.c file. 3. Press <F2> to go to the first tag. 4. From the Library menu, select the following function from the RS-232 Callbacks menu item and fill in the function panel as shown below. After you have finished, select Insert function Call from the Code menu. This function installs a callback associated with a COM port. When the condition is met, the function is invoked.
InstallComCallback (1, LWRS_RECEIVE, 7, 0, callonme, 0);

5. Press <F2>. This callback function was copied from the CVI function panel help. From the Library menu, select the InstallComCallback function from the RS-232 Callbacks menu. Right-click on the Callback Function field. Inside this help window is a prototype of the function. You can copy and paste this function in your code. 6. Notice that in the callonme callback, two ComRd functions are performed. One read retrieves the header information from the instrument. This dictates the number of bytes contained in the data transfer. The second ComRd retrieves the data.

End of Exercise 6-2

National Instruments Corporation

6-3

LabWindows/CVI Basics I Course Manual

Lesson 6 Exercises

Notes

LabWindows/CVI Basics I Course Manual

6-4

National Instruments Corporation

Lesson 7 Exercises
Exercise 7-1
Part I
Objective: To create and use a simple instrument driver. An instrument driver is a collection of functions that allows a programmer to program an instrument easily through GPIB, serial, or VXI. For this exercise, you will create a simple instrument driver that finds the average of two numbers. Obviously, this math function does not relate to instrument control; therefore, you can focus on the instrument driver creation process. In upcoming exercises, you will have the opportunity to examine a true instrument driver (which controls an instrument) in more detail. LabWindows\CVI uses function panels to simplify calling complex functions. As you will see later, a function panel easily converts into a static or dynamic link library (more on this later). You will create your instrument driver by creating a function panel. Some of the steps in this process have been left out so that you are encouraged to think instead of following cookbook instructions. 1. Launch LabWindows/CVI and create a new project. Create a new Function Tree (File menu). 2. You have just created a Function Tree. A Function Tree is a collection of Function Panels. A Function Panel contains exactly one function. Next you need to add an instrument to this currently empty Function Tree. You can do this by choosing Create Instrument. Name the instrument MyMathFunctions and use a prefix of Math. The prefix will be placed at the beginning of all function names.

National Instruments Corporation

7-1

LabWindows/CVI Basics I Course Manual

Lesson 7 Exercises

3. To organize these Function Panels, you can use classes to group similar functions. For example, you may want to group all math analysis Function Panels under a class called Analysis or all arithmetic Function Panels under a class called Arithmetic. For the instrument driver in this exercise, create a class called Helpful Math Functions. 4. Now that you have created a class for your helpful math functions, you are ready to create a Function Panel. Recall that you are trying to create a function called Average. To make things simple to use, you should name the Function Panel the same name as the function. You want this function to be in the class of Helpful Math Functions, so make sure your mouse has highlighted the appropriate area. Create this function panel now. When you are finished, your instrument driver structure should be like the one below.

5. Open your function panel by double-clicking on it.

LabWindows/CVI Basics I Course Manual

7-2

National Instruments Corporation

Lesson 7 Exercises

6. Now that you are looking at your empty Function Panel, you need to create all inputs and outputs for your function: Average. Create a function that takes the average of two integers and returns the result (which would need to be a double). You also need to return the status of the function in case an error occurs during our calculation. Therefore, you need two inputs (integers), one output (double), and a return status (integer). By using the Create menu, create and place these items on your function panel. Use intelligent names for your items so that you can recall what they are in your code. When you are finished, your function panel should resemble the one below (except that your parameter names may be different).

Notice how the function is built in the bottom of the window.

National Instruments Corporation

7-3

LabWindows/CVI Basics I Course Manual

Lesson 7 Exercises

7. Before you proceed, it is a good idea to make notes for your instrument driver user on the various parameters on this function panel. To create comments visible to the end user, right-click on a parameter and free type comments. These comments will be available for the user during normal use (and are very helpful).

8. You are now ready to save your work. Name this file MyMath.fp. 9. The next step is to create the source code skeleton and header file for this Function Tree. LabWindows/CVI will do this automatically for you based on the parameters you created on the Function Panel. You will do this now. Choose the menu item Tools Generate New Source for Function Tree. 10. You have now created two new files: MyMath.c and MyMath.h. All required functions and parameters have been inserted for you to easily complete the code to run the Function Panels. You dont need to modify MyMath.h, just add a little code to MyMath.c. Change to that window and insert the code to complete the Average function. Your code should resemble the following:
#include "MyMath.h" int CVIFUNC Math_Average (int a, int b, double *average) { *average = (a + b) / 2.0; return 0; }

11. Make sure you successfully compile and save your code. You may be prompted for numerous saves, etc. After you have compiled successfully, close all windows so that the Project Window is the only open window.

LabWindows/CVI Basics I Course Manual

7-4

National Instruments Corporation

Lesson 7 Exercises

Part II
Objective: To use the Average function as if it were an instrument driver. At this point, you have created a simple instrument driver. Before you test your work in a program, run the Function Panel interactively. 12. Start fresh by creating a new project. Load the instrument driver you created (MyMath.fp). It may already be loaded. Hint: look under the Instrument menu.

13. Select your instrument driver. You will see the Function Tree that you created.

National Instruments Corporation

7-5

LabWindows/CVI Basics I Course Manual

Lesson 7 Exercises

By double-clicking on the visible classes, you can find the Function Panel you created called Average. Find this Function Panel now.

14. Fill in values for your inputs and run the Function Panel. You should get the correct average and a status of 0. If you did not get correct results, select Instrument Edit and go from there. You may need to return to step 10. At this point, you have tested that the Function Panel is working correctly. You will now use the Average function in a simple program. 15. Create new project and new source code now. On line 1, create a main by selection Edit Insert Construct Main.

LabWindows/CVI Basics I Course Manual

7-6

National Instruments Corporation

Lesson 7 Exercises

16. Using the Instrument menu, bring up the Average Function Panel. 17. Fill it out with variables and declare each one using <Ctrl-D>.

Dont forget to insert the function (<Ctrl-I>) when you have declared all the variables. When you are finished, return to your source code and you will have a small simple program. 18. Insert code to set values for the variables in your program.

National Instruments Corporation

7-7

LabWindows/CVI Basics I Course Manual

Lesson 7 Exercises

19. After the Math_Average function call, insert a printf similar to the one shown below.
printf ("The average of %d and %d is %f", num1, num2, result);

Your program should now look similar to the following:

20. Save your work and run your code (you may be prompted to add lines of code, etc.). You should get correct results using your homemade instrument driver.

LabWindows/CVI Basics I Course Manual

7-8

National Instruments Corporation

Lesson 7 Exercises

Challenge!
If you have extra time, try to solve the following: Create a function in the MyMath instrument driver that contains a calculator function. Write all code to run this Function Panel. A possible solution Function Panel is shown below.

End of Exercise 7-1

National Instruments Corporation

7-9

LabWindows/CVI Basics I Course Manual

Lesson 7 Exercises

Exercise 7-2
Objective: To load and operate a VXIplug&play instrument driver interactively. In this exercise, you will use a VXIplug&play instrument driver to interactively control your Device Simulator.

Setup
Confirm that the GPIB cable is connected to the GPIB board in the computer and to the GPIB Device Simulator. Turn on the Device Simulator. The simulator is at primary GPIB address 2. 1. Select New Project from the File menu. In the dialog box that appears, select Yes to unload the current project. Select OK in the Transfer Projects Options dialog box. 2. Load a new instrument driver by selecting Load from the Instrument menu. Select the file C:\exercises\CVI Basics 1\devsim.fp. LabWindows/CVI will load and compile the instrument driver. 3. From the Instrument menu, choose NI Device Simulator. The function tree for the NI Device Simulator should appear. Choose Initialize and click on the Select button.
Note

You must first initialize a VXIplug&play instrument driver before you can use any other function in the driver.

LabWindows/CVI Basics I Course Manual

7-10

National Instruments Corporation

Lesson 7 Exercises

4. Fill in the function panel for the Device Simulator as shown below. Place your cursor in the Instrument Handle control and select Declare Variable from the Code menu (or press <Ctrl-D>). Select Execute Declaration to place the variable declaration in the Interactive Execution Window. Notice that LabWindows/CVI automatically adds an & in front of the variable handle.

Note

The resource name GPIB0::2::INSTR tells the VISA Library that the Device Simulator is a GPIB device at primary address 2. 5. Choose Run Function Panel from the Code menu or press <Shift-F5>. LabWindows/CVI will create a temporary status variable for Status and return a value of 0x0, indicating success. Right-click on the Status control to view the possible error conditions. When you are finished, close the Initialize function panel.

National Instruments Corporation

7-11

LabWindows/CVI Basics I Course Manual

Lesson 7 Exercises

6. From the Instrument menu, choose NI Device Simulator Configure Waveform Select. Fill in the function panel as shown below.

7. Run the function panel. The function should return 0x0 in the Status control, indicating that the waveform type has been successfully selected. Do not close this function panel.

LabWindows/CVI Basics I Course Manual

7-12

National Instruments Corporation

Lesson 7 Exercises

8. From the Instrument menu, choose NI Device Simulator Data Read Waveform. Fill in the function panel as shown below. Place your cursor in the Waveform Array control and select Declare Variable. Give the array 128 elements and select Execute Declaration.

9. Run the function panel. LabWindows/CVI should return a value of 0x0 when the Device Simulator completes the waveform generation. 10. Double-click in the data space underneath the variable waveform. The Variables window will appear, displaying the contents of waveform. When you finish viewing the data, close both the Array Display window and the Variables window. Do not close the Read Waveform function panel.

National Instruments Corporation

7-13

LabWindows/CVI Basics I Course Manual

Lesson 7 Exercises

11. From the Library menu, select the (User Interface : Pop-up Panels) Y Graph Popup function. Fill in the function panel as shown below.

LabWindows/CVI Basics I Course Manual

7-14

National Instruments Corporation

Lesson 7 Exercises

Run the function panel to view the waveform generated by the Device Simulator. A pop-up graph, similar to the one shown below, should appear.

12. Now, go back to the Waveform Select function panel and choose a different waveform. Run this panel and then use the Read Waveform function panel to place the new waveform into the array waveform. Use the Y Graph Popup function panel to view the new waveform. All waveforms returned by the Device Simulator contain 128 elements.
Tip

Use the Function Panel selection from the Windows menu to navigate between the open function panels. 13. Experiment with the different functions in the NI Device Simulator instrument driver. The Measure DC function in the Data class makes a single simulated DC measurement from the Device Simulator. The Read Sine Waveform function in the Application Functions class combines the Waveform Select function and the Read Waveform function to acquire a simulated sine wave from the Simulator.

National Instruments Corporation

7-15

LabWindows/CVI Basics I Course Manual

Lesson 7 Exercises

14. When you finish experimenting with the NI Device Simulator function panels, select Close from the instrument driver. Type handle into the Instrument Handle control and run the function panel. Close all open NI Device Simulator function panels.
Note

The Interactive Execution window contains all variables declared and functions executed during the course of this exercise.

End of Exercise 7-2

LabWindows/CVI Basics I Course Manual

7-16

National Instruments Corporation

Lesson 7 Exercises

Exercise 7-3
Objective: To use a VXIplug&play instrument driver in a program. You will complete a program that uses the NI Device Simulator instrument driver to acquire and display waveforms on a graph.

Setup
Confirm that the GPIB cable is connected to the GPIB board in the computer and to the GPIB Device Simulator. Turn on the Device Simulator. The simulator is at primary GPIB address 2. 1. Open the project c:\exercises\CVI Basics 1\simwave.prj. 2. Double-click on the filename simwave.uir to open the user interface. You will complete the source code for this project. The waveform select control specifies the type of waveform that the Device Simulator generates. The Acquire button commands the Device Simulator to acquire the selected waveform, and the Quit button terminates the program. 3. From the Code menu, select Generate All Code. Fill in the dialog box as shown below. After you have finished, click on OK.

National Instruments Corporation

7-17

LabWindows/CVI Basics I Course Manual

Lesson 7 Exercises

4. Your generated code shell will come up in an untitled window. Select Add File To Project from the Source window File menu. A dialog box will appear asking if you want to name the file now. Select Yes. Name the file simwave.c and click on the Save button. Your source file has now been added to the project. 5. In the Source window, simwave.c, add a line after the call to the DisplayPanel function and leave your cursor on this blank line. From the Instrument menu, choose NI Device Simulator. Choose Initialize and click on the Select button. Fill in the function panel as shown below.

After you have finished, put your cursor on the Instrument Handle control and select Declare Variable from the Code menu. In the dialog box that appears, make sure Add declaration to the top of target file simwave.c is selected and click on OK. From the Code menu, select Insert Function Call. Close the function panel.

LabWindows/CVI Basics I Course Manual

7-18

National Instruments Corporation

Lesson 7 Exercises

6. Add a line before the QuitUserInterface (0); statement in the Quit() function and leave your cursor on this line. From the Instrument menu, choose NI Device Simulator. Choose Close and click on the Select button. Fill in the function panel as shown below. After you have finished, select Insert Function Call. Close the function panel.

National Instruments Corporation

7-19

LabWindows/CVI Basics I Course Manual

Lesson 7 Exercises

7. Now, move to the line after the case statement EVENT_COMMIT: in the Acquire callback function. From the Library menu, select GetCtrlVal and fill in the function panel as shown below. After you have finished, put your cursor on the Value control and select Declare Variable from the Code menu. In the dialog box that appears, make sure the Variable Type is int and Add declaration to the top of target file simwave.c is selected. Click on OK. From the Code menu, select Insert Function Call. Close the function panel.

8. From the Instrument menu, select the following function and fill in the function panel as shown below. To enter select for the Waveform slide control, choose Toggle Control Style from the Options menu. After you have finished, select Insert Function Call from the Code menu. Waveform Select (NI Device Simulator : Configure) Waveform: Status:
select

Instrument Handle: simHandle Leave blank

LabWindows/CVI Basics I Course Manual

7-20

National Instruments Corporation

Lesson 7 Exercises

9. From the Instrument menu, select the following function and fill in the function panel as shown below. Read Waveform (NI Device Simulator : Data) Waveform Array: Status:
waveArray

Instrument Handle: simHandle Leave blank 10. After you have finished, put your cursor on the Waveform Array control and select Declare Variable from the Code menu. In the dialog box that appears, make sure that Add declaration to the top of target file simwave.c is selected and that the array is set to 128 elements. Click on OK. From the Code menu, select Insert Function Call. 11. From the Library menu, select the following function and fill in the function panel as shown below. After you have finished, select Insert Function Call from the Code menu. Delete Graph Plot (User Interface Library : Controls/Graphs/Strip Charts : Graphs and Strip Charts : Graph Plotting and Deleting) Panel Handle: Control ID: Plot Handle: Refresh: Status:
panelHandle PANEL_GRAPH -1 Immediate Draw

Leave blank

12. From the Library menu, select the following function and fill in the function panel as shown below. After you have finished, select Insert Function Call from the Code menu. Plot Y (User Interface Library : Controls/Graphs/Strip Charts : Graphs and Strip Charts : Graph Plotting and Deleting) Panel Handle: Control ID: Y Array: Number of Points: Plot Handle:
panelHandle PANEL_GRAPH waveArray 128

Leave blank

National Instruments Corporation

7-21

LabWindows/CVI Basics I Course Manual

Lesson 7 Exercises

13. Select Run Project from the Run menu. LabWindows/CVI will alert you that the header file devsim.h needs to be included in your project. Select Yes to include to file and to save changes to your source file before running your project. Try setting different inputs in the waveform select ring. Press the Acquire button to begin the acquisition from the Device Simulator. The waveform transfer may take several seconds.

End of Exercise 7-3

LabWindows/CVI Basics I Course Manual

7-22

National Instruments Corporation

Lesson 7 Exercises

Exercise 7-3 Program Listing


#include #include #include #include static static static static <cvirte.h> <userint.h> "devsim.h" "simwav.h"

int panelHandle; ViReal64 waveArray[128]; int select; ViSession simHandle;

int main (int argc, char *argv[]) { if (InitCVIRTE (0, argv, 0) == 0) return -1; if ((panelHandle = LoadPanel (0, "simwav.uir", PANEL)) < 0) return -1; DisplayPanel (panelHandle); DevSim_init ("GPIB::2::INSTR", VI_ON, VI_OFF, &simHandle); RunUserInterface (); return 0; } int CVICALLBACK Quit (int panel, int control, int event, void *callbackData, int eventData1, int eventData2) { switch (event) { case EVENT_COMMIT: QuitUserInterface (0); DevSim_close (simHandle); break; } return 0; } int CVICALLBACK Acquirecb (int panel, int control, int event, void *callbackData, int eventData1, int eventData2) { switch (event) { case EVENT_COMMIT: GetCtrlVal (panelHandle, PANEL_RING, &select); DevSim_Waveform_Select (simHandle, select); DevSim_Read_Waveform (simHandle, waveArray); DeleteGraphPlot (panelHandle, PANEL_GRAPH, -1, VAL_IMMEDIATE_DRAW); PlotY (panelHandle, PANEL_GRAPH, waveArray, 128, VAL_DOUBLE, VAL_THIN_LINE, VAL_EMPTY_SQUARE, VAL_SOLID, 1, VAL_RED);

National Instruments Corporation

7-23

LabWindows/CVI Basics I Course Manual

Lesson 7 Exercises

break; } return 0; }

End of Exercise 7-3

LabWindows/CVI Basics I Course Manual

7-24

National Instruments Corporation

Lesson 8 Exercises
Exercise 8-1
Objectives: 1) To create an executable out of a project. 2) To create a distribution kit with the executable. Open the project \CVI\BASICS1\tempsys.prj. The project is already created for you. First, you need to make a stand-alone executable. Select Build Create Stand-Alone Executable. Select OK on the dialog box that informs you that debugging will be turned off for executables. (Recall that executables have no debugging and you should always include error checking.) You should see a screen similar to the one below:

National Instruments Corporation

8-1

LabWindows/CVI Basics I Course Manual

Lesson 8 Exercises

Select OK and you should get a dialog box informing you that the executable was successfully created. Run the executable by browsing to it through Windows Explorer (Start Programs Windows Explorer). It should behave exactly as it did in Exercise 1-1. Now, create a distribution kit. Select Build Create Distribution Kit. You should get a screen that looks like this:

Everything should be correct, so press Build to create the distribution kit. You should see a dialog box informing you that the distribution kit was successfully created. The distribution kit should have three files, setup.exe, tempsys.001, and tempsys.002. To distribute this to customers, place setup.exe and tempsys.001 onto one disk, and tempsys.002 onto the second disk. If the distribution kit took up more disks, place them on their respective disks. Run Setup and look at the dialog boxes that appear on the screen. Run the program by selecting Start Programs tempsys tempsys.

End of Exercise 8-1


LabWindows/CVI Basics I Course Manual 8-2
National Instruments Corporation

Appendix
Introduction
This appendix describes some of the file I/O functions, as well as some of the formatting and scanning modifiers used in the Fmt and Scan functions discussed previously. Each section concentrates on one aspect of the data manipulation process.

You Will Learn:


A. About file I/O. B. About formatting and scanning modifiers (reference).

National Instruments Corporation

A-1

LabWindows/CVI Basics I Course Manual

Appendix

A. File I/O
Files are an integral part of a modern, computer-based data acquisition system. By using files, you can archive data on disk and retrieve it at a later time. When working with files, you first must understand the concept of file handles. File handles are numbers that reference a particular file in the computers filing system. When a LabWindows/CVI function returns a file handle, other LabWindows/CVI functions reference the same file handle when accessing that file. A file handle has no intrinsic value to the user, other than to refer to a file. You should never modify the value associated with a file handle. The following basic file I/O functions work with handles.

Open File
int File_Handle = OpenFile (char File_Name[], int Read/Write_Mode, int Action, int File_Type);

OpenFile instructs the computer to create a file specified by File_Name and to assign File_Handle to that file. If the file already exists, LabWindows/CVI opens it and creates a reference number. In both cases, the function returns the reference number for the integer File_Handle. If LabWindows/CVI cannot create the file, the value returned for File_Handle is -1. This error indicates that the disk is full of data, or that the name supplied in File_Name is invalid.
Parameter Read/Write_Mode =0 Open file for reading and writing Truncate file (delete old contents) Use binary code =1 Open file for reading only Append new data to end of existing file Use ASCII mode =2 Open file for writing only Do not truncate file

Action

File_Type

Invalid value

Close File
int status = CloseFile (int File_Handle);

CloseFile closes the file specified by File_Handle. The returned value, status, indicates the success (0) or failure (-1) of this operation. If you open a file anywhere in a LabWindows/CVI application program, you should close it before terminating the application.

LabWindows/CVI Basics I Course Manual

A-2

National Instruments Corporation

Appendix

Write To File
int n = WriteFile(int File_Handle, char Buffer[], int Count[]);

WriteFile writes data from Buffer into the file specified by File_Handle. Count represents the number of bytes to write to this file. Because LabWindows/CVI strings are NUL terminated, using the LabWindows/CVI function StringLength is an easy way to determine the number of bytes to write. Before you can write numerical data to a file, it must be converted to a string. To convert the numerical data to a string, use the Fmt function. This method requires two function calls, Fmt and WriteFile. Another method is to use the FmtFile function to format the data directly to a file.

Fmt File
int n = FmtFile (int File_Handle, char Format_String[], source1, source2,..., sourceN);

FmtFile moves data from the sources, through Format_String, and into a file referenced by an integer called File_Handle. The OpenFile function returns File_Handle. You use this function exactly like the Fmt function; however, the function stores data to this disk file rather than in the computer memory. FmtFile = Fmt + WriteFile

Read from File


int n = ReadFile (int File_Handle, char Buffer[], int Count);

ReadFile reads data from a file. The file must have been opened previously, with a call to OpenFile to return the File_Handle that references the file. The data this function reads is placed in the variable Buffer (a previously declared string). Count is an integer parameter that specifies the maximum number of bytes to read. The value this function call returns, n, represents the actual number of bytes read from the file. After reading the data, the function stores the data as a string. To process the data, as in plotting it or performing numerical operations, you must use the Scan function to convert the string to numerical data. This method requires two function calls, ReadFile and Scan. Another method is to use the ScanFile function to directly convert the data on disk into its correct representation in memory.

National Instruments Corporation

A-3

LabWindows/CVI Basics I Course Manual

Appendix

Scan from File


int n = ScanFile (int File_Handle, char Format_String[], target1, target2,..., targetN);

ScanFile reads data from a file specified by File_Handle and places it into the targets. The rules for transforming the data are the same as those for the Scan function. The OpenFile function returns File_Handle. ScanFile = ReadFile + Scan

File I/O Examples Binary File to Integer Array


int readings[100]; int file_handle; file_handle = OpenFile ("TEST.DAT", 1, 2, 0); ScanFile (file_handle, "%100i>%100i", readings); CloseFile (file_handle);

The ScanFile function reads 100 integers from a binary file and stores them in the integer array readings. In this example, it is expected that each integer in the file is 4 bytes. If not, you would need to use the b2 modifier %100i[b2].

Binary File to Real Array


double waveform[100]; int file_handle; file_handle = OpenFile ("TEST.DAT", 1, 2, 0); ScanFile (file_handle, "%100f>%100f", waveform); CloseFile (file_handle);

The ScanFile function reads 100 real numbers from a binary file and stores them in the read array waveform. In this example, it is expected that each real number in the file is 8 bytes.

LabWindows/CVI Basics I Course Manual

A-4

National Instruments Corporation

Appendix

ASCII File with Comma Separated Numbers to Real Array


The file contains the number of elements at the beginning of the file. For example,
1024 12, 28, 63, ..., 2, 14, 66 <EOF> double values[1024]; int file_handle, count; file_handle = OpenFile ("TEST.DAT", 1, 2, 1); ScanFile (file_handle, "%s>%i", &count); /* number to read */ ScanFile (file_handle, "%s>%*f[x]", count, values); CloseFile (file_handle);

The first ScanFile function reads the number of elements into the integer variable count. The second ScanFile call matches count to the asterisk (*) in the format string. It then reads 1,024 numbers into the real array values. The x modifier causes the comma separators to be discarded.

National Instruments Corporation

A-5

LabWindows/CVI Basics I Course Manual

Appendix

B. Formatting and Scanning Modifiers


modifiers are optional codes used to describe the nature of the source or target data. If you use them, you must enclose the modifiers in square brackets and place them immediately after the format code they modify. If one format specifier requires more than one modifier, enclose all modifiers in the same set of brackets. There is a different set of modifiers for each possible format specifier.

Formatting Integer Modifiers (%i, %d, %x, %o, %c)


bn Specify Length. The b integer modifier specifies the length of the integer argument, or the length of an individual integer array element, in bytes. The default length is 2 B; therefore, simple 2 B integers do not need this modifier. b4 represents long integers, and b1 represents single-byte integers. Specify Array Offset. The i modifier specifies an offset within an integer array argument. It indicates the location within the array where processing begins. n is the zero-based index of the first element to process. Thus, %10d[i2] applied to a source integer array reads the 10 integer values from the third through the twelfth elements of the array. The i modifier is valid only if rep is present. If you use the i modifier with the z modifier, then n is in terms of bytes. Treat String as Integer Array. The z modifier indicates that the data type of the corresponding argument is a string. Nevertheless, the data in the string is treated as an integer array. The z modifier is valid only if rep is present. Specify Radix. The r integer modifier specifies the radix of the integer argument, which is important if the integer was to be converted into string format. Legal radixes are 8 (octal), 10 (decimal, the default), 16 (hexadecimal), and 256 (a special radix representing single 8-bit ASCII characters). Specify String Size. The w integer modifier specifies the exact number of bytes in which to store a string representation of the integer argument, in the event that the integer is converted to a string format. You can enter any non-negative value here. If n is less than the number of digits required to represent the integer, an asterisk (*) will be inserted into the string to signify an overflow. The default for n is zero, which indicates that the integer can occupy whatever room is necessary.

in

rn

wn

LabWindows/CVI Basics I Course Manual

A-6

National Instruments Corporation

Appendix

pc

Specify Padding. The p integer modifier specifies a padding character c, which fills the space to the left of an integer in the event that it does not require the entire width specified with the wn modifier. The default padding character is a blank. Specify as Twos Complement. The s integer modifier indicates that the integer argument is considered a signed twos complement number. This number is the default interpretation of integers, so the s modifier is never explicitly required. Specify as Unsigned. The u integer modifier indicates that the integer is considered an unsigned integer. Specify Byte Ordering. The o modifier is used to describe the byte ordering of raw data so that LabWindows/CVI can map it to the byte order appropriate for the Intel (PC) or Motorola (SPARCstation) architecture. The number of ns must be equal to the byte size of the integer argument as specified by the bn modifier, which must precede the o modifier. In the case of a four-byte integer, o0123 indicates that the bytes are in ascending order of precedence (Intel style), and o3210 indicates that the bytes are in descending order of precedence (Motorola style).

onnnn

In an Fmt function, the buffer containing the raw instrument data should have the o modifier describing the byte ordering. The buffer without the o modifier is guaranteed to be in the mode of the host processor. In other words, LabWindows/CVI will reverse the byte ordering of the buffer without the o modifier depending on which architecture the program is running on. For example, if your GPIB instrument sends two-byte binary data in Intel byte order, your code should appear as follows:
short int instr_buf[100]; short int prog_buf[100]; status = ibrd (ud, instr_buf, 200); Fmt (prog_buf, "%100d<%100d[b2o01]", instr_buf);

If, instead, your GPIB instrument sends two-byte binary data in Motorola byte order, the Fmt function should appear as follows:
Fmt (prog_buf, "%100d<%100d[b2o10]", prog_buf);

In either case, the o modifier is used only on the buffer containing the raw data from the instrument (instr_buf). LabWindows/CVI will ensure that the program buffer (prog_buf) is in the proper byte order for the host processor.

National Instruments Corporation

A-7

LabWindows/CVI Basics I Course Manual

Appendix

Note

When using both the bn and on modifiers on an integer specifier, the bn modifier must be first.

Formatting Floating-Point Modifiers (%f)


bn Specify Length. The b floating-point modifier specifies the length of the floating-point argument, or the length of an individual array element, in bytes. The default length is 8 B; therefore, double-precision values do not need this modifier. Single-precision floating-point values are indicated by b4. The only valid values for n are 8 and 4. Specify Array Offset. You use the i modifier to specify an offset within a floating-point array argument. It indicates the location within the array where processing is to begin. n is the zero-based index of the first element to process. Thus, %10f[i2] applied to a source floating-point array reads the 10 floating-point values from the third through the twelfth elements of the array. The i modifier is valid only if rep is present. If you use the i modifier with the z modifier, then n is in terms of bytes. Treat String as Floating-Point Array. The z modifier indicates that the data type of the corresponding argument is a string. Nevertheless, the data in the string is treated as a floating-point array. The z modifier is valid only if rep is present. Specify String Size. The w floating-point modifier specifies the exact number of bytes in which to store a string representation of the floating-point argument, in the event that the value is converted to a string format. Any non-negative value can be entered here. If n is less than the number of digits required to represent the floating-point number, an asterisk (*) will be inserted into the string to signify an overflow. The default for n is zero, which indicates that the value can occupy whatever room is necessary. Specify Precision. The p floating-point modifier specifies the number of digits to the right of the decimal point in a string representation of the floating-point number. You can lose significant digits by attempting to conform to the precision specification. If the pn modifier is omitted, a default of p6 is assumed. Specify as Scientific Notation. The e floating-point modifier specifies that a value be converted to string format in scientific notation. If omitted, floating-point notation is used. n is optional and specifies the number of digits in the exponent.

in

wn

pn

en

LabWindows/CVI Basics I Course Manual

A-8

National Instruments Corporation

Appendix

For example, %f[e2] formats 10.0 as 1.0e+01. If n is omitted, a default of three is used. f Specify as Floating-Point Notation. You use the f floating-point modifier to specify that the value be converted to string format in floating-point notation. This is the default. Truncate. The t floating-point modifier indicates that in floating-point to integer transformations, the floating-point value is truncated instead of rounded. This is the default. Round. The r floating-point modifier indicates that in floating-point to integer transformations, the floating-point value is rounded instead of truncated. The default method is truncation.

Note

The value can be in scientific notation even if the e modifier is absent. This occurs when the absolute value of the argument is greater than 1.0e40 or less than 1.0e-40, or when the absolute value of the argument is greater than 1.0e20 or less than 1.0e-4 and neither the p nor w modifier is present.

Formatting String Modifiers (%s)


in Specify Array Offset. You can use the i modifier to specify an offset within a string. It indicates the location within the string where processing is to begin. n is the zero-based index of the first byte to process. Thus, %s[i2] applied to a target string begins placing data in the third byte of the string. Append. When applied to a target format specifier, the a modifier specifies that all formatted data be appended to the target string. The data is appended beginning at the first occurrence of an ASCII NUL in the target string. Specify String Size. When modifying a source format specifier, the w modifier specifies the maximum number of bytes to be consumed from the string argument. You can enter any non-negative value, the default being zero, which indicates that the entire string should be consumed.

wn

When modifying a target format specifier, the w modifier specifies the exact number of bytes to store in the string, excluding the terminating ASCII NUL. If n is zero or omitted, then as many bytes are stored as are called for by the sources. When n is greater than the number of bytes available from the source, the remaining bytes are filled with ASCII NULs if the q modifier is used, or blanks if the q modifier is not present.

National Instruments Corporation

A-9

LabWindows/CVI Basics I Course Manual

Appendix

When the w modifier is used in conjunction with the a modifier, n indicates the number of bytes to append to the string excluding the terminating ASCII NUL. If wn modifies a target string and n is larger than the number of bytes in the target argument, the target string is overwritten in compiled C. q Append NULs. When applied to a target string in conjunction with the w modifier, the q modifier specifies that unfilled bytes at the end of the target string be set to ASCII NULs instead of blanks. Terminate on Character. When applied to a source string, the t modifier specifies that the source string is terminated on the first occurrence of the character n, where n is the ASCII value of the character. Thus, %s[t44] causes reading of the source string to stop on an ASCII comma. Using %s[t44] and the source string Hello, World! as an example, Hello is placed into the target. More than one t modifier can occur in the same specifier, in which case the string terminates when any of the terminators occur. If no t modifier is present, reading of the source string stops on an ASCII NUL. This modifier has no effect when applied to the target specifier. Terminate when Full. The t- modifier is similar to tn, except that it specifies that there are no terminating characters. Reading of the source string terminates when the target is full or when the number of bytes specified with the w modifier have been read. Terminate on Number. The t# modifier is equivalent to repeating the t modifier with the ASCII values of the characters +, -, and 0 through 9. It specifies that reading of the source string be terminated upon occurrence of a numeric expression. When you use %s[t#] with the source string ab567, ab is placed in the target.

tn

t-

t#

Scanning Integer Modifiers (%i, %d, %x, %o, %c)


bn Specify Length. The b integer modifier specifies the length of the integer argument, or the length of an individual integer array element, in bytes. The default length is 2 B; therefore, simple 2 B integers do not need this modifier. Long integers are indicated by b4, single-byte integers are represented by b1. Specify Array Offset. Use the i modifier to specify an offset within an integer array argument. It indicates the location within the array where processing is to begin. n is the zero-based index

in

LabWindows/CVI Basics I Course Manual

A-10

National Instruments Corporation

Appendix

of the first element to process. Thus, %10d[i2] applied to a source integer array reads the 10 integer values from the third through the twelfth elements of the array. The i modifier is valid only if rep is present. If the i modifier is used with the z modifier, then n is in terms of bytes. z Treat String as Integer Array. The z modifier indicates that the data type of the corresponding argument is a string. Nevertheless, the data in the string is treated as an integer array. The z modifier is valid only if rep is present. Specify Radix. The r integer modifier specifies the radix of the integer argument, which is important if the integer is converted from a string format. Legal radixes are 8 (octal), 10 (decimal, the default), 16 (hexadecimal), and 256 (a special radix representing single 8-bit ASCII characters). Specify String Size. The w integer modifier specifies the exact number of bytes occupied by a string representation of the integer argument, in the event that the integer is converted from a string format. You can enter any non-negative value here. If n is less than the number of digits required to represent the integer, an asterisk (*) will be inserted into the string to signify an overflow. The default for n is zero, which indicates that the integer can occupy whatever room is necessary. Specify as Twos Complement. The s integer modifier indicates that the integer argument is to be considered a signed twos complement number. This number is the default interpretation of integers, so the s modifier is not required. Specify as Non-negative. The u integer modifier indicates that the integer is to be considered a non-negative integer. Discard Terminator. The x integer causes the character that terminated the numeric data to be discarded. In this way, terminator characters can be skipped when reading lists of numeric input. Thus, %3i[x] reads three integer numbers, disregarding the terminator character that appears after each one. You can use this specifier to scan the string 3, 7, -32. Discard Data. When applied to a target specifier, the d modifier indicates that there is no target argument to correspond to the target specifier. The data that otherwise is placed in the target argument is discarded instead. The count returned by the Scan/ScanFile/ScanIn functions will include the target specifier even if the d modifier is used.

rn

wn

National Instruments Corporation

A-11

LabWindows/CVI Basics I Course Manual

Appendix

onnnn

Specify Byte Ordering. The o modifier is used to describe the byte ordering of raw data so that LabWindows/CVI can map it to the byte order appropriate for the Intel (PC) or Motorola (SPARCstation) architecture. The number of ns must be equal to the byte size of the integer argument as specified by the bn modifier, which must precede the o modifier. In the case of a four-byte integer, o0123 indicates that the bytes are in ascending order of precedence (Intel style), and o3210 indicates that the bytes are in descending order of precedence (Motorola style).

In a Scan function, the buffer containing the raw instrument data should have the o modifier describing the byte ordering. The buffer without the o modifier is guaranteed to be in the mode of the host processor. In other words, LabWindows/CVI will reverse the byte ordering of the buffer without the o modifier depending on which architecture the program is running on. For example, if your GPIB instrument sends two-byte binary data in Intel byte order, your code should appear as follows:
short int instr_buf[100]; short int prog_buf[100]; status = ibrd (ud, instr_buf, 200); Scan (instr_buf, "%100d[b2o01]>%100d", prog_buf);

If, instead, your GPIB instrument sends two-byte binary data in Motorola byte order, the Scan function should appear as follows:
Scan (instr_buf, "%100d[b2o10]>%100d", prog_buf);

In either case, the o modifier is used only on the buffer containing the raw data from the instrument (instr_buf). LabWindows/CVI will ensure that the program buffer (prog_buf) is in the proper byte order for the host processor.
Note

When using both the bn and on modifiers on an integer specifier, the bn modifier must be first.

Scanning Floating-Point Modifiers (%f)


bn Specify Length. The b floating-point modifier specifies the length of the floating-point argument, or the length of an individual array element, in bytes. The default length is 8 B; therefore, double-precision values do not need this modifier. Single-precision floating-point values are indicated by b4. The only valid values for n are 8 and 4.

LabWindows/CVI Basics I Course Manual

A-12

National Instruments Corporation

Appendix

in

Specify Array Offset. You can use the i modifier to specify an offset within a floating-point array argument. It indicates the location within the array where processing is to begin. n is the zero-based index of the first element to process. Thus, %10f[i2] applied to a source floating-point array reads the 10 floating-point values from the third through the twelfth elements of the array. The i modifier is valid only if rep is present. If you use the i modifier with the z modifier, then n is in terms of bytes. Treat String as Floating Point. The z modifier indicates that the data type of the corresponding argument is a string. Nevertheless, the data in the string is treated as a floating-point array. The z modifier is valid only if rep is present. Specify String Size. The w floating-point modifier specifies the exact number of bytes occupied by a string representation of the floating-point argument, in the event that the value is converted from a string format. You can enter any non-negative value here. If n is less than the number of digits required to represent the floating-point number, an asterisk (*) will be inserted into the string to signify an overflow. The default for n is zero, which indicates that the value can occupy whatever room is necessary. Specify Precision. The p floating-point modifier specifies the number of digits to the right of the decimal point in a string representation of the floating-point number. Significant digits may be lost in attempting to conform to the precision specification. If the pn modifier is omitted, a default of p6 is used. The p modifier is valid for sources only. Specify as Scientific Notation. The e floating-point modifier indicates that the string representation of the floating-point value is in scientific notation. If omitted, non-scientific notation is used. n is optional and specifies the number of digits to use in the exponent. For example, %f[e2] causes 10.0 to be formatted as 1.0e+01. If n is omitted, a default of three is used. The e modifier is valid for sources only. Specify as Floating Point. The f floating-point modifier indicates that the string representation of the floating-point value is in non-scientific notation. This is the default even when the f modifier is not present. Discard Terminator. The x integer causes the character that terminated the numeric data to be discarded. In this way, terminator characters can be skipped when reading lists of

wn

pn

en

National Instruments Corporation

A-13

LabWindows/CVI Basics I Course Manual

Appendix

numeric input. Thus, %3[fx] reads three floating-point numbers, disregarding the terminator character that appears after each one; this specifier could then be used to scan the string 3.5, 7.6, -32.4. d Discard Data. When applied to a target specifier, the d modifier indicates that there is no target argument to correspond to the target specifier. The data that otherwise is placed in the target argument is discarded instead. The count returned by the Scan/ScanFile/ScanIn functions will include the target specifier even if the d modifier is used.

Scanning String Modifiers (%s)


in Specify Array Offset. You can use the i modifier to specify an offset within a string. It indicates the location within the string where processing is to begin. n is the zero-based index of the first byte to process. Thus, %s[i2] applied to a target string begins placing data in the third byte of the string. Append. When applied to a target format specifier, the a modifier specifies that all formatted data be appended to the target string, beginning at the first occurrence of an ASCII NUL in the target string. Specify String Size. When modifying a source format specifier, the w modifier specifies the maximum number of bytes from the source string to be used for filling the target arguments. You can enter any non-negative value here; the default is zero, which indicates that the entire string can be used. (For ScanFile and ScanIn, the entire source string is consumed even if the w modifier restricts the number of bytes used to fill in the target arguments.)

wn

When modifying a target format specifier, the w modifier specifies the exact number of bytes to store in the string, excluding the terminating ASCII NUL. If n is zero or omitted, then as many bytes are stored as are called for by the sources. When n is greater than the number of bytes available from the source, the remaining bytes are filled with ASCII NULs if the q modifier is used or blanks if the q modifier is not present. When the w modifier is used in conjunction with the a modifier, n indicates the number of bytes to append to the string excluding the terminating ASCII NUL. If wn modifies a target string and n is larger than the number of bytes in the target argument, the target argument is overwritten in compiled C.

LabWindows/CVI Basics I Course Manual

A-14

National Instruments Corporation

Appendix

Append NULs. When applied to a target string in conjunction with the w modifier, the q modifier specifies that unfilled bytes at the end of the target string be set to ASCII NULs instead of blanks. Append with Spacing. When the source is a string and the y modifier is applied to a target string format specifier, the target string is filled with bytes from the source string without skipping extra spaces or tabs. Terminate on Character. When applied to a source string, the t modifier specifies that the source string is terminated on the first occurrence of the character n, where n is the ASCII value of the character. Thus, %s[t44] causes reading of the source string to stop on an ASCII comma. More than one t modifier can occur in the same specifier, in which case the string terminates when any of the terminators occur. If no t modifier is present, reading of the source string stops on an ASCII NUL.

tn

When applied to a target string that is being filled from a source string, the t modifier specifies that filling of the target is terminated on the first occurrence of the character n, where n is the ASCII value of the character. Thus, %s[t59] causes reading of the source string to stop on an ASCII semicolon. More than one t modifier can occur in the same specifier, in which case filling of the target terminates when any of the terminators occur. If no t modifier is present, filling of the target stops on any whitespace character. tTerminate when Full. The t- modifier is similar to tn, except that it specifies that there are no terminating characters. When applied to a source string, t- specifies that reading of the source string terminates when all of the targets are full or when the number of bytes specified with the w modifier have been read. When applied to a target string, t- specifies that filling of the target string terminates when the source is exhausted or when the number of bytes specified with the w modifier have been placed into the target. Terminate on Number. The t# modifier is equivalent to repeating the t modifier with the ASCII values of the characters +, -, and 0 through 9. When applied to a source (target), it specifies that reading of the source string (filling of the target string) be terminated upon occurrence of a numeric expression. When you use %s>%s[t#]%d with the source string ab567, ab is placed in the first target and the integer 567 is placed in the second target.

t#

National Instruments Corporation

A-15

LabWindows/CVI Basics I Course Manual

Appendix

Discard Terminator. When applied to a target string, the x modifier specifies that the terminating character be discarded before the next target is filled in. Using %s>%s[xt59]%s[xt59] with the source string "abc;XYZ;", "abc" is placed in the first target and "XYZ" is placed in the second target. Discard Data. When applied to a target specifier, the d modifier indicates that there is no target argument to correspond to the target specifier. The data that otherwise is placed in the target argument is discarded instead. The count returned by the Scan/ScanFile/ScanIn functions will include the target specifier even if the d modifier is used

LabWindows/CVI Basics I Course Manual

A-16

National Instruments Corporation

Documentation Comment Form


National Instruments encourages you to comment on the documentation supplied with our products. This information helps us provide quality products to meet your needs.

Title: Edition Date: Part Number:

LabWindows/CVI Basics I Course Manual January 1999 320803F-01

Please comment on the completeness, clarity, and organization of the manual. ____________________________________________________________________________________________ ____________________________________________________________________________________________ ____________________________________________________________________________________________ ____________________________________________________________________________________________ ____________________________________________________________________________________________ ____________________________________________________________________________________________ ____________________________________________________________________________________________ ____________________________________________________________________________________________

If you find errors in the manual, please record the page numbers and describe the errors. ____________________________________________________________________________________________ ____________________________________________________________________________________________ ____________________________________________________________________________________________ ____________________________________________________________________________________________ ____________________________________________________________________________________________ ____________________________________________________________________________________________ ____________________________________________________________________________________________ ____________________________________________________________________________________________ Thank you for your help. Name _______________________________________________________________________________________ Title ________________________________________________________________________________________ Company ____________________________________________________________________________________ Address _____________________________________________________________________________________ ____________________________________________________________________________________________ E-mail Address _______________________________________________________________________________ Phone ( ___ )____________________________________ Fax ( ___ ) ___________________________________

Mail to: Technical Publications


National Instruments Corporation 11500 North Mopac Expressway Austin, Texas 78759

Fax to:

Technical Publications National Instruments Corporation 512 683 6837

Course Evaluation
Course __________________________________________________________________________________________________________ Austin Onsite Regional Location ____________________________________________ Date ____________________________

Instructor__________________________________________________________________

STUDENT INFORMATION

(Optional)

Name ____________________________________________________________________________________________________________________ Company ______________________________________________________ Phone __________________________________________________ Please evaluate the instructor by checking the appropriate circle. Instructors ability to communicate the material Instructors knowledge of the subject matter Instructors presentation skills Outstanding Good Okay Poor Unsatisfactory

INSTRUCTOR

Instructors sensitivity to class needs Instructors preparation for the class

Training facility quality The course length was Too Long

Training equipment quality Just Right Too Much Yes Yes No Yes No If no, how could you have been better prepared for the course? Too Short Just Right No Not Enough

The detail of topics covered in the course was

COURSE

The course material was clear and easy to follow. Did the course cover material as advertised?

Sometimes

I had the skills or knowledge I needed to attend this course.

_________________________________________________________________________________________________________________________ The course met my objectives. Yes No If no, please explain. __________________________________________________________

_________________________________________________________________________________________________________________________ What were the strong points of the course?__________________________________________________________________________________________________ _____________________________________________________________________________________________________________________________________ What part(s) of the course need to be expanded?_____________________________________________________________________________________________ _____________________________________________________________________________________________________________________________________ What part(s) of the course need to be condensed or removed?__________________________________________________________________________________ _____________________________________________________________________________________________________________________________________ What needs to be added to the course to make it better? ______________________________________________________________________________________ _____________________________________________________________________________________________________________________________________ Comments/Ideas _______________________________________________________________________________________________________________________

280104B-01

The Software is the Instrument

NATIONAL INSTRUMENTS

Copyright 1994 National Instruments Corporation. All rights reserved.

071594