cvi basics i (course manual).pdf

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.

Upload: cjalanis

Post on 22-Oct-2015

861 views

Category:

Documents


163 download

TRANSCRIPT

Page 1: CVI Basics I (Course Manual).pdf

LabWindows/CVI Basics ICourse Manual

Course Software Version 3.0January 1999 EditionPart 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.

TrademarksCVI™, 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.

Page 2: CVI Basics I (Course Manual).pdf

Internet SupportE-mail: [email protected] Site: ftp.natinst.comWeb Address: http://www.natinst.com

Bulletin Board SupportBBS United States: 512 794 5422BBS United Kingdom: 01635 551422BBS France: 01 48 65 15 59

Fax-on-Demand Support512 418 1111

Telephone Support (USA)Tel: 512 795 8248Fax: 512 794 5678

International OfficesAustralia 03 9879 5166, Austria 0662 45 79 90 0, Belgium 02 757 00 20, Brazil 011 288 3336, Canada (Ontario) 905 785 0085, Canada (Québec) 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 Headquarters11500 North Mopac Austin, Texas 78759 USA Tel: 512 683 0100

© Copyright 1998 National Instruments Corporation. All rights reserved.

Page 3: CVI Basics I (Course Manual).pdf

Contents

© National Instruments Corporation iii LabWindows/CVI Basics I Course Manual

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

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

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

Page 4: CVI Basics I (Course Manual).pdf

Contents

LabWindows/CVI Basics I Course Manual iv © National Instruments Corporation

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

Lesson 4 ExercisesExercise 4-1 ................................................................................................................4-1

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

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

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

Lesson 8 ExercisesExercise 8-1 ................................................................................................................8-1

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

Page 5: CVI Basics I (Course Manual).pdf

LabWindows/CVI Basics I Course Manual 1 © National Instruments Corporation

LabWindows/CVIBasics I

National Instruments11500B MoPac Expressway

Austin, TX 78759(512) 794-0100

Page 6: CVI Basics I (Course Manual).pdf

LabWindows/CVI Basics I Course Manual 2 © National Instruments Corporation

Evolution of Instrumentation

PC

TV

Radio

Clock

Time

Fle

xibi

lity

0

50100

25 75

PC-based virtual instrumentation has become the newmethodology for instrumentation

Instrumentation helps science and technology progress. Scientists and engineers around theworld use instruments to observe, control, and understand the physical universe. Our quality oflife depends on the future of instrumentation – from basic research in life sciences and medicineto design, test and manufacturing of electronics, to machine and process control in countlessindustries.

The slide above shows the evolution of instrumentation over the last 100 or so years. It isimportant that instruments have always leveraged off widely-used technology. In the 19thcentury, 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 buildthe first electronic instruments. Display technology from the television has contributed tomodern oscilloscopes and analyzers. And finally, modern personal computers contribute high-performance computation and display capabilities.

In the past, data acquisition devices have been traditionally reserved for the standaloneinstrument. Also, advancements in the personal computer area have shifted data acquisition tothe personal computer, which offers greater flexibility, ease of use, and cost-effective analysis.

Page 7: CVI Basics I (Course Manual).pdf

LabWindows/CVI Basics I Course Manual 3 © National Instruments Corporation

Instrumentation

PROCESSOR BUS

Conditioning

TimingA/D

D/A

DI/O

TI/O

DISPLAY

AND

CONTROL488 PORT

µPMath

MEMORYµPROM

Control Panel

Flow

Pressure Alarm Conditions

STOP

Temperature

Standard Instrumentation Virtual Instrumentation

Vendor Defined User Defined

Instruments have evolved in terms of both flexibility and the degree to which they integrate intosystems. The first-generation instruments were analog instruments manually controlled fromtheir front panels. Measurements from these instruments had to be recorded by hand. The usershad no flexibility in user interface design, measurement capabilities, or computational features.

With the invention of the GPIB and digital instruments, users could control systems bothprogrammatically and manually. Each GPIB instrument was designed for a specificmeasurement, and users “racked and stacked” a number of instruments to create a completemeasurement 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 rivalthose of sophisticated workstations at a fraction of the cost. Easy-to-use but powerful softwareand application development environments allow you to develop more capable applicationsfaster.

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 withgeneral-purpose PCs.

Historically, architectural limitations have resulted in hard boundaries between vendor-definedinstruments and user-defined functionality in an instrumentation system. The PC revolution hasequipped users with powerful processing and display capabilities of their own. If you enhancethe fixed capabilities of a traditional instrument with flexible user-defined capabilities of acomputer, you have a virtual instrument.

Page 8: CVI Basics I (Course Manual).pdf

LabWindows/CVI Basics I Course Manual 4 © National Instruments Corporation

The Virtual Instrument

SCXI

1140

SCXI

1140

SCXI

1140

SCXI

1140

SCXI-1001

MAINFRAME

SCXI

SCXI1100

NATIONAL

INSTRUMENTS®

bus

Control Panel

Flow

Pressure Alarm Conditions

STOP

Temperature

GPIB Instruments

Serial Instruments

DAQ Products

Unit Under Test

Process

Modular Instruments (VXI, PXI, CAMAC…)

ApplicationSoftware

PC or Workstation

With virtual instrumentation, you can build your own instrumentation systems with standardcomputers and cost-effective hardware. These software-centered systems leverage off thecomputational, display, and connectivity capabilities of popular computers to give you thepower and flexibility to build each of your instrumentation functions. You can mix and matchyour choice of data acquisition and instrument control hardware, including all of your existinginstruments, 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 computerwith 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 manyapplications. Unlike traditional instruments, which are limited by the design of themanufacturer, a virtual instrument can operate a variety of devices, such as a temperaturemonitor, voltmeter, strip chart recorder, digitizer, and signal analyzer.

Page 9: CVI Basics I (Course Manual).pdf

LabWindows/CVI Basics I Course Manual 5 © National Instruments Corporation

Key Elements of Virtual Instruments

Acquisition PresentationAnalysis

SignalRouting andConditioning

INSTRUMENT

IEEE488 (GPIB)

DAQ Boards

VXI

RS-232

Trigger Control

Format

Calculate

User Interface

File I/O

InterprocessCommunication

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, andtemperature) are converted into digital formats and brought into the computer. Analysis, suchas a frequency response, is performed by specifically optimized software routines available in awide selection of development environments. The presentation of the acquired and analyzedsignal is accomplished using graphical display methods common on computers today.

The four popular methods for acquiring data are plug-in data acquisition boards, GPIBinstruments, VXI instruments, and RS-232 instruments. Data analysis transforms raw data intomeaningful information. Data presentation is the means for communicating with your system inan intuitive, meaningful format. The components listed are but a few examples of the datapresentation tools available.

National Instruments has products available for all of the elements of a virtual instrument.

Page 10: CVI Basics I (Course Manual).pdf

LabWindows/CVI Basics I Course Manual 6 © National Instruments Corporation

What Does National InstrumentsProvide?

Acquisition

IEEE 488.2controllers

Plug-in dataacquisition 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

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

National Instruments is the leading vendor for GPIB control products worldwide. Our GPIBASICs represent the leading edge of GPIB control technology. We manufacture products for awide 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 analoginput boards to low-cost multifunction boards, for all PC platforms.

National Instruments leads the VXI control market with a complete line of VXI controllers andoperating systems. We also invented the MXIbus, a high-speed cable standard, to give desktopcomputers control of VXI systems with the same power and speed as embedded VXIcontrollers.

The foundation for the instrumentation system is the software – LabWindows/CVI,ComponentWorks, and LabVIEW. Each software package accommodates all aspects ofmeasurement and instrumentation, including data acquisition and control, data analysis, anddata presentation. LabWindows/CVI, LabVIEW, and ComponentWorks are designed tosimplify 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 bychanging the way the world uses instrumentation. By taking advantage of high-performanceindustry-standard computers, we are leading a revolution in which scientists and engineers willuse 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 tochanging needs than the instruments of the past. We are leading the way to the future ofinstrumentation, a future in which The Software is the Instrument.

Page 11: CVI Basics I (Course Manual).pdf

LabWindows/CVI Basics I Course Manual 7 © National Instruments Corporation

″ ″ ″

LabWindows/CVI

ANSI CStandard Language

CompilerEditor

DebuggerOpen System

Built-In Instrumentation Libraries

I/O (GPIB, VXI, DAQ, Serial, IMAQ, etc)

Analysis

Network TCP

OLEGUI

Productivity Toolsfor Faster Development

Standard ANSI C Language

CodeGeneration Tools

Interactive Execution ™

LabWindows/CVI addresses all of the challenges of an integrated ANSI C developmentenvironment. It includes a 32-bit compiler and linker with advanced editing and debuggingtools. Best of all – it’s open! You can incorporate the best of other people’s development effortsand produce DLLs for other environments. LabWindows/CVI has a comprehensive suite oflibraries targeted at instrumentation applications, from instrument control to data analysis andgraphing – all you need is right there at your fingertips.

For rapid application development, LabWindows/CVI includes CodeBuilder and interactiveFunction Panels. These two powerful code generation tools mean you can develop yourapplication with the bare minimum of programming. It’s like having your own personal C guruhelping you with your application!

Page 12: CVI Basics I (Course Manual).pdf

LabWindows/CVI Basics I Course Manual 8 © National Instruments Corporation

Software Architecture

Acquisition Analysis Presentation

LabWindows/CVI

Instrument Drivers

NI-488.2 NI-VXI NI-DAQ Serial

RS-232RS-485

Computer Bus

VXIGPIB

Application

Software DriverSoftware

To account for the varying needs of measurement and instrumentation applications, softwaremust 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 hardwareand high-level application development software. With this combination, you have a scalabledevelopment system with the flexibility to handle a very wide range of measurement andinstrumentation applications.

To build virtual instruments, you need software that easily integrates any or all of the fourhardware instrumentation options in a single system. At the lowest level, with standardizeddriver software packages you can control the four acquisition hardware options. The driverpackages include function libraries for programming your hardware. Our NI-488.2 driver is theindustry 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. Mostcomputers include RS-232 driver software. Our driver software packages are standardizedacross all popular computers and a wide variety of operating systems.

You can use our stand-alone driver software and program using the language and operatingsystem of your choice. If you need assistance with programming, our application software is theanswer. With our application software, LabWindows/CVI, you can build your own instruments.LabWindows/CVI works with all aspects of an instrumentation system, including dataacquisition and control, data analysis, and data presentation. LabWindows/CVI also featuresmodular, reusable, high-level instrument drivers for specific instruments and applications thatdramatically reduce your software development task. By using our application softwarepackages, you are free to choose the components necessary to meet your application cost andperformance requirements. You now have the opportunity to build your own instruments toexactly meet your particular application needs.

Page 13: CVI Basics I (Course Manual).pdf

LabWindows/CVI Basics I Course Manual 9 © National Instruments Corporation

LabWindows/CVI -A History of Innovation

• 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

• May 1998

• May 1996

• July 1995

• March 1994

• April 1991

• January 1989

LabWindows first emerged as a set of libraries and a development environment for creatinginstrumentation systems using QuickBasic and Microsoft C under DOS. As DOS memoryextenders became available, it was enhanced to include a user interface library and editor withthe introduction of version 2.0.

Version 3.0 saw a move to Microsoft Windows and the Sun platform as the environmentfocused on C as its fundamental development tool (hence the addition of CVI to the name – Cfor Virtual Instrumentation). Version 3.1 added the capability to automatically generate codefrom 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 ashigh-performance instrument drivers and additions of current technologies like ActiveXAutomation and OpenGL for 3D visualization.

This timeline represents a commitment to innovation and development that has allowed ourcustomers to develop applications secure in the knowledge of a migration path to futureenvironments.

Page 14: CVI Basics I (Course Manual).pdf

LabWindows/CVI Basics I Course Manual 10 © National Instruments Corporation

Course Outline

Day 1• Introduction to

LabWindows/CVI• Graphical User InterfaceDay 2• Data Acquisition (DAQ)• Formatting and Scanning• IEEE 488 (GPIB)Day 3• Serial Communication• Instrument Drivers• Creating and Distributing

Standalone Executables

Page 15: CVI Basics I (Course Manual).pdf

LabWindows/CVI Basics I Course Manual 11 © National Instruments Corporation

Lesson 1Introduction 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 forapplication development.

Page 16: CVI Basics I (Course Manual).pdf

LabWindows/CVI Basics I Course Manual 12 © National Instruments Corporation

Timesavin g Features ofLabWindows/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 andscientific instrumentation applications and includes numerous features to ensure your success.

Function Panel Concept – Function panels are the key to making programming with LabWindows/CVIeasy. You no longer need to remember how many parameters are in a function call or what order theyare in – LabWindows/CVI takes care of them for you!

Automatic Skeleton Code Generation – Minimizes the development effort placed into developingapplications by creating skeleton code to help you begin your program

Tight Integration between Compiler and Linker – LabWindows/CVI is intelligent enough toautomatically include header files required for its internal libraries.

Run-Time Error Checking – LabWindows/CVI prevents you from overwriting memory locations andwill catch errors that other environments may not.

Interactive Execution of Library Functions – Allows developers to test code functionality withouthaving to write a complete program.

Instrumentation Libraries – Instrument Driver, Data Acquisition, GPIB, VXI, and Analysis Librariesare all built in.

Compatibility and Portability – LabWindows/CVI supports ANSI C and is available on severalplatforms. In addition, any code written today will be supported on all future versions ofLabWindows/CVI, and code developed on the Windows 95/98 and NT (Win32) environments can beaccessed from other Win32 development environments. LabWindows/CVI can access third-party DLLsand libraries on these platforms as well. On Solaris operating systems, LabWindows/CVI can accessexternal libraries as well.

Availability of Add-On Packages – Test Executive, Structured Query Language (SQL), ImageProcessing, Statistical Process Control (SPC), PID control, and more!

Page 17: CVI Basics I (Course Manual).pdf

LabWindows/CVI Basics I Course Manual 13 © National Instruments Corporation

LabWindows/CVI Libraries

LabWindows/CVI ships with severaldifferent function libraries. Theselibraries are available to make yourprogramming easier.

Standard and Optional Libraries for LabWindows/CVIUser 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 theanalysis 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 SCXIhardware using simplified functions.

Data Acquisition – Functions for controlling National Instruments plug-in DAQ boards and SCXIhardware.

VXI – Included with the FDS, it is used for controlling a VXI system using National Instruments VXIcontrollers.

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

ANSI C – ANSI specified libraries (stdio, stdlib, and so on).

Page 18: CVI Basics I (Course Manual).pdf

LabWindows/CVI Basics I Course Manual 14 © 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 wascompiled. Double-click on this icon to compile the file.

This icon in the applies only to source (.c ) files and indicates that you enabled theCompile into Object option. If this option is enabled when you compile the sourcefile, LabWindows/CVI creates an object (.obj ) file on disk that containsnondebuggable code rather than generating debuggable code in memory. Double-click on this icon to toggle the option.

The file has been modified since the last time it was saved. Double-click on thisicon 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 newones. 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

Page 19: CVI Basics I (Course Manual).pdf

LabWindows/CVI Basics I Course Manual 15 © National Instruments Corporation

Source Editor Window

LabWindows/CVI Windows

• Split Window

• Tags

The Source Editor window behaves like a standard source code editor but adds many usefulfeatures, such as the ability to insert commonly used C constructs (for loops, casestatements, etc.), color-coding, split windows, and tags.

Split windows offers the ability to view two portions of your code simultaneously. Toaccess this feature, pull down the double bar at the top of the source window (justunderneath the toolbar).

Tags offer an easy way to mark selected lines of code. Press <Shift-F2> to set a tag andpress <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 onemillion lines of code (254 characters per line).

Page 20: CVI Basics I (Course Manual).pdf

LabWindows/CVI Basics I Course Manual 16 © National Instruments Corporation

Standard Input/Output Window

LabWindows/CVI Windows

The Standard Input/Output window is used for simple input and output. This window cancontain up to one million lines of code and 254 characters per line. The contents of thiswindow 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 theCls() 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 doit for you!).

The LabWindows/CVI Standard I/O window is equivalent to a DOS console I/O window.

Page 21: CVI Basics I (Course Manual).pdf

LabWindows/CVI Basics I Course Manual 17 © National Instruments Corporation

Discussed in Lesson 2, this window is used todesign your graphical user interface (GUI)

User Interface Editor Window

LabWindows/CVI Windows

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

Page 22: CVI Basics I (Course Manual).pdf

LabWindows/CVI Basics I Course Manual 18 © National Instruments Corporation

Exercise 1-1

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

Page 23: CVI Basics I (Course Manual).pdf

LabWindows/CVI Basics I Course Manual 19 © National Instruments Corporation

Exercise 1-2

Objective: To examine features of the LabWindows/CVISource Editor.

Page 24: CVI Basics I (Course Manual).pdf

LabWindows/CVI Basics I Course Manual 20 © 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, showthe full pathname of the file or just the filename).

The Build menu commands are for compiling files and building projects (compiling all filesand 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. TheAdvanced Analysis Library, when installed, replaces the regular Analysis Library. For thiscourse, the Advanced Analysis Library has been installed on your computer.

The Tools menu contains wizards to assist with developing ActiveX and IVI instrumentdrivers. 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/CVIenvironment and executing various utilities. Different options include Run Options andCompiler Options.

The Help menu contains commands to invoke the online help.

Page 25: CVI Basics I (Course Manual).pdf

LabWindows/CVI Basics I Course Manual 21 © National Instruments Corporation

LabWindows/CVI Toolbars

You can use toolbars for quick access to selected commands from menus without having topull down any menus. Use the VIEW Toolbar command to display or hide the toolbar. Tocustomize 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 theicon, and a yellow tag strip describing the icon will pop up.

Page 26: CVI Basics I (Course Manual).pdf

LabWindows/CVI Basics I Course Manual 22 © National Instruments Corporation

LabWindows/CVI Options

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

Page 27: CVI Basics I (Course Manual).pdf

LabWindows/CVI Basics I Course Manual 23 © National Instruments Corporation

Exercise 1-3

Objective: To examine various LabWindows/CVI projectoptions.

Page 28: CVI Basics I (Course Manual).pdf

LabWindows/CVI Basics I Course Manual 24 © National Instruments Corporation

Function Panels

Go to the Library menu and select the library you want to search. Navigate through thefunction tree until you find the function you want to operate. Select it and its function panelappears, representing the function with a control for each parameter. By manipulating thecontrols, 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.

Page 29: CVI Basics I (Course Manual).pdf

LabWindows/CVI Basics I Course Manual 25 © 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. Functionpanels are also capable of generating code for inclusion in a program. A function panel is agraphical method of calling a subroutine in a program. You simply select and execute thedesired function panel. The function panel, in turn, calls code in memory that is associatedwith 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 thefunction parameters on the function panel and insert the function call into your code. To dothis, 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 ofparameters associated with any particular function.

Page 30: CVI Basics I (Course Manual).pdf

LabWindows/CVI Basics I Course Manual 26 © National Instruments Corporation

Function Panels - Online Help

Every LabWindows/CVI library function has an associated function panel associated withonline documentation that describes the function in addition to each of the input and outputparameters.

Online documentation for a function panel can be accessed simply by right-clicking on anempty 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 cursorwithin the control and either right-clicking, pressing <F1>, or selecting Help » ControlHelp.

Notice that the function documentation includes a prototype of the function, and the controldocumentation reflects the expected data type.

Page 31: CVI Basics I (Course Manual).pdf

LabWindows/CVI Basics I Course Manual 27 © National Instruments Corporation

Function Panels - Variables

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

Function panels speed development time because they allow you to make variabledeclarations as you develop your program and insert these variable declarations into theInteractive 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 todeclare 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 thetable below.

Option Description

Execute declaration Declares the variable in theInteractive Execution Window

Add declaration to top of target file Places the variable declaration at thebeginning of the currently selectedtarget file. To set the target file pressthe Set Target File button.

Add declaration to current block Places the variable declarations at thetop of the current set of braces{ }.

Page 32: CVI Basics I (Course Manual).pdf

LabWindows/CVI Basics I Course Manual 28 © National Instruments Corporation

Interactive Execution Window

The Interactive Execution window allows you to executeportions of code. You do not need to have a completeprogram in the window. The code shown will executealthough there is no main !

The main use of the Interactive Execution Window (IEW) is to execute functions directlyfrom a function panel. To execute a function from a function panel, just Run it. To run afunction panel, select Code » Run Function Panel, press the icon in the toolbar, orpress <Shift-F5>.

When you execute a function from a function panel, LabWindows/CVI inserts the functioncall into the IEW, where it executes. In this way, the IEW keeps a record of the functionsyou have executed from function panels. When LabWindows/CVI copies a function callfrom 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 isnot already included. When you execute a function call from a function panel, all previouslines in the IEW are automatically excluded. In addition, all variables declared fromfunction panels with the Execute Declaration option selected are copied to the IEW, so thatother 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 inLabWindows/CVI. This clears the variables list available in a function panel andprevents you from accidentally using variables defined in the IEW only.

Page 33: CVI Basics I (Course Manual).pdf

LabWindows/CVI Basics I Course Manual 29 © National Instruments Corporation

Exercise 1-4

Objective: To create a LabWindows/CVI project usingfunction panels.

Page 34: CVI Basics I (Course Manual).pdf

LabWindows/CVI Basics I Course Manual 30 © National Instruments Corporation

Exercise 1-5

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

Page 35: CVI Basics I (Course Manual).pdf

LabWindows/CVI Basics I Course Manual 31 © National Instruments Corporation

LabWindows/CVI DataStructures

Assignments Alternative Assignment Description

short int short integer (2-byte) variable

long int long or int integer (4-byte) variable

unsigned short int unsigned short unsigned integer (2-byte) variable

unsigned long int unsigned long or unsigned int unsigned integer (4-byte) variable

char character variable (1-byte)

float single precision (4-byte) floating point

double double precision (8-byte) floating point

LabWindows/CVI supports standard ANSI C variablesand assignments.

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

Reminder: C variables are case sensitive. The variable Status is different than the variablestatus .

Arrays can be declared statically in the same fashion as they would be in any other ANSI Ccompiler. For example,

int waveform[100]; /* 100-element array of4-byte integers */

char stringFromInstrument [200]; /* 200-element array ofcharacters (string) */

Page 36: CVI Basics I (Course Manual).pdf

LabWindows/CVI Basics I Course Manual 32 © National Instruments Corporation

Scope of Variables

Describes the accessibility of variableswithin different program modules

• Global variables

• Module-globalvariables

• Local variables

When using variables in a program, you must decide what level of accessibility, or scope, is requiredfor each variable and declare it accordingly.

Global VariablesWhen you declare a variable as global, it can be accessed anywhere by any module that ispart 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). Othermodules in the project can access the global variable by redeclaring the variable andprefacing the declaration with the keyword extern.

Module-Global VariablesWhen you declare a variable as global to a module, it can be accessed anywhere in themodule you declare it; however, it cannot be access in any other module. You must declareany module global variables outside any function or main and precede all variabledeclarations with the keyword static.

Local VariablesWhen you declare a variable as local, it can be accessed only in the subprogram (set ofopening and closing curly braces { } ) in which you declare it. Local variables cannot beaccessed in any other subprogram or module.

Note: Local variable can be declared with or without the keyword static. Local variables notdeclared static are kept on the stack. If you declare huge arrays as local variables withoutspecifying them as static, you could get stack overflows. The maximum stack size in a Win16environment is approximately 16 KB with debugging on and 64 KB with debugging turned off. Ina Win32 environment, the stack size can be up to 1 MB.

Page 37: CVI Basics I (Course Manual).pdf

LabWindows/CVI Basics I Course Manual 33 © National Instruments Corporation

int x; // global to all modulesstatic int y; // global to module1

main(){

int z; // local to mainx = 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);

}

Scope of Variables

extern int x; // defined in module1static int y; // global to module2

void foo2(){

static int z; // local to foo2x = 1000;y = 2000;z = 3000;printf ("foo2 x=%d,y=%d,z=%d\n",x,y,z);

}

Module1.c Module2.c

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

To understand how to access variables in different modules, consider a project withtwo modules, source1.c and source2.c .

Because x is defined as a global, it is accessible in both modules. Therefore, thevalue of x was overwritten in the function foo2 . Because y is defined as a staticvariable, its value was preserved between function calls. (The variable y is global toeach modules because it is defined outside of any functions or main ).

Therefore, the output is:foo1 x=1,y=2,z=100foo2 x=1000,y=2000,z=3000main 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 canthink 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 theextern keyword in front of the definition), but the IEW cannot define global variablesfor other modules to use.

Page 38: CVI Basics I (Course Manual).pdf

LabWindows/CVI Basics I Course Manual 34 © National Instruments Corporation

Debugging

• Compiling

• Excluding lines

• Breakpoints/conditional breakpoints

• Single-stepping

• Variables window

• Watch window

DebuggingLabWindows/CVI offers many different debugging options to assist you in creating usablecode. Among the options are:

Compiling – Allows you to check for syntax errors as CVI converts your code into machinecode.

Excluding Lines – Allows a simple and efficient method of commenting out code that youdo not want to be compiled with your project.

Breakpoints/Conditional Breakpoints – Allows you to halt the execution of your programat 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 yourcode 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 similarto the variables window.

Page 39: CVI Basics I (Course Manual).pdf

LabWindows/CVI Basics I Course Manual 35 © National Instruments Corporation

Compilin g Files

Compiling your filechecks for syntaxerrors!

Compiling FilesBy selecting Build » Compile File <Ctrl-K> , LabWindows/CVI will compile theselected file for you. Alternately, you can compile the file by double-clicking on the Cthat appears next to the filename (in the project menu) or by clicking on the icon inthe source window.

When you run the project, the file is automatically compiled and linked prior to theexecution of your program.

Compiling and linking errors are displayed in the Build Errors window. Double-clickingon the error displays and highlights the portion of code generation the error if the error isa 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 notrecognize your function call.

• Forgetting that all statements must be terminated with a semicolon (;). Manyerrors can be fixed by looking for a missing semicolon on the line preceding theerror.

Page 40: CVI Basics I (Course Manual).pdf

LabWindows/CVI Basics I Course Manual 36 © National Instruments Corporation

Excludin g Lines

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

Exclude/Include LinesFor debugging purposes, LabWindows/CVI features a quick and easy method for excludingline of code that you do not want to execute. You can exclude lines by placing the text cursoron the desired line and selecting Edit » Toggle Exclusion (<Ctrl-E>). When you exclude aline, its color changes and it behaves as if it is commented out. You can include previouslyexcluded 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 aline 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 arecausing 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 thatyou want to keep in the same project.

Note: You cannot save a file with excluded lines. LabWindows/CVI will prompt you toresolve the excluded lines.

Page 41: CVI Basics I (Course Manual).pdf

LabWindows/CVI Basics I Course Manual 37 © National Instruments Corporation

Breakpoints

Breakpoints provide a convenient method ofpausing your program at specified points.

BreakpointsYou can pause the program execution without aborting it altogether by parking breakpoints inyour 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 theprogram statement to be executed and outlines the statement. You cannot edit the sourcecode in the window while the breakpoint is in effect. However, you can look at otherwindows, change the state of breakpoints, and modify the value of variables.

Note: The Debugging Level (Project Menu » Options » Run Options) must be set to Norun-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.

Page 42: CVI Basics I (Course Manual).pdf

LabWindows/CVI Basics I Course Manual 38 © National Instruments Corporation

Conditional Breakpoints

LabWindows/CVI allows you to set conditionalbreakpoints.

Conditional BreakpointsLabWindows/CVI also allows you to establish conditional breakpoints. This feature isextremely useful when debugging large programs, because it allows you to break only whencertain 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 placea breakpoint. Next, select Run » Breakpoints… (<F9>) or right-click on the breakpoint iconand select Breakpoints… from the pop-up menu. This brings up the dialog box shown inthe 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 toestablish various conditions for the breakpoint, including a pass count (the number of times acondition must be true for the breakpoint to be valid).

Page 43: CVI Basics I (Course Manual).pdf

LabWindows/CVI Basics I Course Manual 39 © National Instruments Corporation

Single-Steppin g

LabWindows/CVI allows you to single-stepthrough your code.

Single Stepping

To resume execution after a breakpoint, you have several options under the Run menu that control theprogram flow. You can also execute these options by pressing the corresponding icon on the toolbar orby 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 whichyou have placed the text cursor, where it enters another breakpoint state.

Step Over (<F10>) executes an outline statement while in a breakpoint state. Step Overexecutes 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 thefunction. 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 andbreakpoints 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 userinterface while stepping through the code.

By combining breakpoints with program tracing, you can normally execute parts of the programthat are operating correctly and use the trace and step features to manually step through parts ofthe program you are attempting to debug.

Page 44: CVI Basics I (Course Manual).pdf

LabWindows/CVI Basics I Course Manual 40 © National Instruments Corporation

Variables Window

LabWindows/CVI keeps track of the variables you have inyour 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 theVariables window. The current value of numeric scalars, values and contents ofpointers, and string contents are also shown in the Variables window. Variables in thiswindow are updated at each breakpoint.

To view the Variables window, select Window » Variables. Several icons appear to theleft of certain variables. Two of the icons are discussed below.

Character arrays (strings) are not displayed beyond the first NULL byte, because stringsare 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 selectDisplay Entire Buffer .

The variable on this line is the starting pointer to a block of defined data such as anarray, string, or structure. The value next to the icon is the memory offsetcorresponding to the memory location of the variable. Clicking on this icon orselecting View » Expand Variable expands the variable so that you can see eachelement or member.

The variable on this line is the starting pointer to a block of defined data currentlybeing viewed in expanded form. Clicking on this icon or selecting View » CloseVariable 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 anyparticular variable quickly by right-clicking on the top of the name in the sourcewindow and selecting View Variable Value from the pop-up menu.

Page 45: CVI Basics I (Course Manual).pdf

LabWindows/CVI Basics I Course Manual 41 © National Instruments Corporation

Watch Window

The WatchWindow allows youto select your ownset of variablesand expressionsto view

Watch WindowThe Watch window is similar in nature to the Variables windows, except that you can select your ownset of variables and expressions to view in the Watch window. By default, variables and expressionsin the Watch window are updated at each breakpoint, but you can also set them to update continuouslyand 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 WatchExpression.

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 afile, 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 toa file or local to a function.

Function corresponds to the function where the variable or expression is defined if its scope islocal to a function.

Replace replaces the existing attributes of the current variable or expression of the same namein the Watch window with the current attributes in the dialog box. Replace is available onlywhen the dialog box is invoked from the Watch window.

Add inserts the variable or expression to the Watch window.

Page 46: CVI Basics I (Course Manual).pdf

LabWindows/CVI Basics I Course Manual 42 © National Instruments Corporation

Exercise 1-6

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

Page 47: CVI Basics I (Course Manual).pdf

LabWindows/CVI Basics I Course Manual 43 © National Instruments Corporation

Exercise 1-7

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

Page 48: CVI Basics I (Course Manual).pdf

LabWindows/CVI Basics I Course Manual 44 © National Instruments Corporation

Summar y 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 ofthe different windows that LabWindows/CVI uses. They are the Project window, theSource 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 yourLabWindows/CVI application.

The Source window is where the program is actually coded. You can type code directly inthe Source window, or you can use the LabWindows/CVI code builder (discussed in Lesson2) 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 panelcontrols 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.

Page 49: CVI Basics I (Course Manual).pdf

LabWindows/CVI Basics I Course Manual 45 © National Instruments Corporation

Tips and Shortcuts

Menu Item Keyboard Shortcut

Compile File Ctrl-K

Build Project Ctrl-M

Run Project Shift-F5

Halt Execution Ctrl-F12

Toggle Exclusion Ctrl-E

Balance Ctrl-B

Find Shift-F3

Find Next F3

Go to Definition Ctrl-I

Recall Function Panel Ctrl-P

Find Function Panel Ctrl-Shift-P

Toggle Tag Shift-F2

Next Tag F2

Previous Tag Ctrl-F2

Menu Item Keyboard Shortcut

Declare Variable Ctrl-D

Select Variable Ctrl-A

Close Window Ctrl-W

Insert Code Ctrl-I

Select User Interface Constant Enter

Common Keyboard Shortcuts

Common Function Panel Shortcuts

There are many shortcutsavailable to speed up yourdevelopment! Pop-upmenus and toolbar shortcutsare also available.

Page 50: CVI Basics I (Course Manual).pdf

LabWindows/CVI Basics I Course Manual 46 © National Instruments Corporation

Lesson 2Creatin g 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

Page 51: CVI Basics I (Course Manual).pdf

LabWindows/CVI Basics I Course Manual 47 © National Instruments Corporation

Graphical User Interface

Decoration

CommandButton

Knob

LED Numeric Indicator Panel Strip Chart

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 createan application that has an associated GUI.

Page 52: CVI Basics I (Course Manual).pdf

LabWindows/CVI Basics I Course Manual 48 © National Instruments Corporation

User Interface Editor

The UserInterfaceEditor isused tocreate aGUI.

The User Interface Editor is the starting point for designing the layout of your graphicalprogram 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. Usethe tool bar beneath the menu bar for high-level editing with the mouse. When you click on aparticular tool, the mouse cursor changes to reflect the new editing mode.

Toolbar CommandsUse the Operating tool to operate objects. When you are in operate mode, eventsdisplay 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 mousebutton displays a color palette from which you can choose a color. Clicking with theleft mouse button automatically colors the object with the current color of the coloringtool. You can pick up a color from and existing object or colored area by holdingdown the <Ctrl> key (the tool changes to an eyedropper icon, ) and clicking on theobject.

Menu Bar CommandsAll of the functionality in the User Interface Editor is found in the User InterfaceEditor Menu commands. We will be reviewing these commands as we progressthrough this lesson. There are commands to create panels, create controls, arrangecontrols, generate code, etc. By the time you finish with this lesson, you will befamiliar with these commands.

Page 53: CVI Basics I (Course Manual).pdf

LabWindows/CVI Basics I Course Manual 49 © National Instruments Corporation

Creatin g a GUI

Above is an example of a simple GUI. This GUIconsists of a panel, a numeric control, threecommand buttons, and a graph.

Panel

NumericInput

CommandButtons

Graph

The GUI is the interface to your program that your users will see. Any functions in yourprogram 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 UserInterface Editor. LabWindows/CVI saves the user interface as a .uir file. Then, you use thecommands in the User Interface Library to load the .uir file and process the GUI controls andindicators.

Page 54: CVI Basics I (Course Manual).pdf

LabWindows/CVI Basics I Course Manual 50 © National Instruments Corporation

Creatin g a Panel

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

Page 55: CVI Basics I (Course Manual).pdf

LabWindows/CVI Basics I Course Manual 51 © National Instruments Corporation

Double-Click

Panel Pro perties

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

Panel PropertiesThe property page of the panel has four main sections. The top section is the Source CodeConnection. 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 willmake more sense as you start to program with them.

• Constant Name – The constant name (also called the Resource ID) for the panel. Youpass this ID to the LoadPanel function to load the panel into memory. The ConstantName 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 isgenerated 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 optionsfrom the Create menu.

Note: A UIR file can have multiple panels associated with it, provided that each panel has aunique Constant Name.

Page 56: CVI Basics I (Course Manual).pdf

LabWindows/CVI Basics I Course Manual 52 © National Instruments Corporation

Creatin g Controls

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

Page 57: CVI Basics I (Course Manual).pdf

LabWindows/CVI Basics I Course Manual 53 © National Instruments Corporation

Double-Click

Control Pro perties

Control PropertiesLike a panel, you can edit a control by double-clicking on it. Depending on the control beingedited, the Edit Control dialog box usually has six sections, titled Source Code Connection,Control Settings, Shortcut Key, Control Appearance, Quick Edit Windows, and LabelAppearance. (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 theother sections to set the different control attributes.

• Constant Name – The User Interface Editor appends the constant name of the control to theconstant name of the panel to create the Resource ID for the control. The Resource IDidentifies the control in any control-specific function such as GetCtrlVal (discussedshortly). The Resource ID is defined in the .h file when you save the .uir file. Forexample, the Resource ID for the control on this slide would be PANEL_GENERATE if itwere placed on the panel of the previous slide (the constant name of the panel is PANEL andthe constant name of the control is GENERATE). The “_” separates the panel constant nameand the control constant name.

• Callback Function – Type the name of the function to be called when an event is generatedon 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 willsave the user interface as a .uir file.

Page 58: CVI Basics I (Course Manual).pdf

LabWindows/CVI Basics I Course Manual 54 © National Instruments Corporation

The underline inQuit is created byplacing a doubleunderscore in theLabel field.

When a controlhas an underlinedcharacter, press<Alt-Char> toaccess it.

Control Labels, Shortcut Ke ys

When you create a control such as a command button, you can create special keys as shortcutsto the control. This can be done in two ways. One is to type a double underscore before anyletter in the label. When you do this, LabWindows/CVI underlines the character immediatelyfollowing 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 youaccess controls on pop-up panels.

For example, notice the underlined Q in the Quit button on the slide. To create this, place adouble 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 Keysection 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.

Page 59: CVI Basics I (Course Manual).pdf

LabWindows/CVI Basics I Course Manual 55 © 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 controlbecomes the next active control when the user presses <Tab> or <Shift-Tab>. Usually, you willset 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 acontrol, the new control sits immediately before the source control in the tab order. To put thepanel 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 thenumber in the Click to set to box. You can change the cursor to the special eyedropper cursorby holding down the <Ctrl> key. This eyedropper cursor changes the number in the Click to setto box to the current tab position associated with that control. The new tabbing order willappear in the black box on the right side of the control, while the original tab order will appearin the white box. Clicking on sets the new tab order. Clicking on keeps the original taborder.

Page 60: CVI Basics I (Course Manual).pdf

LabWindows/CVI Basics I Course Manual 56 © National Instruments Corporation

Checkbox toenable zooming

The LabWindows/CVIGraph Control hasbuilt-in zooming andpanning. Double-clickon the graph controlto set the EnableZooming option.

Graph Control Zoomin g

Zooming and Panning on GraphsYou can use zooming, the ability to expand or contract the viewport around a particular point inthe graph control. When you zoom in, the area of the graph shown in the viewpoint getssmaller, thereby showing the area with higher resolution. When you zoom out, the viewportshows 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 mustexplicitly enable them programmatically or in the User Interface Editor. Also, a graph controlmust be in Hot mode if zooming and panning are to be used. (Hot mode will be described laterin this lesson.)

To start zooming in on a point, press the <Ctrl> key and press the left mouse button with thecursor over the point to zoom in around. The resolution of the viewport is continuouslyincreased until you release the mouse. (You do not need to keep pressing the <Ctrl> key.) Ifyou 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 theleft mouse button.

To start panning, press <Ctrl-Shift> and the left mouse button with the cursor over a point onthe viewport. Drag the mouse to another point. The graph viewport is scrolled so that theoriginal point now appears under the new mouse cursor location. You can drag the mouseanywhere 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 whilezooming or panning. If any plotting occurs while the end user is zooming or panning, thezooming or panning is terminated and the new data is shown using autoscaling.

Page 61: CVI Basics I (Course Manual).pdf

LabWindows/CVI Basics I Course Manual 57 © National Instruments Corporation

The User InterfaceHeader File is thelink between theUIR and theapplicationprogram.

User Interface Header File

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 thecorresponding 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 Libraryfunctions). For this reason, you must include the .h file at the beginning of the applicationprogram.

Page 62: CVI Basics I (Course Manual).pdf

LabWindows/CVI Basics I Course Manual 58 © National Instruments Corporation

Exercise 2-1 (5 min.)

Objective: To view and run an application programcontaining a GUI.

Page 63: CVI Basics I (Course Manual).pdf

LabWindows/CVI Basics I Course Manual 59 © National Instruments Corporation

Exercise 2-2 (15 min.)

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

Page 64: CVI Basics I (Course Manual).pdf

LabWindows/CVI Basics I Course Manual 60 © National Instruments Corporation

Commonl y Used Controls - I

NumericControls

StringControls Text

Message

Text BoxControls

Command ButtonControls

Numeric ControlsNumeric controls are used to input or display numeric values. A typical use of these controls might be toinput 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) tochange the value of the control.

• Click on the scale labels to set the control to the value of the label.

String ControlsString controls are used to input or view a string of characters. You can use these controls to input user orinstrument information.

Text MessageText messages are indicators used to programmatically display strings of text. You cannot operate themusing the keyboard, but you can assign callback functions to them so that they respond to mouse-clickevents.

Text Box ControlsText box controls are large string controls that feature line, word, and character wrap modes as well asscroll bars to facilitate displaying large amounts of text. As with the string control, you can interactivelyenter text into the text boxes and you can control the text box programmatically.

Command Button ControlsCommand buttons are used to trigger an action, which is indicated by the label on the button. To operatea push button with the mouse, click on the button. The button remains depressed until the user releasesthe mouse button or moves it off the button.

Page 65: CVI Basics I (Course Manual).pdf

LabWindows/CVI Basics I Course Manual 61 © National Instruments Corporation

Commonl y Used Controls - II

Toggle ButtonControls

LED Controls

Binary SwitchControls

Ring Controls

Toggle Button ControlsToggle button controls allow you to select between two different states. A toggle button has twopositions: 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 itsstate.

LED ControlsLEDs (Light Emitting Diodes) indicate an on/off state. When the LED is on, its value is 1 and itdisplays its ON color. When the LED is off, its value is 0 and it displays its OFF color. LEDcontrols operate like toggle button controls.

Binary Switch ControlsBinary 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 operatelike toggle button controls

Ring ControlsYou use ring controls to select from a group of items. Many of the ring controls look likenumeric controls, but ring controls have a finite set of label/value pairs. Ring controls witharrows can be operated in a pop-up format by clicking in the text area of the control. This willdisplay all ring items in a linear list.

Page 66: CVI Basics I (Course Manual).pdf

LabWindows/CVI Basics I Course Manual 62 © National Instruments Corporation

DecorationsList Box

Strip ChartPicture

Commonl y Used Controls - III

List Box ControlsList 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 individualcharacters as well as create columns.DecorationsDecorations are used to enhance the visual appeal of the GUI. They do not contain data (theycan, however, contain bitmaps), but they can be assigned callback functions so that they canrespond to mouse clicks.Strip Chart ControlsStrip chart controls display graphical data in real time. A strip chart consists of one or moretraces that are updated simultaneously.Picture ControlsA picture control allows you to place images on panels, such as logos and diagrams. Forexample, you can use a picture control to place a schematic that instructs the user how to hookup a unit for testing. When you want to place images on a command button, toggle button, oron 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 PlatformPCX Windows and UNIXBMP, DIB, RLE, ICO Windows onlyXWD UNIX onlyWMF, EMF Windows 95 and NT only

Page 67: CVI Basics I (Course Manual).pdf

LabWindows/CVI Basics I Course Manual 63 © National Instruments Corporation

Graph

CanvasTimer

Commonl y Used Controls - IV

Graph ControlsGraph controls display graphical data as one or more plots. A plot consists of a curve, point, geometricshape, 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 untilthe user releases the mouse button and then it snaps to the nearest data point. If the cursor is infree-form mode, the cursor tracks the mouse until the user releases the mouse button and thenstays at the new position.

• Move the active cursor left and right by dragging the active cursor marker at the top or bottomedge of the plot area. Likewise, you can move the active cursor up and down by dragging theactive cursor marker at the left or right edge of the plot area.

Timer ControlsUse timer controls to trigger actions at specific time intervals. The timer control schedules these actionsso that you do not have to schedule them. Timer controls repeat a given action at a specified time intervalfor an indefinite period of time, which makes them useful programming tools when a repeated action isrequired. 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 InterfaceEditor. Timer controls will be discussed in greater detail later in this lesson.Canvas ControlsUse canvas controls as an arbitrary drawing surface. You can draw text, shapes, and bitmap images. Anoffscreen bitmap is maintained so the appearance of the canvas can be restored when the region isexposed. If you want to display images that are not rectangular or that have holes in them, you can usebitmaps that have a transparent background.

Page 68: CVI Basics I (Course Manual).pdf

LabWindows/CVI Basics I Course Manual 64 © National Instruments Corporation

Exercise 2-3 (15 min.)

Objective: To build a graphical user interface.

Page 69: CVI Basics I (Course Manual).pdf

LabWindows/CVI Basics I Course Manual 65 © National Instruments Corporation

User Interface Librar y

PanelsLoad Panel LoadPanelDisplay Panel DisplayPanel

Pop-up PanelsMessage Popup MessagePopup

Controls/Graphs/Strip Charts: General FunctionsSet Control Value SetCtrlValGet Control Value GetCtrlVal

User Interface ManagementRun User Interface RunUserInterfaceQuit User Interface QuitUserInterface

The User Interface Library contains many functions for programming the menus, panels, andcontrols in the .uir file. Among these functions are loading and displaying menu bars andpanels, controlling strip charts, graphs, push buttons and LEDs, and receiving user input fromthe objects in the .uir file.

The tables on this and the next page list the User Interface Library functions discussed in thislesson. The table is fashioned after the LabWindows/CVI User Interface Library menu.

Page 70: CVI Basics I (Course Manual).pdf

LabWindows/CVI Basics I Course Manual 66 © National Instruments Corporation

User Interface Librar y

Controls/Graphs/Strip Charts: Graphs and Strip Charts:Graph Plotting and Deleting

Plot Y PlotYDelete Graph Plot DeleteGraphPlot

Controls/Graphs/Strip Charts: Graphs and Strip Charts:Strip Chart Traces

Plot Strip Chart PlotStripChartClear Strip Chart ClearStripChart

Page 71: CVI Basics I (Course Manual).pdf

LabWindows/CVI Basics I Course Manual 67 © National Instruments Corporation

• Load panels

• Display panels

• Manipulatecontrols

Functions in theUser InterfaceLibrary areused to:

User Interface Librar y

Controlling a Graphical User InterfaceAfter you build your GUI, you must develop a C program to process the events generated from the userinterface and to control the flow of your program. LabWindows/CVI features two basic methods fordesigning your programs: callback functions and event loops. You can use either method in your programor 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 inthe .uir file. Among these are functions for loading and displaying menu bars and panels, controllingstrip 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 isnegative, an error occurred. Otherwise, the function completed successfully.

Loading a PanelTo load a panel into memory, use the LoadPanel function. LoadPanel returns a handle used toreference 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 specifythis panel.

parentPanelHandle: If you want this panel to appear inside of another panel, you specifythe panelHandle of the panel in which you want to display thispanel.

filename: The name of the .uir file in which the panel is saved.panelResourceID: The constant name that was given to this panel in the User Interface

Editor.

Page 72: CVI Basics I (Course Manual).pdf

LabWindows/CVI Basics I Course Manual 68 © National Instruments Corporation

User Interface Librar yContinued

Displaying a PanelLoading a panel does not automatically display it. Use the DisplayPanel function to display apanel.

int status = DisplayPanel (int panelHandle);

The panelHandle parameter is the value returned from LoadPanel and determines whichpanel 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 toStandard or Extended. To change the Debugging Level, go to the Project Windows, andfrom 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 checkfor errors as shown in the example on the previous page.

Page 73: CVI Basics I (Course Manual).pdf

LabWindows/CVI Basics I Course Manual 69 © National Instruments Corporation

SetCtrlVal isused to updatethe value of acontrol on theuser interface

Set Control Value

Setting Control ValuesYou use the SetCtrlVal function to set the value of a panel control. The value can be aninteger, a floating point, a string, and so on. It must match the data type of the control beingmodified.

int status = SetCtrlVal (int panelHandle, int controlID, voidvalue);

panelHandle the value returned from LoadPanelcontrolID the Resource ID of the control to modifyvalue 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. Thefirst SetCtrlVal function displays the value of buffer (“Hello”) in the string indicatorPANEL_STROUT. The second SetCtrlVal function displays the value of number (1.23) inthe numeric indicator PANEL_NUMOUT.

Note that the variable, number , and control object, “Numeric Output,” are both associated withthe data type of double. Run-time errors result when the datatype of the variable and the controlobject to do not match.

Page 74: CVI Basics I (Course Manual).pdf

LabWindows/CVI Basics I Course Manual 70 © National Instruments Corporation

GetCtrlVal isused to retrievethe value of acontrol on theuser interface

Get Control Value

Getting Control ValuesYou use the GetCtrlVal function to get the value from a panel control. The value can be aninteger, a floating point, a string, and so on. It must match the data type of the control beingqueried.

int status = GetCtrlVal (int panelHandle, int controlID, void*value);

panelHandle The value returned from LoadPanel .ControlID The Resource ID of the control to query.value 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. Thefirst GetCtrlVal function queries the string indicator PANEL_STRIN for its value and storesthe result in buffer (you can see the results of buffer in the variables window). The secondGetCtrlVal function queries the numeric indicator PANEL_NUMIN for its value and storesthe result in number . Notice that you must pass the address of number because its value ismodified in the function call.

Page 75: CVI Basics I (Course Manual).pdf

LabWindows/CVI Basics I Course Manual 71 © National Instruments Corporation

Attributes define thecharacteristics of an object

Set Control Attribute

Setting Control AttributesIn 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 leftand right axes, plot color, grid lines, and so on. Many of these attributes can be set in the UIReditor. Using SetCtrlAttribute , you can change the current value of an attributeprogrammatically.

int status = SetCtrlAttribute (int panelHandle, int controlID,int controlAttribute, ...);

panelHandle The value returned from LoadPanel .ControlID The Resource ID of the control to modify.ControlAttribute 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 firstSetCtrlAttribute function sets the color of the command button to BLUE. The secondSetCtrlAttribute function sets the top of the command button to be at pixel 20.

Page 76: CVI Basics I (Course Manual).pdf

LabWindows/CVI Basics I Course Manual 72 © National Instruments Corporation

Click

SetCtrlAttribute Function Panel

There are defined constants for each attribute that can be set. Remembering all of theseconstants is not necessary (or likely). LabWindows/CVI has special function panels that assistyou in finding the attributes you want to set. By left-clicking on the Control Attributeparameter in the function panel, you get a special dialog box that lists all the possible attributesorganized in a hierarchical fashion.

The dialog also presents the attributes in an easily understandable format with help on eachattribute. You can filter attributes for the particular control type you are working on bychanging the Control Type ring control.

Once the desired attribute has been selected, select OK to get back to the function panel.

Page 77: CVI Basics I (Course Manual).pdf

LabWindows/CVI Basics I Course Manual 73 © National Instruments Corporation

Press Enter

SetCtrlAttribute Function Panel

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

Page 78: CVI Basics I (Course Manual).pdf

LabWindows/CVI Basics I Course Manual 74 © National Instruments Corporation

Attributes define thecharacteristics of an object

Get Control Attribute

Getting Control AttributesNot only can you set the specific attributes of a control, you can also retrieve themprogrammatically. The function you use is called GetCtrlAttribute .

int status = GetCtrlAttribute(int panelHandle, int controlID, intcontrolAttribute, void *attributeValue);

panelHandle The value returned from LoadPanel .ControlID The Resource ID of the control to modify.ControlAttribute The attribute you want to query.AttributeValue 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 acontrol. The first GetCtrlAttribute queries the control for the pixel location of the topedge, while the second GetCtrlAttribute queries the control to determine whether or not itis visible.

Page 79: CVI Basics I (Course Manual).pdf

LabWindows/CVI Basics I Course Manual 75 © National Instruments Corporation

Panel Attributes

Panel AttributesPanels also have attributes associated with them. The functions used for setting or retrievingthem are called SetPanelAttribute and GetPanelAttribute .

int status = SetPanelAttribute(int panelHandle, intpanelAttribute, ...);

panelHandle The value returned from LoadPanel .PanelAttribute 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, intpanelAttribute, void *attributeValue);

panelHandle The value returned from LoadPanel .PanelAttribute The attribute you want to query.AttributeValue 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).

Page 80: CVI Basics I (Course Manual).pdf

LabWindows/CVI Basics I Course Manual 76 © National Instruments Corporation

Event Driven Pro grammin g

When you program with LabWindows/CVI, you are generating event-driven code. When youare using event-driven code, you are physically linking an object on the user interface (forexample, a command button) with a function in your code. Every time you perform an action onthe UIR control, an event is generated. LabWindows/CVI determines which control the eventoccurred on, and if you have a callback function associated with the control, the function isinvoked.

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 callbackfunction associated with it. For example, to pass information to and from the Num Cyclescontrol, use SetCtrlVal and GetCtrlVal .

Every callback function in LabWindows/CVI has the exact same prototype. The first parameteris the handle (not Constant name!) of the panel on which the control is located. The secondparameter is the Contstant ID of the control that generated the event. The third parameter iswhich event was generated that caused the callback function to be invoked. The fourthparameter is callback data, which is used to pass data between callback functions. This can beof any user-defined data type and is not discussed in this course. The fifth and sixth parametersare data generated with the event and are different for each event. We will discuss events andeventData1 and 2 shortly.

Page 81: CVI Basics I (Course Manual).pdf

LabWindows/CVI Basics I Course Manual 77 © National Instruments Corporation

You can usethe operatortool from thetoolbar toview thedifferent run-time eventsthat aregenerated

Viewin g Run-Time Events

The LabWindows/CVI graphical user interface editor has a convenient tool that allows theprogrammer to see what type of events are generated by certain actions on the GUI he or shecreates. 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 theevents you are generating. These are obviously slowed down so that they can be seen, but theevents 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 calledRunUserInterface . This function is generally called once in main after the first panel isloaded and displayed. RunUserInterface is the function that continually monitors the UIRfor 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 controland panel on which the events occur. This is important, because chances are you do not want aleft-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, theCVI programmer has a lot of versatility in how he or she controls the execution of the finalapplication.

Page 82: CVI Basics I (Course Manual).pdf

LabWindows/CVI Basics I Course Manual 78 © National Instruments Corporation

Event Type Event panel control eventData1 eventData2Controland MenuEvents

EVENT_COMMIT p c

ControlEvent

EVENT_VAL_CHANGED p c

Controland PanelEvent

EVENT_LEFT_CLICKEVENT_LEFT_DOUBLE_CLICKEVENT_RIGHT_CLICKEVENT_RIGHT_DOUBLE_CLICKEVENT_KEYPRESSEVENT_GOT_FOCUSEVENT_LOST_FOCUS

ppppppp

ccccccc

xxxx

key code

yyyy

ptr to keycode

PanelEvent

EVENT_CLOSEEVENT_PANEL_SIZEEVENT_PANEL_MOVE

ppp

ContinuousEvent

EVENT_TIMER_TICK ptr totime

ptr to timesince lasttick event

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

LabWindows/CVI Events

Applications written in LabWindows/CVI that take advantage of a GUI operate on a principlecalled event-driven programming. This simply means that unlike other text-based programs,which execute top to bottom, LabWindows/CVI executes segments of code (called callbackfunctions) in response to “events” that occur on the user interface. These events can occur onany object on the panel or on the panel itself. The basic events that CVI looks for are eventssuch as left-clicks, right-clicks, left and right double-clicks, and so on. In future lessons in thiscourse and the LabWindows/CVI Basics II course, you will see that CVI can respond to eventsother than the simple ones discussed here. For example, you can have a serial port generate anevent when a certain number of bytes have been received, or if your application is set up to runas 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. Afew of the less self-explanatory events are given below:

EVENT_COMMIT – A control generates a commit event when you click on a control withthe left mouse button and release the mouse button while still on top of the control, or ifyou select a control and press <Enter>. This is valid only if the control mode is set toHot or Validate.

EVENT_GOT_FOCUS and EVENT_LOST_FOCUS – A control generates a got focusevent when it is made the active control. To make the control the active control, you caneither 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 . Thisproject is an example of the different events that you will be able to see on a typical userinterface.

Page 83: CVI Basics I (Course Manual).pdf

LabWindows/CVI Basics I Course Manual 79 © National Instruments Corporation

Control Modes

Control ModesControls in LabWindows/CVI have four different control modes.

Normal specifies that the user can operate the control and that it can be changedprogrammatically.

Hot is identical to normal except that the control generates a commit event when acted on by theuser. 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 programvalidates 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 invalidcondition, LabWindows/CVI activates the control, causing a notification box to display. Thevalidate control cannot generate a commit event until the user enters a new valid value into allcontrols that are out of range. This process ensures that all numeric/scalar controls are validbefore the commit event is reported to your application program.

Indicator specifies that you can change the control programmatically, but users cannot generatecommit or value-changed events. Strip chart and text message controls are always indicators.

Page 84: CVI Basics I (Course Manual).pdf

LabWindows/CVI Basics I Course Manual 80 © National Instruments Corporation

Processin g Events

RunUserInterface

QuitUserInterface

ProcessSystemEvents

When programming, it is not sufficient just to make applications that are functional. A good programmeralways makes sure that his or her program is also well behaved. When developing applications inLabWindows/CVI, it is very important to understand the way the workhorse functions operate. The threefunctions we will discuss in this section are RunUserInterface , QuitUserInterface , andProcessSystemEvents .

As we have just discussed and demonstrated, a callback function is called when an event occurs on anobject. 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 callbackfunction. What happens is that this new event is queued up, and its callback function executes when theapplication hits RunUserInterface again (that is, when execution returns from the currentlyexecuting function). This is generally not a problem, unless the callback the program is currently in takesa long time to execute. It could be a matter of seconds or even tens of seconds before the programresponds 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 inCVI. 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 anypoint in the program, the programmer can make an explicit call to ProcessSystemEvents , eveninside a callback function. This can come in handy when you know that a particular callback will take along time to execute and you want to make sure that other events are being handled. When the code hitsProcessSystemEvents , it goes out and executes any callbacks that may have been queued up andthen returns to continue where it left off.

Page 85: CVI Basics I (Course Manual).pdf

LabWindows/CVI Basics I Course Manual 81 © National Instruments Corporation

Relationship ofRun/QuitUserInterface

General relationship between RunUserInterfaceand QuitUserInterface

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

Page 86: CVI Basics I (Course Manual).pdf

LabWindows/CVI Basics I Course Manual 82 © National Instruments Corporation

Exercise 2-4 (20-25 min.)

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

Page 87: CVI Basics I (Course Manual).pdf

LabWindows/CVI Basics I Course Manual 83 © National Instruments Corporation

The CVICode Buildermakes thedevelopmentof yourapplicationeasier andfaster.

Code Builder

To make the development of your application easier and faster, LabWindows/CVI has abuilt-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 theCode » Preferences menu of the User Interface Editor. You then make modifications tothe 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, selectCode » Generate » All Code. Code builder will ask you to select a function that will bethe quit function because applications generally have at least one callback that callsQuitUserInterface . Code builder creates the main function for you and generatesa callback function for each object you specified as needing a callback function from theUser Interface editor. In the main function, any panels you select from the code buildermenu are loaded and displayed if you select this as an option when generating the code.

Page 88: CVI Basics I (Course Manual).pdf

LabWindows/CVI Basics I Course Manual 84 © National Instruments Corporation

Select Code » Preferences » DefaultControl Events

“Skeleton code” is createdfrom the preferences selected

Code Builder

You can select the different “Default” events that are monitored in your program byselecting Code » Preferences » Default Control/Panel Events.

The screen shot above shows the screen for Default Control Events. Notice that youcan select many of the events discussed previously for each control. In this screen, wehave checked EVENT_COMMIT and EVENT_RIGHT_CLICK. When we selectGenerate All Code, a skeleton code (as shown in the slide above) is created. Notice thatthe events we chose in our preferences are generated in the C code.

Page 89: CVI Basics I (Course Manual).pdf

LabWindows/CVI Basics I Course Manual 85 © National Instruments Corporation

Exercise 2-5 (10 min.)

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

Page 90: CVI Basics I (Course Manual).pdf

LabWindows/CVI Basics I Course Manual 86 © National Instruments Corporation

Exercise 2-6 (10 min.)

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

Page 91: CVI Basics I (Course Manual).pdf

LabWindows/CVI Basics I Course Manual 87 © National Instruments Corporation

MessagePopup ("LabWindows/CVI”, "CVI Rocks");

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

ConfirmPopup ("This is a ConfirmPopup”, "Press Yes or No");

Pop-Up Panels

LabWindows/CVI has a number of high-level pop-up panels that can be called. Thesepanels will simply pop up and wait for the user to address them before the programcontinues.

The simplest of these is MessagePopup . MessagePopup takes two parameters; the firstdetermines 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 functionreturns which button was pressed.

Another convenient pop-up panel is PromptPopup . This function will pop up a messagethat prompts the user for a response string before moving on. The parameters are like theMessagePopup parameters, but include variables to store the response and an integer tolimit the length of the response.

These pop-up panels and many others can be found in the User Interface Library under thePop-Up Panels subclass.

Page 92: CVI Basics I (Course Manual).pdf

LabWindows/CVI Basics I Course Manual 88 © National Instruments Corporation

• Use a timer tocarry out periodictasks.

• When a timer tickoccurs, the timercallback functionis invoked.

Timer Control

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 tooccur. One of the most common of these is a timer. A timer is a special type of control that theprogrammer can place on the user interface that continuously generates an event(EVENT_TIMER_TICK) at a periodic interval throughout the duration of the application. Thisevent 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 atank. Because it is unlikely that these values will change rapidly, the application can probablyget by just checking these values once per second. A timer could be set up so that once persecond, 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 UserInterface Editor. This timer will not appear at runtime, so you can place it anywhere. Bydouble-clicking on the timer object, you will pop up the Edit Timer screen. The callbackfunction in the Source Code Connection block determines which function is called every timethe timer goes off. The Interval input controls how often the timer goes off. The unit isseconds 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. Thecode placed in this case statement is executed once per interval.

Just as you can programmatically perform functions on other controls in the user interface, thereare functions that can be called to regulate the behavior of timers. For example, a call can bemade to SuspendTimerCallbacks to temporarily suspend all timers, andResumeTimerCallbacks can re-enable them. ResetTimer can be used to reset theinterval start time for a timer. Just like all other controls, you can use SetCtrlAttributeto modify the specific attributes for a given timer, such as its interval and whether or not it isactive.

Page 93: CVI Basics I (Course Manual).pdf

LabWindows/CVI Basics I Course Manual 89 © National Instruments Corporation

Strip charts are used todisplay continuouslyacquired data.

Strip Charts

You use the PlotStripChart function to plot points on a strip chart.

int status = PlotStripchart (int panelHandle, intcontrolID, void *yArray, int numberOfPoints,int startingIndex, int skipCount, intyDataType);

Using the PlotStripChart function can be confusing at first, because you must passthe point in an array. Although this passing may appear awkward at first, you can use itto plot multiple traces on a strip chart. Assuming one point is plotted per trace, eachelement in the array contains the point for each trace. The entire trace would be plottedby 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 1yArray[1] = value for trace 2yArray[n-1] = value for trace n

numberOfPoints is the number of points to be added to the strip chart. If you areadding 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 mostcases, startingIndex is zero, and skipCount is also zero. yDataType specifiesthe data type for the yArray .

The example in the slide shows a strip chart with one trace. Timers are often used tocollect data and display it on a strip chart.

Page 94: CVI Basics I (Course Manual).pdf

LabWindows/CVI Basics I Course Manual 90 © National Instruments Corporation

You can display morethan one trace at a time.

Strip Charts

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 thisby 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 The handle returned from LoadPanel for the panel that the stripchart is on.

controlID The Resource ID of the strip chart to clear.

Page 95: CVI Basics I (Course Manual).pdf

LabWindows/CVI Basics I Course Manual 91 © National Instruments Corporation

Strip Charts

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

Page 96: CVI Basics I (Course Manual).pdf

LabWindows/CVI Basics I Course Manual 92 © National Instruments Corporation

Exercise 2-7 (25 min.)

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

Page 97: CVI Basics I (Course Manual).pdf

LabWindows/CVI Basics I Course Manual 93 © National Instruments Corporation

Exercise 2-8 (30 min.)(Challen ge/Optional)

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

Page 98: CVI Basics I (Course Manual).pdf

LabWindows/CVI Basics I Course Manual 94 © National Instruments Corporation

Summar y 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

Page 99: CVI Basics I (Course Manual).pdf

LabWindows/CVI Basics I Course Manual 95 © National Instruments Corporation

Lesson 3Data Acquisition

Objectives:• Learn about data acquisition basics: analog-to-digital

theory, signal processing, system configuration, boardconsiderations, etc.

• Learn about DAQ ECHO controls and how to build aDAQ 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 associatedLabWindows/CVI functions. The LabWindows/CVI Data Acquisition Library containsfunctions to perform a wide range of acquisition and control operations. The supportedinterface buses span the spectrum of ISA, EISA, PCMCIA, PCI, Sbus, NuBus, PXI, USB, andparallel.

LabWindows/CVI provides three levels of DAQ functionality: DAQ ECHO controls, the EasyI/O Library, and the Data Acquisition Library. In this course, we will focus on DAQ ECHOcontrols and the Easy I/O Library, which are easy to use and provide the flexibility necessary formost DAQ applications.

Page 100: CVI Basics I (Course Manual).pdf

LabWindows/CVI Basics I Course Manual 96 © National Instruments Corporation

- Reduces the complexityof building a dataacquisition (DAQ) system

- Saves you time byguiding you through theselection process andmaking recommendations

- Ensures that you select allthe products andcomponents you need

DAQ Desi gner

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 nowmerged into one system. National Instruments data acquisition boards can provide a varietyof 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 boarddepends on the signal sources, physical environment, financial resources, computer systemlimitations, grounding schemes, data acquisition components, performance requirements,and much more. To simplify the data acquisition selection process, you can use NationalInstruments DAQ Designer. This software application serves as a decision aid when itcomes to selecting the proper board for your application.

DAQ Designer is available for free from National Instruments and will quickly help youidentify the necessary system components and accessories best suited for your dataacquisition solution. You can obtain a copy of DAQ Designer from our web site, request aDAQ 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 signalacquisition hardware, digital I/O, computer-based instruments (such as oscilloscopes,arbitrary waveform generators, etc.), signal conditioning modules, and motion control. As acomputer-aided selection tool, DAQ Designer will help you navigate through the NationalInstruments product line and help reduce your decision-making time.

Page 101: CVI Basics I (Course Manual).pdf

LabWindows/CVI Basics I Course Manual 97 © National Instruments Corporation

Exercise 3-1 (15 min.)

Objective: To explore the functionality of DAQ Designer.

Page 102: CVI Basics I (Course Manual).pdf

LabWindows/CVI Basics I Course Manual 98 © National Instruments Corporation

A - Desktop PC with aplug-in DAQ board

B - Laptop computer witha PCMCIA-DAQ

DAQ System Components

B

A

The fundamental task of a DAQ system is the measurement or generation of real-worldphysical signals, where a signal is a physical phenomenon whose magnitude varies withtime. 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 bya computer-based system, there are several factors that must be taken into consideration: thesignal measurement system, signal conversion, and signal conditioning.

This signal measurement system involves understanding the importance of ground, differenttypes of signal sources, and how one implements measurements. The method by which onemeasures system or chassis ground throughout the instrumentation system may lead to thepickup 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 ofdata obtained, because the integrity of acquired data depends on the entire analog or digitalsignal path. Depending on the signal source chosen, this will determine the type ofmeasurement system needed (single ended, nonreferenced single ended, and differential).

Signal conversion is necessary because physical signals may not be in a format that isdesirable for the instrumentation system. More often than not, the format of choice is eithercurrent or voltage. Therefore, physical signals such as strain, pressure, temperature, etc.,must be converted to electrical signals through a device called a transducer. Examples oftransducers include thermocouples, RTDs (Resistive Thermal Devices), strain gauges,photoelectric cells, piezoelectric crystals, and many others.

Page 103: CVI Basics I (Course Manual).pdf

LabWindows/CVI Basics I Course Manual 99 © National Instruments Corporation

DAQ System ComponentsContinued

In addition, unlike most standalone instruments, sometimes you may not be able to connecta converted signal to a data acquisition board directly. Before the signal can be connectedto a DAQ board, you might need to insert a signal-conditioning accessory, such as aNational Instruments SCXI module, to modify the incoming electrical signal. Factors thatmay 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 thiscourse, but they are important enough to mention when you are designing a data acquisitionsystem.

Once the signal measurement system, signal conversion, and signal conditioning have beenintegrated into the total system, you can take subsequent steps to build the DAQ application.

Page 104: CVI Basics I (Course Manual).pdf

LabWindows/CVI Basics I Course Manual 100 © National Instruments Corporation

DAQ Software Architecture Windows 95

LabWindows/CVI

DAQ Import LibraryNI-DAQ Configuration Utility

Win95 Device Manager

nidaq32.dll for Win95

Win95 Registry

DAQ Board

DAQ-STC

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 operatingsystem assigns the necessary hardware resources. Legacy boards contain dip-switches and jumpersfor 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 settingsof other boards in the system.

Regardless of whether or not the board is PnP, the DAQ board must be configured through softwareusing the NI-DAQ driver software. For this class, the boards have been configured already. Thefollowing 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 therequired files for LabWindows/CVI DAQ onto your computer. LabWindows/CVI for Windows 95DAQ functions use an import library, dataacq.lib , to access the National Instruments standardNI-DAQ for Windows 95 32-bit dynamic link library (DLL). The NI-DAQ setup program installsthe NIDAQ32.DLL in the windows\system directory. NI-DAQ for Windows 95 supports allNational Instruments DAQ Boards and SCXI modules. The NIDAQ32.DLL file, the high-levelinterface to your board, is loaded in the Windows 95 System directory. The NIDAQ32.DLL filethen interfaces with the Windows 95 Registry to obtain the configuration parameters defined by theNI-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 95Configuration Manager automatically detects and configures your board. If you have a non-PnPboard (known as a legacy device) you must configure the board manually using the Windows 95Add New Hardware option under the Control Panel.

Page 105: CVI Basics I (Course Manual).pdf

LabWindows/CVI Basics I Course Manual 101 © National Instruments Corporation

DAQ Software Architecture

• Use the NI-DAQConfiguration Utility toconfigure your DAQcards

• Information is stored inthe Windows 95Registry andniconfig.daq

• Start » Programs »CVI » NI-DAQConfiguration 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 listsall DAQ boards installed in your computer. Highlight a DAQ board and select Propertiesor 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 theboard. You use the Resources tab to specify the system resources to the board such asinterrupt levels, DMA, and base address for software configurable boards.

NI-DAQ for Windows 95 installs the NI-DAQ Configuration Utility, which establishes allboard configuration parameters. After installing a DAQ board in your computer andconfiguring the board with the Device Manager as described above, you must run thisconfiguration utility. The utility reads the information that the device manager records inthe Windows 95 registry and assigns a logical device number to each DAQ board. You usethe device number to refer to the board in LabWindows/CVI. You access the configurationutility by selecting Start » Programs » CVI » NI-DAQ Configuration Utility . The figureabove shows the primary NI-DAQ Configuration Utility window. The NI-DAQConfiguration Utility is also the means for SCXI configuration. The board parameters thatyou can set using the configuration utility depend on the board. The configuration utilitysaves the logical device number and configuration parameters in the Windows 95 registry.

Page 106: CVI Basics I (Course Manual).pdf

LabWindows/CVI Basics I Course Manual 102 © National Instruments Corporation

Exercise 3-2 (10 min.)

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

Page 107: CVI Basics I (Course Manual).pdf

LabWindows/CVI Basics I Course Manual 103 © National Instruments Corporation

DAQ ECHO Controls

• Extended Code Hierarchy Object

• Easily output and acquire signals from your DAQhardware 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 havebeen extended to have DAQ capabilities. Currently, there are two types of DAQ ECHO controlsavailable: DAQ Numerics and DAQ Charts. A DAQ Numeric is simply a user interface display suchas a tank, thermometer, or knob that is automatically tied to an analog channel. You can set a DAQNumeric to any input or output channel, including SCXI channels. A DAQ Chart is a strip chart thatcan be tied to one or more analog input channels, and it features display, alarm, and data loggingcapabilities.

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 thedaq_num.fp driver to create and configure DAQ-based numeric controls and the daqchart.fpdriver to create and configure DAQ-based charts. With DAQ ECHO controls, you can output andacquire signals from your National Instruments data acquisition hardware with very littleprogramming. You can customize the operation of DAQ controls at run-time by simply right-clickingon the control and changing the user-configurable properties.

For more information regarding DAQ ECHO controls, select Help » Search for Help on…. TypeECHO 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 thecontrol is in output mode, the value is tied to an associated analog channel. When the control is ininput mode, its value is periodically updated by reading the voltage from its associated analog inputchannel at the rate specified by the refresh frequency.

DAQ Chart Controls – A DAQ Chart control is a strip chart that automatically reads and plots datafrom its associated input channels. DAQ Charts maintain a history buffer containing the acquired dataand can be configured to watch for alarm conditions and log data to disk. The input channels, dataacquisition rate, and so on can be configured programmatically or interactively.

Page 108: CVI Basics I (Course Manual).pdf

LabWindows/CVI Basics I Course Manual 104 © National Instruments Corporation

Exercise 3-3 (15 min.)

Objective: To build a DAQ application quickly usingECHO controls.

Page 109: CVI Basics I (Course Manual).pdf

LabWindows/CVI Basics I Course Manual 105 © National Instruments Corporation

Easy I/O Librar y

• The Easy I/O for DAQ Library makes it easier to writeDAQ programs

• You will use the Easy I/O for DAQ Library in thiscourse

• 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 justused the Data Acquisition Library. The Easy I/O for DAQ Library implements a subset of theData Acquisition Library functionality, but it does not use the same functions. The table on thenext 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. Ifthere is a problem during function execution, the function returns a nonzero value. You can find alist of error codes for an Easy I/O for DAQ function by right-clicking on the Error control in itsfunction panel. Also, you can call the GetDAQErrorString function for a description of thenumeric error codes returned by function calls in the Easy I/O for DAQ Library.

char *GetDAQErrorString (short errorNumber);

Page 110: CVI Basics I (Course Manual).pdf

LabWindows/CVI Basics I Course Manual 106 © National Instruments Corporation

Easy I/O Librar yFunctions

Easy I/O for DAQ Function Names:

Analog InputAISampleChannelAISampleChannelsAIAcquireWaveformsAIAcquireTriggeredWaveformsAsynchronous Acquisition

AIStartAcquisitionAICheckAcquisitionAIReadAcquisitionAIClearAcquisitionPlotLastAIWaveformsPopup

Analog OutputAOUpdateChannelAOUpdateChannelsAOGenerateWaveformsAOClearWaveforms

Digital Input/OutputReadFromDigitalLineReadFromDigitalPortWriteToDigitalLineWriteToDigitalPortCounterReadCounterStopICounterControl

MiscellaneousGetDAQErrorStringGetNumChannelsGetChannelIndicesGetChannelNameFromIndexGetAILimitsOfChannelGroupByChannelSetEasyIOMultitaskingMode

Page 111: CVI Basics I (Course Manual).pdf

LabWindows/CVI Basics I Course Manual 107 © National Instruments Corporation

Single-Ended vs. Differential

Resolution

Analo g Input Considerations

Range

Gain

Analog InputThe 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 thataffect the digitized signal quality: single-ended and differential inputs, resolution, range, samplingrate, and noise.

Analog Input ConsiderationsSingle-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. Thedrawback is that in differential mode, only half the number of channels are available, as compared tosingle-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 preferredconfiguration. For the best accuracy and good noise immunity, the desired input mode isdifferential.

Resolution: Resolution is the number of bits that the analog-digital converter (ADC) used torepresent the analog signal. The higher the resolution, the higher the number of divisions into whichthe range is divided, and therefore, the smaller the detectable voltage change. The figure in the slideshows 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 signalis not a good representation of the original signal because information is lost in the conversion. Byincreasing the resolution to 16 bits, however, the ADC’s number of codes increases from eight to 65,536 (216), and it can obtain an extremely accurate representation of the analog signal.

Page 112: CVI Basics I (Course Manual).pdf

LabWindows/CVI Basics I Course Manual 108 © National Instruments Corporation

Analo g Input Considerations

Range: Range refers to the minimum and maximum voltage levels that the ADC canquantize. DAQ boards offer selectable ranges (typically 0 to 10 V or –10 to 10 V) to matchthe signal range to that of the ADC and to take advantage of the resolution available toaccurately measure the signal.

Gain: Gain refers to any amplification or attenuation of a signal that may occur before thesignal is digitized. By applying gain to a signal, you can effectively decrease the inputrange of an ADC and thus allow the ADC to use as many of the available digital divisionsas possible to represent the signal. For example, using a 3-bit ADC and a range setting of0 to 10 V, the figure in the slide shows the effects of applying gain to a signal that fluctuatesbetween 0 and 5 V.

With no gain applied, or gain = 1, the ADC uses only four of the eight divisions in theconversion. By amplifying the signal with a gain of two before digitizing, the ADC nowuses 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 signalabove 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 willautomatically supply the correct gain for the analog-to-digital converter.

Note: This gain is used only for precision in the analog-to-digital conversion. Thevoltage level measured with the NI-DAQ driver will be readjusted to the correct level afterthe signal has been digitized.

Page 113: CVI Basics I (Course Manual).pdf

LabWindows/CVI Basics I Course Manual 109 © National Instruments Corporation

Analo g Input Considerations

Sampling RateAdequately Sampled

Aliased due to undersampling

10

1 * 216= 0.15 mVCode Width

range

gain*

2resolution in bits

Noise

in bitsresolutiongain

rangecode width

2×=

ragedpoints avenumber of /1

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

Sampling Rate: Sampling rate determines how often the conversions take place. A fast sampling rate acquiresmore points in a given time and therefore can often form a better representation of the original signal than aslow sampling rate. All input signals must be sampled at a sufficiently fast rate to faithfully reproduce theanalog signal. According to the Nyquist Sampling Theorem, you must sample at least twice the rate of themaximum 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 theother hand, temperature transducers usually do not require a high sampling rate because temperature does notchange rapidly in most applications. Therefore, a board with a slower sampling rate can acquire temperaturesignals properly.

Noise: Unwanted noise distorts the analog signal before it is converted to a digital signal. The source of thisnoise may be external or internal to the computer. You can limit external noise by using proper signalconditioning and/or differential input mode. You can also minimize the effects of this noise by over-samplingthe signal and then averaging the over-sampled points. The reduction in noise is linearly proportional to:

For example, if you average 100 points, the effect of the noise is the signal is reduced to 10% of the originalnoise.

Note: The individual and accumulative effects of these factors require that preplanning and understandingof the entire data acquisition system be taken into consideration.

Page 114: CVI Basics I (Course Manual).pdf

LabWindows/CVI Basics I Course Manual 110 © National Instruments Corporation

Samplin g Analo g Channels - I

short AISampleChannel (short device, charsingleChannel[], double highLimitVolts,double lowLimitVolts, double *voltage);

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

Parameters

Acquiring a single voltage from a single input channel

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 andlowLimitVolts . These parameters are used internally by NI-DAQ to specify the gain.By using the best values of highLimitVolts and lowLimitVolts , you will get themost accurate digital representation possible.

Page 115: CVI Basics I (Course Manual).pdf

LabWindows/CVI Basics I Course Manual 111 © National Instruments Corporation

Samplin g Analo g Channels - II

short AISampleChannels (short device, charchannelString[], double highLimitVolts,double lowLimitVolts, doublevoltageArray[]);

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 channelvoltages

Parameters

Acquiring a single voltage from multiple channels

Page 116: CVI Basics I (Course Manual).pdf

LabWindows/CVI Basics I Course Manual 112 © National Instruments Corporation

Samplin g Analo g Channels - III

short AIAcquireWaveforms (short device, charchannelString[], double numberOfScans, doublescanSecond, double highLimitVolts, doublelowLimitVolts, double *actualScanRate, shortfillMode, double waveforms[]);

numberOfScans: number of scans to acquirescanSecond: number of scans to perform per second

(timed by the DAQ hardware)

Parameters

Acquiring multiple voltages from multiple channels

actualScanRate: actual scan rate at which the acquisitiontook place

fill mode: group by scan or group by channelwaveforms: array containing the scanned data

AIAcquireWaveforms performs a timed acquisition of voltage data from the analogchannels specified by channelString[].

A Scan is defined as one sample from every channel. The parameter scanSecond is thenumber of scans to perform every second. This parameter is analogous to the sample ratebecause one scan is the equivalent of one sample from every channel. Because the actualscan rate can vary from the requested scan rate (due to hardware limitations or otherexternal factors), the actualScanRate is used in calculations to make the data accurate.

Page 117: CVI Basics I (Course Manual).pdf

LabWindows/CVI Basics I Course Manual 113 © National Instruments Corporation

Different Fill Modes

Group-By-Scan

Group-By-Channel

Ch 1Pt 0

Ch 2Pt 0

Ch 1Pt 1

Ch 2Pt 1 • • •

Ch 1Pt 998

Ch 2Pt 998

Ch 1Pt 999

Ch 2Pt 999

Ch 1Pt 0

Ch 1Pt 1 • • •

Ch 1Pt 999

Ch 2Pt 0

Ch 2Pt 1 • • •

Ch 2Pt 999

0 2 3 1996 1997 1998 19991

0 999 1000 1001 19991

Channel 1 data Channel 2 data

If you are acquiring data from channels 1 and 2 and placing it into an array called buffer, thegroup-by-scan mode places the data in the buffer in the following manner (depicted in the toppicture of the slide). Data is collected in scans (which you will recall is a data point from everychannel). The hardware will read a voltage from channel one and then a voltage from channel2. This will alternate until all of the data is collected. The data is placed into the array in theorder it was received.

In the group-by-channel mode, the data is placed in the buffer in the following manner (depictedin the bottom picture of the slide). Data is collected the same way, but instead of writing data tothe array in the order it was received, it is placed in the array as if you collected all the data fromchannel 1 and then all of the data from channel 2. Therefore, the first data point collected (fromchannel 1) will go into the first entry into the array. Then, the second data point collected (thefirst point from channel 2) will be placed into the array at the point after where all of channel1’s 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/CVIacquires 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 andindependent of the computer you are using.

Page 118: CVI Basics I (Course Manual).pdf

LabWindows/CVI Basics I Course Manual 114 © National Instruments Corporation

Samplin g Analo g Channels - IV

short PlotLastAIWaveformsPopup (short device,double waveformsBuffer[]);

device: board ID specified by the NI-DAQ ConfigurationUtility

waveformsBuffer: array containing the scanned data

Parameters

Quickly displaying timed analog 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 byAIAcquireWaveforms , you can use the Easy I/O for DAQ Library functionPlotLastAIWaveformsPopup .

PlotLastAIWaveformsPopup plots the last waveform that was acquired from the functionAIAcquireWaveforms . The data must be grouped by channel mode before it is passed tothis function. If you acquired the data in group-by-scan mode, you can call GroupbyChannel(Easy I/O for DAQ: Miscellaneous) before calling PlotLastAIWaveformsPopup .

Page 119: CVI Basics I (Course Manual).pdf

LabWindows/CVI Basics I Course Manual 115 © National Instruments Corporation

The DAQ Si gnal Accessor y

The exercises in this lesson use the DAQ Signal Accessory. Here are some of the highlights ofthis 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 inthe lower central portion of the top panel. The IC temperature sensor is hard-wired toAI channel 0 and is located in the lower-right corner of the top panel. Thetemperature sensor will return a voltage between 0 V and 1 V, corresponding to 0 °Cand 100 °C, respectively.

• Analog output channels 0 and 1 are available at the quick connect terminal located atthe lower central portion of the top panel.

• The function generator is located in the lower central portion of the top panel. Itproduces a sine wave and a square wave. Use the Frequency Range selector switchto select a frequency range and then use the Frequency Adjust knob next to it tofurther adjust the frequency.

• There is a row of four LEDs in the middle of the DAQ Signal Accessory thatcorrespond to Lines 0 to 3 on Port 0 of the MIO board. The four LEDs use invertedlogic.

Page 120: CVI Basics I (Course Manual).pdf

LabWindows/CVI Basics I Course Manual 116 © National Instruments Corporation

Exercise 3-4 (30 min.)

Objectives: I) To measure temperature using a DAQboard and plot it on a strip chart.II) To acquire waveforms from multiplechannels.

Page 121: CVI Basics I (Course Manual).pdf

LabWindows/CVI Basics I Course Manual 117 © National Instruments Corporation

Asynchronous Acquisition

• Returns immediately whileboard handles acquisition

• Data is stored in a circularbuffer

• Flowchart demonstratescontinuous, asynchronousacquisition

Start

Check Acquisition

Clear Acquisition

Buffer 1/2 Full?

Complete?

Read Acquisition

Stop

Start Acquisition

N

Y

N

Y

When you are not concerned with time in your DAQ applications, the aforementioned Easy I/Ofunctions serve their purpose well. However, if time is critical, the previously mentionedfunctions are synchronous, meaning that all the functions do not return control to your programuntil the DAQ board acquires all of the data points. If the acquisition takes a long time (forexample, acquiring many points at a very slow sample rate), the computer cannot perform othertasks if you use synchronous calls. The LabWindows/CVI Easy I/O for DAQ Library containsfunctions that you can use to collect data in the background, allowing other parts of yourprogram 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

Page 122: CVI Basics I (Course Manual).pdf

LabWindows/CVI Basics I Course Manual 118 © National Instruments Corporation

Asynchronous AcquisitionFunctions

• Allow you to perform other tasks while theDAQ 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, doublelowLimitVolts, double *actualScanRate, unsigned long*taskID);

device : board ID from the NI-DAQ configuration utilitychannelString[] : string representing the set of input channelsbufferSize : size of the circular buffer in scans. This must be an even numberscanSecond : number of scans to acquire per secondhighLimitVolts : maximum voltage to measurelowLimitVolts : minimum voltage to measureactualScanRate : actual rate at which the data was scannedtaskID : 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 : identifier for the asynchronous acquisition that was returned byAIStartAcquisition

scanBacklog : number of scans that have been acquired into the circular bufferbut have not been read using AIReadAcquisition

Page 123: CVI Basics I (Course Manual).pdf

LabWindows/CVI Basics I Course Manual 119 © National Instruments Corporation

Asynchronous AcquisitionContinued

Reading the Acquisition:short AIReadAcquisition (unsigned long taskID, long scansToRead,

unsigned short readMode, unsigned long *scanBacklog, shortfillMode, double waveforms[]);

taskID : identifier for the asynchronous acquisition that was returned byAIStartAcquisition

scansToRead: number of scans that will be read from the internal circular bufferreadMode: specifies whether to read the circular buffer starting from the last

scan that was read or to read the most recently acquired datascanBacklog : number of scans that have been acquired into the circular buffer

but have not been read using AIReadAcquisitionfillmode: group-by-scan or group-by-channelwaveforms: contains the voltages acquired

Clearing the Acquisition:short AIClearAcquisition (unsigned long taskID, unsigned long

*scanBacklog);

taskID : identifier for the asynchronous acquisition that was returned byAIStartAcquisition .

scanBacklog : number of scans that have been acquired into the circular bufferbut have not been read using AIReadAcquisition

Page 124: CVI Basics I (Course Manual).pdf

LabWindows/CVI Basics I Course Manual 120 © National Instruments Corporation

Exercise 3-5 (20 min.)

Objectives: To perform asynchronous timed analog inputusing callback functions.

Page 125: CVI Basics I (Course Manual).pdf

LabWindows/CVI Basics I Course Manual 121 © National Instruments Corporation

Analo g 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 OutputThough analog input is the most common type of data acquisition, there are times when you need togenerate analog voltages for purposes such as waveform generation, power sources, excitation, etc.National Instruments multifunction DAQ boards contain digital-to-analog (DAC) converters that cangenerate required output voltages.

FactorsRange: 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 toanalog input accuracy – the higher the DAC resolution, the higher the number of digitallevels, and hence, the higher the accuracy. Also, as the DAC range increases, the DACaccuracy decreases.

Monotonicity: A DAC is monotonic if its analog output increases as the digital inputincreases.

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 fora full-range change in voltage. Settling time and slew rate work together in determininghow fast the DAC can change the output signal level. A DAC with a small settling timeand a high slew rate can generate high frequency signals because little time is needed toaccurately change the output to a new voltage level.

Page 126: CVI Basics I (Course Manual).pdf

LabWindows/CVI Basics I Course Manual 122 © National Instruments Corporation

Analo g OutputFunctions

• Allow you to output voltages from yourDAQ board

• Uses three functions:

• AOUpdateChannel

• AOUpdateChannels

• AOGenerateWaveforms

Single Point to a Channel:short AOUpdateChannel (short device, char singleChannel[], double

voltage);

device : board ID from the NI-DAQ configuration utilitysingleChannel[] : analog channel where the voltage will be appliedvoltage : value that will be output to the analog channel

Single Point to Multiple Channels:short AOUpdateChannels (short device, char channelString[], double

voltageArray[]);

channelString[] : analog channel where the voltage will be appliedvoltageArray[] : 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, intiterations, double waveforms[], unsigned long *TaskID);

updatesPerSecond : how often a voltage will be applied per channelupdatesPerChannel : how many voltage values are stored in the array for each channeliterations : how many times to output the waveform. Pass a 0 for continuous

generation.taskID : handle for the waveform. This is used if you set iterations to 0.

You need to pass the taskID to AOClearWaveforms

Page 127: CVI Basics I (Course Manual).pdf

LabWindows/CVI Basics I Course Manual 123 © National Instruments Corporation

Exercise 3-6 (25 min.)

Objectives: To perform a single-point analog outputoperation.

Page 128: CVI Basics I (Course Manual).pdf

LabWindows/CVI Basics I Course Manual 124 © National Instruments Corporation

Digital Input/Output

• Digital lines are grouped as ports

• For the AT-MIO-16E-2, there are eight lines toa 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/OutputFeatures of the digital input and output functions vary depending on the type of DAQ board, buta few features remain constant for all types of DAQ boards. The Easy I/O for DAQ librarytakes 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 MIOboard used in this class). The digital I/O functions can write to and read from an entire port or asingle digital line within a port.

To write to an entire port, the functions write a binary pattern to the port to generate a digitaloutput. To read from a port, the function return a byte of data as a digital input pattern. Themapping of the byte value to the digital I/O lines follows the line numbering. (For example, line0 is the least significant bit and line 7 is the most significant bit for an 8-bit port.) When a portis configured as an input port, reading that port returns the value of the digital lines. In thiscase, external devices connected to and driving digital lines determine the state of those lines. Ifno external device is driving the lines, the lines float to some indeterminate state and can be readin either state 0 or state 1. If a port is configured as an output port, writing to the port sets eachdigital 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 readfrom and which line within that port you want to retrieve the value from. The resultant answeris either a one (logical high) or a zero (logical low). To write to a line, you specify the port andline that you want to change the state of and write a one (TTL high) or a zero (TTL low) tothe port.

Page 129: CVI Basics I (Course Manual).pdf

LabWindows/CVI Basics I Course Manual 125 © 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 : the board ID specified in the NI-DAQ Configuration UtilityportNumber[] : which port to read the pattern fromportWidth : total width of the port in bitsconfigure : specifies whether to configure the digital port before reading.

When calling ReadFromDigitalPort in a loop, you canincrease performance by configuring the digital port only on thefirst iteration

pattern : passed by reference, this variable contains the data read fromthe port

Writing to a Digital Port:short WriteToDigitalPort (short device, char portNumber[], short

portWidth, long configure, unsigned long pattern);

device : the board ID specified in the NI-DAQ Configuration UtilityportNumber[] : which port to write the pattern toportWidth : total width of the port in bitsconfigure : specifies whether to configure the digital port before writingpattern : this variable specifies the new state of the lines in the port

Page 130: CVI Basics I (Course Manual).pdf

LabWindows/CVI Basics I Course Manual 126 © 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 : the board ID specified in the NI-DAQ Configuration UtilityportNumber[] : which port to read the pattern fromline : the individual bit or line within the port used for I/OportWidth : total width of the port in bitsconfigure : specifies whether to configure the digital port before readinglineState : 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 longlineState);

device : the board ID specified in the NI-DAQ Configuration UtilityportNumber[] : which port to write toline : the individual bit or line within the port used for I/OportWidth : total width of the port in bitsconfigure : specifies whether to configure the digital port before readinglineState : specifies the new state of the digital line. lineState can be

either a zero (TTL low) or a one (TTL high)

Page 131: CVI Basics I (Course Manual).pdf

LabWindows/CVI Basics I Course Manual 127 © National Instruments Corporation

Exercise 3-7 (15 min.)

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

Page 132: CVI Basics I (Course Manual).pdf

LabWindows/CVI Basics I Course Manual 128 © National Instruments Corporation

Summar y 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 forDAQ Library also features timed analog input capabilities.

• You can use the Easy I/O for DAQ Library function to outputanalog voltages and perform digital I/O operations.

• The User Interface and Analysis Libraries include functions toview and analyze the data acquired with the Easy I/O for DAQLibrary.

• LabWindows/CVI uses the asynchronous functions from the EasyI/O for DAQ Library to collect data in the background. Thisfeature is very useful if you are performing other tasks during thedata acquisition.

Page 133: CVI Basics I (Course Manual).pdf

LabWindows/CVI Basics I Course Manual 129 © National Instruments Corporation

Lesson 4Formattin g and Scannin g

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

Page 134: CVI Basics I (Course Manual).pdf

LabWindows/CVI Basics I Course Manual 130 © National Instruments Corporation

Data Conversion

Binary Value Decimal ASCII

0100 0001 65 ‘A’

0011 0100 54 ‘6’

0011 0101 53 ‘5’

• Decimal 65 stored differently than ASCII 65

• Use data conversion to convert from ASCII to decimaland 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 convertdecimal 65 to the characters “6” and “5” (“65”)

Data Representation and ConversionIn the world of computers, there are many ways to store data. If you look at the data foundon contemporary machines, you can notice that it ranges from ordinary ASCII files (inhuman-readable form), to binary stored integer and floating-point numbers, to encrypteddata. Different computers also have different ways of looking into this data when it ispresented to them in the binary form (for example, Big Endian and Little Endian machinesdiffer 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 hasaccess to formatted input and output functions from the standard library such as printf ,scanf , etc. Those functions, in conjunction with getchar , putchar , atoi , atof andsimilar, are sufficient for any data manipulation, whether we talk about strings andcharacters, long and short integers, or single- and double-precision floating-point numbers.

Page 135: CVI Basics I (Course Manual).pdf

LabWindows/CVI Basics I Course Manual 131 © National Instruments Corporation

LabWindows/CVI vs. ANSI

In addition to these, LabWindows/CVI offers its own Formatting and I/O library. Functionsfrom this library provide more powerful tools for putting together and breaking down yourdata structures, whether we are talking about strings of characters, arrays of floating-pointnumbers, or any combination of basic data types. All that in one function call! Naturally, toget such a power, you need to give up the simplicity of the formatting strings of ANSI Cfunctions. For example, printing the famous “Hello, world!” with ANSI C printf functionwould look like this:

printf (“ %s\n” , “ Hello, world!” );

And using CVI’s 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 everydayoutputs 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 basicrules for drafting this formatting string will make even the most complicated conversionseasy.

Let us introduce the main functions that are covered in this chapter. Depending on youroutput target or input source (memory, file, or Standard I/O window), you have threeformatting and scanning options to choose from. As with their ANSI siblings, thesefunctions also take a variable number of arguments and format the output according to thegiven formatting string.

Page 136: CVI Basics I (Course Manual).pdf

LabWindows/CVI Basics I Course Manual 132 © National Instruments Corporation

Formattin g 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 FunctionsThese functions allow you to convert datatypes. The Fmt, FmtFile , and FmtOut functions differonly 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 StringsThe formatting and scanning functions use format strings to determine how to convert the sourceargument(s) into the target argument(s). The format string is actually a mini-program that tells theformatting/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 thetarget(s). The syntax shows that formatting functions build a single target from multiple sourcesand scanning functions break a single source into multiple targets.

Page 137: CVI Basics I (Course Manual).pdf

LabWindows/CVI Basics I Course Manual 133 © National Instruments Corporation

Scannin g 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

Page 138: CVI Basics I (Course Manual).pdf

LabWindows/CVI Basics I Course Manual 134 © National Instruments Corporation

Format Codes

%s %100f %i[b2u]

% repetitions format code [modifiers]

Always preceded by a %

Three components - repetitions, format code, andformat modifier

Common format codes - s, i, d, x, f, c

Format String SpecifiersThe 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 arepetition code. If the code is omitted, a one (1) is implied. This parameter indicates howmany times the Fmt or Scan function should apply the particular format specifier. Thisparameter is useful when formatting arrays of numeric data. Repcodes are not allowedwhen the format code is a string (s). formatcode indicates the nature or type of dataelement. The commonly used types are:

s string datai,d integer datax integer data in hexadecimal formatf real numberc character

A few commonly used modifiers are:bn The b modifier specifies the length of the integer argument in bytespn The p modifier specifies to what precision to convert a floating-point numberx The x modifier tells a scanning function to discard the terminatort n The t modifier tells a scanning function to terminate on a particular characteru The u modifier tells a scanning function to treat an integer as unsigned

Page 139: CVI Basics I (Course Manual).pdf

LabWindows/CVI Basics I Course Manual 135 © National Instruments Corporation

Arra y Formattin g Example

Equivalent

For most of the examples on the next few pages, we will provide you with both theLabWindows/CVI method of data conversion and the ANSI C method of data conversionfor comparison.

We will start with a simple task of outputting the members of a double-precision array onthe screen. To display an array of five double-precision numbers on the standard I/Owindows with ANSI C functions, it takes a loop and a printf statement. With theFormatting function, it takes only one statement. Notice that the output of each of thesefunctions is the same. Because both methods produce the same result, you can use eithermethod in your program. As we start to discuss more complex formatting, you will see thatthe 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 elementsin the array. We are also using two modifiers, [p2] and [w5] . The [p2] modifierspecifies 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 willnotice that each number took exactly five characters in the Standard I/O window (four forthe number and one for the space in between the numbers).

Page 140: CVI Basics I (Course Manual).pdf

LabWindows/CVI Basics I Course Manual 136 © National Instruments Corporation

Arra y Scannin g Example

Similarly, the task of converting the string output of an instrument into a data array may besimplified by using Scan functions. Assuming that the instrument returns a string with commadelimited single-precision numbers, the conversion may be done with the ANSI sscanffunction. Using the LabWindows/CVI Scan function, you can avoid having to list all thearguments.

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-pointnumbers. Accordingly, the %d and the %f formatting codes assume 32-bit integers and 64-bitfloats respectively. Therefore it is necessary to place the [b4] modifier for single-precisionnumbers in formatting strings and the [b2] modifier for short integers. The [x] modifierindicates that the numbers in the original string are delimited by a character, and we want toremove it from the final result.

Page 141: CVI Basics I (Course Manual).pdf

LabWindows/CVI Basics I Course Manual 137 © National Instruments Corporation

Removin g 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. Toignore a part of the string, ANSI formatting strings use an asterisk. The Scan functionuses the [d] modifier for discarding the data. It indicates that there is no target argumentfor 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.

Page 142: CVI Basics I (Course Manual).pdf

LabWindows/CVI Basics I Course Manual 138 © National Instruments Corporation

Modif ying Byte Order

Note: This operation can be executed in place - itdoes 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 limitedto your computer only and does not involve any external hardware that may have been built usingdifferent chips. However, if your application will establish some kind of binary connection with otherhardware (or software), you must take care of your data format.

Let’s 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 inthe case of communication with hardware, CVI talks to the device driver, which is essentially a softwarecomponent.) Let’s further assume that this component accepts only binary data and that it accepts it inthe 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 theSun CPU stores the data the same way. If, however, you are on a PC, you must do some data conversionfirst before sending it out. The solution can be a simple loop that goes through all the numbers in thearray and swaps the array elements. This solution is good, but it is also platform dependent. It will workon a PC platform, but if you use the same source code on the Sun platform, swapping is unnecessary andwrong in that case. LabWindows/CVI offers the modifier that solves this problem in one line (nounnecessary looping and swapping) and the solution is platform independent – your array will always beof 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 ofprecedence) as compared to [01] , which would be an ascending order of precedence.

Page 143: CVI Basics I (Course Manual).pdf

LabWindows/CVI Basics I Course Manual 139 © National Instruments Corporation

Discardin g Unwanted Data

Sometimes you are particularly interested in a character in the string: something either beginswith it or ends when that character is encountered. This example shows how to extract theinformation 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 areinterested in dividing the email address around the “@” to create separate strings with the username and the domain name.

The [t n] modifier indicates the character on which scanning should terminate. The ASCIIcode for “@” is 64; thus, [t64] indicates that we should terminate the first %s when we seethe @ symbol. The [x] modifier instructs LabWindows/CVI to skip over the “@” characteritself and not store it with either of the strings. If [x] was not used, the domain name stringwould have included the “@” character.

Note that if you didn’t want to save the user name, you could have added the [d] modifier, andthe Scan function would have discarded the user name.

Page 144: CVI Basics I (Course Manual).pdf

LabWindows/CVI Basics I Course Manual 140 © National Instruments Corporation

Formattin g 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 ofmodifiers, refer to the Formatting and Scanning Modifiers section in the appendix.

Page 145: CVI Basics I (Course Manual).pdf

LabWindows/CVI Basics I Course Manual 141 © National Instruments Corporation

Exercise 4-1 (15 min.)

Objective: To use a Scanning function to parse a datastring.

Page 146: CVI Basics I (Course Manual).pdf

LabWindows/CVI Basics I Course Manual 142 © National Instruments Corporation

Summar y 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 thedata from an unusable form to a usable form.

Example: If you have a string of numeric data from an instrument, you need toconvert the data from its string format to its decimal format to be able tomanipulate it.

Example: If you have an array of numeric data and you need to save it to disk, youmay 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 standardANSI C conversion functions such as sprintf , sscanf , etc.

LabWindows/CVI has powerful additional conversion functions that are easier to useand faster than the ANSI C counterpoints.

Page 147: CVI Basics I (Course Manual).pdf

LabWindows/CVI Basics I Course Manual 143 © National Instruments Corporation

Lesson 5General-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 high-level and low-level functions for communicating across the GPIB. High-level functionsautomatically execute sequences of commands that handle all necessary bus managementoperations while writing to or reading from a device. Low-level functions perform fundamentalbus management operations and require knowledge of the GPIB protocol.

This lesson introduces you to the GPIB Library. It explains how to establish communicationwith a device using a combination of high-level and low-level GPIB functions.

Page 148: CVI Basics I (Course Manual).pdf

LabWindows/CVI Basics I Course Manual 144 © 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 ofElectrical and Electronic Engineers, Inc. (IEEE) standardized the GPIB bus in 1975 asIEEE 488. The terms GPIB, HP-IB, and IEEE 488 are all synonymous. The originalpurpose of GPIB was to allow computer control of test and measurement instruments;however, given that GPIB is quite versatile, applications also include computer-to-computercommunication and control of scanners and film recorders.

Because the original IEEE 488 document contained no guidelines for preferred syntax andformat conventions, work continued on the specification to enhance system compatibilityand configurability among test systems. This work resulted in a supplemental standard –IEEE 488.2, Codes, Formats, Protocols, and Common Commands – that you use withIEEE 488 (which was renamed to IEEE 488.1).

Page 149: CVI Basics I (Course Manual).pdf

LabWindows/CVI Basics I Course Manual 145 © 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 busmanagement lines (ATN, EOI, IFC, REN, and SRQ), three handshaking lines (DAV,NRFD, and NDAC), and eight ground lines. GPIB communication uses an 8-bit paralleldata transfer scheme. With this data transfer scheme, whole bytes are sequentiallyhandshaked 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, GPIBprovides 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 additionto) the EOI line assertion. Finally, the listener(s) can count the number of bytes handshakedand stop reading when a byte count limit is reached. The byte count method is most oftenused as a default terminator because the transfer stops on the logical OR of EOI, EOS (ifused), and byte count. Thus, you typically set the byte count equal to or (slightly) largerthan the expected number of bytes to read.

Page 150: CVI Basics I (Course Manual).pdf

LabWindows/CVI Basics I Course Manual 146 © National Instruments Corporation

GPIB Common Terms

• Primary Address

• System Controller

• Controller-in-Charge

• Talker/Listener

• Commands

• Data

Primary AddressEvery device, including the computer interface card, must have a unique primary GPIBaddress between 0 and 30. Primary address 0 is normally assigned to the GPIB interfaceboard. The instruments on the GPIB can use addresses 1-30.

System ControllerThe GPIB bus can have only one System Controller (usually your computer) that performsall 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 drivingthe ATN line. You can have multiple instruments capable of being a controller, but you canhave only one active controller (controller in charge) at any given time.

Talkers and ListenersThe GPIB allows the bus to have one talker and one or more listeners. A talker is thedevice that is sourcing data bytes, while a listener is a device that is receiving the data.

Commands and DataTo transfer instrument commands and data on the bus, the controller in charge addressesone Talker and one or more Listeners. To perform addressing, the controller sendscommands. Commands are ASCII bytes that are sent with the ATN line active. Onceeverybody is addressed, the ATN line is dropped and data begins to be transferred from thetalker to the listener(s). The high-level LabWindows/CVI GPIB functions automaticallyaddress talkers and listeners.

Page 151: CVI Basics I (Course Manual).pdf

LabWindows/CVI Basics I Course Manual 147 © National Instruments Corporation

GPIB Global Variables - ibsta

Mnemonic Bit Hex Type DescriptionERR 15 8000 dev, brd GPIB error

TIMO 14 4000 dev, brd Time limit exceededEND 13 2000 dev, brd END or EOS detectedSRQI 12 1000 brd SRQ interrupt receivedRQS 11 800 dev Device requesting service

CMPL 8 100 dev, brd I/O completedLOK 7 80 brd Lockout StateREM 6 40 brd Remote StateCIC 5 20 brd Controller-In-ChargeATN 4 10 brd Attention is assertedTACS 3 8 brd TalkerLACS 2 4 brd ListenerDTAS 1 2 brd Device Trigger StateDCAS 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 . Thesevariables 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, andiberr updates when a GPIB error occurs. These three variables are very useful fordebugging 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 – ibstaAll GPIB functions return a status word (16 bits) containing specific information about thestate of the GPIB bus. If the most significant bit is set, a GPIB error has occurred. Thetable 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.

Page 152: CVI Basics I (Course Manual).pdf

LabWindows/CVI Basics I Course Manual 148 © National Instruments Corporation

GPIB Global Variables - iberrMnemonic Value Meaning

EDVR 0 System errorECIC 1 Function requires GPIB board to be CICENOL 2 No Listeners on the GPIBEADR 3 GPIB board not addressed correctlyEARG 4 Invalid argument to function callESAC 5 GPIB board not System Controller as requiredEABO 6 I/O operation aborted (timeout)ENEB 7 Nonexistent GPIB boardEDMA 8 DMA errorEOIP 10 Asynchronous I/O in progressECAP 11 No capability for operationEFSO 12 File system errorEBUS 14 GPIB bus errorESTB 15 Serial poll status byte queue overflowESRQ 16 SRQ stuck in ON positionETAB 20 Table problem

© 1998 National Instruments Corporation. All Rights Reserved.

GPIB Error – iberriberr will indicate which GPIB error occurred. If the ERR bit of ibsta is not set, thevalue 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 installedcorrectly or you are trying to access a device that doesn’t exist.

ENOL: This means that there are no listeners at the address you are trying tocommunicate to. Verify the Primary Address of the instrument.

EADR: This means that there is an addressing error. This is usually caused byhaving the primary address of the GPIB board set to the same address as theinstrument you are trying to communicate with.

EABO: This means that driver aborted the operation. This is usually seen on aGPIB read and is an indication that you wrote a command to the instrumentthat it didn’t understand. Either verify spelling or look in the user manual ofthe instrument for valid commands.

EBUS: This is a bus error. It usually means that there are no instruments connectedto your computer or that all of the instruments are turned off.

GPIB Count – ibcntThe count variable contains the number of bytes transferred to or from the GPIB through theinterface card. This is also used when you get an EDVR error to indicate which driver erroroccurred. 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.

Page 153: CVI Basics I (Course Manual).pdf

LabWindows/CVI Basics I Course Manual 149 © National Instruments Corporation

GPIB Communication

• Open/Close• Find Board/Device ibfind• Find Unused Device ibdev• Online/Offline ibonl

• Configuration• Change Config Parameter ibconfig

• Bus Control• Send Interface Clear ibsic• Set/Clear Remote Enable ibsre

• I/O• Write ibwrt• Read 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 isthe philosophy of device handles. Usually, at the beginning of your program you will opena 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 beused in subsequent function calls to refer to that particular session. The 488.1 commandscan either be board level or device level. If the handle passed to the function is that of aboard, it is known as a “board-level function”; if the handle that is passed to the function isthat of a device, it is known as a “device-level function.” When you use a board-levelfunction, you must manually perform low-level bus addressing. However, the device-levelfunctions 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 forthe primary address of the device(s) to talk to. We will use the 488.1 functions in thiscourse. The functions we will use are listed on the slide above.

Page 154: CVI Basics I (Course Manual).pdf

LabWindows/CVI Basics I Course Manual 150 © National Instruments Corporation

Openin g/Closin g Devices - I

• Open a device

• ibfind - open session to board/device

• ibdev - open session to device

• Both return a handle which is used insubsequent calls

• Close a device

• ibonl - close session to board or device

Opening and Closing DevicesBefore using a LabWindows/CVI GPIB function (488.1 only) to communicate with aninstrument, you must open a handle to the device with either the ibfind or ibdevfunction. When you open a session to a device using either function, it returns an integervalue called the unit descriptor. To communicate to a particular device in all subsequentoperations, such as ibwrt or ibrd , you reference the device using the unit descriptor.

Find Board/Deviceibfind opens a session to a GPIB board or to a preconfigured device that is configured inthe device template. ibfind returns a unit descriptor used in all references to that board ordevice in subsequent GPIB functions. If ibfind cannot get a valid descriptor, –1 isreturned.

int board/device = ibfind (char *board/deviceName);

board/deviceName : This is a string containing a default or preconfigured device orboard name. The device strings are assigned in the devicetemplate, which can be found in the Device Manager, GPIBControl Panel, or ibconf (depending on your particular OS). Theboard names can be found in the configuration utility for theparticular board (also found in the Device Manager, GPIBControl Panel, or ibconf).

Page 155: CVI Basics I (Course Manual).pdf

LabWindows/CVI Basics I Course Manual 151 © National Instruments Corporation

Openin g/Closin g Devices - I

General Programming Flow:

• Open and configure all devices

• Communicate with all devices

• Close all sessions to devices

Find Unused Deviceibdev 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 (thatis, Primary Address, Board Index, Timeout Value). By using ibdev , you make your code moreportable across computers by not relying on a specific device template. ibdev returns a unit descriptorused in all references to that device in subsequent GPIB functions. If ibdev cannot get a validdescriptor, a –1 is returned.

int device = ibdev (int boardIndex, int primaryAddress, intsecondaryAddress, int timeoutValue, int ENDMessage, intEOSCharacter);

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 validvalues 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 isyes/0 is no) for write operations.

EOSCharacter : Used to configure the driver to stop transmitting data when you send a particularEOS character and/or terminate its read when it detects the particular EOS character. Forvalid values, refer to the NI-488.2(M) Function Reference Manual or look at the functionpanel help.

Page 156: CVI Basics I (Course Manual).pdf

LabWindows/CVI Basics I Course Manual 152 © National Instruments Corporation

Openin g/Closin g Devices - II

Example using ibfind , ibdev , and ibonl

Online/OfflineWhen you use either ibdev or ibfind , you are creating an entry into a tablecreated by the driver. Because this table has only a finite number of entries availableto store unit descriptors, you should close all unit descriptors when you are finishedwith them. The function call used to close a device is called ibonl . This functioneither 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 usingibfind ).

int status = ibonl (int board/device, int operationMode);

board/device : The unit descriptor returned by ibfind or ibdevoperationMode : Determines whether the device should be placed offline (0) or

reset to its original configuration (1)

Page 157: CVI Basics I (Course Manual).pdf

LabWindows/CVI Basics I Course Manual 153 © National Instruments Corporation

Confi guration

ibconfig allows you to programmatically changethe attributes of a given instrument.

ConfigurationThe GPIB Library allows you to modify the configuration of your GPIB interfaceprogrammatically. This allows you the flexibility to reconfigure your board/devicewhenever necessary.

Change Config Paramerteribconfig modifies the settings of a particular board or device. There are two setsof 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, thedevice options are in use.

int Status = ibconfig (int board/device, int option, intvalue);

board/device : The unit descriptor returned by ibfind or ibdev

option : A number or macro specifying which configurable item you want tochange. For a list of options, see your NI-488.2(M) Function ReferenceManual or check the ibconfig function panel.

value : The value to which you want to set the particular option

Page 158: CVI Basics I (Course Manual).pdf

LabWindows/CVI Basics I Course Manual 154 © National Instruments Corporation

Bus Control

Using ibsic and ibsre allows you to set thebus into a known state.

Bus ControlThe GPIB Library offers a variety of functions to handle bus configuration. The two functionsdiscussed in this section are ibsic and ibsre .

Send Interface ClearThis function causes the GPIB board to assert the Interface Clear (IFC) signal for at least 100 µSprovided the GPIB board has System Controller Capability. This places all devices on the GPIBbus into a known quiescent state and makes the interface board Controller-in-Charge. This actionmust initially be done to establish Controller status. It is a good habit always to use this action atthe beginning of your code.

int status = ibsic (int board);

board : The unit descriptor returned by ibfind

Set/Clear Remote EnableThis function (ibsre ) turns the Remote Enable (REN) signal on and off. Devices use the RENline to select between local and remote mode. Many older devices require this line to be assertedbefore you can control them via GPIB. It is a good habit to always use this at the beginning ofyour code.

int status = ibsre (int board, int lineStatus);

board : The unit descriptor returned by ibfindoperationMode : Specifies whether to assert (1) or unassert (0) the REN line

Page 159: CVI Basics I (Course Manual).pdf

LabWindows/CVI Basics I Course Manual 155 © National Instruments Corporation

Input/Output

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

Input/OutputThe GPIB Library contains many functions that handle all aspects of GPIBcommunication. The most important and most frequently used functions are the writeand read functions. These two functions are discussed below.

WriteThis 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 ibdevdataBuffer : Contains the data to be sent over the GPIBbyteCount : Specifies the number of bytes to be written. It is usually the string

length of dataBuffer .ReadThis 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 ibdevdataBuffer : The variable where the data that is read from the GPIB will be storedbyteCount : Specifies the maximum number of bytes to be read.

Page 160: CVI Basics I (Course Manual).pdf

LabWindows/CVI Basics I Course Manual 156 © National Instruments Corporation

Exercise 5-1 (25 min)

Objective: To establish communication with a GPIB instrument.

Page 161: CVI Basics I (Course Manual).pdf

LabWindows/CVI Basics I Course Manual 157 © National Instruments Corporation

Exercise 5-2 (30 min)

Objective: To continuously obtain data from the devicesimulator using GPIB.

Page 162: CVI Basics I (Course Manual).pdf

LabWindows/CVI Basics I Course Manual 158 © National Instruments Corporation

GPIB Service Requests

• Callbacks• Install Synchronous Callback ibInstallCallback• Install Asynchronous Callback ibnotify

• Device Control• Get Serial Poll Byte ibrsp

In GPIB communication, the controller dictates when tasks are performed. No device cancommunicate unless it is addressed to talk. A device may, however, need to communicate withthe controller before the controller tells it to talk. To do this, any device can assert the SRQline, 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 longtime to collect a data point. You want the instrument to send that data to the controller as soonas 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 apotential 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 collectingdata so that the controller can then start reading it. The controller will acknowledge the servicerequest by polling to determine which instrument needs service. Once the controller finds thecorrect instrument, it will interpret the status byte and act appropriately. By using servicerequests, you can allow your system to do other work while your instrument is collecting data.

Page 163: CVI Basics I (Course Manual).pdf

LabWindows/CVI Basics I Course Manual 159 © National Instruments Corporation

Serial Pollin g

• SRQ line indicates an instrument needs service

• Serial poll instruments to determine whorequested service

• Automatic Serial Poll

• Manual Serial Poll

• Serial Poll Status Byte determines if and why theinstrument requested service

• Bit 6 of the byte determines if the instrumentrequested service

• All other bits are instrument defined

The purpose of the SRQ line is to signal the controller that a device needs service. Whenthe SRQ line is asserted, it is the responsibility of the Controller to determine who requestedservice by checking all devices individually. A serial poll obtains specific information froma 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 byasserting the SRQ line. The device uses the other seven bits of the status byte to specifywhy it needs attention.

Automatic Serial PollingBy default, whenever the SRQ line is asserted, our GPIB driver will conduct a serial poll ofevery instrument connected to the bus and determine which instruments asserted the SRQline. The driver informs you as to which instrument asserted the line by setting the RQS bitof the instruments ibsta (you can get the ibsta value for any instrument by callingibwait with the unit descriptor of the instrument as the first parameter). Thisphenomenon is known as AutoSerialPolling and can be turned on in the configuration utilityor 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 ibwaitbut use the unit descriptor of the GPIB board). The SRQI bit will inform you that at leastone instrument is requesting service. You must then serial poll all the instruments todetermine which instrument(s) is requesting service.

Page 164: CVI Basics I (Course Manual).pdf

LabWindows/CVI Basics I Course Manual 160 © National Instruments Corporation

488.2 Service Request Model

488.2 Status ModelWhile 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 differentregister 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 theinstrument 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 Registerwill generate an SRQ. For example, if you write a 0x10 (decimal 16) to the SRE register, that willinstruct the instrument to generate an SRQ when it has a message available.

Get Serial Poll Status Byteibrsp serially polls a device and returns its status response. The response consists of a single bytein 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.1standard. In the IEEE 488.2 standard (see slide), bits 4 and 5 are also reserved.

int status = ibrsp (int device, char *serialPollResponse);

device : The unit descriptor returned from ibdev or ibfindserialPollResponse : 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 requestingservice.

Page 165: CVI Basics I (Course Manual).pdf

LabWindows/CVI Basics I Course Manual 161 © National Instruments Corporation

GPIB Service Requests

GPIB ExampleThe example on the slide shows how you would serial poll an instrument. There are afew 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 simplemethod would be to use a while loop similar to the one below:

while (!done) {ibwait (board, 0); // update the statusif (ibsta & SRQI) // check for the SRQ line

done = 1;}

The string “*SRE 0x10; *IDN?” causes the instrument to assert the SRQ line whenever ithas finished generating its identification. It does this by writing a 0x10 (which sets theMAV mask) to the SRE register. This causes the instrument to assert the SRQ wheneverit has a message available. The *IDN? is going to cause the instrument to generate amessage.

With serial polling, first check to see whether or not bit 6 is asserted. This will let youknow whether or not the instrument is asserting the SRQ line. Then, check to seewhether or not the instrument is requesting service because of MAV (we could havemany different if/case statements checking for other device-dependent bits).

Page 166: CVI Basics I (Course Manual).pdf

LabWindows/CVI Basics I Course Manual 162 © National Instruments Corporation

Service Request Callbacks

Using ibInstallCallback• Prototype the Callback Function

• Install the callback using ibInstallCallback

• Callback occurs synchronously uponoccurrence 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 statusbyte. Now you need a way to detect the SRQ line being asserted to begin the serial pollprocess. Keeping with its callback structure, LabWindows/CVI provides two uniquefunctions that will notify the application when an SRQ occurs. These two functions areibInstallCallback and ibnotify .

ibInstallCallback (synchronous)

int ibInstallCallback (int board/device, int eventMask,GPIBCallbackPtr callbackFunction,void *callbackData);

board/device : The unit descriptor returned from ibfind or ibdeveventMask : The event(s) that cause the callback function to be invoked

(usually you will have an eventMask of 0x1000 to indicatethe SRQ line (see ibsta ))

callbackFunction : The function that will be invoked when the specified eventoccurs

callbackData : A void pointer to be used to pass data between callbackfunctions

This function allows you to install a synchronous callback function for a specified boardor device.

Page 167: CVI Basics I (Course Manual).pdf

LabWindows/CVI Basics I Course Manual 163 © National Instruments Corporation

Service Request Callbacks

The callback function is called when any GPIB event specified in the eventMaskparameter has occurred on the specified board or device. Because this callback functionis synchronous, it will be called only when the system is free to process events. Thesystem can process events when you call ProcessSystemEvents or have calledRunUserInterface and none of your callback functions is currently active. Thecallbacks 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 cando in a synchronous callback. However, the latency between the occurrence of a GPIBevent and the invocation of the callback function is greater with synchronous callbacksthan with asynchronous callbacks.

Only one callback function can apply for each board or device. Each call to this functionfor the same board or device supersedes the previous call. To disable callbacks for aboard or device, pass 0 as the eventMask parameter.

Page 168: CVI Basics I (Course Manual).pdf

LabWindows/CVI Basics I Course Manual 164 © National Instruments Corporation

Service Request Callbacks

Using ibnotify• Prototype the Callback Function

• Install the callback using ibnotify

• Callback occurs asynchronously upon occurrenceof event specified in eventMask

• Restrictions on operations in asynchronouscallbacks

• Refer to the course manual for more information.

Note: the callback function has a different prototype in ibnotifythan 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 particularboard or device. To install a synchronous callback, use the ibInstallCallbackfunction instead.

The callback function is called when any of the GPIB events specified in theeventMask parameter has occurred on the specified board or device. Unlike thesynchronous 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 ordevice. Each call to this function for the same board or device supersedes the previouscall. To disable callbacks for a board or device, pass a 0 for the eventMask parameter.

Page 169: CVI Basics I (Course Manual).pdf

LabWindows/CVI Basics I Course Manual 165 © National Instruments Corporation

Service Request Callbacks

Asynchronous Callback LimitationsAsynchronous callbacks can be called anytime while the system is running. You do notneed to allow the system to process events. This means that you are restricted in whatyou can do inside the asynchronous callback. Things that you can do inside anasynchronous callback are:

• Call PostDeferredCall (schedules a different callback to be calledsynchronously)

• 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 performfile I/O.

• Call malloc , calloc , realloc , or free

For more information about the restrictions, see the LabWindows/CVI Standard LibrariesReference Manual.

Note: ibnotify is supported on only the Windows 95 and Windows NT platforms. Touse ibnotify, you must be running version 1.1 or greater of the NI-488.2M software forWindows 95 or version 1.2 or greater of the NI-488.2M software for Windows NT.

Page 170: CVI Basics I (Course Manual).pdf

LabWindows/CVI Basics I Course Manual 166 © National Instruments Corporation

Exercise 5-3 (15 min.)

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

Page 171: CVI Basics I (Course Manual).pdf

LabWindows/CVI Basics I Course Manual 167 © National Instruments Corporation

Troubleshootin g GPIBProblems

National Instruments offers many ways to troubleshoot GPIB problems. The first step introubleshooting GPIB problems is to run the appropriate diagnostic utility (Diagnostics inWin95/NT, Hardware diagnostics and Software diagnostics in Windows 3.x, and ibtstain Solaris). This is a good way to verify that your hardware and software are correctlyinstalled. If they are not, please see your user manual on proper installation or contacttechnical support.

Once you have verified that your GPIB board and its driver are correctly installed, the nextstep is to determine whether or not your instrument is working. The easiest way to verifythat your instrument is working is to attempt communication. National Instrumentsprovides an interactive control program called ibic (on Windows platforms, it is called theWin16/32 Interactive Control). This program allows you to communicate directly with thedriver. By forgoing your application software, you can verify communication with yourinstrument.

Another advantage of the Win32 Interactive Control is the ability to verify yourprogramming philosophy. By interactively writing and reading from your instrument, youcan determine whether the command sequence you are using in your program is valid.

Page 172: CVI Basics I (Course Manual).pdf

LabWindows/CVI Basics I Course Manual 168 © National Instruments Corporation

Troubleshootin g : 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 Windowsdrivers (Win 3.x, Win95, and WinNT) is a utility called NI Spy or GPIB Spy. This utilitycaptures all calls made into the appropriate DLL (gpib.dll for Win 3.x, gpib-32.dll forWin95/NT) and reports the status of each call (ibsta , iberr , and ibcntl ). By determiningwhich calls are made into the driver, you can determine if the code you are writing is logicallycorrect.

Page 173: CVI Basics I (Course Manual).pdf

LabWindows/CVI Basics I Course Manual 169 © National Instruments Corporation

Troubleshootin g : GPIB Anal yzer

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 onthe GPIB. Whenever any of the five bus management lines or the three handshake lineschange state, all 16 hardware lines (24 total minus eight ground) are logged. With thisknowledge, you can determine whether a device is not handshaking correctly or whether thedata you are sending to or receiving from the instrument is the data you expect. With ananalyzer, 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 eventsif you do not have one of these three boards.

Page 174: CVI Basics I (Course Manual).pdf

LabWindows/CVI Basics I Course Manual 170 © National Instruments Corporation

Exercise 5-4 (15 min.)

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

Page 175: CVI Basics I (Course Manual).pdf

LabWindows/CVI Basics I Course Manual 171 © National Instruments Corporation

Summar y 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

Page 176: CVI Basics I (Course Manual).pdf

LabWindows/CVI Basics I Course Manual 172 © National Instruments Corporation

Lesson 6Serial 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 withgreater versatility. However, GPIB requires hardware that does not come standard with thecomputer. Another very common protocol for device communication that comes standard onjust about every PC is serial communication. Most computers include one or two RS-232-basedserial 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 fordata acquisition in conjunction with a remote sampling device. In this section, we will discussthe fundamentals of serial communication, establish serial communication usingLabWindows/CVI, use the LabWindows/CVI InstallComCallback function to obtain datafrom serial devices, and provide methods for debugging serial communication problems.

Page 177: CVI Basics I (Course Manual).pdf

LabWindows/CVI Basics I Course Manual 173 © 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 aprogramming 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 asRS-485 and RS-422, because these are less common, require extra hardware, and differ fromRS-232 only electrically. The above slide illustrates some of the similarities and differencesbetween RS-232, RS-485, and RS-422.

Page 178: CVI Basics I (Course Manual).pdf

LabWindows/CVI Basics I Course Manual 174 © National Instruments Corporation

Serial Communication Lines

• RS-232 data lines (single-ended)• TXD• RXD• GND

• RS-485 data lines (differential)• TXD+, TXD-• RXD+, RXD-

Pin DTE DCE

1 DCD Input Output2 RXD I O3 TXD O I4 DTR O I5 GND - -6 DSR I O7 RTS O I8 CTS I O9 RI I O

RS-232

The concept of serial communication is simple. The serial port sends and receives bytes ofinformation one bit at a time. Although this is slower than parallel communication, which couldsend 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 than20 meters total, with no more than 2 meters between any two devices; however, serial canextend as many as 1220 meters.

Typically, serial is used to transmit ASCII data. RS-232 communication is completed usingthree transmission lines: (1) Transmit, (2) Receive, and (3) Ground. To communicate, connectthe transmit line of one device to the receive line of another. Devices can have two differentconnectors, DTE and DCE. If you are connecting a DTE to a DCE, all you need to do is wireall of the pins straight through (pin 1 to pin 1, pin 2 to pin 2, etc.), but if you are wiring a DTEto a DTE or a DCE to a DCE, you need to swap transmit and receive lines, because they havethe same connector. This can be done easily with a NULL-Modem cable, which automaticallyswaps the transmit and receive lines on opposite ends of the cable.

Page 179: CVI Basics I (Course Manual).pdf

LabWindows/CVI Basics I Course Manual 175 © National Instruments Corporation

Handshakin g 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 islimited in being able to respond to problems such as the receiver being overloaded. This iswhere serial handshaking can help. You have three handshaking options regarding the transferof data over a serial connection: hardware handshaking, software handshaking, and nohandshaking.

Hardware handshaking requires that two addition lines be connected, CTS and RTS. When areceiver is ready for data, it asserts the RTS line, indicating it is ready to receive data. Thesender sees this input as CTS because, in a null modem cable, the CTS and RTS lines arecrossed. When the sender’s 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 thesender via the transmit line. The sender will then stop transfers until it sees the XON characterat its receive line.

With no handshaking, the sender transmits all information without verifying that the receivercan handle the data. If data is sent faster than the receiver can read, information is lost.

Page 180: CVI Basics I (Course Manual).pdf

LabWindows/CVI Basics I Course Manual 176 © National Instruments Corporation

Serial Confi gurationBaud Rate - Speed of communication (bits/sec)Data Bits - Number of bits used for data in a frameStop Bits - Signal end of frame transferParity - Bit used for error checking

The important serial characteristics are baud rate, data bits, stop bits, and parity. For two portsto 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. Aframe is defined as the number of bits sent to transfer one data byte. When the computer sendsa frame of information, the amount of actual data may not be 8 bits. Standard values for the databits parameter are 5, 7, and 8. Which setting you choose depends on the type of information youare transferring. For example, standard ASCII has values from 0 to 127 (7 bits). ExtendedASCII 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 ofall of the data bits in the communication (logic high equals one, logic low equals zero), it will beeither an odd number or an even number. The parity bit added to sum of the data bits createseither an even or odd number.

Page 181: CVI Basics I (Course Manual).pdf

LabWindows/CVI Basics I Course Manual 177 © National Instruments Corporation

Programmin g Methodolo gy

• 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 toyour COM port using the OpenComConfig function. This function will open a COM port andallow you to specify the baud rate, data bits, stop bits, and parity. LabWindows/CVI also allowsyou 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. Toguarantee that all bytes were written before closing the port, monitor the output queue with theGetOutQLen 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. Thecount specifies the number of bytes to write. strlen (ANCI C Library) determines the size ofa buffer. The value returned from strlen is often used to specify the number of bytes to bewritten.

ComRd reads a specified number of bytes from the determined COM Port. Use the functionGetInQLen to obtain the number of bytes present at the serial input queue. Use this value todetermine the number of bytes to read.

Page 182: CVI Basics I (Course Manual).pdf

LabWindows/CVI Basics I Course Manual 178 © National Instruments Corporation

Exercise 6-1 (25 min.)

Objective: To establish communication with a serialinstrument.

Page 183: CVI Basics I (Course Manual).pdf

LabWindows/CVI Basics I Course Manual 179 © 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,intnotifyCount, int eventCharacter,ComCallbackPtrcallbackFunction, void *callbackData);

Commonly used eventMasks :• Any character received LWRS_RXCHAR• Received certain character LWRS_RXFLAG• Notify count bytes in inqueue LWRS_RECEIVE

Consider a situation in which an instrument generates a large amount of data, or takes a longtime to obtain a data point. The instrument needs to send data to the computer as soon as thedata is acquired. Because you do not want to tie up computer resources waiting for ComRd tocomplete and you do not want to make the serial input buffer extremely large, you must benotified when data is present at the port. This prevents you from waiting on data and enablesyou 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 EventMaskparameter occur on the COM port.

Some of the common COM port events are LWRS_RXCHAR, LWRS_RXFLAG, andLWRS_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 weset the eventCharacter to the value “Z” and we receive a “Z” at the COM port, theLWRS_RXFLAG will be generated. LWRS_RECEIVE will be generated when the number ofbytes received at the COM port equals notifyCount .

Page 184: CVI Basics I (Course Manual).pdf

LabWindows/CVI Basics I Course Manual 180 © National Instruments Corporation

Exercise 6-2 (20 min.)

Objective: Use InstallComCallback to retrievewaveforms from a serial instrument.

Page 185: CVI Basics I (Course Manual).pdf

LabWindows/CVI Basics I Course Manual 181 © National Instruments Corporation

Debugging Methods

• Verify settings match device• Perform a loopback test

• Use HyperTerminal - Microsoft serial applicationStart » 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. Thedata 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 baudrate, 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 theserial port, data travels out of the transmit line and into the receive line. You are thenable to read all the data written to the port. A number of applications may be used toimplement a loopback test. One method of performing a loopback test is using theWindows HyperTerminal program, located under the Accessories folder. Anothermethod is using the LabWindows/CVI serial example \CVI\SAMPLES\RS232\SERIAL.PRJ .

Page 186: CVI Basics I (Course Manual).pdf

LabWindows/CVI Basics I Course Manual 182 © 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.

Page 187: CVI Basics I (Course Manual).pdf

LabWindows/CVI Basics I Course Manual 183 © National Instruments Corporation

Lesson 7Instrument Drivers

Objectives:

• Multiple modules within one project• Learn about instrument drivers

• Learn how to create an instrument driver• Learn about VISA API

Page 188: CVI Basics I (Course Manual).pdf

LabWindows/CVI Basics I Course Manual 184 © National Instruments Corporation

Multiple Modules

Calling functions from other ModulesYou can call functions from other modules by simply adding a .c file to yourLabWindows/CVI project that contains the functions you want to call. To make the functioncalls, 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 andstoreName are defined in the names.c module. The phonbook.c module (which containsmain ) has the statement #include “ name.h” because the functions need to beprototyped before they can be used within phonbook.c .

When accessing variables in different modules, you must pay a particular attention whendefining the variables. Lesson 1 contains a section that covers in detail the scope of variables inLabWindows/CVI.

Page 189: CVI Basics I (Course Manual).pdf

LabWindows/CVI Basics I Course Manual 185 © 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. Manytimes, you may want to separate the functions in your project to reside in multiple files toorganize 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 almostidentical to the multiple modules model discussed on the previous slide. An instrument driversimply defines function panels, which you have been using throughout this course when youused 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 offunctions. Then, under this same framework, you will learn how instrument drivers inLabWindows/CVI help simplify instrumentation control.

Page 190: CVI Basics I (Course Manual).pdf

LabWindows/CVI Basics I Course Manual 186 © 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

FUNCTION PANELS

INSTNAME.FPINSTNAME.SUB

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

SOURCE CODE

INCLUDE FILEINSTNAME.H

Attach

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

• The instrument function panel file (.fp ), which contains information that defines theFunction 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 IVIinstrument drivers.

Page 191: CVI Basics I (Course Manual).pdf

LabWindows/CVI Basics I Course Manual 187 © National Instruments Corporation

Loadin g an Instrument Driver

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

Page 192: CVI Basics I (Course Manual).pdf

LabWindows/CVI Basics I Course Manual 188 © National Instruments Corporation

Instrument Driver Function Tree

You use the instrument driver exactly as you use the standard LabWindows/CVI libraryfunctions. 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 acontrol for each parameter. By manipulating the controls, you can construct a specific functioncall that you can either interactively execute or paste into a program.

Page 193: CVI Basics I (Course Manual).pdf

LabWindows/CVI Basics I Course Manual 189 © National Instruments Corporation

Creatin g an Instrument Driver

Steps:1) Create function tree (.fp file)2) Create function panels for functions3) Create documentation directly from Function

Tree Editor4) Create header file and source code skeleton

directly from Function Tree Editor5) Complete all function definitions in source

code skeleton

Creating an Instrument DriverTo 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. Onceyou create the function tree, you create a function panel for each function. Fill in the online helpas you create your functions. Once you have the function panel help written for all the functionsin your function tree, you can automatically create a .doc file that contains all the helpinformation documented on each function. LabWindows/CVI 5.0 can automatically create asource code skeleton and header file that contains the function prototypes of all the functions inthe 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 eachstep required to create an instrument driver.

Page 194: CVI Basics I (Course Manual).pdf

LabWindows/CVI Basics I Course Manual 190 © National Instruments Corporation

Creatin g .fp File

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

Page 195: CVI Basics I (Course Manual).pdf

LabWindows/CVI Basics I Course Manual 191 © National Instruments Corporation

Creatin g Instruments

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

Page 196: CVI Basics I (Course Manual).pdf

LabWindows/CVI Basics I Course Manual 192 © National Instruments Corporation

Creatin g Classes

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

Page 197: CVI Basics I (Course Manual).pdf

LabWindows/CVI Basics I Course Manual 193 © National Instruments Corporation

Creatin g Function Trees

You create functions by selecting Create » Function Panel Window from the menubar. Fill inthe Create Function Panel Window Node dialog box. The Name field defines the name of theFunction Panel window, which appears while searching through the instrument driver functiontree. The Function Name field defines the actual name of the function that performs a givenoperation (which will then be preceded by the instrument prefix once you paste it in the sourcecode). The Function Name field must follow ANSI C rules of naming a function (that is, nospaces, etc). An example of the prefix with the function name is:

Prefix: namesFunction Name: displayNameFunction Name in source code: names_displayName

Page 198: CVI Basics I (Course Manual).pdf

LabWindows/CVI Basics I Course Manual 194 © National Instruments Corporation

Creatin g Function Panels

Creating a Function PanelTo create a function panel, double-click on the name of the desired function defined in theFunction Tree or highlight the function and select Edit » Edit Function Panel Window fromthe 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 inputparameters of the function. You can also place output controls, which represent the outputparameters 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 objectfrom the Create menu in menu bar or by clicking on one of the following icons on the toolbarof the function panel window:

Creates an input control Creates a numeric control

Creates a slide control Creates an output

Creates a binary control Creates a return value

Creates a ring control

Selecting a control brings up a dialog box where you can fill in the parameters for eachparticular control. This dialog box is discussed on the next slide.

Page 199: CVI Basics I (Course Manual).pdf

LabWindows/CVI Basics I Course Manual 195 © National Instruments Corporation

Creatin g Function Panels

When creating an input, output, or a return value, a dialog box will appear requesting thefollowing 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 onthe 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 thein the same way as in the graphical user interface editor.

You can also place global variable indicators on the function panel. These variables areupdated 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 themenu bar or by clicking on the icon.

Page 200: CVI Basics I (Course Manual).pdf

LabWindows/CVI Basics I Course Manual 196 © National Instruments Corporation

Documentin g Instruments

Documenting the Instrument DriverYou can document a function directly from the function panel editor. You create a help windowfor the function by right-clicking on an open area of the function panel. Type in all the helpinformation pertaining to the function.

You can also document the function parameters. To do this, right-click on the functionparameter and type in all the necessary help information for the parameter. LabWindows/CVIautomatically adds the prototype of the function to the function help and the data type to theparameter 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 createthis file automatically based on the help text entered on the function panels. This documentprovides information such as the function tree layout, the data types associated with eachfunction parameter, and the information entered on the help windows of each function panel. Inaddition, LabWindows/CVI also automatically adds general instrument driver information and itcan document the functions in Visual Basic or in C format. To have LabWindows/CVI generatea .doc file automatically, select Options » Generate Documentation from the menubar. Adialog box appears, in which you can specify the type and format of the information to place inthe document.

Page 201: CVI Basics I (Course Manual).pdf

LabWindows/CVI Basics I Course Manual 197 © National Instruments Corporation

Generatin g Source Codeand Header

Generating the Header File and the Source Code SkeletonLabWindows/CVI can automatically generate a header file (.h ) containing the functionprototypes 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, selectTools » Generate New Source For Function Tree.

Page 202: CVI Basics I (Course Manual).pdf

LabWindows/CVI Basics I Course Manual 198 © National Instruments Corporation

Skeleton Code Files

Header File and the Source Code SkeletonThe figure above shows an example of the resulting source “skeleton code” and the headerfile. 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 sourcecode to compile, you must add the #include <cvidef.h> line in the instrument driverheader file.

You can now begin coding all the functions of your instrument driver by filling in theblanks!

Page 203: CVI Basics I (Course Manual).pdf

LabWindows/CVI Basics I Course Manual 199 © National Instruments Corporation

Editin g an Instrument Driver

• Select Instrument » Edit and select the instrumentdriver you want to edit

Editing Instrument Driver FilesWhen working with instrument drivers, you use the Edit command from the Instrument menuto either invoke the Function Panel Editor or to modify the relationship between the functionpanel file (.fp ) and its associated program file.

• Show Info - displays the names of the current function panel file and the attached programfile.

• Attach and Edit Source - searches the directory that contains the function panel for afilename 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 directorythat contains the function panel for a program file that has the same prefix as the functionpanel file and a .lib , .obj , .dll , or.c extension.

• Edit Function Tree - invokes the Function Tree Editor.

Page 204: CVI Basics I (Course Manual).pdf

LabWindows/CVI Basics I Course Manual 200 © National Instruments Corporation

Exercise 7-1 (30 min.)

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

Page 205: CVI Basics I (Course Manual).pdf

LabWindows/CVI Basics I Course Manual 201 © National Instruments Corporation

Instrument Control withan Instrument Driver

• Handles low-level interface operations (GPIB, Serial,VXI, PXI)

• Command set for instrument preprogrammed intodriver

• National Instruments instrument drivers come withsource 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 DriverSo far, you have seen how instrument drivers are used as a library of functions. How does thisfit into actual instruments? Consider a power supply that can interface to a computer through theGPIB bus. To generate a voltage, it could take several GPIB calls, which involve passingconfiguration parameters to the power supply before the actual voltage generation. With aninstrument driver, this could take a single function call because the driver acts as a high-leveltranslator for communicating with your instrument.

When you use an instrument driver, you can bypass time-consuming instrument programmingtasks, 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 thelow-level details. LabWindows/CVI has a growing list of more than 650 instrument driversavailable for GPIB, VXI, and serial interfaces. Each driver is designed for a specific instrumentand comes with source code. You can change, optimize, or add functionality to the driver sourcecode to meet the needs of your application.

Page 206: CVI Basics I (Course Manual).pdf

LabWindows/CVI Basics I Course Manual 202 © National Instruments Corporation

VXIpnp Instrument Drivers

VXIpnp Instrument DriverAn alliance called the VXIplug&play System Alliance (VXIpnp) designed a model forinstrument drivers that is generally used among companies. This alliance defines certain aspectsof an instrument driver, the most important being the organization of functions. The functiontree shown above is the Fluke 45 instrument driver. This driver conforms to the VXIpnpstandard. As you can see, the instrument driver is a high-level library, broken down intofunctions for initializing, configuring, and measuring data from your instrument. All VXIpnpinstrument drivers follow the same Initialize-Configure-Action/Status-Data-Utility-Closeformat.

• Initialize Function – Initializes the software connection to the instrument. The initializefunction can optionally perform an instrument identification query as well as a resetoperation. In addition, it can perform any necessary actions to place the instrument in itsdefault power-on state or other specific state.

• Configuration Functions – A collection of software routines that configure the instrumentto 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 functionscause the instrument to initiate or terminate test and measurement operations. Statusfunctions obtain the current status of the instrument or the status of pending operations. Thespecific routines in this category and the actual operations performed by those routines areleft up to the instrument driver developer.

Page 207: CVI Basics I (Course Manual).pdf

LabWindows/CVI Basics I Course Manual 203 © National Instruments Corporation

Example of an Instrument Driver

• Data Functions – Functions that transfer data to or from the instruments. Examples includefunctions 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 routinesare 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 bythe developer.

• Close Function – All LabWindows/CVI instrument drivers have a close function thatterminates the software connection to the instrument and deallocates system resources.

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

Page 208: CVI Basics I (Course Manual).pdf

LabWindows/CVI Basics I Course Manual 204 © 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 Resource Name Grammar

GPIB GPIB[board]::primary address[::INSTR]

Serial ASRL[board][::INSTR]

VXI VXI[board]::VXI logical address[::INSTR]

GPIB-VXI GPIB-VXI[board][::GPIB-VXI primary address]::VXI logical address[::INSTR]

PXI PXI[bus]::deviceNumber[::functionNumber][::INSTR]

What is VISA?Instrument drivers have become increasingly popular over the last several years, and both usersand vendors have taken advantage of the technology. Increased use of instrument drivers hasfueled a continuous improvement process, resulting in high-quality instrument drivers.

To address customers’ needs for reusable, interoperable software, National Instruments helpeddevelop the Virtual Instrument System Architecture (VISA) specification. It is a standardendorsed by the VXIplug&play Systems Alliance, which includes more than 35 of the largestinstrumentation companies in the industry. The VISA standard unifies the industry to makesoftware interoperable and reusable over time and regardless of the instrument I/O option. VISAis a single interface library for controlling GPIB, Serial, VXI, and PXI instruments on allLabWindows/CVI platforms.

To establish communication with a specified device, you need to open a session to the devicespecifying an instrument descriptor, which contains information on the type of I/O interface anddevice address. For example, based on the table above, the instrument descriptor required toopen a session to a GPIB instrument with a GPIB address of 2 and connected to your GPIB0interface board would be GPIB0::2::INSTR. The next page illustrates an example of how toopen a session to a GPIB instrument and perform an I/O operation.

Page 209: CVI Basics I (Course Manual).pdf

LabWindows/CVI Basics I Course Manual 205 © National Instruments Corporation

Communicatin g with VISA

VISA ExampleThe example above shows how to perform an I/O operation using VISA function calls. TheviOpenDefaultRM function must be called before any VISA operations can be invoked. Thecall to this function initializes the VISA system, including the Default Resource Managerresource (please refer to the VISA reference manual for more details), and returns a handle tothat resource. The viOpen function opens a session to the instrument and returns a handle thatwill be used in any subsequent VISA I/O operations performed with the instrument. Notice thatyou pass the instrument descriptor GPIB0::2::INSTR to this function. The viWritefunction sends the “*idn?” command to the instrument to query its identification. The viReadfunction reads the response back from the instrument and stores it in the array buffer. TheviWrite and viRead functions know which instrument to communicate with by means ofthe handle (instrHandle) returned by the viOpen function. When all the I/O operations havebeen completed, you close the VISA sessions returned by both viOpenDefaultRM andviOpen functions using the viClose function.

The VISA specification defines a set of variable declarations, which are contained in the headerfile visa.h . For example, the variables defaultRM and instrHandle sessions are of the typeViSession, which is defined as an integer in visa.h .

Page 210: CVI Basics I (Course Manual).pdf

LabWindows/CVI Basics I Course Manual 206 © National Instruments Corporation

Exercise 7-2 (15 min.)

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

Page 211: CVI Basics I (Course Manual).pdf

LabWindows/CVI Basics I Course Manual 207 © National Instruments Corporation

Exercise 7-3 (25 min.)

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

Page 212: CVI Basics I (Course Manual).pdf

LabWindows/CVI Basics I Course Manual 208 © 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 throughthe Function Tree Editor.

• A function panel is a graphical representation of a function. Youcan 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 textentered on the function panels.

• An instrument driver can be used to handle all low-leveloperations of a particular instrument.

• VISA is a specification that provides a single set of function callsto interface with GPIB, Serial, VXI, and PXI devices.

Page 213: CVI Basics I (Course Manual).pdf

LabWindows/CVI Basics I Course Manual 209 © National Instruments Corporation

Lesson 8Standalone Executables

Objectives:• Learn how to create a standalone

executable• Learn about the LabWindows/CVI

run-time engine• Learn how to distribute a standalone

executable

Page 214: CVI Basics I (Course Manual).pdf

LabWindows/CVI Basics I Course Manual 210 © 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 EngineThe Run-Time Engine contains all of the built-in library, memory, and program execution tools presentin the LabWindows/CVI environment without all of the program development tools such as the SourceEditor, compiler, debugger, and User Interface Editor. The Run-Time Engine is smaller than theLabWindows/CVI environment, so it loads faster and consumes less memory. It must be present on anytarget computer on which you want to run your executable program and you only need one copy of theRun-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 theRun-Time Engine with your executable when you create your distribution kit (discussed later in thelesson), or you can distribute it separately.

Error CheckingWhen you develop applications in LabWindows/CVI, you typically have debugging set to eitherstandard 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 relaxedin your own error checking. However, in compiled modules and standalone executables, debugging andBreak on Library Errors are disabled. This results in smaller and faster code, but you must performyour own error checking or unpredictable results may occur. You should remember that many problemscould occur in compiled modules and standalone executables even if the program works inside theenvironment.

It is important to check for errors that can occur due to external factors beyond the control of yourprogram. 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 mustdo your own error checking for these types of functions. Other functions return errors only if yourprogram is incorrect.

Page 215: CVI Basics I (Course Manual).pdf

LabWindows/CVI Basics I Course Manual 211 © National Instruments Corporation

Creatin g Executables

From the Project window selectBuild » 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 debugginglevel will be changed to None. Recall that standalone executables run without the debugger, andyou must have your own error checking. Next, you should get a dialog box similar to the onedepicted 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 modulesthat you load at run-time by calling LoadExternalModule ). You can also add versioninformation 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 thetarget machine. The next two slides will tell you what files you need to transfer to the targetmachine and how to use LabWindows/CVI’s automated distribution kit to make it easier.

Page 216: CVI Basics I (Course Manual).pdf

LabWindows/CVI Basics I Course Manual 212 © National Instruments Corporation

Necessar y FilesExecutable

Startup code

CompiledSource Code

InstrumentDriver Code

.obj or .o

.lib or .a

Name and Icon

LW/CVI Run-Time Engine

ProgramExecutionSupport

MemoryManagement

Built-in CVILibraries

.UIR .DLLExternal

.lib

Otherfiles

External

.obj

Necessary FilesFor your executable to run successfully on a target computer, any files that are required by theexecutable must be accessible. If you create your distribution kit (discussed next) properly, thefinal distribution kit should contain all the necessary files for installing your LabWindows/CVIexecutable 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 projectand any instrument driver program files that are statically linked to your project. It also containsthe application name and icon resource to be registered to the operating system. The executablehas an associated icon on which you can double-click to start the application. When theexecutable is started, it loads and starts the Run-Time Engine..uir Files – These files contain the user interface panels that are used by your applicationprogram. They must be included separately because they are actually loaded by the executableusing LoadPanel ..dll Files – You need to include any Windows dynamic link library (DLL) files that are usedby your application program.External .lib Files – Any 32-bit .lib files loaded by LoadExternalModule and are notlisted in the project.External .obj Files – Any 32-bit .obj files loaded by LoadExternalModule and are notlisted in the project.Other Files – Any additional files used by your program including, but not limited to, bitmapfiles, files opened in your code using fopen or OpenFile , and .ini files used forconfiguration.

Page 217: CVI Basics I (Course Manual).pdf

LabWindows/CVI Basics I Course Manual 213 © National Instruments Corporation

Distributin g Executables

Build » Create Distribution Kit

After you create an executable, you can easily distribute it by making a set of disks fromwhich 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. TheCreate Distribution Kit command automatically includes all the files necessary to run yourexecutable program on a target computer except for DLLs for National Instrumentshardware and files that are loaded using LoadExternalModule .

DLLs for National Instruments hardware should not be part of your distribution kit. TheseDLLs must be installed by the end-user from the hardware installation disks supplied byNational Instruments. For example, if your application uses a GPIB board, you must installthe 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 usingthe 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 theHelp 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 mouseover the image. The mouse cursor will turn into a hand over items on which you can getfurther help. Click with the left mouse button to access this additional information.

Page 218: CVI Basics I (Course Manual).pdf

LabWindows/CVI Basics I Course Manual 214 © 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.

Page 219: CVI Basics I (Course Manual).pdf

LabWindows/CVI Basics I Course Manual 215 © National Instruments Corporation

Summar y 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

Page 220: CVI Basics I (Course Manual).pdf
Page 221: CVI Basics I (Course Manual).pdf

© National Instruments Corporation 1-1 LabWindows/CVI Basics I Course Manual

Lesson 1Exercises

Exercise 1-1Objective: 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.

Page 222: CVI Basics I (Course Manual).pdf

Lesson 1 Exercises

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

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.

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.

Run Projecttoolbar icon

Page 223: CVI Basics I (Course Manual).pdf

Lesson 1 Exercises

© National Instruments Corporation 1-3 LabWindows/CVI Basics I Course Manual

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

Page 224: CVI Basics I (Course Manual).pdf

Lesson 1 Exercises

LabWindows/CVI Basics I Course Manual 1-4 © National Instruments Corporation

Exercise 1-2Objective: 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.

Page 225: CVI Basics I (Course Manual).pdf

Lesson 1 Exercises

© National Instruments Corporation 1-5 LabWindows/CVI Basics I Course Manual

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 tagsusing <Shift-F2>

Move betweentags using F2

Page 226: CVI Basics I (Course Manual).pdf

Lesson 1 Exercises

LabWindows/CVI Basics I Course Manual 1-6 © National Instruments Corporation

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

Page 227: CVI Basics I (Course Manual).pdf

Lesson 1 Exercises

© National Instruments Corporation 1-7 LabWindows/CVI Basics I Course Manual

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

Page 228: CVI Basics I (Course Manual).pdf

Lesson 1 Exercises

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

Exercise 1-3Objective: 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.

Page 229: CVI Basics I (Course Manual).pdf

Lesson 1 Exercises

© National Instruments Corporation 1-9 LabWindows/CVI Basics I Course Manual

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.

Page 230: CVI Basics I (Course Manual).pdf

Lesson 1 Exercises

LabWindows/CVI Basics I Course Manual 1-10 © National Instruments Corporation

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

None—Source 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 checking—In this mode, you can set breakpoints and use the Variable Display window, but you have no user protection.

Standard—In this mode, you can set breakpoints and use the Variable Display window and have user protection.

Extended—This mode has the same benefits as Standard mode, with added user protection that validates every attempt to free

Page 231: CVI Basics I (Course Manual).pdf

Lesson 1 Exercises

© National Instruments Corporation 1-11 LabWindows/CVI Basics I Course Manual

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

Page 232: CVI Basics I (Course Manual).pdf

Lesson 1 Exercises

LabWindows/CVI Basics I Course Manual 1-12 © National Instruments Corporation

Exercise 1-4Objective: 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.

Page 233: CVI Basics I (Course Manual).pdf

Lesson 1 Exercises

© National Instruments Corporation 1-13 LabWindows/CVI Basics I Course Manual

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.

Page 234: CVI Basics I (Course Manual).pdf

Lesson 1 Exercises

LabWindows/CVI Basics I Course Manual 1-14 © National Instruments Corporation

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.

Page 235: CVI Basics I (Course Manual).pdf

Lesson 1 Exercises

© National Instruments Corporation 1-15 LabWindows/CVI Basics I Course Manual

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.

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 .

Declare Variabletoolbar icon

Page 236: CVI Basics I (Course Manual).pdf

Lesson 1 Exercises

LabWindows/CVI Basics I Course Manual 1-16 © National Instruments Corporation

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 the Insert Function Call icon from the toolbar.) If your project has 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).

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.

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.

Set Targettoolbar icon

Insert Function Calltoolbar icon

Select Variabletoolbar icon

Page 237: CVI Basics I (Course Manual).pdf

Lesson 1 Exercises

© National Instruments Corporation 1-17 LabWindows/CVI Basics I Course Manual

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.

Page 238: CVI Basics I (Course Manual).pdf

Lesson 1 Exercises

LabWindows/CVI Basics I Course Manual 1-18 © National Instruments Corporation

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.

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

Run Projecttoolbar icon

Page 239: CVI Basics I (Course Manual).pdf

Lesson 1 Exercises

© National Instruments Corporation 1-19 LabWindows/CVI Basics I Course Manual

Exercise 1-5Objective: 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 . Don’t 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);

Page 240: CVI Basics I (Course Manual).pdf

Lesson 1 Exercises

LabWindows/CVI Basics I Course Manual 1-20 © National Instruments Corporation

Exercise 1-6Objective: 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 .

Page 241: CVI Basics I (Course Manual).pdf

Lesson 1 Exercises

© National Instruments Corporation 1-21 LabWindows/CVI Basics I Course Manual

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 .

Page 242: CVI Basics I (Course Manual).pdf

Lesson 1 Exercises

LabWindows/CVI Basics I Course Manual 1-22 © National Instruments Corporation

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.

Page 243: CVI Basics I (Course Manual).pdf

Lesson 1 Exercises

© National Instruments Corporation 1-23 LabWindows/CVI Basics I Course Manual

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

Page 244: CVI Basics I (Course Manual).pdf

Lesson 1 Exercises

LabWindows/CVI Basics I Course Manual 1-24 © National Instruments Corporation

Exercise 1-7Objective: 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.)

Page 245: CVI Basics I (Course Manual).pdf

Lesson 1 Exercises

© National Instruments Corporation 1-25 LabWindows/CVI Basics I Course Manual

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.

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 to Cursortoolbar icon

Go toolbaricon

Stoptoolbar icon

Page 246: CVI Basics I (Course Manual).pdf

Lesson 1 Exercises

LabWindows/CVI Basics I Course Manual 1-26 © National Instruments Corporation

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.

Page 247: CVI Basics I (Course Manual).pdf

Lesson 1 Exercises

© National Instruments Corporation 1-27 LabWindows/CVI Basics I Course Manual

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.

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.

Stoptoolbar icon

Page 248: CVI Basics I (Course Manual).pdf

Lesson 1 Exercises

LabWindows/CVI Basics I Course Manual 1-28 © National Instruments Corporation

Notes

Page 249: CVI Basics I (Course Manual).pdf

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

Lesson 2Exercises

Exercise 2-1Objective: 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

Page 250: CVI Basics I (Course Manual).pdf

Lesson 2 Exercises

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

Exercise 2-2Objective: 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.

Page 251: CVI Basics I (Course Manual).pdf

Lesson 2 Exercises

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

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

Page 252: CVI Basics I (Course Manual).pdf

Lesson 2 Exercises

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

Exercise 2-3Objective: To build a GUI.

Creating the Panel1. 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:

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.

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 Numeric6. 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 PANEL

Panel Title Increment/Decrement

Constant Name COUNTDefault Value 0Data Types intMinimum -2147483648Maximum 2147483647Inc Value 1Range Checking NotifyControl Mode IndicatorLabel Count

Coloring tool

Page 253: CVI Basics I (Course Manual).pdf

Lesson 2 Exercises

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

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.

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

Creating the Command Buttons7. 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).

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

Button Name

Constant Name INCREMENT DECREMENT RESET QUIT

Callback Function AddOne SubtractOne SetToZero QuitProgram

Control Mode Hot Hot Hot Hot

Label __Increment __Decrement __Reset __Quit

Page 254: CVI Basics I (Course Manual).pdf

Lesson 2 Exercises

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

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 File10. 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 __cplusplusextern "C" {

#endif

/* Panels and Controls: */

#define PANEL 1#define PANEL_COUNT 2#define PANEL_INCREMENT 3 /* callback function: AddOne */#define PANEL_DECREMENT 4 /* callback function: SubractOne */#define PANEL_RESET 5 /* callback function: SetToZero */#define PANEL_QUIT 6 /* callback function: 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

Page 255: CVI Basics I (Course Manual).pdf

Lesson 2 Exercises

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

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

Page 256: CVI Basics I (Course Manual).pdf

Lesson 2 Exercises

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

Exercise 2-4Objectives: 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 user’s selection. At any point, the user should be able to reset the value to zero and continue.

Understanding Events1. 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.

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

{

Operatingtoolbar icon

Page 257: CVI Basics I (Course Manual).pdf

Lesson 2 Exercises

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

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;

}

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

Run Projecttoolbar icon

Page 258: CVI Basics I (Course Manual).pdf

Lesson 2 Exercises

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

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

Understanding Event-Driven Programming

Now that you’re 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.

Page 259: CVI Basics I (Course Manual).pdf

Lesson 2 Exercises

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

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

Page 260: CVI Basics I (Course Manual).pdf

Lesson 2 Exercises

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

Exercise 2-5Objective: 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.)

Page 261: CVI Basics I (Course Manual).pdf

Lesson 2 Exercises

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

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

Page 262: CVI Basics I (Course Manual).pdf

Lesson 2 Exercises

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

Exercise 2-6Objectives: To understand how to develop well behaved applications in LabWindows/CVI.

To understand the functionality of RunUserInterface, QuitUserInterface, and ProcessSystemEvents.

Procedure1. 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 places—after 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

Page 263: CVI Basics I (Course Manual).pdf

Lesson 2 Exercises

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

Exercise 2-7Objective: 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 Chart2. 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 CHART

Points per Screen 100

Scroll Mode Continuous

Y-axis...

Axis Name Random Numbers

Minimum 0.00

Maximum 100.00

Divisions 5

Precision 1

Label Random Number Chart

Adding the Timer Control4. 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 TIMER

Callback Function TimerCB

Interval (seconds) 0.100

Label Timer

Page 264: CVI Basics I (Course Manual).pdf

Lesson 2 Exercises

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

5. Close and save your GUI.

Modifying the Source File6. 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 panelHandle

Control ID PANEL_CHART

YArray dataPoints

Number of Points 1

Starting Index 0

Skip Count 0

Y Data Type double precision

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

Page 265: CVI Basics I (Course Manual).pdf

Lesson 2 Exercises

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

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

Page 266: CVI Basics I (Course Manual).pdf

Lesson 2 Exercises

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

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.

Note 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 C:\exercises\CVI Basics 1\INCDEC2.PRJ

GUI File C:\exercises\CVI Basics 1\INCDEC2.UIR

Source File C:\exercises\CVI Basics 1\INCDEC2.C

End of Exercise 2-8

Page 267: CVI Basics I (Course Manual).pdf

© National Instruments Corporation 3 -1 LabWindows/CVI Basics I Course Manual

Lesson 3Exercises

Exercise 3-1Objective: 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.

Page 268: CVI Basics I (Course Manual).pdf

Lesson 3 Exercises

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

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

Page 269: CVI Basics I (Course Manual).pdf

Lesson 3 Exercises

© National Instruments Corporation 3 -3 LabWindows/CVI Basics I Course Manual

Exercise 3-2Objective: To open the NI-DAQ Configuration Utility and study the current setup. You will also

test the board interactively with the utility.

Instructor’s Note Explain the features and capabilities of the DAQ Signal Accessory.

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.

Page 270: CVI Basics I (Course Manual).pdf

Lesson 3 Exercises

LabWindows/CVI Basics I Course Manual 3 -4 © National Instruments Corporation

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

Page 271: CVI Basics I (Course Manual).pdf

Lesson 3 Exercises

© National Instruments Corporation 3 -5 LabWindows/CVI Basics I Course Manual

Exercise 3-3Objective: 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.

Page 272: CVI Basics I (Course Manual).pdf

Lesson 3 Exercises

LabWindows/CVI Basics I Course Manual 3 -6 © National Instruments Corporation

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

Page 273: CVI Basics I (Course Manual).pdf

Lesson 3 Exercises

© National Instruments Corporation 3 -7 LabWindows/CVI Basics I Course Manual

Exercise 3-4Objective: 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 Recall how PlotStripChart handles multiple traces.

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

Page 274: CVI Basics I (Course Manual).pdf

Lesson 3 Exercises

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

Part BYou 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.

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 points—1,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.

Panel Constant Name: PANELPanel Title: Acquire and Plot Waveform

Constant Name: GRAPHGraph Title: WaveformY-axis Name: VoltageX-axis Name: secX-axis precision: 2

Constant Name: QUITCallback Function: Quit

Constant Name: ACQUIRECallback Function: Acquire

Constant Name: RATEData Type: Double

Minimum: 100 Maximum: 40000Range Checking: NotifyControl Mode: Validate

Page 275: CVI Basics I (Course Manual).pdf

Lesson 3 Exercises

© National Instruments Corporation 3 -9 LabWindows/CVI Basics I Course Manual

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 1

Channel String "1:2"

Number of Scans 1000

Scans/Second scan_rate

High Limit (volts) +5.0

Low Limit (volts) -5.0

Actual Scan Rate &act_scan_rate

Fill Mode Group by Channel

Waveform(s) waveforms

Error 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

Page 276: CVI Basics I (Course Manual).pdf

Lesson 3 Exercises

LabWindows/CVI Basics I Course Manual 3 -10 © National Instruments Corporation

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

Page 277: CVI Basics I (Course Manual).pdf

Lesson 3 Exercises

© National Instruments Corporation 3 -11 LabWindows/CVI Basics I Course Manual

Exercise 3-5Objective: 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.

Page 278: CVI Basics I (Course Manual).pdf

Lesson 3 Exercises

LabWindows/CVI Basics I Course Manual 3 -12 © National Instruments Corporation

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

Constant Name: BACKLOGData Type: unsigned intControl Mode: Indicator

Constant Name: TIMERCallback Function: ProcessLoopInterval: 0.00

Constant Name: RATE Data Type: Double Minimum: 100 Maximum: 1000 Range Checking: Notify Control Mode: Validate

Constant Name: ACQUIRECallback Function: Acquire

Callback Function: QuitConstant Name: QUIT

Constant Name: GRAPHGraph Title: WaveformY-axis Name: VoltageX-axis Name: secX-Axis Precision: 2

Panel Constant Name: PANELPanel Title: Asynchronous Data Acquisition

Page 279: CVI Basics I (Course Manual).pdf

Lesson 3 Exercises

© National Instruments Corporation 3 -13 LabWindows/CVI Basics I Course Manual

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 task

Scans Backlog &scans_acquired

Error 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 task

Scans to Read 500

Read Mode Consecutive

Scans Backlog &scans_remaining

Fill Mode Group by Channel

Waveforms waveform

Error 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 task

Error Leave blank

Page 280: CVI Basics I (Course Manual).pdf

Lesson 3 Exercises

LabWindows/CVI Basics I Course Manual 3 -14 © National Instruments Corporation

11. Make sure your code looks functionally equivalent to the code shown below.

#include "easyio.h"#include <userint.h>#include <cvirte.h> /* Needed if linking in external compiler; harmless otherwise */#include "daqasync.h"

#define TRUE 1#define FALSE 0

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

}}

Page 281: CVI Basics I (Course Manual).pdf

Lesson 3 Exercises

© National Instruments Corporation 3 -15 LabWindows/CVI Basics I Course Manual

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.

Page 282: CVI Basics I (Course Manual).pdf

Lesson 3 Exercises

LabWindows/CVI Basics I Course Manual 3 -16 © National Instruments Corporation

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 board’s FIFO buffer.

End of Exercise 3-5

Page 283: CVI Basics I (Course Manual).pdf

Lesson 3 Exercises

© National Instruments Corporation 3 -17 LabWindows/CVI Basics I Course Manual

Exercise 3-6Objective: 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

Page 284: CVI Basics I (Course Manual).pdf

Lesson 3 Exercises

LabWindows/CVI Basics I Course Manual 3 -18 © National Instruments Corporation

Exercise 3-7Objective: 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

Page 285: CVI Basics I (Course Manual).pdf

© National Instruments Corporation 4-1 LabWindows/CVI Basics I Course Manual

Lesson 4Exercises

Exercise 4-1Objective: 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

Page 286: CVI Basics I (Course Manual).pdf

Lesson 4 Exercises

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

Notes

Page 287: CVI Basics I (Course Manual).pdf

© National Instruments Corporation 5-1 LabWindows/CVI Basics I Course Manual

Lesson 5Exercises

Exercise 5-1Objective: 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

Page 288: CVI Basics I (Course Manual).pdf

Lesson 5 Exercises

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

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.

Page 289: CVI Basics I (Course Manual).pdf

Lesson 5 Exercises

© National Instruments Corporation 5-3 LabWindows/CVI Basics I Course Manual

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 0

Primary Address 2

Secondary Address NO SAD (or 0)

Timeout 10 Sec

End Message Enable

EOS Character 0

Device 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 simulator

Data Buffer writeBuffer

Byte Count strlen (writeBuffer)

Status Returned 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.

Page 290: CVI Basics I (Course Manual).pdf

Lesson 5 Exercises

LabWindows/CVI Basics I Course Manual 5-4 © National Instruments Corporation

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 simulator

Data Buffer readBuffer

Byte Count count

Status Returned 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 simulator

Operation Mode 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? Output sine waveform

SOUR:FUNC SQU;SENS:DATA? Output square waveform

SOUR:FUNC NOIS;SENS:DATA? Output noisy sine waveform

SOUR:FUNC RAND;SENS:DATA? Output random noise waveform

SOUR:FUNC PCH;SENS:DATA? Output chirp waveform

Page 291: CVI Basics I (Course Manual).pdf

Lesson 5 Exercises

© National Instruments Corporation 5-5 LabWindows/CVI Basics I Course Manual

Examining Errors15. 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

Page 292: CVI Basics I (Course Manual).pdf

Lesson 5 Exercises

LabWindows/CVI Basics I Course Manual 5-6 © National Instruments Corporation

Exercise 5-2Objective: 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

Page 293: CVI Basics I (Course Manual).pdf

Lesson 5 Exercises

© National Instruments Corporation 5-7 LabWindows/CVI Basics I Course Manual

Exercise 5-2 Program Listing#include <ansi_c.h>#include <formatio.h>#include <gpib.h>#include <userint.h>#include <cvirte.h> /* Needed if linking in external compiler; harmless

otherwise */#include "gpibrand.h"

#define TRUE 1#define FALSE 0

static int panelHandle;static int device;static int board;static int 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]);

Page 294: CVI Basics I (Course Manual).pdf

Lesson 5 Exercises

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

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

}

Page 295: CVI Basics I (Course Manual).pdf

Lesson 5 Exercises

© National Instruments Corporation 5-9 LabWindows/CVI Basics I Course Manual

Exercise 5-3Objective: 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 .

Page 296: CVI Basics I (Course Manual).pdf

Lesson 5 Exercises

LabWindows/CVI Basics I Course Manual 5-10 © National Instruments Corporation

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 board

Event Mask 0x1000

Callback Function WaveCallback

Callback Data 0

Status Returned 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

Page 297: CVI Basics I (Course Manual).pdf

Lesson 5 Exercises

© National Instruments Corporation 5-11 LabWindows/CVI Basics I Course Manual

Exercise 5-4Objective: 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.

Page 298: CVI Basics I (Course Manual).pdf

Lesson 5 Exercises

LabWindows/CVI Basics I Course Manual 5-12 © National Instruments Corporation

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

Page 299: CVI Basics I (Course Manual).pdf

Lesson 5 Exercises

© National Instruments Corporation 5-13 LabWindows/CVI Basics I Course Manual

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

Page 300: CVI Basics I (Course Manual).pdf

Lesson 5 Exercises

LabWindows/CVI Basics I Course Manual 5-14 © National Instruments Corporation

Notes

Page 301: CVI Basics I (Course Manual).pdf

© National Instruments Corporation 6-1 LabWindows/CVI Basics I Course Manual

Lesson 6Exercises

Exercise 6-1Objective: 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.

SetupConfirm that the serial instrument is connected to the computer’s COM1. Set the NI Instrument Simulator switches to the following locations:

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)

NI Instrument Simulator Switch Settings

OFF

ON

Page 302: CVI Basics I (Course Manual).pdf

Lesson 6 Exercises

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

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 program’s functionality. The simulator will respond to the same commands given in the GPIB section.

End of Exercise 6-1

Page 303: CVI Basics I (Course Manual).pdf

Lesson 6 Exercises

© National Instruments Corporation 6-3 LabWindows/CVI Basics I Course Manual

Exercise 6-2Objective: 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

Page 304: CVI Basics I (Course Manual).pdf

Lesson 6 Exercises

LabWindows/CVI Basics I Course Manual 6-4 © National Instruments Corporation

Notes

Page 305: CVI Basics I (Course Manual).pdf

© National Instruments Corporation 7-1 LabWindows/CVI Basics I Course Manual

Lesson 7Exercises

Exercise 7-1

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

Page 306: CVI Basics I (Course Manual).pdf

Lesson 7 Exercises

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

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.

Page 307: CVI Basics I (Course Manual).pdf

Lesson 7 Exercises

© National Instruments Corporation 7-3 LabWindows/CVI Basics I Course Manual

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.

Page 308: CVI Basics I (Course Manual).pdf

Lesson 7 Exercises

LabWindows/CVI Basics I Course Manual 7-4 © National Instruments Corporation

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 don’t 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.

Page 309: CVI Basics I (Course Manual).pdf

Lesson 7 Exercises

© National Instruments Corporation 7-5 LabWindows/CVI Basics I Course Manual

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

Page 310: CVI Basics I (Course Manual).pdf

Lesson 7 Exercises

LabWindows/CVI Basics I Course Manual 7-6 © National Instruments Corporation

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.

Page 311: CVI Basics I (Course Manual).pdf

Lesson 7 Exercises

© National Instruments Corporation 7-7 LabWindows/CVI Basics I Course Manual

16. Using the Instrument menu, bring up the Average Function Panel.

17. Fill it out with variables and declare each one using <Ctrl-D>.

Don’t 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.

Page 312: CVI Basics I (Course Manual).pdf

Lesson 7 Exercises

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

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.

Page 313: CVI Basics I (Course Manual).pdf

Lesson 7 Exercises

© National Instruments Corporation 7-9 LabWindows/CVI Basics I Course Manual

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

Page 314: CVI Basics I (Course Manual).pdf

Lesson 7 Exercises

LabWindows/CVI Basics I Course Manual 7-10 © National Instruments Corporation

Exercise 7-2Objective: 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.

Page 315: CVI Basics I (Course Manual).pdf

Lesson 7 Exercises

© National Instruments Corporation 7-11 LabWindows/CVI Basics I Course Manual

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.

Page 316: CVI Basics I (Course Manual).pdf

Lesson 7 Exercises

LabWindows/CVI Basics I Course Manual 7-12 © National Instruments Corporation

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.

Page 317: CVI Basics I (Course Manual).pdf

Lesson 7 Exercises

© National Instruments Corporation 7-13 LabWindows/CVI Basics I Course Manual

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.

Page 318: CVI Basics I (Course Manual).pdf

Lesson 7 Exercises

LabWindows/CVI Basics I Course Manual 7-14 © National Instruments Corporation

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

Page 319: CVI Basics I (Course Manual).pdf

Lesson 7 Exercises

© National Instruments Corporation 7-15 LabWindows/CVI Basics I Course Manual

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.

Page 320: CVI Basics I (Course Manual).pdf

Lesson 7 Exercises

LabWindows/CVI Basics I Course Manual 7-16 © National Instruments Corporation

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

Page 321: CVI Basics I (Course Manual).pdf

Lesson 7 Exercises

© National Instruments Corporation 7-17 LabWindows/CVI Basics I Course Manual

Exercise 7-3Objective: 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.

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

Page 322: CVI Basics I (Course Manual).pdf

Lesson 7 Exercises

LabWindows/CVI Basics I Course Manual 7-18 © National Instruments Corporation

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.

Page 323: CVI Basics I (Course Manual).pdf

Lesson 7 Exercises

© National Instruments Corporation 7-19 LabWindows/CVI Basics I Course Manual

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.

Page 324: CVI Basics I (Course Manual).pdf

Lesson 7 Exercises

LabWindows/CVI Basics I Course Manual 7-20 © National Instruments Corporation

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

Instrument Handle: simHandle

Status: Leave blank

Page 325: CVI Basics I (Course Manual).pdf

Lesson 7 Exercises

© National Instruments Corporation 7-21 LabWindows/CVI Basics I Course Manual

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 Arra y: waveArray

Instrument Handle: simHandle

Status: 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: panelHandle

Control ID: PANEL_GRAPH

Plot Handle: -1

Refresh: Immediate Draw

Status: 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: panelHandle

Control ID: PANEL_GRAPH

Y Arra y: waveArray

Number of Points: 128

Plot Handle: Leave blank

Page 326: CVI Basics I (Course Manual).pdf

Lesson 7 Exercises

LabWindows/CVI Basics I Course Manual 7-22 © National Instruments Corporation

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

Page 327: CVI Basics I (Course Manual).pdf

Lesson 7 Exercises

© National Instruments Corporation 7-23 LabWindows/CVI Basics I Course Manual

Exercise 7-3 Program Listing#include <cvirte.h>#include <userint.h>#include "devsim.h"#include "simwav.h"

static int panelHandle;static ViReal64 waveArray[128]; static int select;static 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);

Page 328: CVI Basics I (Course Manual).pdf

Lesson 7 Exercises

LabWindows/CVI Basics I Course Manual 7-24 © National Instruments Corporation

break;}return 0;

}

End of Exercise 7-3

Page 329: CVI Basics I (Course Manual).pdf

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

Lesson 8Exercises

Exercise 8-1Objectives: 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:

Page 330: CVI Basics I (Course Manual).pdf

Lesson 8 Exercises

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

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

Page 331: CVI Basics I (Course Manual).pdf

© National Instruments Corporation A-1 LabWindows/CVI Basics I Course Manual

Appendix

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

Page 332: CVI Basics I (Course Manual).pdf

Appendix

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

A. File I/OFiles 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 computer’s 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 Fileint 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.

Close Fileint 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.

Parameter = 0 = 1 = 2

Read/Write_Mode Open file for reading and writing

Open file for reading only

Open file for writing only

Action Truncate file (delete old contents)

Append new data to end of existing file

Do not truncate file

File_Type Use binary code Use ASCII mode Invalid value

Page 333: CVI Basics I (Course Manual).pdf

Appendix

© National Instruments Corporation A-3 LabWindows/CVI Basics I Course Manual

Write To Fileint 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 Fileint 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 Fileint 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.

Page 334: CVI Basics I (Course Manual).pdf

Appendix

LabWindows/CVI Basics I Course Manual A-4 © National Instruments Corporation

Scan from Fileint 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

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

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.

int readings[100];int file_handle;

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

double waveform[100];int file_handle;

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

Page 335: CVI Basics I (Course Manual).pdf

Appendix

© National Instruments Corporation A-5 LabWindows/CVI Basics I Course Manual

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>

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.

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

Page 336: CVI Basics I (Course Manual).pdf

Appendix

LabWindows/CVI Basics I Course Manual A-6 © National Instruments Corporation

B. Formatting and Scanning Modifiersmodifiers 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.

i n 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.

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.

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

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

Page 337: CVI Basics I (Course Manual).pdf

Appendix

© National Instruments Corporation A-7 LabWindows/CVI Basics I Course Manual

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.

s Specify as Two’s Complement. The s integer modifier indicates that the integer argument is considered a signed two’s complement number. This number is the default interpretation of integers, so the s modifier is never explicitly required.

u Specify as Unsigned. The u integer modifier indicates that the integer is considered an unsigned integer.

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 n’s 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 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.

Page 338: CVI Basics I (Course Manual).pdf

Appendix

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

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.

i n 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.

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

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

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

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

Page 339: CVI Basics I (Course Manual).pdf

Appendix

© National Instruments Corporation A-9 LabWindows/CVI Basics I Course Manual

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.

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

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

i n 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.

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

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

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.

Page 340: CVI Basics I (Course Manual).pdf

Appendix

LabWindows/CVI Basics I Course Manual A-10 © National Instruments Corporation

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.

t n 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.

t- Terminate when Full. The t- modifier is similar to t n, 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.

t# 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.

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 .

i n 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

Page 341: CVI Basics I (Course Manual).pdf

Appendix

© National Instruments Corporation A-11 LabWindows/CVI Basics I Course Manual

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.

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

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

s Specify as Two’s Complement. The s integer modifier indicates that the integer argument is to be considered a signed two’s complement number. This number is the default interpretation of integers, so the s modifier is not required.

u Specify as Non-negative. The u integer modifier indicates that the integer is to be considered a non-negative integer.

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

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.

Page 342: CVI Basics I (Course Manual).pdf

Appendix

LabWindows/CVI Basics I Course Manual A-12 © National Instruments Corporation

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 n’s 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.

Page 343: CVI Basics I (Course Manual).pdf

Appendix

© National Instruments Corporation A-13 LabWindows/CVI Basics I Course Manual

i n 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.

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

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

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

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

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

x 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

Page 344: CVI Basics I (Course Manual).pdf

Appendix

LabWindows/CVI Basics I Course Manual A-14 © National Instruments Corporation

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)

i n 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.

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

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

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.

Page 345: CVI Basics I (Course Manual).pdf

Appendix

© National Instruments Corporation A-15 LabWindows/CVI Basics I Course Manual

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.

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

t n 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.

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.

t- Terminate when Full. The t- modifier is similar to t n, 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.

t# 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.

Page 346: CVI Basics I (Course Manual).pdf

Appendix

LabWindows/CVI Basics I Course Manual A-16 © National Instruments Corporation

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

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

Page 347: CVI Basics I (Course Manual).pdf

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

Title: LabWindows/CVI Basics I Course Manual

Edition Date: January 1999

Part Number: 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 Fax to: Technical PublicationsNational Instruments Corporation National Instruments Corporation11500 North Mopac Expressway 512 683 6837Austin, Texas 78759

Page 348: CVI Basics I (Course Manual).pdf
Page 349: CVI Basics I (Course Manual).pdf

Course __________________________________________________________________________________________________________

Austin Onsite Regional Location ____________________________________________

Instructor__________________________________________________________________ Date ____________________________

STUD

ENT

INFO

RMAT

ION

INST

RUCT

ORCO

URSE

© Copyright 1994 National Instruments Corporation. All rights reserved.280104B-01071594

Course Evaluation

NATIONAL INSTRUMENTS™

The Software is the Instrument ®

(Optional)

Name ____________________________________________________________________________________________________________________

Company ______________________________________________________ Phone __________________________________________________

Please evaluate the instructor by checking the appropriate circle. Outstanding Good Okay Poor Unsatisfactory

Instructor’s ability to communicate the material Instructor’s sensitivity to class needs

Instructor’s knowledge of the subject matter Instructor’s preparation for the class

Instructor’s presentation skills

Training facility quality Training equipment quality

The course length was Too Long Just Right Too Short

The detail of topics covered in the course was Too Much Just Right Not Enough

The course material was clear and easy to follow. Yes No Sometimes

Did the course cover material as advertised? Yes No

I had the skills or knowledge I needed to attend this course. Yes No If no, how could you have been better prepared for the 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 _______________________________________________________________________________________________________________________

Page 350: CVI Basics I (Course Manual).pdf