Labwindows SL
Labwindows SL
Labwindows SL
Standard Libraries
Reference Manual
Internet Support
GPIB: gpib.support@natinst.com
DAQ: daq.support@natinst.com
VXI: vxi.support@natinst.com
LabVIEW: lv.support@natinst.com
LabWindows: lw.support@natinst.com
HiQ: hiq.support@natinst.com
VISA: visa.support@natinst.com
Lookout: lookout.support@natinst.com
FTP Site: ftp.natinst.com
Web Address: www.natinst.com
Bulletin Board Support
BBS United States: (512) 794-5422 or (800) 327-3077
BBS United Kingdom: 01635 551422
BBS France: 1 48 65 15 59
FaxBack Support
(512) 418-1111
International Offices
Australia 03 9 879 9422, Austria 0662 45 79 90 0, Belgium 02 757 00 20,
Canada (Ontario) 519 622 9310, Canada (Qubec) 514 694 8521, Denmark 45 76 26 00,
Finland 90 527 2321, France 1 48 14 24 24, Germany 089 741 31 30, Hong Kong 2645 3186,
Italy 02 413091, Japan 03 5472 2970, Korea 02 596 7456, Mexico 95 800 010 0793,
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, U.K. 01635 523545
Austin, TX 78730-5039
Warranty
The media on which you receive National Instruments software are warranted not to fail to execute programming
instructions, due to defects in materials and workmanship, for a period of 90 days from date of shipment, as
evidenced by receipts or other documentation. National Instruments will, at its option, repair or replace software
media that do not execute programming instructions if National Instruments receives notice of such defects during
the warranty period. National Instruments does not warrant that the operation of the software shall be uninterrupted
or error free.
A Return Material Authorization (RMA) number must be obtained from the factory and clearly marked on the
outside of the package before any equipment will be accepted for warranty work. National Instruments will pay the
shipping costs of returning to the owner parts which are covered by warranty.
National Instruments believes that the information in this manual is accurate. The document has been carefully
reviewed for technical accuracy. In the event that technical or typographical errors exist, National Instruments
reserves the right to make changes to subsequent editions of this document without prior notice to holders of this
edition. The reader should consult National Instruments if errors are suspected. In no event shall National
Instruments be liable for any damages arising out of or related to this document or the information contained in it.
EXCEPT AS SPECIFIED HEREIN, NATIONAL INSTRUMENTS MAKES NO WARRANTIES, EXPRESS OR IMPLIED, AND
SPECIFICALLY DISCLAIMS ANY WARRANTY OF MERCHANTABILITY OR FITNESS FOR A PARTICULAR PURPOSE.
CUSTOMERS RIGHT TO RECOVER DAMAGES CAUSED BY FAULT OR NEGLIGENCE ON THE PART OF NATIONAL
INSTRUMENTS SHALL BE LIMITED TO THE AMOUNT THERETOFORE PAID BY THE CUSTOMER. NATIONAL INSTRUMENTS
WILL NOT BE LIABLE FOR DAMAGES RESULTING FROM LOSS OF DATA, PROFITS, USE OF PRODUCTS, OR INCIDENTAL OR
CONSEQUENTIAL DAMAGES, EVEN IF ADVISED OF THE POSSIBILITY THEREOF. This limitation of the liability of
National Instruments will apply regardless of the form of action, whether in contract or tort, including negligence.
Any action against National Instruments must be brought within one year after the cause of action accrues. National
Instruments shall not be liable for any delay in performance due to causes beyond its reasonable control. The
warranty provided herein does not cover damages, defects, malfunctions, or service failures caused by owners
failure to follow the National Instruments installation, operation, or maintenance instructions; owners modification
of the product; owners abuse, misuse, or negligent acts; and power failure or surges, fire, flood, accident, actions of
third parties, or other events outside reasonable control.
Copyright
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
NI-DAQ, NI-488.2, and NI-488.2M are trademarks of National Instruments Corporation.
Product and company names listed are trademarks or trade names of their respective companies.
Contents
_____________________________________________________________________________
Chapter 1
ANSI C Library ................................................................................................................1-1
Low-Level I/O Functions .............................................................................................1-2
Standard Language Additions ......................................................................................1-2
Character Processing ....................................................................................................1-5
String Processing..........................................................................................................1-5
Input/Output Facilities .................................................................................................1-6
errno Set by File I/O Functions ....................................................................................1-6
Mathematical Functions ...............................................................................................1-6
Time and Date Functions .............................................................................................1-6
Control Functions.........................................................................................................1-7
ANSI C Library Function Reference............................................................................1-9
fdopen...............................................................................................................1-9
Chapter 2
Formatting and I/O Library ........................................................................................2-1
Formatting and I/O Library Function Overview ..........................................................2-1
The Formatting and I/O Library Function Panels ............................................2-1
The String Manipulation Functions .................................................................2-3
The Special Nature of the Formatting and Scanning Functions.......................2-3
Formatting and I/O Library Function Reference..........................................................2-4
ArrayToFile......................................................................................................2-4
CloseFile ..........................................................................................................2-7
CompareBytes ..................................................................................................2-7
CompareStrings................................................................................................2-8
CopyBytes ........................................................................................................2-9
CopyString .......................................................................................................2-10
FileToArray......................................................................................................2-11
FillBytes ...........................................................................................................2-13
FindPattern .......................................................................................................2-13
Fmt ...................................................................................................................2-14
FmtFile .............................................................................................................2-15
FmtOut .............................................................................................................2-16
GetFileInfo .......................................................................................................2-17
Contents
GetFmtErrNdx..................................................................................................2-18
GetFmtIOError .................................................................................................2-18
GetFmtIOErrorString .......................................................................................2-19
NumFmtdBytes ................................................................................................2-20
OpenFile ...........................................................................................................2-20
ReadFile ...........................................................................................................2-22
ReadLine ..........................................................................................................2-23
Scan ..................................................................................................................2-24
ScanFile............................................................................................................2-25
ScanIn...............................................................................................................2-25
SetFilePtr..........................................................................................................2-26
StringLength.....................................................................................................2-28
StringLowerCase..............................................................................................2-28
StringUpperCase ..............................................................................................2-29
WriteFile...........................................................................................................2-29
WriteLine .........................................................................................................2-30
Using the Formatting and Scanning Functions ............................................................2-31
Introductory Formatting and Scanning Examples............................................2-31
Formatting Functions .......................................................................................2-32
Formatting FunctionsFormat String.................................................2-33
Formatting Modifiers ...........................................................................2-35
Formatting Integer Modifiers (%i, %d, %x, %o, %c)..............2-35
Formatting Floating-Point Modifiers (%f)...............................2-37
Formatting String Modifiers (%s) ............................................2-38
Fmt, FmtFile, FmtOutAsterisks (*) Instead of Constants
in Format Specifiers .............................................................................2-39
Fmt, FmtFile, FmtOutLiterals in the Format String.........................2-40
Scanning Functions ..........................................................................................2-40
Scanning FunctionsFormat String....................................................2-41
Scanning Modifiers ..............................................................................2-43
Scanning Integer Modifiers (%i, %d, %x, %o, %c).................2-43
Scanning Floating-Point Modifiers (%f)..................................2-45
Scanning String Modifiers (%s)...............................................2-46
Scan, ScanFile, ScanInAsterisks (*) Instead of Constants
in Format Specifiers .............................................................................2-48
Scan, ScanFile, ScanInLiterals in the Format String .......................2-48
Formatting and I/O Library Programming Examples ..................................................2-49
Fmt/FmtFile/FmtOut Examples in C ...............................................................2-50
Integer to String....................................................................................2-50
Long Integer to String ..........................................................................2-51
Real to String in Floating-Point Notation ............................................2-51
Real to String in Scientific Notation ....................................................2-52
Integer and Real to String with Literals ...............................................2-53
Two Integers to ASCII File with Error Checking ................................2-53
Real Array to ASCII File in Columns and with Comma Separators ...2-53
vi
Contents
vii
Contents
Chapter 3
Analysis Library ...............................................................................................................3-1
Analysis Library Function Overview...........................................................................3-1
The Analysis Library Function Panels .............................................................3-1
Hints for Using Analysis Function Panels ...........................................3-3
Reporting Analysis Errors................................................................................3-4
Analysis Library Function Reference...........................................................................3-4
Abs1D...............................................................................................................3-4
Add1D ..............................................................................................................3-5
Add2D ..............................................................................................................3-5
Clear1D ............................................................................................................3-6
Copy1D ............................................................................................................3-7
CxAdd ..............................................................................................................3-7
CxAdd1D .........................................................................................................3-8
CxDiv ...............................................................................................................3-9
CxDiv1D ..........................................................................................................3-10
CxLinEv1D ......................................................................................................3-11
CxMul ..............................................................................................................3-12
CxMul1D..........................................................................................................3-12
CxRecip............................................................................................................3-13
CxSub ...............................................................................................................3-14
CxSub1D ..........................................................................................................3-15
Determinant......................................................................................................3-16
Div1D ...............................................................................................................3-16
Div2D ...............................................................................................................3-17
DotProduct .......................................................................................................3-18
GetAnalysisErrorString....................................................................................3-19
Histogram .........................................................................................................3-19
InvMatrix..........................................................................................................3-20
LinEv1D ...........................................................................................................3-21
LinEv2D ...........................................................................................................3-22
MatrixMul ........................................................................................................3-23
MaxMin1D .......................................................................................................3-24
MaxMin2D .......................................................................................................3-24
Mean.................................................................................................................3-25
Mul1D ..............................................................................................................3-26
Mul2D ..............................................................................................................3-27
Neg1D ..............................................................................................................3-28
Set1D................................................................................................................3-28
Sort ...................................................................................................................3-29
StdDev..............................................................................................................3-29
Sub1D...............................................................................................................3-30
Sub2D...............................................................................................................3-31
Subset1D ..........................................................................................................3-32
ToPolar .............................................................................................................3-32
viii
Contents
ToPolar1D ........................................................................................................3-33
ToRect ..............................................................................................................3-34
ToRect1D .........................................................................................................3-35
Transpose .........................................................................................................3-36
Error Conditions...........................................................................................................3-37
Chapter 4
GPIB/GPIB-488.2 Library ...........................................................................................4-1
GPIB Library Function Overview................................................................................4-1
GPIB Functions Library Function Panels ........................................................4-1
GPIB Library Concepts................................................................................................4-5
GPIB Libraries and the GPIB Dynamic Link Library/Device Driver..............4-5
Guidelines and Restrictions for Using the GPIB Libraries ..............................4-6
Device and Board Functions ............................................................................4-7
Automatic Serial Polling ..................................................................................4-7
Autopolling Compatibility ...................................................................4-8
Hardware Interrupts and Autopolling...............................................................4-8
Read and Write Termination ............................................................................4-9
Timeouts...........................................................................................................4-9
Global Variables for the GPIB Library ............................................................4-10
Different Levels of Functionality Depending on Platform and GPIB Board...4-10
Windows 95..........................................................................................4-10
Native 32-Bit Driver.................................................................4-10
Compatibility Driver ................................................................4-11
Windows NT ........................................................................................4-11
Limitations on Transfer Size ............................................................................4-11
Multithreading..................................................................................................4-11
Notification of SRQ and Other GPIB Events...................................................4-12
Synchronous Callbacks ........................................................................4-12
Asynchronous Callbacks ......................................................................4-12
Driver Version Requirements...............................................................4-12
GPIB Function Reference ............................................................................................4-13
CloseDev ..........................................................................................................4-13
CloseInstrDevs .................................................................................................4-14
ibInstallCallback...............................................................................................4-14
SRQI, RQS, and Auto Serial Polling ...................................................4-16
CallbackFunction .................................................................................4-17
ibNotify ............................................................................................................4-17
eventMask ............................................................................................4-18
SRQI, RQS, and Auto Serial Polling ...................................................4-19
CallbackFunction .................................................................................4-19
Restrictions on Operations in Asynchronous Callbacks ......................4-20
OpenDev...........................................................................................................4-21
ThreadIbcnt ......................................................................................................4-22
ThreadIbcntl .....................................................................................................4-22
ix
Contents
ThreadIberr.......................................................................................................4-23
ThreadIbsta.......................................................................................................4-25
Chapter 5
RS-232 Library .................................................................................................................5-1
RS-232 Library Function Overview.............................................................................5-1
The RS-232 Library Function Panels...............................................................5-1
Using RS-485 ...................................................................................................5-3
Reporting RS-232 Errors..................................................................................5-3
XModem File Transfer Functions ....................................................................5-3
Troubleshooting ...............................................................................................5-3
RS-232 Cable Information ...............................................................................5-4
Handshaking.....................................................................................................5-6
Software Handshaking .........................................................................5-6
Hardware Handshaking ........................................................................5-7
RS-232 Library Function Reference ............................................................................5-8
CloseCom .........................................................................................................5-8
ComBreak.........................................................................................................5-9
ComFromFile ...................................................................................................5-9
ComRd .............................................................................................................5-11
ComRdByte......................................................................................................5-12
ComRdTerm.....................................................................................................5-12
ComSetEscape..................................................................................................5-14
ComToFile .......................................................................................................5-15
ComWrt............................................................................................................5-16
ComWrtByte ....................................................................................................5-17
FlushInQ...........................................................................................................5-18
FlushOutQ ........................................................................................................5-19
GetComStat ......................................................................................................5-19
GetInQLen........................................................................................................5-20
GetOutQLen .....................................................................................................5-21
GetRS232ErrorString .......................................................................................5-22
InstallComCallback..........................................................................................5-22
OpenCom .........................................................................................................5-25
OpenComConfig ..............................................................................................5-26
ReturnRS232Err ...............................................................................................5-28
SetComTime ....................................................................................................5-29
SetCTSMode ....................................................................................................5-30
SetXMode.........................................................................................................5-31
XModemConfig ...............................................................................................5-31
XModemReceive..............................................................................................5-33
XModemSend...................................................................................................5-34
Error Conditions...........................................................................................................5-36
Contents
Chapter 6
DDE Library ......................................................................................................................6-1
DDE Library Function Overview.................................................................................6-1
The DDE Library Function Panels...................................................................6-1
DDE Clients and Servers..................................................................................6-2
The DDE Callback Function ............................................................................6-2
DDE Links........................................................................................................6-4
A DDE Library Example Using Microsoft Excel and LabWindows/CVI.......6-5
DDE Library Function Reference ................................................................................6-6
AdviseDDEDataReady.....................................................................................6-6
BroadcastDDEDataReady ................................................................................6-8
ClientDDEExecute ...........................................................................................6-10
ClientDDERead................................................................................................6-10
ClientDDEWrite...............................................................................................6-12
ConnectToDDEServer .....................................................................................6-13
DisconnectFromDDEServer.............................................................................6-15
GetDDEErrorString..........................................................................................6-15
RegisterDDEServer..........................................................................................6-16
ServerDDEWrite ..............................................................................................6-19
SetUpDDEHotLink ..........................................................................................6-20
SetUpDDEWarmLink ......................................................................................6-21
TerminateDDELink..........................................................................................6-22
UnregisterDDEServer ......................................................................................6-23
Error Conditions...........................................................................................................6-23
Chapter 7
TCP Library .......................................................................................................................7-1
TCP Library Function Overview..................................................................................7-1
The TCP Library Function Panels....................................................................7-1
TCP Clients and Servers ..................................................................................7-2
The TCP Callback Function.............................................................................7-2
TCP Library Function Reference .................................................................................7-3
ClientTCPRead ................................................................................................7-3
ClientTCPWrite................................................................................................7-4
ConnectToTCPServer ......................................................................................7-5
DisconnectFromTCPServer .............................................................................7-7
DisconnectTCPClient.......................................................................................7-7
GetTCPErrorString...........................................................................................7-8
RegisterTCPServer...........................................................................................7-8
ServerTCPRead................................................................................................7-10
ServerTCPWrite ...............................................................................................7-11
UnregisterTCPServer .......................................................................................7-11
Error Conditions...........................................................................................................7-12
xi
Contents
Chapter 8
Utility Library ...................................................................................................................8-1
The Utility Library Function Panels.............................................................................8-1
Utility Library Function Reference ..............................................................................8-5
Beep..................................................................................................................8-5
Breakpoint ........................................................................................................8-6
CloseCVIRTE ..................................................................................................8-6
Cls ....................................................................................................................8-7
CopyFile ...........................................................................................................8-7
CVILowLevelSupportDriverLoaded................................................................8-8
DateStr..............................................................................................................8-9
Delay ................................................................................................................8-9
DeleteDir ..........................................................................................................8-10
DeleteFile .........................................................................................................8-10
DisableBreakOnLibraryErrors .........................................................................8-11
DisableInterrupts ..............................................................................................8-12
DisableTaskSwitching......................................................................................8-12
EnableBreakOnLibraryErrors ..........................................................................8-15
EnableInterrupts ...............................................................................................8-15
EnableTaskSwitching.......................................................................................8-16
ExecutableHasTerminated................................................................................8-16
GetBreakOnLibraryErrors................................................................................8-17
GetBreakOnProtectionErrors ...........................................................................8-18
GetCVIVersion.................................................................................................8-18
GetCurrentPlatform..........................................................................................8-19
GetDir...............................................................................................................8-20
GetDrive ...........................................................................................................8-20
GetExternalModuleAddr..................................................................................8-21
GetFileAttrs......................................................................................................8-23
GetFileDate ......................................................................................................8-24
GetFileSize .......................................................................................................8-25
GetFileTime .....................................................................................................8-26
GetFirstFile ......................................................................................................8-27
GetFullPathFromProject ..................................................................................8-29
GetInterruptState ..............................................................................................8-30
GetKey .............................................................................................................8-30
GetModuleDir ..................................................................................................8-31
GetNextFile ......................................................................................................8-33
GetPersistentVariable.......................................................................................8-33
GetProjectDir ...................................................................................................8-34
GetStdioPort .....................................................................................................8-35
GetStdioWindowOptions .................................................................................8-35
GetStdioWindowPosition.................................................................................8-36
GetStdioWindowSize .......................................................................................8-37
GetStdioWindowVisibility...............................................................................8-37
xii
Contents
GetSystemDate.................................................................................................8-38
GetSystemTime................................................................................................8-39
GetWindowDisplaySetting...............................................................................8-39
InitCVIRTE......................................................................................................8-40
inp.....................................................................................................................8-42
inpw..................................................................................................................8-42
InStandaloneExecutable ...................................................................................8-43
KeyHit ..............................................................................................................8-43
LaunchExecutable ............................................................................................8-44
LaunchExecutableEx........................................................................................8-47
LoadExternalModule........................................................................................8-49
LoadExternalModuleEx ...................................................................................8-52
MakeDir ...........................................................................................................8-54
MakePathname .................................................................................................8-55
outp...................................................................................................................8-56
outpw................................................................................................................8-56
ReadFromPhysicalMemory..............................................................................8-57
ReadFromPhysicalMemoryEx .........................................................................8-58
ReleaseExternalModule ...................................................................................8-59
RenameFile.......................................................................................................8-60
RetireExecutableHandle...................................................................................8-61
RoundRealToNearestInteger ............................................................................8-61
RunExternalModule .........................................................................................8-62
SetBreakOnLibraryErrors ................................................................................8-63
SetBreakOnProtectionErrors............................................................................8-64
SetDir ...............................................................................................................8-66
SetDrive............................................................................................................8-66
SetFileAttrs ......................................................................................................8-67
SetFileDate .......................................................................................................8-68
SetFileTime ......................................................................................................8-70
SetPersistentVariable .......................................................................................8-71
SetStdioPort......................................................................................................8-71
SetStdioWindowOptions..................................................................................8-72
SetStdioWindowPosition .................................................................................8-74
SetStdioWindowSize........................................................................................8-75
SetStdioWindowVisibility ...............................................................................8-76
SetSystemDate .................................................................................................8-76
SetSystemTime ................................................................................................8-77
SplitPath ...........................................................................................................8-77
SyncWait ..........................................................................................................8-79
SystemHelp ......................................................................................................8-79
TerminateExecutable........................................................................................8-82
Timer ................................................................................................................8-83
TimeStr.............................................................................................................8-83
TruncateRealNumber .......................................................................................8-84
xiii
Contents
UnloadExternalModule ....................................................................................8-84
WriteToPhysicalMemory .................................................................................8-85
WriteToPhysicalMemoryEx.............................................................................8-86
Chapter 9
X Property Library .........................................................................................................9-1
X Property Library Overview.......................................................................................9-1
The X Property Library Function Panels .........................................................9-1
X Interclient Communication...........................................................................9-2
Property Handles and Types ............................................................................9-3
Communicating with Local Applications ........................................................9-3
The Hidden Window ........................................................................................9-3
Property Callback Functions ............................................................................9-4
Error Codes ......................................................................................................9-4
Using the Library Outside of LabWindows/CVI .............................................9-7
X Property Library Function Reference.......................................................................9-7
ConnectToXDisplay.........................................................................................9-7
CreateXProperty...............................................................................................9-9
CreateXPropType.............................................................................................9-10
DestroyXProperty.............................................................................................9-12
DestroyXPropType...........................................................................................9-13
DisconnectFromXDisplay................................................................................9-14
GetXPropErrorString .......................................................................................9-15
GetXPropertyName..........................................................................................9-15
GetXPropertyType ...........................................................................................9-16
GetXPropTypeName........................................................................................9-17
GetXPropTypeSize...........................................................................................9-18
GetXPropTypeUnit ..........................................................................................9-19
GetXWindowPropertyItem ..............................................................................9-20
GetXWindowPropertyValue ............................................................................9-22
InstallXPropertyCallback .................................................................................9-25
PutXWindowPropertyItem...............................................................................9-27
PutXWindowPropertyValue.............................................................................9-29
RemoveXWindowProperty ..............................................................................9-31
UninstallXPropertyCallback ............................................................................9-33
Chapter 10
Easy I/O for DAQ Library ...........................................................................................10-1
Easy I/O for DAQ Library Function Overview............................................................10-1
Advantages of Using the Easy I/O for DAQ Library.......................................10-1
Limitations of Using the Easy I/O for DAQ Library .......................................10-2
Easy I/O for DAQ Library Function Panels.....................................................10-2
Device Numbers...............................................................................................10-4
Channel String for Analog Input Functions .....................................................10-4
Command Strings.............................................................................................10-6
xiv
Contents
Appendix A
Customer Communication .............................................................................................A-1
Glossary ................................................................................................................................G-1
Index ......................................................................................................................................I-1
xv
Contents
Tables
Table 1-1. ANSI C Standard Library Classes .........................................................................1-1
Table 1-2. C Locale Information Values.................................................................................1-3
Table 2-1. The Formatting and I/O Library Function Tree.....................................................2-2
Table 3-1. The Analysis Library Function Tree......................................................................3-1
Table 3-2. Analysis Library Error Codes ................................................................................3-37
Table 4-1. The GPIB Functions Library Function Tree..........................................................4-2
Table 5-1.
Table 5-2.
Table 5-3.
Table 5-4.
Table 5-5.
Table 5-6.
Table 10-1.
Table 10-2.
Table 10-3.
Table 10-4.
Table 10-5.
xvi
Chapter 2, Formatting and I/O Library, describes the functions in the LabWindows/CVI
Formatting and I/O Library, and contains many examples of how to use them. The
Formatting and I/O Library contains functions that input and output data to files and
manipulate the format of data in a program.
Chapter 4, GPIB/GPIB-488.2 Library, describes the NI-488 and NI-488.2 functions in the
LabWindows/CVI GPIB Library, as well as the Device Manager functions in
LabWindows/CVI. The GPIB Library Function Overview section contains general
information about the GPIB Library functions and panels, the GPIB DLL, and guidelines
and restrictions you should know when using the GPIB Library. Detailed descriptions of the
NI-488 and NI-488.2 functions can be found in your NI-488.2 function reference manual.
The GPIB Function Reference section contains an alphabetical list of descriptions for the
Device Manager functions, the callback installation functions, and the functions for returning
the thread-specific status variables.
xvii
Chapter 5, RS-232 Library, describes the functions in the LabWindows/CVI RS-232 Library.
The RS-232 Library Function Overview section contains general information about the RS-232
Library functions and panels. The RS-232 Library Function Reference section contains an
alphabetical list of function descriptions.
Chapter 6, DDE Library, describes the functions in the LabWindows/CVI DDE (Dynamic
Data Exchange) Library. The DDE Library Function Overview section contains general
information about the DDE Library functions and panels. The DDE Library Function
Reference section contains an alphabetical list of function descriptions. This library is
available for LabWindows/CVI for Microsoft Windows only.
Chapter 7, TCP Library, describes the functions in the LabWindows/CVI TCP (Transmission
Control Protocol) Library. The TCP Library Function Overview section contains general
information about the TCP Library functions and panels. The TCP Library Function
Reference section contains an alphabetical list of function descriptions.
Chapter 8, Utility Library, describes the functions in the LabWindows/CVI Utility Library.
The Utility Library contains functions that do not fit into any of the other LabWindows/CVI
libraries. The Utility Library Function Panels section contains general information about the
Utility Library functions and panels. The Utility Library Function Reference section contains
an alphabetical list of function descriptions.
Chapter 9, X Property Library, describes the functions in the Lab/Windows CVI X Property
Library. The X Property Library contains functions that read and write properties to and from
X Windows. The X Property Library Overview section contains general information about
the X Property Library functions and panels. The X Property Library Function Reference
section contains an alphabetical list of function descriptions.
Chapter 10, Easy I/O for DAQ Library describes the functions in the Easy I/O for DAQ
Library. The Easy I/O for DAQ Library Function Overview section contains general
information about the functions, and guidelines and restrictions you should know when using
the Easy I/O for DAQ Library. The Easy I/O for DAQ Library Function Reference section
contains an alphabetical list of function descriptions.
Appendix A, Customer Communication, contains forms you can use to request help from
National Instruments or to comment on our products and manuals.
The Glossary contains an alphabetical list and description of terms used in this manual,
including abbreviations, acronyms, metric prefixes, mnemonics, and symbols.
The Index contains an alphabetical list of key terms and topics in this manual, including the
page where you can find each one.
xviii
italic
bold italic
monospace
Text in this font denotes text or characters that you should literally
enter from the keyboard. Sections of code, programming
examples, and syntax examples also appear in this font. This font
also is used for the proper names of disk drives, paths, directories,
programs, subprograms, subroutines, device names, variables,
filenames, and extensions, and for statements and comments taken
from program code.
italic monospace
Italic text in this font denotes that you must supply the appropriate
words or values in the place of these items.
<>
The symbol leads you through nested menu items and dialog
box options to a final action. The sequence
File Page Setup Options Substitute Fonts
directs you to pull down the File menu, select the Page Setup
item, select Options, and finally select the Substitute Fonts
option from the last dialog box.
paths
IEEE 488, IEEE 488 and IEEE 488.2 refer to the ANSI/IEEE Standard 488.1-1987, IEEE 488.2
and the ANSI/IEEE Standard 488.2-1992, respectively, which define the GPIB.
Abbreviations, acronyms, metric prefixes, mnemonics, symbols, and terms are listed in the
Glossary.
xix
Related Documentation
The following documents contain information that you may find helpful as you read this manual:
ANSI/IEEE Standard 488.2-1992, IEEE Standard Codes, Formats, Protocols, and Common
Commands
Harbison, Samuel P. and Guy L. Steele, Jr., C: A Reference Manual, Englewood Cliffs, NJ:
Prentice-Hall, Inc., 1995.
Nye, Adrian. Xlib Programming Manual. Sebastopol, California: O'Reilly & Associates,
1994. ISBN 0-937175-27-7
Gettys, James and Robert W. Scheifler. XlibC Language X Interface, MIT X Consortium
Standard. Cambridge, Massachussetts: X Consortium, 1994. ISBN (none)
Customer Communication
National Instruments wants to receive your comments on our products and manuals. We are
interested in the applications you develop with our products, and we want to help if you have
problems with them. To make it easy for you to contact us, this manual contains comment and
technical support forms for you to complete. These forms are in the appendix, Customer
Communication, at the end of this manual.
xx
Chapter 1
ANSI C Library
This chapter describes the ANSI C Standard Library as implemented in LabWindows/CVI.
Note: When you link your executable or DLL with an external compiler, you are using the
ANSI C library of the external compiler.
Table 1-1. ANSI C Standard Library Classes
Class
Character Handling
Character Testing
Character Case Mapping
Date and Time
Time Operations
Time Conversion
Time Formatting
Localization
Mathematics
Trigonometric Functions
Hyperbolic Functions
Exp and Log Functions
Power Functions
Nonlocal Jumping
Signal Handling
Input/Output
Open/Close
Read/Write/Flush
Line Input/Output
Character Input/Output
Formatted Input/Output
Buffer Control
File Positioning
File System Operations
Error Handling
Header File
<ctype.h>
<time.h>
<locale.h>
<math.h>
<setjmp.h>
<signal.h>
<stdio.h>
(continues)
1-1
ANSI C Library
Chapter 1
<stdlib.h>
<string.h>
1-2
Chapter 1
ANSI C Library
Type
decimal_point
char *
"."
thousands_sep
char *
""
grouping
char *
""
int_curr_symbol
char *
""
currency_symbol
char *
""
mon_decimal_point
char *
""
mon_thousands_sep
char *
""
mon_grouping
char *
""
positive_sign
char *
""
negative_sign
char *
""
int_frac_digits
char
CHAR_MAX
frac_digits
char
CHAR_MAX
p_cs_precedes
char
CHAR_MAX
p_sep_by_space
char
CHAR_MAX
n_cs_precedes
char
CHAR_MAX
n_sep_by_space
char
CHAR_MAX
p_sign_posn
char
CHAR_MAX
n_sign_posn
char
CHAR_MAX
1-3
ANSI C Library
Chapter 1
Under Windows, LabWindows/CVI implements the default locale by using the appropriate items
from the Intl section of the WIN.INI file and appropriate Microsoft Windows functions.
Anything not mentioned here has the same behavior under the default locale as specified in the C
locale.
For the LC_NUMERIC locale:
decimal_point maps to the value of sDecimal.
thousands_sep maps to the value of sThousand.
For the LC_MONETARY locale:
currency_symbol maps to the value of sCurrency.
mon_decimal_point maps to the value of sDecimal.
mon_thousands_sep maps to the value of sThousand.
frac_digits maps to the value of iCurrDigits.
int_frac_digits maps to the value of iCurrDigits.
p_cs_precedes and n_cs_precedes are set to 1 if iCurrency equals 0 or 2,
otherwise they are set to 0.
p_sep_by_space and n_sep_by_space are set to 0 if iCurrency equals 0 or 1,
otherwise they are set to 0.
p_sign_posn and n_sign_posn are determined by the value of iNegCurr as follows:
Value of iNegCurr
Value of
p_sign_posn/n_sign_posn
0, 4
1, 5, 8, 9
3, 7, 10
1-4
Chapter 1
ANSI C Library
The names of the weekdays and the names of the months match the language version of
LabWindows/CVI. That is, a German version of LabWindows/CVI would use the German
names of months and days.
Character Processing
LabWindows/CVI implements all the ANSI C character processing facilities as both macros and
functions. The macros are disabled when the LabWindows/CVI debugging level is set to
Standard or Extended, so that user protection is available for the arguments to the functions.
String Processing
Under UNIX, the strcoll function is equivalent to strcmp and its behavior is not affected by
the LC_COLLATE locale. Under Windows, strcoll is equivalent to the Windows function
lstrcmp. For both platforms, the function strxfrm performs a string copy using strncpy
and returns the length of its second argument.
1-5
ANSI C Library
Chapter 1
Input/Output Facilities
The function rename fails if the target file already exists. Under Microsoft Windows, rename
fails if the source and target files are on different disk drives. Under UNIX, rename fails if the
source and target files are on different file systems.
The functions fgetpos and ftell set errno to EFILPOS on error.
Mathematical Functions
The macro HUGE_VAL defined in the header math.h as well as the macros FLT_EPSILON,
FLT_MAX, FLT_MIN, DBL_EPSILON, DBL_MAX, DBL_MIN, LDBL_EPSILON, LDBL_MAX,
and DBL_MIN defined in the header float.h all refer to variables. Consequently, these
macros cannot be used in places where constant expressions are required, such as in global
initializations.
1-6
Chapter 1
ANSI C Library
The AAA and BBB fields specify the names of the standard and daylight savings time zones,
respectively (such as EST for Eastern Standard Time and EDT for Eastern Daylight Time). The
optional sign field S indicates whether the local time zone is to the west (+) or to the east (-) of
UTC (Greenwich Mean Time). The hour field (HH) and the optional minutes field (:MM) specify
the number of hours and minutes from UTC. As an example, the string EST05EDT specifies the
time zone information for the eastern part of the United States.
The functions gmtime, localtime, and mktime make corrections for daylight savings time
(DST). LabWindows/CVI uses a set of rules for determining when daylight savings time begins
and ends. A string in the messages file cvimsgs.txt in the LabWindows/CVI bin directory
specifies these rules. The following is the default value of this string.
":(1986)040102+0:110102-0:(1967)040102-0:110102-0"
This states that for the years from 1986 to the present, DST begins at 2:00 a.m. on the first
Sunday in April, and ends at 2:00 a.m. on the last Sunday in October. For the years from 1967 to
1985, DST begins at 2:00 a.m. on the last Sunday in March, and ends at 2:00 a.m. on the last
Sunday in October. You can change the way LabWindows/CVI determines DST by changing
this string in the cvimsgs.txt file. The countmsg.exe program must be executed after
changing the text file. You should execute the following line.
countmsg cvimsgs.txt
Control Functions
The assert macro defined by LabWindows/CVI does not print diagnostics to the standard
error stream when the debugging level is anything other than None. Instead, when the value of
its argument evaluates to zero, LabWindows/CVI will display a dialog box with a message
containing the file name, line number, and expression that caused the assert to fail.
Under UNIX, system passes the specified command to the Bourne shell (sh) as input, as if the
current process was performing a wait(2V) system call and was waiting until the shell
terminated. Callbacks are not called while the command is executing.
Under Windows, the executable can be either an MS DOS or Microsoft Windows executable,
including *.exe, *.com, *.bat, and *.pif files. The function does not return until the
command terminates, and user keyboard and mouse events are ignored until the command exits.
Callbacks for asynchronous events, such as idle events, Windows messages, and VXI interrupts,
PostDeferredCall calls, and DAQ events are called while the command is executing. If
you need to execute a command built into command.com such as copy, dir, and others, you
can call system with the command command.com /C DosCommand args, where
DosCommand is the shell command you would like executed. Refer to your DOS
documentation for further help with command.com. DOS executables (.exe, .com, and
.bat files) use the settings in _default.pif (in your Windows directory) when they are
running. You can change their priority, display options, and more by editing _default.pif
1-7
ANSI C Library
Chapter 1
or by creating another .pif file. Refer to your Microsoft Windows documentation for help on
creating and editing .pif files.
If the function is passed a null pointer, LabWindows/CVI returns a non zero value if a command
processor is available. Under UNIX, if the argument is not a null pointer, the program returns a
zero. Under Microsoft Windows, if the argument is not a null pointer, the program returns zero
if the program was successfully started, otherwise it returns one of the following error codes.
-1
-3
-4
-6
-7
-9
-11
-12
-13
-14
-15
-16
-17
-20
-21
-22
-23
-24
System was out of memory, executable file was corrupt, or relocations were invalid.
File was not found.
Path was not found.
Attempt was made to dynamically link to a task, or there was a sharing or network
protection error.
Library required separate data segments for each task.
There was insufficient memory to start the application.
Windows version was incorrect.
Executable file was invalid. Either it was not a Windows application or there was an error
in the .EXE image.
Application was designed for a different operating system.
Application was designed for MS-DOS 4.0.
Type of executable file was unknown.
Attempt made to load a real-mode application (developed for an earlier Windows version.)
Attempt was made to load a second instance of an executable file containing multiple data
segments that were not marked read-only.
Attempt was made to load a compressed executable file. The file must be decompressed
before it can be loaded.
Dynamic-link library (DLL) file was invalid. One of the DLLs required to run this
application was corrupt.
Application requires Microsoft Windows 32-bit extensions.
Could not find toolhelp.dll or toolhelp.dll is corrupted.
Could not allocate a GetProcUserDefinedHandle.
The exit function does not actually flush and close the open streams. LabWindows/CVI leaves
files open so that they may be used from within the Interactive Window after execution of the
project terminates. The Close Libraries menu option under the Run menu performs this library
cleanup. This library cleanup is also performed when you restart execution of the project by
selecting Run Project from the Run menu. The argument passed to function exit is not used
by the LabWindows/CVI environment. Under UNIX, standalone executables created by
LabWindows/CVI return the value of the argument passed to the exit function.
1-8
Chapter 1
ANSI C Library
The UNIX version of LabWindows/CVI works with all the signals supported by UNIX in
addition to the ANSI C signals.
fdopen
FILE *fp = fdopen (int fileHandle, char *mode);
Note: This function is available only in the Windows version of LabWindows/CVI.
Purpose
You can use this function to obtain a pointer to a buffered I/O stream from a file handle returned
by one of the following functions.
(low-level I/O)
(low-level I/O)
open
sopen
You can use the return value just as if you had obtained it from fopen.
(Although this function is not in the ANSI standard, it is included in this library because it
returns a pointer to a buffered I/O stream.)
Parameters
Input
fileHandle
integer
mode
string
Return Value
fp
Return Codes
NULL (0)
1-9
ANSI C Library
Chapter 1
Parameter Discussion
mode is the same as the mode parameter to fopen.
You should use a mode value that is consistent with the mode in which you originally opened the
file. If you use write capabilities that were not enabled when the file handle was originally
opened, the call to fdopen succeeds, but any attempt to write fails. For instance, if you
originally opened the file for reading only, you can pass "rw" to fdopen, but any call to
fwrite fails.
1-10
Chapter 2
Formatting and I/O Library
This chapter describes the functions in the LabWindows/CVI Formatting and I/O Library, and
contains many examples of how to use them. The Formatting and I/O Library contains functions
that input and output data to files and manipulate the format of data in a program.
The Formatting and I/O Library Function Overview section contains general information about
the Formatting and I/O Library functions and panels. Because the Formatting and I/O Library
differs in many respects from the other LabWindows/CVI libraries, it is very important to read
the overview before reading the other sections of this chapter.
The Formatting and I/O Library Function Reference section contains an alphabetical list of
function descriptions. This section is helpful for determining the syntax of the file I/O and string
manipulation functions.
The Using the Formatting and Scanning Functions section describes in detail this special class of
functions. Although these functions are listed in the function reference, their versatility and
complex nature require a more complete discussion.
The final section, Formatting and I/O Library Programming Examples, contains many examples
of program code that call Formatting and I/O Library functions. Most of the examples use the
formatting and scanning functions.
2-1
Chapter 2
OpenFile
CloseFile
ReadFile
WriteFile
ArrayToFile
FileToArray
GetFileInfo
SetFilePtr
StringLength
StringLowerCase
StringUpperCase
FillBytes
CopyBytes
CopyString
CompareBytes
CompareStrings
FindPattern
ReadLine
WriteLine
Fmt
FmtFile
FmtOut
Scan
ScanFile
ScanIn
NumFmtdBytes
GetFmtErrNdx
GetFmtIOError
GetFmtIOErrorString
The File I/O function panels open, close, read, write, and obtain information about files.
The String Manipulation function panels manipulate strings and character buffers.
2-2
Chapter 2
The Data Formatting function panels perform intricate formatting operations with a single
function call.
Status Functions, a subclass of Data formatting, contains function panels that return
information about the success or failure of a formatting or scanning call.
The online help with each panel contains specific information about operating each function
panel.
and place the first value in an integer variable and the second in a real variable.
Take the elements from an integer array, swap the high and low bytes in each element, and
place the resulting values in a real array.
To perform these operations, each formatting and scanning function takes a format string as one
of its parameters. In effect, a format string is a mini-program that instructs the formatting and
scanning functions on how to transform the input arguments to the output arguments. For
conciseness, format strings are constructed using single-character codes. These codes are
2-3
Chapter 2
described in detail in the Using the Formatting and Scanning Functions section later in this
chapter.
You may find the formatting and scanning functions more difficult to learn than other
LabWindows/CVI functions. To help you in this learning process, read the discussions in the
Formatting and I/O Library Programming Examples section at the end of this chapter.
ArrayToFile
int status = ArrayToFile (char *fileName, void *array, int dataType,
int numberOfElements, int numberOfGroups,
int arrayDataOrder, int fileLayout, int colSepStyle,
int fieldWidth, int fileType, int fileAction);
Purpose
Saves an array to a file using various formatting options. The function handles creating, opening,
writing, and closing the file. The file can later be read back into an array using the
FileToArray function.
Parameters
Input
fileName
string
File pathname.
array
void *
Numeric array.
dataType
integer
numberOfElements
integer
numberOfGroups
integer
arrayDataOrder
integer
fileLayout
integer
colSepStyle
integer
fieldWidth
integer
fileType
integer
ASCII/binary mode.
fileAction
integer
2-4
Chapter 2
Return Value
status
integer
Indicates success/failure.
Return Codes
0
Success.
-1
-2
-3
-4
-5
-6
-7
-8
-9
-10
-11
-12
Parameter Discussion
FileName may be an absolute pathname or a relative file name. If you use a relative file name,
the file is created relative to the current working directory.
DataType must be one of the following.
VAL_CHAR
VAL_SHORT_INTEGER
VAL_INTEGER
VAL_FLOAT
VAL_DOUBLE
VAL_UNSIGNED_SHORT_INTEGER
VAL_UNSIGNED_INTEGER
VAL_UNSIGNED_CHAR
If you save the array data in ASCII format, you may divide the array data into groups. Groups
can be written as either columns or rows. NumberOfGroups specifies the number of groups into
which to divide the array data. If you do not want to divide your data into groups, use 1.
If you divide your array data into groups, arrayDataOrder specifies how the data is ordered in
the array. The two choices are as follows.
2-5
Chapter 2
is assumed that the first point from each data group is stored
together, followed by the second point from each group and so on.
VAL_DATA_MULTIPLEXEDit
If you save the array data in ASCII format, fileLayout specifies how the data appears in the file.
The two choices are as follows.
VAL_GROUPS_AS_COLUMNS
VAL_GROUPS_AS_ROWS
If you have only one group, use VAL_GROUPS_AS_COLUMNS to write each array element on a
separate line.
If you specify that multiple values be written on each line, colSepStyle specifies how the values
are separated. The choices are as follows.
VAL_ASCII
VAL_BINARY
FileAction specifies the location in the file to begin writing data if the named file already exists.
The choices are as follows.
VAL_TRUNCATEPositions the file pointer to the beginning of the file and deletes its prior
contents.
VAL_OPEN_AS_ISPositions the file pointer at the beginning of the file but does not
affect the prior file contents.
2-6
Chapter 2
CloseFile
int status = CloseFile (int fileHandle);
Purpose
Closes the file associated with fileHandle. fileHandle is the file handle that was returned from
the OpenFile function and specifies the file to close.
Parameter
Input
fileHandle
integer
File handle.
integer
Return Value
status
Return Codes
-1
Success.
CompareBytes
int result = CompareBytes (char *buffer#1, int buffer#1Index, char *buffer#2,
int buffer#2Index, int numberofBytes, int caseSensitive);
Purpose
Compares the numberofBytes starting at position buffer#1Index of buffer#1 to the
numberofBytes starting at position buffer#2Index of buffer#2.
Parameters
Input
buffer#1
string
String 1.
buffer#1Index
integer
buffer#2
string
String 2.
buffer#2Index
integer
numberofBytes
integer
caseSensitive
integer
2-7
Chapter 2
Return Value
integer
result
Return Codes
-1
Parameter Discussion
Both buffer#1Index and buffer#2Index are zero-based.
If caseSensitive is zero, alphabetic characters are compared without regard to case. If
caseSensitive is non-zero, alphabetic characters are considered equal only if they have the same
case.
The function returns an integer value indicating the lexicographic relationship between the two
sets of bytes.
CompareStrings
int result = CompareStrings (char *string#1, int string#1Index, char *string#2,
int string#2Index, int caseSensitive);
Purpose
Compares the NUL-terminated string starting at position string#1Index of string#1 to the
NUL-terminated string starting at position string#2Index of string#2. Both string#1Index and
string#2Index are zero-based.
Parameters
Input
string#1
string
String 1.
string#1Index
integer
string#2
string
String 2.
string#2Index
integer
caseSensitive
integer
2-8
Chapter 2
Return Value
integer
result
Return Codes
-1
Parameter Discussion
If caseSensitive is zero, alphabetic characters are compared without regard to case. If
caseSensitive is non-zero, alphabetic characters are equal only if they have the same case.
The function returns an integer value indicating the lexicographic relationship between the two
strings.
CopyBytes
void CopyBytes (char targetBuffer[], int targetIndex, char *sourceBuffer,
int sourceIndex, int numberofBytes);
Purpose
Copies the numberofBytes bytes starting at position sourceIndex of sourceBuffer to position
targetIndex of targetBuffer.
Parameters
Input
Output
targetIndex
integer
Starting position in
targetBuffer.
sourceBuffer
string
Source buffer.
sourceIndex
integer
Starting position in
sourceBuffer.
numberofBytes
integer
targetBuffer
string
Destination buffer.
Return Value
None
National Instruments Corporation
2-9
Chapter 2
Parameter Discussion
Both sourceIndex and targetIndex are zero-based.
You can use this function even when sourceBuffer and targetBuffer overlap.
CopyString
void CopyString (char targetString[], int targetIndex, char *sourceString,
int sourceIndex, int maximum#Bytes);
Purpose
Copies the string starting at position sourceIndex of sourceString to position targetIndex of
targetString until an ASCII NUL is copied or maximum#Bytes bytes have been copied.
Appends an ASCII NUL if no ASCII NUL was copied.
Parameters
Input
targetIndex
integer
sourceString
string
Source buffer.
sourceIndex
integer
maximum#Bytes integer
Output
targetString
string
Return Value
None
Parameter Discussion
Both sourceIndex and targetIndex are zero-based. If you want to use maximum#Bytes to
prevent from writing beyond the end of targetString, make sure that you allow room for the
ASCII NUL. For example, if maximum#Bytes is 40, the destination buffer should contain at
least 41 bytes.
If you do not want to specify a maximum number of bytes to copy, use -1 for maximum#Bytes.
You can use this function even when sourceString and targetString overlap.
Note: The value of maximum#Bytes must not exceed one less than the number of bytes in
the target variable.
2-10
Chapter 2
FileToArray
int status = FileToArray (char *fileName, void *array, int dataType,
int numberOfElements, int numberOfGroups,
int arrayDataOrder, int fileLayout, int fileType);
Purpose
Reads data from a file into an array. Can be used with files created using the ArrayToFile
function. The function handles creating, opening, reading, and closing the file.
Parameters
Input
Output
fileName
string
File pathname.
dataType
integer
numberOfElements
integer
numberOfGroups
integer
arrayDataOrder
integer
fileLayout
integer
fileType
integer
ASCII/binary mode.
array
void*
Numeric array.
integer
Return Value
status
Return Code
0
Success.
-1
-2
-3
-4
-5
-6
-7
-8
-9
2-11
Chapter 2
Parameter Discussion
FileName may be an absolute pathname or a relative file name. If you use a relative file name,
the file is located relative to the current working directory.
DataType must be one of the following.
VAL_CHAR
VAL_SHORT_INTEGER
VAL_INTEGER
VAL_FLOAT
VAL_DOUBLE
VAL_UNSIGNED_SHORT_INTEGER
VAL_UNSIGNED_INTEGER
VAL_UNSIGNED_CHAR
NumberOfGroups specifies the number of groups into which the data in the file is divided.
Groups can be in the form of either columns or rows. If there are no groups, use 1. This
parameter only applies if the file type is ASCII.
If the data is divided into groups, arrayDataOrder specifies the order in which the data is to be
stored in the array. The two choices are as follows.
VAL_GROUPS_TOGETHER all points from one data group are stored together followed by
all points from the next data group.
If the file is in ASCII format, fileLayout specifies how the data appears in the file. The two
choices are as follows.
VAL_GROUPS_AS_COLUMNS
VAL_GROUPS_AS_ROWS
If there is only one group, VAL_GROUPS_AS_COLUMNS specifies that each value in the file is
on a separate line.
FileType specifies whether the file is in ASCII or binary format. The choices are as follows.
VAL_ASCII
VAL_BINARY
2-12
Chapter 2
FillBytes
void FillBytes (char buffer[], int startingIndex, int numberofBytes, int value);
Purpose
Sets the numberofBytes bytes starting at position startingIndex of buffer to the value in the
lower byte of value. startingIndex is zero-based.
Parameters
Input
buffer
string
Destination buffer.
startingIndex
integer
numberofBytes
integer
value
integer
Return Value
None
FindPattern
int ndx = FindPattern (char *buffer, int startingIndex, int numberofBytes,
char *pattern, int caseSensitive, int startFromRight);
Purpose
Searches a character buffer for a pattern of bytes. The pattern of bytes is specified by the string
pattern.
Parameters
Input
buffer
string
Buffer to be searched.
startingIndex
integer
numberofBytes
integer
pattern
string
caseSensitive
integer
Case-sensitivity mode.
startFromRight
integer
Direction of search.
2-13
Chapter 2
Return Value
ndx
integer
Return Code
-1
Parameter Discussion
The buffer searched is the set of numberofBytes bytes starting at position startingIndex of
buffer. Exception: If numberofBytes is -1, the buffer searched is the set of bytes starting at
position startingIndex of buffer up to the first ASCII NUL. startingIndex is zero-based.
If caseSensitive is zero, alphabetic characters are compared without regard to case. If
caseSensitive is non-zero, alphabetic characters are considered equal only if they have the same
case. If startFromRight is zero, the leftmost occurrence of the pattern in the buffer will be
found. If startFromRight is non-zero, the rightmost occurrence of the pattern in the buffer will
be found.
If the pattern is found, pattern returns the index relative to the beginning of buffer where it
found the first byte of the pattern. If the pattern is not found, pattern returns -1.
The following example returns 4, which is the index of the second of the three occurrences of ab
in the string 1ab2ab3ab4. The first occurrence is skipped because startingIndex is 3. Of the
two remaining occurrences, the leftmost is found because startFromRight is zero:
ndx = FindPattern ("1ab2ab3ab4", 3, -1, "AB", 0, 0);
On the other hand, the following line returns 7, which is the index of the last occurrence of ab,
because startFromRight is non-zero:
ndx = FindPattern ("1ab2ab3ab4", 3, -1, "AB", 0, 1);
Fmt
int n = Fmt (void *target, char *formatString, source1,...,sourcen);
Purpose
Formats the source1 ... sourcen arguments according to descriptions in the formatString
argument.
2-14
Chapter 2
Parameters
Input
formatString
String.
target
Return Value
integer
Return Code
-1
FmtFile
int n = FmtFile (int fileHandle, char *formatString, source1,,sourcen);
Purpose
Formats the source1 ... sourcen arguments according to descriptions in the formatString
argument. The result of the formatting is written into the file corresponding to the fileHandle
argument, which was obtained by a call to the LabWindows/CVI function OpenFile.
Parameters
Input
fileHandle
integer
formatString
string
source1,,sourcen
File handle.
2-15
Chapter 2
Return Value
integer
Return Codes
-1
-2
I/O error.
FmtOut
int n = FmtOut (char *formatString, source1,,sourcen);
Purpose
Formats the source1 ... sourcen arguments according to descriptions in the formatString
argument. The result of the formatting is written to the Standard I/O window.
Parameters
Input
formatString
String.
integer
Return Codes
-1
-2
I/O error.
2-16
Chapter 2
GetFileInfo
int status = GetFileInfo (char *fileName, long *fileSize);
Purpose
Verifies if a file exists. Returns an integer value of zero if no file is present and 1 if file is
present. fileSize is a long variable that contains the file size in bytes or zero if no file exists.
Parameters
Input
fileName
string
Output
fileSize
long
integer
Return Value
status
Return Codes
1
File exists.
-1
Example
/*
Check for presence of file A:\DATA\TEST1.DAT. */
/*
Print its size */
/*
if file exists or message stating file does not exist. */
int n;
long size;
n = GetFileInfo("a:\\data\\test1.dat",&size);
if (n == 0)
FmtOut("File does not exist.");
else
FmtOut("File size = %i[b4]",size);
2-17
Chapter 2
GetFmtErrNdx
int n = GetFmtErrNdx (void);
Purpose
Returns the zero-based index into the format string where an error occurred in the last formatting
or scanning call.
Parameters
None
Return Value
integer
Return Code
-1
No error.
GetFmtIOError
int status = GetFmtIOError (void);
Purpose
This function returns specific I/O information for the last call to a Formatting and I/O function
that performs file I/O. If the last function was successful, GetLastFmtIOError returns zero (no
2-18
Chapter 2
error). If the last function that performs I/O encountered an I/O error, GetLastFmtIOError
returns a nonzero value.
Return Value
status
integer
Return Codes
FmtIONoErr
No error.
FmtIONoFileErr
FmtIOGenErr
FmtIOBadHandleErr
FmtIOInsuffMemErr
FmtIOFileExistsErr
FmtIOAccessErr
Permission denied.
FmtIOInvalArgErr
Invalid argument.
FmtIOMaxFilesErr
FmtIODiskFullErr
Disk is full.
FmtIONameTooLongErr 10
GetFmtIOErrorString
char *message = GetFmtIOErrorString (int errorNum);
Purpose
Converts the error number returned by GetLastFmtIOError into a meaningful error message.
Parameters
Input errorNum
integer
string
Explanation of error.
Return Value
message
2-19
Chapter 2
NumFmtdBytes
int n = NumFmtdBytes (void);
Purpose
Returns the number of bytes formatted or scanned by the previous formatting or scanning call.
Parameters
None
Return Value
integer
OpenFile
int handle = OpenFile (char *fileName, int read/writeMode, int action, int fileType);
Purpose
Opens a file for input and/or output.
2-20
Chapter 2
Parameters
Input
fileName
string
Pathname.
read/writeMode
integer
Read/write mode.
action
integer
fileType
integer
ASCII/binary mode.
integer
Return Value
handle
Return Code
-1
Parameter Discussion
fileName is a pathname specifying the file to be opened. If the read/writeMode argument is
write or read/write, this function creates the file if it does not already exist. If a file is created, it
is created with no protection; that is, both reading and writing can be performed on it. Use the
function GetFileInfo if it is necessary to determine whether a file already exists.
read/writeMode specifies how the file is opened:
action specifies whether to delete the old contents of the file, and whether to force the file
pointer to the end of the file before each write operation. action is meaningful only if
read/writeMode = write or read/write. After read operations are performed, the file pointer
points to the byte following the last byte read. action values are as follows:
VAL_TRUNCATE = truncate file (deletes its old contents and positions the file pointer at the
beginning of the file.
VAL_APPEND = do not truncate file (all write operations append to end of file).
VAL_OPEN_AS_IS = do not truncate file (positions the file pointer at the beginning of the
file. )
2-21
Chapter 2
fileType specifies whether to treat file as ASCII or binary. When performing I/O on a file in
binary mode, no special treatment is given to carriage returns (CR) and line feeds (LF). When
you open the file in ASCII mode, CR LF combination translates to LF when reading, and LF
translates to CR LF when writing. fileType values are as follows:
VAL_BINARY = binary
VAL_ASCII = ASCII
ReadFile
int n = ReadFile (int fileHandle, char buffer[], int count);
Purpose
Reads up to count bytes of data from a file or STDIN into buffer. Reading starts at the current
position of the file pointer. When the function completes, the file pointer points to the next
unread character in the file.
Parameters
Input
Output
fileHandle
integer
File handle.
count
integer
buffer
string
Input buffer.
integer
Return Value
n
Return Codes
-1
0
Parameter Discussion
fileHandle is the file handle returned by the OpenFile function. fileHandle points to the file
from which you want to read. If fileHandle =0, input is read from STDIN, and no prior
OpenFile call is needed. buffer is the buffer into which you read data. You must allocate
space for this buffer before you call this function. count specifies the number of bytes to read.
count must not be greater than buffer size.
2-22
Chapter 2
ReadLine
int n = ReadLine (int fileHandle, char lineBuffer[], int maximum#Bytes);
Purpose
Reads bytes from a file until a linefeed is encountered.
Parameters
Input
Output
fileHandle
integer
File handle.
maximum#Bytes
integer
lineBuffer
string
Input buffer.
integer
Return Value
n
Return Codes
-2
End of file.
-1
I/O error.
Parameter Discussion
This function places up to maximum#Bytes bytes, excluding the linefeed, into lineBuffer.
Appends an ASCII NUL to lineBuffer. If there are more than maximum#Bytes bytes before the
linefeed, the extra bytes are discarded.
fileHandle is the file handle that was returned from the OpenFile function and specifies the
file from which to read the line. The file should be opened in ASCII mode so that a
2-23
Chapter 2
Scan
int n = Scan (void *source, char *formatString, targetptr1,,targetptrn);
Purpose
Scans a single source item in memory and breaks it into component parts according to format
specifiers found in a formatString. The components are then placed into the target parameters.
Parameters
Input
Output
source
formatString
string.
targetptr1,,targetptrn
Return Value
n
integer
Return Code
-1
2-24
Chapter 2
ScanFile
int n = ScanFile (int fileHandle, char *formatString, targetptr1,,targetptrn);
Purpose
Performs the same basic operation as the Scan function, except that the source material is
obtained from the file referred to by the fileHandle argument, which is obtained by calling the
LabWindows/CVI function OpenFile.
Parameters
Input
Output
fileHandle
Integer.
formatString
String.
targetptr1,,targetptrn
Return Value
n
integer
Return Codes
-1
-2
I/O error.
ScanIn
int n = ScanIn (char *formatString, targetptr1,,targetptrn);
Purpose
Performs the same basic operation as the ScanFile function, except that the source material is
obtained from STDIN.
2-25
Chapter 2
Parameters
Input
formatString
String.
Output
targetptr1,,targetptrn
Return Value
integer
Return Codes
-1
-2
I/O error.
SetFilePtr
long position = SetFilePtr (int fileHandle, long offset, int origin);
Purpose
Moves the file pointer for the file specified by fileHandle to a location that is offset bytes from
origin. Returns the offset of the new file pointer position from the beginning of the file.
Parameters
Input
fileHandle
integer
offset
long integer
origin
integer
2-26
Chapter 2
Return Value
position
long integer
Return Code
-1
Parameter Discussion
The valid values of origin are as follows:
0 = beginning of file
2 = end of file
2-27
Chapter 2
StringLength
int n = StringLength (char *string);
Purpose
Returns the number of bytes in the string before the first ASCII NUL.
Parameter
Input
string
String.
Return Value
integer
Example
char s[100];
int nbytes;
nbytes = StringLength (s);
StringLowerCase
void StringLowerCase (char string[]);
Purpose
Converts all uppercase alphabetic characters in the NUL-terminated string to lowercase.
Parameter
Input/Output string
String.
2-28
Chapter 2
Return Value
None
StringUpperCase
void StringUpperCase (char string[]);
Purpose
Converts all lowercase alphabetic characters in the NUL-terminated string to uppercase.
Parameter
Input/Output string
String.
Return Value
None
WriteFile
int n = WriteFile (int fileHandle, char *buffer, unsigned int count);
Purpose
Writes up to count bytes of data from buffer to a file or to STDOUT. Writing starts at the
current position of the file pointer, and when the function completes, the file pointer is
incremented by the number of bytes written.
Parameters
Input
fileHandle
integer
File handle.
buffer
string
Data buffer.
count
integer
integer
Return Value
n
2-29
Chapter 2
Return Code
-1
Error.
Parameter Discussion
fileHandle is the file handle that was returned from the OpenFile function. If fileHandle=1,
data is written to STDOUT and no prior OpenFile call is needed.
buffer is the buffer from which to write data.
count specifies number of bytes to write. The count parameter overrides the buffer size in
determining the number of bytes to write. Buffers containing embedded NUL bytes are written in
full. count must not be greater than buffer size.
Using This Function
For files opened in ASCII mode, each LF character is replaced with a CR-LF combination in the
output. In this case, the return value does not include the CR character written to the output.
An error can indicate a bad file handle, an attempt to access a protected file, an attempt to write
to a file opened as ReadOnly, or no more space left on disk.
WriteLine
int n = WriteLine (int fileHandle, char *lineBuffer, int numberofBytes);
Purpose
Writes numberofBytes bytes from lineBuffer to a file and then writes a linefeed to the file.
Parameters
Input
fileHandle
integer
File handle.
lineBuffer
string
Data buffer.
numberofBytes
integer
integer
Return Value
n
2-30
Chapter 2
Return Code
-1
I/O error.
Parameter Discussion
If numberofBytes is -1, only the bytes in lineBuffer before the first ASCII NUL are written,
followed by a linefeed.
fileHandle is the file handle that was returned from the OpenFile function. The file should be
opened in ASCII mode so that a carriage return will be written before the linefeed. If fileHandle
is 1, the line will be written to the STDOUT.
Using This Function
WriteLine returns the number of bytes written to the file, excluding the linefeed. If an I/O
error occurs, WriteLine returns -1.
Formatting functions
Scanning functions
Status functions
You use formatting functions to combine and format one or more source items into a single
target item, and you use scanning functions to break apart a single source item into several target
items. The status functions return information regarding the success or failure of the formatting
or scanning functions.
2-31
Chapter 2
Convert the integer value 23 to its ASCII representation and place the contents in a string
variable:
char a[5];
int b,n;
b = 23;
n = Fmt (a, "%s<%i", b);
Formatting Functions
The following information is a brief description of the three formatting functions:
The Fmt function formats the source1, ..., sourcen arguments according to
descriptions in the formatstring argument. The function places the result of the
formatting into the target argument.
The FmtFile function formats the source1, ..., sourcen arguments according to
descriptions in the formatstring argument. The function writes the result of the
formatting into the file corresponding to the handle argument.
The FmtOut function formats the source1, ..., sourcen arguments according to
descriptions in the formatstring argument. The function writes the result of the
formatting to Standard Out.
2-32
Chapter 2
Each of these formatting functions return the number of source format specifiers satisfied. If
there is an error in the format string, -1 is returned.
The formatting functions are used to format and combine multiple source items into a single
target item. The only difference in the workings of the three functions is the location of the
target data. For the function Fmt, the target is a data item in memory which is passed to the
function by reference. For FmtFile, the target is a file whose handle is passed as the first
argument. The LabWindows/CVI function OpenFile returns this handle. For the function
FmtOut, the target is Standard Out (typically the display), and in this case the target argument
present in the other two functions is omitted. Except for these differences, the following
descriptions apply to all the formatting functions.
The target parameter for Fmt must be passed by reference (that is, must be a pointer).
Formatting FunctionsFormat String
Consider the following formatting function:
n = Fmt(target, formatstring, source1, ..., sourcen);
where formatstring contains the information to transform the source arguments to the target
argument.
Format strings for all the formatting functions are of the form:
"target_spec < source_specs_and_literals"
where target_spec is a format specifier that describes the nature of the target data item, and
source_specs_and_literals is a sequence of format specifiers and literal characters that
indicate how the source material is to be combined into the target.
Examples of format strings for the formatting functions are as follows.
"%s < RANGE %i"
"%s < %s; %i"
The character < is a visual reminder of the direction of the data transformation (that is, from the
sources to the target), and also separates the single target format specifier from the (perhaps
multiple) source format specifiers and literals. The target format specifier can be omitted, in
which case a %s string format is assumed. If the target format specifier is omitted, the
< character can be omitted also, or retained for clarity.
Notice that the target format specifier is located to the left of the < symbol, just as the target
parameter is located to the left of the format string. Likewise, the source format specifiers are
located to the right of the < symbol, just as the source parameters are located to the right of the
format string.
2-33
Chapter 2
Format specifiers describe the inputs and outputs of data transformations. Each format specifier
has the following form.
%
[ rep ]
formatcode
[[ modifiers ]]
The character % introduces all format specifiers. rep indicates how many times the format
repeats with respect to the arguments. formatcode is a code character which indicates the
nature of the data items being formatted. modifiers is an optional bracket-enclosed sequence
of codes which further describe the data format.
Examples of format specifiers are as follows.
%s
%100f
%i[b2u]
2-34
Chapter 2
f real number. This source or target specifier indicates that the corresponding parameter is
a real number, or if rep is present, a real array. The function performs conversions to
ASCII when converting to or from the string format %s.
c character. This source or target specifier indicates that the corresponding parameter is an
integer with one significant byte, or, if rep is present, an array of 1-byte integers. The
function does not perform conversion to ASCII when converting to or from the string
format %s. The byte is copied directly to or from the string.
Formatting Modifiers
modifiers are optional codes used to describe the nature of the source or target data. If you
use them, you must enclose the modifiers in square brackets and place them immediately after
the format code they modify. If one format specifier requires more than one modifier, enclose all
modifiers in the same set of brackets.
There is a different set of modifiers for each possible format specifier.
Formatting Integer Modifiers (%i, %d, %x, %o, %c)
bn
Specify Length. The b integer modifier specifies the length of the integer
argument, or the length of an individual integer array element, in bytes. The
default length is 4 B; therefore, simple 4 B integers do not need this modifier.
The modifier b2 represents short integers. The modifier b1 represents single-byte
integers.
in
Treat String as Integer Array. The z integer 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.
rn
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
2-35
Chapter 2
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 space is necessary.
pc
Specify as Twos Complement. The s integer modifier indicates that the integer
argument is considered a signed two's complement number. This is the default
interpretation of integers, so the s modifier is never explicitly required.
onnnn
Specify Byte Ordering. The o integer 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 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.
2-36
Chapter 2
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
in
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 the i modifier is used with the z modifier, then n is in
terms of bytes.
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 space 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, the default value is p6.
en
2-37
Chapter 2
Note: The value can be represented in scientific notation even when 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 modifier nor the w modifier is present.
Formatting String Modifiers (%s)
in
Specify Array Offset. The i string modifier specifies an offset within a string. It
indicates the location within the string where processing is to begin. n is the zerobased index of the first byte to process. Thus, %s[i2] applied to a target string
begins placing data in the third byte of the string.
Append. When applied to a target format specifier, the a string 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 string modifier
specifies the maximum number of bytes to be consumed from the string argument.
You can enter any non-negative value here, the default being zero, which indicates
that the entire string should be consumed.
When modifying a target format specifier, the w string modifier specifies the exact
number of bytes to store in the string, excluding the terminating ASCII NUL. If n is
zero or omitted, 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 string modifier is used in conjunction with the a string 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.
Append NULs. When applied to a target string in conjunction with the w string
modifier, the q string modifier specifies that unfilled bytes at the end of the target
string be set to ASCII NULs instead of blanks.
2-38
Chapter 2
tn
t-
Terminate when Full. This is similar to tn, except that it specifies that there are no
terminating characters. Reading of the source string terminates when the target is full
or when the number of bytes specified with the w modifier have been read.
t#
When you use one or more asterisks instead of constants in a target specifier, the arguments
corresponding to the asterisks must appear after the format string in the same order as their
corresponding asterisks appear in the format specifier.
When you use one or more asterisks instead of constants in a source specifier, the arguments
corresponding to the asterisks must precede the source argument and must be in the same order
as their corresponding asterisks in the format specifier.
2-39
Chapter 2
Scanning Functions
The following information is a brief description of the three scanning functions.
The Scan function inspects the source argument and applies transformations to it
according to descriptions in the formatstring argument. The results of the
transformations are placed into the targetptr1 ... targetptrn arguments.
The ScanFile function reads data from the file corresponding to the handle argument
and applies transformations to it according to descriptions in the formatstring argument.
The results of the transformations are placed into the targetptr1 ... targetptrn
arguments.
The ScanIn function reads data from standard input and applies transformations to it
according to descriptions in the formatstring argument. The results of the
transformations are placed into the targetptr1 ... targetptrn arguments.
All of the above functions return the number of target format specifiers satisfied. The
function returns a -1 if there is an error in the format string.
The scanning functions break apart a source item into component parts and store the parts into
parameters passed to the function. The only difference between the three functions is the
location of the source data. For the function Scan, the source item is a data item in memory
which is passed to the function. For ScanFile, the source item is a file, whose handle is
passed as the first argument. The handle is obtained by a call to the LabWindows/CVI function
OpenFile. For the function ScanIn, the source is taken from Standard In (typically the
keyboard), and the source argument present in the other two functions is omitted.
All target parameters must be passed by reference.
2-40
Chapter 2
where formatstring contains the information to transform the source argument to the
targetptr arguments.
Format strings for the scanning functions are of the following form.
"source_spec > target_specs_and_literals"
where source_spec is a format specifier that describes the nature of the source parameter and
target_specs_and_literals is a sequence of format specifiers and literal characters that
indicate how to divide and reformat the source argument into the desired target.
Examples of format strings for the scanning functions are:
"%s > %i"
The character > is a visual reminder of the direction of the data transformation, and also
separates the single source format specifier from the (possibly multiple) target format specifiers
and literals. The source format specifier can be omitted, in which case a %s string format is
assumed. If the source format specifier is omitted, the > character can be omitted also, or
retained for clarity.
Notice that the source format specifier is located to the left of the > symbol, just as the source
parameter is located to the left of the format string. Likewise, the target format specifiers are
located to the right of the > symbol, just as the target parameters are located to the right of the
format string.
Format specifiers describe the inputs and outputs of data transformations. Each format specifier
is of the following form.
%
[ rep ]
formatcode
[[ modifiers ]]
The character % introduces all format specifiers. rep indicates how many times the format
repeats with respect to the arguments. formatcode is a code character which indicates the
nature of the data items being formatted. modifiers is an optional bracket enclosed sequence
of codes which further describe the data format.
The following are examples of format specifiers.
%s[t59]
%100i[z]
%f
2-41
Chapter 2
2-42
Chapter 2
f real number. As a source or target specifier, this indicates that the corresponding
parameter is a real number, or if rep is present, a real array. As a source specifier in
conversions to string formats, the floating-point value is converted into ASCII form. As
a target specifier in conversions from string format, bytes of the source parameter are
consumed as long as they match the pattern of floating-point ASCII numbers, or until the
end of the string is encountered. The scanned characters are converted to a floating-point
value and placed into the corresponding floating-point or floating-point array target
parameter. If the format is repeated, the operation is repeated the appropriate number of
times with successive elements of the array parameter. The pattern for floating-point
ASCII numbers is an optional sign (+ or -), a series of one or more decimal digits
possibly containing a decimal point, and an optional exponent consisting of an E or e
followed by an optionally signed decimal integer value.
c character. As a source specifier, this indicates that the source parameter is an integer with
one significant byte or, if rep is present, an array of 1-byte integers. As a target specifier
this indicates that a byte of the source parameter is to be consumed, and the scanned
character placed directly into the corresponding target parameter, which is an integer
passed by reference. If the format is repeated, this operation is repeated the appropriate
number of times and the results stored into successive elements of the integer array.
Scanning Modifiers
modifiers are optional codes used to describe the nature of the source or target data. If you
use them, you must enclose the modifiers in square brackets and place them immediately after
the format code they modify. If one format specifier requires more than one modifier, enclose all
modifiers in the same set of brackets. There is a different set of modifiers for each possible
format specifier.
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
4 B; therefore, simple 4 B integers do not need this modifier. The modifier b2
represents short integers. The modifier b1 represents single-byte integers.
in
Specify Array Offset. Use the i integer 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 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.
Treat String as Integer Array. The z integer 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.
2-43
Chapter 2
rn
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.
Specify as Twos Complement. The s integer modifier indicates that the integer
argument is to be considered a signed two's complement number. This is the default
interpretation of integers, so the s modifier is not required.
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 which appears after each one. You can use this specifier to scan
the string 3, 7, -32.
Discard Data. When applied to a target specifier, the d integer 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.
onnnn
Specify Byte Ordering. The o integer 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. LabWindows/CVI will reverse the
byte ordering of the buffer without the o modifier depending on which architecture
the program is running.
For example, if your GPIB instrument sends two-byte binary data in Intel byte order,
your code should appear as follows.
2-44
Chapter 2
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
in
Specify Array Offset. You can use the i floating-point modifier to specify an offset
within a floating-point array argument. It indicates the location within the array
where processing is to begin. n is the zero-based index of the first element to process.
Thus, %10f[i2] applied to a source floating-point array reads the 10 floating-point
values from the third through the twelfth elements of the array. The i modifier is
valid only if rep is present. If you use the i modifier with the z modifier, then n is
in terms of bytes.
Treat String as Floating Point. The z floating-point 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 space 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.
2-45
Chapter 2
Specify as Floating Point. The f floating-point modifier indicates that the string
representation of the floating-point value is in non-scientific notation. This is the
default even when the f modifier is not present.
Discard Data. When applied to a target specifier, the d modifier indicates 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.
Specify Array Offset. The i string modifier specifies an offset within a string. It
indicates the location within the string where processing is to begin. n is the zerobased index of the first byte to process. Thus, %s[i2] applied to a target string
begins placing data in the third byte of the string.
Append. When applied to a target format specifier, the a string 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 string 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 being
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, as many bytes are stored as are called for by the sources. When n is greater
2-46
Chapter 2
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.
q
Append NULs. When applied to a target string in conjunction with the w string
modifier, the q string modifier specifies that unfilled bytes at the end of the target
string be set to ASCII NULs instead of blanks.
Append with Spacing. When the source is a string and the y modifier is applied to a
target string format specifier, the target string is filled with bytes from the source
string without skipping leading spaces or tabs.
tn
t-
Terminate when Full. This is similar to tn, except that it specifies that there are no
terminating characters. When applied to a source string, t- specifies that reading of
the source string terminates when all of the targets are full or when the number of
bytes specified with the w modifier have been read. When applied to a target string,
t- specifies that filling of the target string terminates when the source is exhausted or
when the number of bytes specified with the w modifier have been placed into the
target.
t#
2-47
Chapter 2
Discard Terminator. When applied to a target string, the x modifier specifies that
the terminating character be discarded before the next target is filled in. Using
%s>%s[xt59]%s[xt59] with the source string "abc;XYZ;", "abc" is placed
in the first target and "XYZ" is placed in the second target.
Discard Data. When applied to a target specifier, the d modifier indicates that there
is no target argument to correspond to the target specifier. The data that otherwise is
placed in the target argument is discarded instead. The count returned by the
Scan/ScanFile/ScanIn functions will include the target specifier even if the
d modifier is used.
When you use one or more asterisks instead of constants in a source specifier, the arguments
corresponding to the asterisks must appear after the format string in the same order as their
corresponding asterisks appear in the format specifier.
When you use one or more asterisks instead of constants in a target specifier, the arguments
corresponding to the asterisks must precede the target argument and must be in the same order as
their corresponding asterisks in the format specifier.
Scan, ScanFile, ScanInLiterals in the Format String
Literal characters appearing in a scanning function format string indicate that the literal
characters are expected in the source parameter. They are not stored into any target parameter,
but are skipped over when encountered. If a literal character specified in the format string fails
to appear in the source in the expected position, the scanning function immediately returns.
2-48
Chapter 2
Some formats may have been correctly detected in the input, and the corresponding target
parameters will have been filled in. Formats situated after the literal which did not appear,
however, will not have been executed.
The function return value can be used to determine exactly how many target parameters were
actually fulfilled by the input. You can use the function NumFmtdBytes to determine the
number of bytes consumed from the source parameter.
Because the left side of the > symbol must be a single format specifier, literal characters, if
present, must be on the right side of the symbol. Literals on the left side, or more than one
format specifier on the left side, result in a -1 error, indicating a faulty format string. The
function GetFmtErrNdx can then be used to determine exactly where in the format string the
error lies.
The characters %, [, ], <, and > have special meaning in the format strings. To specify that these
characters be taken literally, they should be preceded by %.
2-49
Chapter 2
Fmt/FmtFile/FmtOut Examples in C
This section contains examples of program code that use the Fmt, FmtFile, and FmtOut
functions from the Formatting and I/O Library. To eliminate redundancy, error checking on I/O
operations has been omitted from all of the examples in this section except the Two Integers to
ASCII File with Error Checking example.
Integer to String
char buf[10];
int a;
a = 16;
Fmt (buf, "%s<%i", a);
a = 16;
Fmt (buf, "%s<%x", a);
a = 16;
Fmt (buf, "%s<%o", a);
a = -1;
Fmt (buf, "%s<%i", a);
a = -1;
Fmt (buf, "%s<%i[u]", a);
a = 1234;
Fmt (buf, "%s<%i[w6]", a);
a = 1234;
/* result: "16" */
/* result: "10" */
/* result: "20" */
/* result: "-1" */
/* result: "4294967295" */
/* result: "
2-50
1234" */
Chapter 2
/* result: "001234" */
/* result: "*4" */
Remarks
The results shown are the contents of buf after each call to Fmt. The last call demonstrates
what occurs when the width specified by the w modifier is too small.
/* result: "123456" */
/* result: "1e240" */
/* result: "361100" */
/* result: "-1" */
/* result: "4294967295" */
/* result: "
123456" */
/* result: "00123456" */
/* result: "*456" */
Remarks
The results shown are the contents of buf after each call to Fmt. The last call demonstrates
what occurs when the width specified by the w modifier is too small.
/* result: "12.345679" */
/* result: "12.35" */
/* result: "12.3456789000" */
/* result: "12.345" */
2-51
Fmt
x =
Fmt
x =
Fmt
x =
Fmt
x =
Fmt
x =
Fmt
x =
Fmt
Chapter 2
/* result: "12." */
/* result: "12.345000" */
/* result: "-12.345" */
/* result: "-12.3*" */
/* result: "0.00000012" */
/* result: "1.2e-007" */
/* result: "4.5e050" */
Remarks
The results shown are the contents of buf after each call to Fmt. The last two calls demonstrate
that very large and very small values are sometimes forced into scientific notation even when the
e modifier is absent.
/* result: "1.234568e+001" */
/* result: "1.23e+001" */
/* result: "1.23e+01" */
/* result: "1.234500e+001" */
/* result: "
1.23e+001" */
/* result: "1.23e*" */
Remarks
The results shown are the contents of buf after each call to Fmt. The last call demonstrates
what occurs when the width specified by the w modifier is too small.
2-52
Chapter 2
Remarks
After the Fmt call, buf contains "F4R3; V1.2;".
Remarks
OpenFile opens the file FILE.DAT as an ASCII file for writing only. If the function
succeeds, it returns a file handle with a positive integer value. FmtFile writes the ASCII
representation of two integer values to the file. If FmtFile succeeds, it returns 2 (because there
are two source specifiers in the format string).
2-53
Chapter 2
if ((i % 5) == 4)
WriteFile (file_handle, "\n", 1);
}
CloseFile (file_handle);
Remarks
The FmtFile call writes the ASCII representation of a real array element to the file, followed
by a comma. The w modifier specifies that the number be right-justified in a 15-character field.
The WriteFile call writes a linefeed to the file after every fifth call to FmtFile. Because
the file is opened in ASCII mode, the linefeed is automatically written as a linefeed/carriage
return combination.
Note: If the format string is "%s[w15]<%f,", the number and the comma are left-justified
together in a 15-character field.
Remarks
The FmtFile call writes all 100 elements of the integer array readings to a file in binary
form. If the FmtFile call is successful, nbytes = 200 (100 integers, 2 bytes per integer).
Remarks
The FmtFile call writes all 100 elements of the real array waveform to a file in binary form.
If the FmtFile call is successful, nbytes = 800 (100 integers, 8 bytes per real number).
2-54
Chapter 2
}
Remarks
This example shows how a function can be used to write an array of real numbers to a binary file.
The function's parameters are a real array, the number of elements to be written, and the
filename.
The FmtFile call writes the first count elements of x to a file in binary form. The two
asterisks (*) in the format string are matched to count. For instance, if count is 100, then the
format string is equivalent to %100f<100f.
Remarks
This example is an extension of the previous example. The function also writes a variable
number of elements of a real array to a file. Instead of beginning at the first element of the array,
a starting index is passed to the function.
The FmtFile call writes count elements of x, starting from x[start], to a file in binary
form. The first two asterisks (*) in the format string are matched to count. The third asterisk
is matched to start. For instance, if count is 100 and start is 30, then the format string is
equivalent to %100f<100f[i30]. Because the i modifier specifies a zero-based index into
the real array, the array elements from x[30] through x[129] are written to the file.
2-55
Chapter 2
Remarks
The two switch constructs assign constant strings to the string variables wave_str and
signal_str. The Fmt call concatenates the contents of wave_str and signal_str into
buf. After the call, buf contains "SQUARE;OUTPUT OFF;". NumFmtdBytes returns
the number of bytes in the concatenated string.
Appending to a String
char buf[30];
int wave_type, signal_output;
int nbytes;
switch (wave_type) {
case 0:
Fmt (buf, "%s<SINE;");
break;
case 1:
Fmt (buf, "%s<SQUARE;");
break;
2-56
Chapter 2
case 2:
Fmt (buf, "%s<TRIANGLE;");
break;
}
switch (signal_output) {
case 0:
Fmt (buf, "%s[a]<OUTPUT OFF;");
break;
case 1:
Fmt (buf, "%s[a]<OUTPUT ON;");
break;
}
nbytes = StringLength (buf);
Remarks
This example shows how to append characters to a string without writing over the existing
contents of the string. The first switch construct writes one of three strings into buf. The
second switch construct appends one of two strings to the string already in buf. After the
call, buf contains "SQUARE;OUTPUT OFF;". Notice that the a modifier applies to the
target specifier.
StringLength returns the number of bytes in the resulting string. In this case,
StringLength is used instead of NumFmtdBytes, because NumFmtdBytes would return
only the number of bytes appended.
*/
*/
*/
*/
Remarks
To allocate the space for each filename in the array, a separate constant string must be assigned
to each array element. Then Fmt is used to format each file name. The resulting file names are
FILE0000.DAT, FILE0001.DAT, FILE0002.DAT, and FILE0003.DAT.
2-57
Chapter 2
Remarks
In this example, the output is as follows:
A = 12
B = 34
Remarks
This example demonstrates how to write to the Standard Output without a linefeed/carriage
return by omitting the '\n' from the format string. The output in this example is as follows.
One 2 3.4
2-58
Chapter 2
Scan/ScanFile/ScanIn Examples in C
This section contains examples of program code that use the Scan, ScanFile, and ScanIn
functions from the Formatting and I/O Library. To eliminate redundancy, the examples include
no error checking on I/O operations in this section except for the ASCII File to Two Integers with
Error Checking example.
String to Integer
char *s;
int a, n;
s = "32";
n = Scan (s, "%s>%i",
s = "-32";
n = Scan (s, "%s>%i",
s = "
+32";
n = Scan (s, "%s>%i",
s = "x32";
n = Scan (s, "%s>%i",
&a);
/* result: a = 32, n = 1 */
&a);
/* result: a = -32, n = 1 */
&a);
/* result: a = 32, n = 1 */
&a);
/* result: a = ??, n = 0 */
Remarks
When locating an integer in a string, Scan skips over white space characters such as spaces,
tabs, linefeeds, and carriage returns. If a non-numeric character other than a white space
character, +, or - is found before the first numeric character, the Scan call fails. Thus, Scan
fails on the x in x32; it leaves the value in a unmodified and returns zero, indicating that no
target specifiers were satisfied.
s
n
s
n
s
n
s
n
=
=
=
=
=
=
=
=
"032";
Scan (s,
"32a";
Scan (s,
"32";
Scan (s,
"32";
Scan (s,
"%s>%i", &a);
/* result: a = 32, n = 1 */
"%s>%i", &a);
/* result: a = 32, n = 1 */
"%s>%o", &a);
/* result: a = 26, n = 1 */
"%s>%x", &a);
/* result: a = 50, n = 1 */
Remarks
When the %i specifier is used, numeric characters are interpreted as decimal, even when they
might appear to be octal (as in 032) or hexadecimal (as in 32a). When the %o specifier is
used, the numeric characters (01234567) are always interpreted as octal. When the %x
specifier is used, the numeric characters (0123456789abcdef) are always interpreted as
hexadecimal.
s = "32x1";
n = Scan (s, "%s>%i", &a);
/* result: a = 32, n = 1 */
2-59
Chapter 2
Scan considers the occurrence of a non-numeric character (such as the x in 32x1) to mark the
end of the integer.
s = "32567";
n = Scan (s, "%s>%i[w3]", &a);
/* result: a = 325, n = 1 */
The w3 modifier specifies that only the first 3 bytes of the string are scanned.
/* result: a = 99999, n = 1 */
/* result: a = 99999, n = 1 */
/* result: a = 65535, n = 1 */
Remarks
Scan extracts long integers from strings in the same way it extracts integers. The only
differences are that the b4 modifier must be used and the target argument must be a long integer.
See the String to Integer example earlier in this section for more details on using Scan to extract
integers and long integers from strings.
String to Real
char *s;
double x;
int n;
s = "12.3";
n = Scan (s, "%s>%f", &x); /* result: x = 12.3, n = 1 */
s = "-1.23e+1";
n = Scan (s, "%s>%f", &x); /* result: x = -1.23, n = 1 */
s = "1.23e-1";
n = Scan (s, "%s>%f", &x); /* result: x = 0.123, n = 1 */
Remarks
When locating a real number in a string, Scan accepts either floating-point notation or scientific
notation.
s
n
s
n
=
=
=
=
"
12.3";
Scan (s, "%s>%f", &x); /* result: x = 12.3, n = 1 */
"p12.3";
Scan (s, "%s>%f", &x); /* result: x = ????, n = 0 */
2-60
Chapter 2
When locating a real number in a string, Scan skips over white space characters. If a nonnumeric character other than a white space character, +, or - is found before the first numeric
character, the Scan call fails. Thus, Scan fails on the p in p12.3; it leaves the value in x
unmodified and returns zero, indicating that no target specifiers were satisfied.
s
n
s
n
s
n
=
=
=
=
=
=
"12.3m";
Scan (s, "%s>%f", &x); /* result: x = 12.3, n = 1 */
"12.3.4";
Scan (s, "%s>%f", &x); /* result: x = 12.3, n = 1 */
"1.23e";
Scan (s, "%s>%f", &x); /* result: x = ????, n = 0 */
Scan considers the occurrence of a non-numeric character (such as the m in 12.3m) to mark the
end of the real number. A second decimal point also marks the end of the number. However,
Scan fails on "1.23e" because the value of the exponent is missing.
s = "1.2345";
n = Scan (s, "%s>%f[w4]", &x);/* result: x = 1.23, n = 1 */
The w4 modifier specifies that only the first 4 bytes of the string are scanned.
Remarks
After each of the first two calls to Scan, a = 32, x = 1.23, and n = 2 (indicating that two target
specifiers were satisfied). In the second call, the x modifier is used to discard the separating
comma.
In the third call, there is a comma separator after the integer, but the x modifier is absent.
Consequently, Scan fails when attempting to find the real number. x remains unmodified, and
n = 1 (indicating that only one target specifier was satisfied).
2-61
Chapter 2
String to String
char *s;
char buf[10];
int n;
s = " abc ";
n = Scan (s, "%s>%s", buf);
s = " abc ";
n = Scan (s, "%s>%s[y]", buf);
abc" */
Remarks
When extracting a substring from a string, Scan skips leading spaces and tabs unless the y
modifier is present.
s
n
s
n
=
=
=
=
"a b c; d";
Scan (s, "%s>%s", buf);
/* result: buf = "a" */
"a b c; d";
Scan (s, "%s>%s[t59]", buf); /* result: buf = "a b c" */
When Scan extracts a substring from a string and the t modifier is not present, the substring is
considered to be terminated by a white space character. To include embedded white space in the
target string, use the t modifier to change the target string termination character. In the second
call to Scan, [t59] changes the termination character to a semicolon (ASCII 59).
s = " abcdefghijklmnop";
n = Scan (s, "%s>%s[w9]", buf);
s
n
s
n
=
=
=
=
Remarks
The w modifier can be used to prevent Scan from writing beyond the end of a target string. The
width specified does not include the ASCII NUL that Scan places at the end of the target string.
Therefore, the width specified should be at least one less than the width of the target character
buffer.
When the w modifier is used and the string extracted is smaller than the width specified, the
remaining bytes in the target string are blank-filled. However, if the q modifier is also used,
ASCII NULs fill the remaining bytes.
2-62
Chapter 2
Remarks
After the first call to Scan, a = 32, buf = "abc", and n = 2. Notice there are no spaces in the
format string between the two target specifiers. In the second call, there is a space between %i
and %s. Consequently, Scan expects a space to occur in s immediately after the integer.
Because there is no space in s, Scan fails at that point. It leaves buf unmodified and returns 1
(indicating that only one target specifier is satisfied).
Note: Do not put spaces between specifiers in Scan, ScanFile, or ScanIn format strings.
1.2";
"%s>%s[dt#]%f", &x);
1.2";
"%s[i8]>%f", &x);
1.2";
"%s>VOLTS = %f", &x);
/* result: x = 1.2, n = 2 */
/* result: x = 1.2, n = 1 */
/* result: x = 1.2, n = 1 */
Remarks
The three different format strings represent different methods for skipping over non-numeric
characters. In the first call, the format string contains two target specifiers. In the first specifier
(%s[dt#]), the t# modifier instructs Scan to read bytes from s until a number is
encountered. The d modifier indicates that the bytes must be discarded because there is no
argument corresponding to the specifier. When the Scan call succeeds, it returns 2, indicating
that two target specifiers were satisfied, even though there is only one target argument.
In the second call, the source specifier %s[i8] instructs Scan to ignore the first 8 bytes of s.
This method works only if the location of the number within s is always the same.
In the third call, the format string contains the non-numeric characters literally. This method
works only if the non-numeric characters in s are always the same.
2-63
Chapter 2
Remarks
Some strings returned by programmable instruments contain headers that consist of numeric as
well as non-numeric data and are terminated by a particular character, such as a semicolon. This
example shows how such a header can be skipped.
The format string contains two target specifiers. In the first specifier (%s[xdt#]), the t#
modifier instructs Scan to read bytes from s until a number is encountered. The d modifier
indicates that the bytes must be discarded because there is no argument corresponding to the
specifier. The x modifier indicates that the semicolon should also be discarded.
When the Scan call succeeds, it returns 2, indicating that two target specifiers were satisfied,
even though there is only one target argument.
Remarks
This example is similar to the previous one, except that portion of the string to be skipped is
terminated by a substring (DATA) rather than by a single character. The Formatting and I/O
Library function FindPattern is used to find the index where DATA begins in s. Four is
added to the index so that it points to the first byte after DATA. The index is then passed to
Scan and matched with the asterisk (*) in the format string.
In this example, FindPattern returns 15, and index is 19. When index is matched to the
asterisk in the format string in the Scan call, the format string is interpreted as %s[i19]>%f.
The i19 indicates that the first 19 bytes of s should be ignored. Scan then extracts the real
number from the remaining string, 3.71E+2, and assigns it to x. Scan returns 1, indicating
that one target specifier is satisfied.
2-64
Chapter 2
Remarks
The x modifier causes the comma separators to be discarded.
Scan considers an array target to be satisfied when at least one element of the array is filled in.
If the source string in this example were 12.3, only the first element of a would be filled in, the
other elements would remain unmodified, and Scan would return 1.
Remarks
All of the previous examples assume that s is a NUL-terminated string. However, when reading
data from programmable instruments using the GPIB and RS-232 Library functions, the data
transferred is not NUL-terminated. This example uses ibrd to read up to 15 B from a GPIB
instrument. The global variable ibcnt contains the actual number of bytes transferred. Scan
uses the value in ibcnt in conjunction with the w modifier to specify the width of the source
string.
For example, if ibcnt is 12, the format string is interpreted as %s[w12]>%f, causing Scan to
use only the first 12 bytes of s.
The following example is an alternative method for handling strings that are not
NUL-terminated:
int bd;
double x;
char s[20];
ibrd (bd, s, 15);
s[15] = 0; /* ASCII NUL is 0 */
Scan (s, "%s>%f", &x);
2-65
Chapter 2
This code shows how to insert an ASCII NUL at the end of the transferred bytes. After the
assignment, s is NUL-terminated.
Remarks
Each integer in ivals is converted to real number and then written into dvals.
Remarks
Each integer in ivals is byte-swapped, converted to a real number, and written into dvals.
Byte swapping is useful when a programmable instrument sends back 2-byte integers with the
high byte first, followed by the low byte. When this data is read into an integer array, the
placement of the bytes is such that the high byte is interpreted as the low byte. The
o10 modifier specifies that the bytes be interpreted in the opposite order.
Remarks
Sometimes, each element in an integer array is used to store two 1-byte integers. This example
shows how to unpack the 1-byte integers and store them in a real array. The b1 indicates that
each binary integer is only one byte long.
2-66
Chapter 2
The first call to Scan treats the 1-byte integers as signed values (from -128 to +127). The
second call includes a u in the format string. This causes Scan to treat the 1-byte integers as
unsigned values (from 0 to 255).
Remarks
Sometimes data from a programmable instrument is read into a character buffer even though it
contains binary data. This example shows how to treat a character buffer as an integer array.
The format string in each Scan call specifies that the source (s) contains an array of 100
integers. The z modifier is used to indicate that the source is actually a character buffer.
In some cases, the integer data may not start at the beginning of the character buffer. For
instance, the data in the buffer can begin with an ASCII header. In the second call to Scan, the
i6 modifier is used to indicate that the first 6 bytes of s are to be ignored.
Note: When the i modifier is used in conjunction with a character buffer, the number
following the i specifies the number of bytes within the buffer to ignore. This is true
even when the z modifier is also present. On the other hand, when the i modifier is
used in conjunction with an array variable, the number following the i indicates the
number of array elements to ignore.
Remarks
This example is similar to the previous example, except that s contains a single binary real
number (in IEEE format), rather an array of binary integers. The format string in each Scan call
indicates that the source (s) is to be treated as a 1-element array of real numbers. The z modifier
indicates that the source is actually a character buffer. The repetition count of 1 in the format
string is required; otherwise, the z modifier is not accepted.
2-67
Chapter 2
The first call to Scan assumes that the real number is at the beginning of s. The second call
assumes that the real number starts at the sixth byte of s. The i5 modifier causes the first
5 bytes of s to be ignored.
Remarks
OpenFile opens the file FILE.DAT as an ASCII file for reading only. If OpenFile
succeeds in opening the file, it returns a file handle with a positive integer value. ScanFile
reads the ASCII representation of two integer values from the file. If ScanFile succeeds, it
returns 2 (indicating that two target specifiers were satisfied).
ASCII File with Comma Separated Numbers to Real Array, with Number of Elements at
Beginning of File
double values[1000];
int file_handle, count;
file_handle = OpenFile ("FILE.DAT", 1, 2, 1);
ScanFile (file_handle, "%s>%i", &count);
if (count > 1000) {
FmtOut ("Count too large\n");
exit(1);
}
ScanFile (file_handle, "%s>%*f[x]", count, values);
CloseFile (file_handle);
Remarks
The first ScanFile call reads the number of elements into the integer variable count. If the
value in count exceeds the number of elements in the real array values, an error is reported.
Otherwise, the second ScanFile call matches count to the asterisk (*) in the format string. It
2-68
Chapter 2
then reads the correct number of elements into values. The x modifier causes the comma
separators to be discarded.
Remarks
The ScanFile call reads 100 integers from a binary file and stores them in the integer array
readings. If the ScanFile call is successful, nbytes = 200 (100 integers, 2 bytes per
integer).
Remarks
The ScanFile call reads 100 real numbers from a binary file and stores them in the real array
waveform. If the ScanFile call is successful, nbytes = 800 (100 integers, 8 bytes per real
number).
2-69
Chapter 2
Remarks
This example shows how a subroutine can be used to read an array of real numbers from a binary
file. The subroutine takes as parameters a real array, the number of elements to be read, and the
filename.
The ScanFile call reads the first count elements of x from a binary file. The two asterisks
(*) in the format string are matched to count. For instance, if count is 100, then the format
string is equivalent to %100f>100f.
Remarks
This example shows how to get user input from the keyboard. The FmtOut call writes the
prompt string to the screen without a linefeed or carriage return. The ScanIn call attempts to
read an integer value from the keyboard and place it in num_readings. If ScanIn succeeds,
it returns 1, and the loop is exited. Otherwise, the prompt string is repeated.
The format string in the ScanIn call contains a source specifier of %l. This has two
consequences. First, ScanIn returns whenever the user presses ENTER, even if the input line is
empty. This allows the prompt string to be repeated at the beginning of each line until the user
enters an integer value. Second, any characters entered after the integer value are discarded.
Remarks
This example is similar to the previous example, except that the item being read from the
keyboard is a string instead of an integer. The w modifier is used to prevent ScanIn from
2-70
Chapter 2
writing beyond the end of filename. Notice that the width specified is one less than the size
of filename. This allows room for the ASCII NUL that ScanIn appends at the end of
filename. The q modifier causes ScanIn to fill any unused bytes at the end of filename
with ASCII NULs. Without the q modifier, all unused bytes are filled with spaces, except for the
ASCII NUL at the end.
The call to ScanIn in this example skips over leading spaces and tabs and terminates the string
on an embedded space. For other options, see the String to String example earlier in this section.
Remarks
The previous two examples show how to read single items from the keyboard. When you are
prompted to enter several items on one line, it is often easier to read the entire line into a buffer
before parsing it. This can be done via the Formatting and I/O Library function ReadLine.
The first parameter to ReadLine is a file handle. In this case, the file handle is zero, which is
the handle reserved for the Standard Input. The other two parameters are a buffer and the
maximum number of bytes to place in the buffer. ReadLine always appends an ASCII NUL at
the end of the bytes read. Thus, the maximum number of bytes passed to ReadLine must be at
least one less than the size of the buffer.
ReadLine transfers every character from the input line to the buffer, including leading,
embedded, and trailing spaces, until the maximum number of bytes (for example, 80) have been
transferred. Any remaining characters at the end of the line are discarded. The linefeed is never
transferred to the buffer.
ReadLine returns the number of bytes read, including the number discarded, but excluding the
linefeed.
2-71
Chapter 3
Analysis Library
This chapter describes the functions in the LabWindows/CVI Analysis Library. The Analysis
Library Function Overview section contains general information about the Analysis Library
functions and panels. The Analysis Library Function Reference section contains an alphabetical
list of the function descriptions.
Clear1D
Set1D
Copy1D
Add1D
Sub1D
Mul1D
Div1D
Abs1D
Neg1D
(continues)
3-1
Analysis Library
Chapter 3
3-2
LinEv1D
MaxMin1D
Subset1D
Sort
Add2D
Sub2D
Mul2D
Div2D
LinEv2D
MaxMin2D
CxAdd
CxSub
CxMul
CxDiv
CxRecip
ToPolar
ToRect
CxAdd1D
CxSub1D
CxMul1D
CxDiv1D
CxLinEv1D
ToPolar1D
ToRect1D
Mean
StdDev
Histogram
DotProduct
MatrixMul
InvMatrix
Transpose
Determinant
Clear1D
Set1D
Copy1D
GetAnalysisErrorString
Chapter 3
Analysis Library
The classes and subclasses in the function tree are described here.
The Array Operations function panels perform arithmetic operations on 1D and 2D arrays.
The Complex Operations function panels perform complex arithmetic operations. The
Complex Operations function panels can operate on complex scalars or 1D arrays. The real
and imaginary parts of complex numbers are processed separately.
The Vector & Matrix Algebra function panels perform vector and matrix operations.
Vectors and matrices are represented by 1D and 2D arrays, respectively.
The Array Utilities function panels copy, initialize, and clear arrays.
The online help with each panel contains specific information about operating each function
panel.
Hints for Using Analysis Function Panels
With the analysis function panels, you can manipulate scalars and arrays of data interactively.
You will find it helpful to use the Analysis Library function panels in conjunction with the User
Interface Library function panels to view the results of analysis routines. When using the
Analysis Library function panels, remember the following things.
The processing speed of the analysis functions is affected by the computer on which you are
running LabWindows/CVI. A numeric coprocessor, especially, increases the speed of
floating-point computations. If you are using an Analysis Library function panel and nothing
seems to happen for an inordinate amount of time, keep the constraints of your hardware in
mind.
Many analysis routines for arrays run in place. That is, the input and output data can be
stored in the same array. This is very important to keep in mind when you are processing
3-3
Analysis Library
Chapter 3
large amounts of data. Large double-precision arrays consume a lot of memory. If the
results you want do not require that you keep the original array or intermediate arrays of data,
perform analysis operations in place where possible.
The Interactive window maintains a record of generated code. If you forget to keep the code
from a function panel, you can cut and paste code between the Interactive and Program
windows.
Abs1D
int status = Abs1D (double inputArray[], int numberofElements,
double outputArray[]);
Purpose
Finds the absolute value of the inputArray. The function performs the operation in place;
inputArray and outputArray can be the same array.
Parameters
Input
inputArray
double-precision
array
numberofElements integer
Output
outputArray
Input array.
Number of elements.
double-precision
array
3-4
Chapter 3
Analysis Library
Return Value
integer
status
Add1D
int status = Add1D (double arrayX[], double arrayY[], int numberofElements,
double outputArray[]);
Purpose
Adds one-dimensional (1D) arrays. The function obtains the ith element of the output array by
using the following formula:
zi = xi + yi
The function performs the operation in place; that is, outputArray can be the same array as
either arrayX or arrayY.
Parameters
Input
arrayX
double-precision
array
Input array.
arrayY
double-precision
array
Input array.
numberofElements integer
Output
outputArray
Number of elements to be
added.
double-precision
array
Result array.
integer
Return Value
status
Add2D
int status = Add2D (void *arrayX, void *arrayY, int numberofRows,
int numberofColumns, void *outputArray);
3-5
Analysis Library
Chapter 3
Purpose
Adds two (2D) arrays. The function obtains the (ith, jth) element of the output array by using the
following formula.
z i , j = x i , j + yi , j
The function performs the operation in place; outputArray can be the same array as either
arrayX or arrayY.
Parameters
Input
arrayX
arrayY
numberofRows
integer
numberofColumns integer
Output
outputArray
Return Value
integer
status
Clear1D
int status = Clear1D (double array[], int numberofElements);
Purpose
Sets the elements of the array to zero.
Parameters
Input
numberofElements integer
Output
array
double-precision
array
3-6
Cleared array.
Chapter 3
Analysis Library
Return Value
integer
status
Copy1D
int status = Copy1D (double inputArray[], int numberofElements,
double outputArray[]);
Purpose
Copies the elements of the inputArray. This function is useful to duplicate arrays for in-place
operations.
Parameters
Input
inputArray
numberofElements integer
Output
outputArray
Number of elements in
inputArray.
Return Value
status
integer
CxAdd
int status = CxAdd (double xReal, double xImaginary, double yReal,
double yImaginary, double *outputReal
double*outputImaginary);
Purpose
Adds two complex numbers. The function obtains the resulting complex number by using the
formulas.
zr = xr + yr
zi = xi + yi
3-7
Analysis Library
Chapter 3
Parameters
Input
Output
xReal
double-precision
Real part of x.
xImaginary
double-precision
Imaginary part of x.
yReal
double-precision
Real part of y.
yImaginary
double-precision
Imaginary part of y.
outputReal
double-precision
Real part of z.
outputImaginary
double-precision
Imaginary part of z.
integer
Return Value
status
CxAdd1D
int status = CxAdd1D (double arrayXReal[], double arrayXImaginary[],
double arrayYReal[], double arrayYImaginary[],
int numberofElements, double outputArrayReal[],
double outputArrayImaginary[]);
Purpose
Adds two 1D complex arrays. The function obtains the ith element of the resulting complex
array by using the following formulas.
zri = xri + yri
zii = xii + yii
The function performs the operations in place; that is, the input and output complex arrays can be
the same.
Parameters
Input
Output
arrayXReal
double-precision array
Real part of x.
arrayXImaginary
double-precision array
Imaginary part of x.
arrayYReal
double-precision array
Real part of y.
arrayYImaginary
double-precision array
Imaginary part of y.
numberofElements
integer
Number of elements.
outputArrayReal
double-precision array
Real part of z.
3-8
Imaginary part of z.
Chapter 3
Analysis Library
Return Value
integer
status
CxDiv
int status = CxDiv (double xReal, double xImaginary, double yReal, yImaginary,
double *outputReal, double *outputImaginary);
Purpose
Divides two complex numbers. The function obtains the resulting complex number by using the
following formulas.
zr = (xr*yr + xi*yi) / (yr2 + yi2)
zi = (xi*yr - xr*yi ) / (yr2 + yi2)
Parameters
Input
Output
xReal
double-precision
Real part of x.
xImaginary
double-precision
Imaginary part of x.
yReal
double-precision
Real part of y.
yImaginary
double-precision
Imaginary part of y.
outputReal
double-precision
Real part of z.
outputImaginary
double-precision
Imaginary part of z.
integer
Return Value
status
3-9
Analysis Library
Chapter 3
CxDiv1D
int status = CxDiv1D (double arrayXReal[], double arrayXImaginary[],
double arrayYReal[], double arrayYImaginary)[],
int numberofElements, double outputArrayReal[],
double outputArrayImaginary[]);
Purpose
Divides two 1D complex arrays. The function obtains the ith element of the resulting complex
array by using the following formulas.
zri = ( xri yri + xii yii ) / ( yri 2 + yii 2 )
zii = ( xii yri xri yii ) / ( yri 2 + yii 2 )
The function performs the operations in place; that is, the input and output complex arrays can be
the same.
Parameters
Input
Output
arrayXReal
double-precision
array
Real part of x.
arrayXImaginary
double-precision
array
Imaginary part of x.
arrayYReal
double-precision
array
Real part of y.
arrayYImaginary
double-precision
array
Imaginary part of y.
numberofElements
integer
Number of elements.
outputArrayReal
double-precision
array
Real part of z.
outputArrayImaginary double-precision
array
Imaginary part of z.
Return Value
status
integer
3-10
Chapter 3
Analysis Library
CxLinEv1D
int status = CxLinEv1D (double arrayXReal[], double arrayXImaginary[],
int numberofElements, double aReal, double aImaginary,
double bReal, double bImaginary,
double outputArrayReal[],
double outputArrayImaginary[]);
Purpose
Performs a complex linear evaluation of a 1D complex array. The function obtains the ith
element of the resulting complex array by using the following formulas.
yri = ( ar xri ai xii ) + br
yii = (ar xii + ai xri ) + bi
The function performs the operations in place; that is, the input and output complex arrays can be
the same.
Parameters
Input
Output
arrayXReal
double-precision
array
Real part of x.
arrayXImaginary
double-precision
array
Imaginary part of x.
numberofElements
integer
Number of elements.
aReal
double-precision
Real part of a.
aImaginary
double-precision
Imaginary part of a.
bReal
double-precision
Real part of b.
bImaginary
double-precision
Imaginary part of b.
outputArrayReal
double-precision
array
Real part of y.
outputArrayImaginary double-precision
array
Imaginary part of y.
Return Value
status
integer
3-11
Analysis Library
Chapter 3
CxMul
int status = CxMul (double xReal, double xImaginary, double yReal,
double yImaginary, double *outputReal,
double *outputImaginary);
Purpose
Multiplies two complex numbers. The function obtains the resulting complex number by using
the following formulas.
zr = xr*yr - xi*yi
zi = xr*yi + xi*yr
Parameters
Input
Output
xReal
double-precision
Real part of x.
xImaginary
double-precision
Imaginary part of x.
yReal
double-precision
Real part of y.
yImaginary
double-precision
Imaginary part of y.
outputReal
double-precision
Real part of z.
outputImaginary
double-precision
Imaginary part of z.
integer
Return Value
status
CxMul1D
int status = CxMul1D (double arrayXReal[], double arrayXImaginary[],
double arrayYReal[], double arrayYImaginary[],
int numberofElements, double outputArrayReal[],
double outputArrayImaginary[]);
Purpose
Multiplies two 1D complex arrays. The function obtains the ith element of the resulting complex
array by using the formulas:
zri = xri yri xii yii
zii = xri yii + xii yri
3-12
Chapter 3
Analysis Library
The function performs the operations in place; that is, the input and output complex arrays can be
the same.
Parameters
Input
Output
arrayXReal
double-precision
array
Real part of x.
arrayXImaginary
double-precision
array
Imaginary part of x.
arrayYReal
double-precision
array
Real part of y.
arrayYImaginary
double-precision
array
Imaginary part of y.
numberofElements
integer
Number of elements.
outputArrayReal
double-precision
array
Real part of z.
outputArrayImaginary double-precision
array
Imaginary part of z.
Return Value
status
integer
CxRecip
int status = CxRecip (double xReal, double xImaginary, double *outputReal,
double *outputImaginary);
Purpose
Finds the reciprocal of a complex number. The function obtains the resulting complex number
by using the following formulas.
yr = xr / (xr2 + xi2)
yi = -xi / (xr2 + xi2)
3-13
Analysis Library
Chapter 3
Parameters
Input
Output
xReal
double-precision
Real part of x.
xImaginary
double-precision
Imaginary part of x.
outputReal
double-precision
Real part of y.
outputImaginary
double-precision
Imaginary part of y.
integer
Return Value
status
CxSub
int status = CxSub (double xReal, double xImaginary, double yReal,
double yImaginary, double *outputReal,
double *outputImaginary);
Purpose
Subtracts two complex numbers. The function obtains the resulting complex number by using
the following formulas.
zr = xr - yr
zi = xi - yi
Parameters
Input
Output
xReal
double-precision
Real part of x.
xImaginary
double-precision
Imaginary part of x.
yReal
double-precision
Real part of y.
yImaginary
double-precision
Imaginary part of y.
outputReal
double-precision
Real part of z.
outputImaginary
double-precision
Imaginary part of z.
integer
Return Value
status
3-14
Chapter 3
Analysis Library
CxSub1D
int status = CxSub1D (double arrayXReal[], double arrayXImaginary[],
double arrayYReal[], double arrayYImaginary[],
int numberofElements, double outputArrayReal[],
double outputArrayImaginary[]);
Purpose
Subtracts two 1D complex arrays. The function obtains the ith element of the resulting complex
array by using the following formulas.
zri = xri yri
zii = xii yii
The function performs the operations in place; that is, the input and output complex arrays can be
the same.
Parameters
Input
Output
arrayXReal
double-precision
array
Real part of x.
arrayXImaginary
double-precision
array
Imaginary part of x.
arrayYReal
double-precision
array
Real part of y.
arrayYImaginary
double-precision
array
Imaginary part of y.
numberofElements
integer
Number of elements.
outputArrayReal
double-precision
array
Real part of z.
outputArrayImaginary double-precision
array
Imaginary part of z.
Return Value
status
integer
3-15
Analysis Library
Chapter 3
Determinant
int status = Determinant (void *inputMatrix, int matrixSize, double *determinant);
Purpose
Finds the determinant of a matrixSize by matrixSize 2D input matrix.
Parameters
Input
Output
inputMatrix
matrixSize
integer
determinant
double-precision
Determinant.
integer
Div1D
int status = Div1D (double arrayX[], double arrayY[], int numberofElements,
double outputArray[]);
Purpose
Divides two 1D arrays. The function obtains the ith element of the output array by using the
following formula.
zi = xi / yi
The function performs the operation in place; that is, outputArray can be the same array as
either arrayX or arrayY.
3-16
Chapter 3
Analysis Library
Parameters
Input
Output
arrayX
double-precision
array
Input array.
arrayY
double-precision
array
Input array.
numberofElements
integer
outputArray
double-precision
array
Result array.
integer
Return Value
status
Div2D
int status = Div2D (void *arrayX, void *arrayY, int numberofRows,
int numberofColumns, void *outputArray);
Purpose
Divides two 2D arrays. The function obtains the (ith, jth) element of the output array by using
the following formula.
zi, j = xi, j / yi, j
The function performs the operation in place; that is, outputArray can be the same array as
either arrayX or arrayY.
Parameters
Input
arrayX
arrayY
numberofRows
integer
numberofColumns integer
Output
outputArray
3-17
Analysis Library
Chapter 3
Return Value
integer
status
DotProduct
int status = DotProduct (double vectorX[], double vectorY[],
int numberofElements,
double *dotProduct);
Purpose
Computes the dot product of the vectorX and vectorY input arrays. The function obtains the dot
product by using the following formula:
n 1
dotproduct = x y = xi yi
i=0
Parameters
Input
vectorX
double-precision
array
Input vector.
vectorY
double-precision
array
Input vector.
numberofElements integer
Output
dotProduct
Number of elements.
double-precision
Dot product.
integer
Return Value
status
3-18
Chapter 3
Analysis Library
GetAnalysisErrorString
char *message = GetAnalysisErrorString (int errorNum)
Purpose
Converts the error number returned by an Analysis Library function into a meaningful error
message.
Parameters
Input
errorNum
integer
Status returned by an
Analysis function.
string
Explanation of error.
Return Value
message
Histogram
int status = Histogram (double inputArray[], int numberofElements, double base,
double top, int histogramArray[], double axisArray[],
int intervals);
Purpose
Computes the histogram of the inputArray. The histogram is obtained by counting the number
of times that the elements in the input array fall in the ith interval. Let
{10
histi = y( x j , i )
j =0
The values of the histogram axis are the mid-point values of the intervals:
axisi = ix + x / 2 + xBase
3-19
Analysis Library
Chapter 3
Parameters
Input
inputArray
double-precision
array
numberofElements integer
Input array.
Number of elements in
Input Array.
Output
base
double-precision
Lower range.
top
double-precision
Upper range.
intervals
integer
Number of intervals.
histogramArray
integer array
axisArray
double-precision
array
integer
Return Value
status
InvMatrix
int status = InvMatrix (void *inputMatrix, int matrixSize, void *outputMatrix);
Purpose
Finds the inverse matrix of an input matrix. The operation can be performed in place; that is,
inputMatrix and outputMatrix can be the same matrices.
Parameters
Input
Output
inputMatrix
matrixSize
integer
outputMatrix
Dimension of matrix.
3-20
Chapter 3
Analysis Library
Return Value
integer
status
LinEv1D
int status = LinEv1D (double inputArray[], int numberofElements,
double multiplier, double additiveConstant,
double outputArray[]);
Purpose
Performs a linear evaluation of a 1D array. The function obtains the ith element of the output
array by using the following formula.
yi = a xi + b
The operation can be performed in place; that is, inputArray and outputArray can be the same
array.
Parameters
Input
inputArray
double-precision
array
numberofElements integer
double-precision
multiplier
Output
Input array.
Number of elements.
Multiplicative constant.
additiveConstant
double-precision
Additive constant.
outputArray
double-precision
array
integer
Return Value
status
3-21
Analysis Library
Chapter 3
LinEv2D
int status = LinEv2D (void *inputArray, int numberofRows, int numberofColumns,
double multiplier, double additiveConstant,
void *outputArray);
Purpose
Performs a linear evaluation of a 2D array. The function obtains the (ith, jth) element of the
output array by using the following formula.
yi,j = a* xi,j + b
The function performs the operation in place; that is, inputArray and outputArray can be the
same array.
Parameters
Input
inputArray
numberofRows
integer
numberofColumns integer
Output
multiplier
double-precision
Multiplicative constant.
additiveConstant
double-precision
Additive constant.
outputArray
Return Value
status
integer
3-22
Chapter 3
Analysis Library
MatrixMul
int status = MatrixMul (void *matrixX, void *matrixY, int #ofRowsInX,
int cols/rowsInX/Y, int #ofColumnsInY,
void *outputMatrix);
Purpose
Multiplies two 2D input matrices. The function obtains the (ith, jth) element of the output matrix
by using the following formula.
k 1
zi , j = x i , p y p , j
p= 0
Parameters
Input
Output
matrixX
matrixY
#ofRowsInX
integer
cols/rowsInX/Y
integer
#ofColumnsInY
integer
outputMatrix
Return Value
integer
status
Parameter Discussion
Note: Be sure to use the correct array sizes. The following array sizes must be met:
3-23
Analysis Library
Chapter 3
MaxMin1D
int status = MaxMin1D (double inputArray[], int numberofElements,
double *maximumValue, int *maximumIndex,
double *minimumValue, int *minimumIndex);
Purpose
Finds the maximum and minimum values in the input array, as well as the respective indices of
the first occurrence of the maximum and minimum values.
Parameters
Input
inputArray
double-precision
array
numberofElements integer
Output
Input array.
Number of elements.
maximumValue
double-precision
Maximum value.
maximumIndex
integer
Index of maximumValue in
inputArray.
minimumValue
double-precision
Minimum value.
minimumIndex
integer
Index of minimumValue in
inputArray.
integer
Return Value
status
MaxMin2D
int status = MaxMin2D (void *inputArray, int numberofRows,
int numberofColumns, double *maximumValue,
int *maximumRowIndex, int *maximumColumnIndex,
double *minimumValue, int *minimumRowIndex,
int *minimumColumnIndex);
Purpose
Finds the maximum and the minimum values in the 2D input array, as well as the respective
indices of the first occurrence of the maximum and minimum values. The inputArray is
scanned by rows.
3-24
Chapter 3
Analysis Library
Parameters
Input
Output
inputArray
double-precision
2D array
Input array.
numberofRows
integer
numberofColumns
integer
maximumValue
double-precision
Maximum value.
maximumRowIndex
integer
Index of maximumValue in
inputArray array (first
dimension).
maximumColumnIndex
integer
Index of maximumValue in
inputArray (second
dimension).
minimumValue
double-precision
Minimum value.
minimumRowIndex
integer
Index of minimumValue in
inputArray (first dimension).
minimumColumnIndex
integer
Index of minimumValue in
inputArray array (second
dimension).
Return Value
integer
status
Mean
int status = Mean (double inputArray[], int numberofElements, double *mean);
Purpose
Compute the mean (average) value of the input array. The function uses the following formula
to find the mean.
n 1
meanval = x i / n
i=0
3-25
Analysis Library
Chapter 3
Parameters
Input
inputArray
double-precision
array
numberofElements integer
Output
mean
Input array.
Number of elements in
inputArray.
double-precision
Mean value.
integer
Return Value
status
Mul1D
int status = Mul1D (double arrayX[], double arrayY[], int numberofElements,
double outputArray[]);
Purpose
Multiplies two 1D arrays. The function obtains the ith element of the output array by using the
following formula.
zi = xi yi
The function performs the operation in place; that is, outputArray can be the same array as
either arrayX or arrayY.
Parameters
Input
arrayX
double-precision
array
Input array.
arrayY
double-precision
array
Input array.
numberofElements integer
Output
outputArray
Number of elements to be
multiplied.
double-precision
array
3-26
Result array.
Chapter 3
Analysis Library
Return Value
integer
status
Mul2D
int status = Mul2D (void *arrayX, void *arrayY, int numberofRows,
int numberofColumns, void *outputArray);
Purpose
Multiplies two 2D arrays. The function obtains the (ith, jth) element of the output array by using
the following formula.
z i , j = x i, j * yi , j
The function performs the operation in place; that is, outputArray can be the same array as
either arrayX or arrayY.
Parameters
Input
arrayX
arrayY
numberofRows
integer
numberofColumns integer
Output
outputArray
Return Value
status
integer
3-27
Analysis Library
Chapter 3
Neg1D
int status = Neg1D (double inputArray[], int numberofElements,
double outputArray[]);
Purpose
Negates the elements of the input array. The function performs the operation in place; that is,
inputArray and outputArray can be the same array.
Parameters
Input
Output
inputArray
numberofElements
integer
outputArray
Number of elements.
Return Value
integer
status
Set1D
int status = Set1D (double array[], int numberofElements, double setValue);
Purpose
Sets the elements of the input array to a constant value.
Parameters
Input
Output
numberofElements
integer
setValue
double-precision
Constant value.
array
double-precision
array
integer
Return Value
status
3-28
Chapter 3
Analysis Library
Sort
int status = Sort (double inputArray[], int numberofElements, int direction,
double outputArray[]);
Purpose
Sorts the input array in ascending or descending order. The function performs the operation in
place; that is, inputArray and outputArray can be the same array.
Parameters
Input
inputArray
double-precision
array
numberofElements integer
direction
Input array.
Number of elements to be
sorted.
integer
0: ascending.
Non-zero: descending.
Output
outputArray
double-precision
array
Sorted array.
integer
Return Value
status
StdDev
int status = StdDev (double inputArray[], int numberofElements, double *mean,
double *standardDeviation);
Purpose
Computes the standard deviation and the mean (average) values of the input array. The formulas
used to find the mean and the standard deviation are as follows.
n 1
meanval = x i / n
i=0
n-1
sDev =
[x i - ave]2 / n
i=0
3-29
Analysis Library
Chapter 3
Parameters
Input
inputArray
double-precision
array
numberofElements integer
Output
Input array.
Number of elements in
inputArray.
mean
double-precision
Mean value.
standardDeviation
double-precision
Standard deviation.
integer
Return Value
status
Sub1D
int status = Sub1D (double arrayX[], double arrayY[], int numberofElements,
double outputArray[]);
Purpose
Subtracts two 1D arrays. The function obtains the ith element of the output array by using the
following formula:
zi = xi yi
The operation can be performed in place; that is, outputArray can be in place of either arrayX
or arrayY.
Parameters
Input
arrayX
double-precision
array
Input array.
arrayY
double-precision
array
Input array.
numberofElements integer
Output
outputArray
Number of elements to be
subtracted.
double-precision
array
3-30
Result array.
Chapter 3
Analysis Library
Return Value
integer
status
Sub2D
int status = Sub2D (void *arrayX, void *arrayY, int numberofRows,
int numberofColumns, void *outputArray);
Purpose
Subtracts two 2D arrays. The function obtains the (ith, jth) element of the output array by using
the formula:
z i , j = x i , j yi , j
The function performs the operation in place; that is, outputArray can be in place of either
arrayX or arrayY.
Parameters
Input
arrayX
arrayY
numberofRows
integer
numberofColumns integer
Output
outputArray
Return Value
status
integer
3-31
Analysis Library
Chapter 3
Subset1D
int status = Subset1D (double inputArray[], int numberofElements, int index,
int length, double outputArray[]);
Purpose
Extracts a subset of the inputArray input array containing the number of elements specified by
the length and starting at the index element.
Parameters
Input
inputArray
double-precision
array
numberofElements integer
Output
Input array.
Number of elements in
inputArray.
index
integer
length
integer
outputArray
double-precision
array
Subset array.
integer
Return Value
status
ToPolar
int status = ToPolar (double xReal, double yImaginary, double *magnitude,
double *phaseRadians);
Purpose
Converts the rectangular coordinates (xReal, yImaginary) to polar coordinates (magnitude,
phaseRadians). The formulas used to obtain the polar coordinates are as follows.
mag =
x2 + y2
3-32
Chapter 3
Analysis Library
Parameters
Input
Output
xReal
double-precision
X coordinate.
yImaginary
double-precision
X coordinate.
magnitude
double-precision
Magnitude.
phaseRadians
double-precision
integer
Return Value
status
ToPolar1D
int status = ToPolar1D (double arrayXReal[], double arrayYImaginary[],
int numberofElements, double magnitude[],
double phaseRadians[]);
Purpose
Converts the set of rectangular coordinate points (arrayXReal, arrayYImaginary) to a set of
polar coordinate points (magnitude, phaseRadians). The function obtains the ith element of the
polar coordinate set by using the following formulas.
magi =
xi 2 + yi 2
phasei = arctan yi / xi
The phaseRadians value is in the range of [ - to ].
The function performs the operations in place; that is, arrayXReal and magnitude, and
arrayYImaginary and phaseRadians, can be the same arrays, respectively.
3-33
Analysis Library
Chapter 3
Parameters
Input
arrayXReal
double-precision
array
X coordinate.
arrayYImaginary
double-precision
array
Y coordinate.
numberofElements integer
Output
Number of elements.
magnitude
double-precision
array
Magnitude.
phaseRadians
double-precision
array
integer
Return Value
status
ToRect
int status = ToRect (double magnitude, double phaseRadians, double *xReal,
double *yImaginary);
Purpose
Converts the polar coordinates (magnitude, phaseRadians) to rectangular coordinates (xReal,
yImaginary). The formulas used to obtain the rectangular coordinates are as follows.
x = mag * cos(phase)
y = mag * sin(phase)
Parameters
Input
Output
magnitude
double-precision
Magnitude.
phaseRadians
double-precision
xReal
double-precision
X coordinate.
yImaginary
double-precision
Y coordinate.
3-34
Chapter 3
Analysis Library
Return Value
integer
status
ToRect1D
int status = ToRect1D (double magnitude[], double phaseRadians[],
int numberofElements, double outputArrayReal[],
double outputArrayImaginary[]);
Purpose
Converts the set of polar coordinate points (magnitude, phaseRadians) to a set of rectangular
coordinate points (outputArrayReal, outputArrayImaginary). The function obtains the ith
element of the rectangular set by using the following formulas.
xi = magi cos( phasei )
yi = magi sin( phasei )
The function performs the operations in place; that is, outputArrayReal and magnitude, and
outputArrayImaginary and phaseRadians, can be the same arrays, respectively.
Parameters
Input
Output
magnitude
double-precision
array
Magnitude.
phaseRadians
double-precision
array
numberofElements
integer
Number of elements.
outputArrayReal
double-precision
array
X coordinate.
outputArrayImaginary double-precision
array
Y coordinate.
Return Value
status
integer
3-35
Analysis Library
Chapter 3
Transpose
int status = Transpose (void *inputMatrix, int numberofRows,
int numberofColumns, void *outputMatrix);
Purpose
Finds the transpose of a 2D input matrix. The (ith, jth) element of the resulting matrix uses the
formula:
yi,j = xi,j
Parameters
Input
inputMatrix
numberofRows
integer
numberofColumns integer
Output
outputMatrix
integer
3-36
Chapter 3
Analysis Library
Error Conditions
If an error condition occurs during a call to any of the functions in the LabWindows/CVI
Analysis Library, the status return value contains the error code. This code is a value that
specifies the type of error that occurred. The currently defined error codes and their associated
meanings are given in Table 3-2.
Table 3-2. Analysis Library Error Codes
Symbolic Name
Code
Error Message
BaseGETopAnlysErr
-20101
DivByZeroAnlysErr
-20060
IndexLengthAnlysErr
-20018
NoAnlysErr
OutOfMemAnlysErr
-20001
SamplesGEZeroAnlysErr
-20004
SamplesGTZeroAnlysErr
-20003
SingularMatrixAnlysErr
-20041
3-37
Chapter 4
GPIB/GPIB-488.2 Library
This describes the NI-488 and NI-488.2 functions in the LabWindows/CVI GPIB Library, as
well as the Device Manager functions in LabWindows/CVI. The GPIB Library Function
Overview section contains general information about the GPIB Library functions and panels, the
GPIB DLL, and guidelines and restrictions you should know when using the GPIB Library.
Detailed descriptions of the NI-488 and NI-488.2 functions can be found in your NI-488.2
function reference manual. The GPIB Function Reference section contains an alphabetical list of
descriptions for the Device Manager functions, the callback installation functions, and the
functions for returning the thread-specific status variables.
4-1
GPIB/GPIB-488.2 Library
Chapter 4
OpenDev
CloseDev
CloseInstrDevs
ibfind
ibdev
ibonl
ibpad
ibsad
ibbna
ibtmo
ibeos
ibeot
ibdma
ibrsc
ibconfig
ibask
ibrd
ibrda
ibrdf
ibwrt
ibwrta
ibwrtf
ibstop
ibrsp
ibclr
ibtrg
ibln
ibwait
ibloc
ibppc
ibpct
(continues)
4-2
Chapter 4
GPIB/GPIB-488.2 Library
ibsic
ibcac
ibgts
ibsre
ibcmd
ibcmda
ibrpp
iblines
ibwait
ibevent
ibsignal
ibloc
ibppc
ibrsv
ibist
ibwrtkey
ibrdkey
ibInstallCallback
ibNotify
ThreadIbsta
ThreadIberr
ThreadIbcnt
ThreadIbcntl
Send
SendList
Receive
Trigger
TriggerList
DevClear
DevClearList
(continues)
4-3
GPIB/GPIB-488.2 Library
Chapter 4
TestSRQ
WaitSRQ
FindRQS
ReadStatusByte
AllSpoll
PPoll
PPollConfig
PPollUnconfig
EnableRemote
EnableLocal
SetRWLS
SendLLO
ResetSys
SendlFC
TestSys
FinsLstn
PassControl
SendCmds
SendSetup
SendDataBytes
ReceiveSetup
RcvRespMsg
The Open/Close function panels open and close GPIB boards and devices.
The Configuration function panels alter configuration parameters that were set during
installation of the GPIB handler or during the execution of previous program statements.
The I/O function panels read and write data over the GPIB. These functions can be used at
either the board or the device level.
The Device Control function panels provide high-level, commonly used GPIB services for
instrument control applications.
4-4
Chapter 4
GPIB/GPIB-488.2 Library
The Bus Control function panels provide low-level control of the GPIB bus.
The Board Control function panels provide low-level control of the GPIB board. These
functions are normally used when the GPIB board is not controller-in-charge.
The Callbacks function panels install callback functions that are invoked when certain GPIB
events occur. The functions in this class are available only under Windows. Under UNIX,
you can use the ibsgnl function.
The Thread-Specific Status function panels return the value of the thread-specific GPIB
status variables for the current thread. The functions in this class are needed only for
multithreaded applications and are available only on Windows 95 and NT.
The GPIB 488.2 Functions function panels directly adhere to the IEEE-488.2 standard for
communicating with and controlling GPIB devices.
The Device I/O function panels read data from, and write data to, devices on the GPIB.
The Trigger and Clear function panels trigger and clear GPIB devices.
The SRQ and Serial Polls function panels handle service requests and perform
serial polls.
The Parallel Polls function panels conduct parallel polls and configure devices to
respond to them.
The Remote/Local function panels enable and disable operation of devices remotely via
the GPIB or locally via the front panel of the device.
The System Control function panels perform system-wide functions, obtain system-wide
status information, and pass system control to other devices.
The Low-Level I/O function panels perform I/O functions at a lower-level than the
function panels in the other classes.
4-5
GPIB/GPIB-488.2 Library
Chapter 4
drivers are packaged with your GPIB interface board and are not included with
LabWindows/CVI. LabWindows/CVI does not require any special procedures for installing and
using the device driver. Follow the directions outlined in your board documentation.
You can use a utility program called IBCONF, included with your GPIB software, to specify
configuration parameters for devices on the GPIB. If your device has special configuration
parameters, such as a secondary address or a special termination character, you can specify these
using IBCONF. When you are using the LabWindows/CVI GPIB Library function panels,
parameters that you specified using IBCONF are still in effect. You can also modify
configuration parameters directly from one of the LabWindows/CVI configuration function
panels, or from your program.
If you are using a LabWindows/CVI Instrument Library module, you do not need to make any
changes using IBCONF. The module takes into account any special configuration requirements
for the instrument controlled by the module. If special parameters must be specified, the module
sets them programmatically.
Before performing any other operations, open the device. You must use either the
OpenDev, the ibfind, or the ibdev function. Instrument modules must use the
OpenDev function. When you open a device, an integer value representing a device
descriptor is returned. All subsequent operations that involve a particular device require that
you specify this device descriptor.
If OpenDev is used, the CloseDev function should be used to close the device at the end
of the program.
Each GPIB Library function panel has three global controls labeled Status, Error, and Count.
These controls show the values of the GPIB status (ibsta), error (iberr) and byte count
(ibcntl) variables.
The Status control displays in hexadecimal format. The help information for Status
explains the meaning of each bit in the status word. If the most significant bit is set, a
GPIB error has occurred.
When an error occurs, the Error control displays an error number. The help information
for Error describes the type of error associated with each error number.
Count displays the number of bytes transferred over the GPIB during the most recent bus
transfer.
4-6
Chapter 4
GPIB/GPIB-488.2 Library
Note: When writing instrument modules, you must use the Device Manager functions
(OpenDev and CloseDev) instead of ibfind or ibdev. You must also use the
Device Manager functions in application programs that make calls to instrument
modules. The Device Manager functions allow instrument modules to open devices
without specific device names, thereby preventing device name conflicts. They also
help the LabWindows/CVI interactive program ensure that devices are closed when no
longer needed.
4-7
GPIB/GPIB-488.2 Library
Chapter 4
included in the wait mask. Aside from the difficulty caused by ESRQ in waiting for RQS, the
error will have no detrimental effects on other GPIB operations.
If you call the serial poll function ibrsp and have received one or more responses previously
via the automatic serial poll feature, the ibrsp function returns the first queued response. Other
responses are read in FIFO (first-in-first-out) fashion. If the RQS bit of the status word is not set
when you call ibrsp, the function conducts a serial poll and returns whatever response it
receives.
If your application requires that requests for service be noticed, call the ibrsp function
whenever the RQS bit appears in the status word. A serial poll response queue of a device can
overflow with old status bytes when you neglect to call ibrsp. ibrsp returns the error
condition ESTB when status bytes have been discarded because the queue is full. If your
application has no interest in SRQ or status bytes, you can ignore the occurrence of the automatic
polls.
Note: If the RQS bit of the device status word is still set after you call ibrsp, the response
byte queue has at least one more response byte remaining. You should call ibrsp
until RQS is cleared to gather all stored response bytes and to guard against queue
overflow.
Autopolling Compatibility
You cannot detect the SRQI bit in device status words (ibsta) if you enable Autopolling. The
goal of Autopolling is to remove the SRQ from the IEEE 488 bus, thus preventing visibility of
the SRQI bit in status words for both board calls and device calls. If you choose to look for
SRQI in your program, you must disable Autopolling.
Board functions are also incompatible with Autopolling. The handler disables Autopolling
whenever you make a board call, and re-enables it at the end of a subsequent device call.
4-8
Chapter 4
GPIB/GPIB-488.2 Library
The last GPIB call was a board call. Autopolling is re-instated after a subsequent device call.
GPIB I/O is in progress. In particular, during asynchronous GPIB I/O, autopolling will not
occur until the asynchronous I/O has completed.
The "stuck SRQ" condition exists.
Autopolling has been disabled by IBCONF or by ibconfig.
END message. The Talker asserts the EOI (End Or Identify) signal simultaneously with
transmission of the last data byte. By design, the Listener stops reading when it detects a
data message accompanied by EOI, regardless of the value of the byte.
End-of-string (EOS) character. The Talker uses a special character at the end of its data
string. By prior arrangement, the Listener stops receiving data when it detects that character.
You can use either a 7-bit ASCII character or a full 8-bit binary byte.
You can use these methods individually or in combination. However, the Listener must be
properly configured to unambiguously detect the end of a transmission.
Using the configuration program, you can accommodate all permissible forms of read and write
termination. (You cannot force the handler to ignore END on read operations.) The default
configuration settings for read and write termination can also be changed at run time using the
ibeos and ibeot functions.
Timeouts
A timeout mechanism regulates the GPIB routines that transfer command sequences or data
messages. A default timeout period of 10 sec is preconfigured in the handler; thus, all I/O must
complete within that period to avoid a timeout error. The default timeout value can be changed
with the IBCONF utility. In addition, you can use the NI-488 board function call ibtmo to
programmatically alter the timeout period.
Regardless of the I/O and Wait timeout period, a much shorter timeout is enforced for responses
to serial polls. This shorter timeout period takes effect whenever a serial poll is conducted.
Because devices normally respond quickly to polls, there is no need to wait the relatively lengthy
I/O timeout period for a nonresponsive device.
4-9
GPIB/GPIB-488.2 Library
Chapter 4
These variables are updated after each NI-488 or NI-488.2 routine to reflect the status of the
device or board just accessed. Refer to your NI-488.2 user manual for detailed information on
the GPIB global variables.
Description
NI-488.2M
NI-488.2
Compatibility driver.
AT-GPIB/TNT
AT-GPIB/TNT+
AT-GPIB/TNT (PnP)
PCI-GPIB
PCMCIA-GPIB
PCMCIA-GPIB+
4-10
Chapter 4
GPIB/GPIB-488.2 Library
If you want to use GPIB under Windows 95 and you have an older board, it is recommended that
you upgrade to one of the boards in this list.
Compatibility Driver
The compatibility driver is a 32-to-16-bit thunking DLL that you can use with the Windows 3.1
GPIB driver under Windows 95. All GPIB boards are supported by the compatibility driver. The
compatibility driver has several limitations. In particular, it does not support multithreading and
transfers are limited to 64k bytes.
Windows NT
The GPIB driver for Windows NT is a native 32-bit driver written specifically for Windows NT.
Version 1.0 supports the following boards:
AT-GPIB
AT-GPIB/TNT
Version 1.2, due to be released in the second half of 1996, will add support for the PCI-GPIB and
PCMCIA-GPIB.
Multithreading
If you are using multithreading in an external compiler, you can call GPIB functions from more
than one thread at the same time under Windows NT or under Windows 95 with the native 32-bit
driver. In order to be truly multithreaded safe, you must use on of the following versions of the
GPIB driver.
Although previous versions of the drivers support multithreading, they do not support the
ThreadIbsta, ThreadIberr, ThreadIbcnt, or ThreadIbcntl functions. You need
these functions to obtain thread-specific status values when calling GPIB functions from more
than one thread. The global status variables ibsta, iberr, ibcnt, and ibcntl, are not
reliable in this case because they are maintained on a per process basis.
4-11
GPIB/GPIB-488.2 Library
Chapter 4
4-12
Chapter 4
GPIB/GPIB-488.2 Library
CloseDev
int result = CloseDev (int Device);
Purpose
Closes a device.
Parameter
Input
Device
integer
integer
Return Value
result
Return Codes
-1
0
4-13
GPIB/GPIB-488.2 Library
Chapter 4
CloseInstrDevs
int result = CloseInstrDevs (char *instrumentPrefix);
Purpose
Closes instrument devices.
Parameter
Input
instrumentPrefix
string
Must be null-terminated.
integer
Return Value
result
Return Codes
0
Success.
ibInstallCallback
int status = ibInstallCallback (int boardOrDevice, int eventMask,
GPIBCallbackPtr callbackFunction,
void *callbackData)
Note: This function is available only on Microsoft Windows. On UNIX, use the ibsgnl
function. On Windows 3.1, the data type of the return value and the first two
parameters is short rather than int.
Purpose
This function allows you to install a synchronous callback function for a specified board or
device. If you want to install an asynchronous callback, use the ibnotify function instead.
4-14
Chapter 4
GPIB/GPIB-488.2 Library
The callback function is called when any of the GPIB events specified in the Event Mask
parameter have occurred on the board or device, but only while you allow the system to process
events. The system can process events when you call ProcessSystemEvents or
GetUserEvent, or when you have called RunUserInterface and none of your callback
functions are currently active. The callbacks are termed "synchronous" because they can be
invoked only in the context of normal event processing.
Unlike asynchronous callbacks, there are no restrictions on what you can do in a synchronous
callback. On the other hand, the latency between the occurrence of a GPIB event and the
invocation of the callback function is greater and more unbounded with synchronous callbacks
than with asynchronous callbacks.
Only one callback function can apply for each board or device. Each call to this function for the
same board or device supersedes the previous call.
To disable callbacks for a board or device, pass 0 for the event Mask parameter.
To use this function with the NI-488.2M (native 32-bit) driver, you must have one of the
following versions.
If you use the NI-488.2 driver (the Windows 3.1 driver or the compatibility driver in Windows 95),
you must pass a board index for the first parameter, and you can use only SRQI or CMPL for the
event mask parameter.
Parameters
Input
boardOrDevice
integer
(short integer on
Windows 3.1)
eventMask
integer
(short integer on
Windows 3.1)
callbackFunction
callbackData
void pointer
4-15
GPIB/GPIB-488.2 Library
Chapter 4
Return Value
status
integer
(short integer on
Windows 3.1)
eventMask
The conditions upon which to invoke the callback function are specified as bits in the
eventMask parameter. The bits corresponds to the bits of the ibsta status word. This value
reflects a sum of one or more events. If any one of the conditions occur, the callback is called.
If, when you install the callback, one of the bits you have set in the mask is already TRUE, the
callback is scheduled immediately. For example, if you pass CMPL as the eventMask, and the
ibwait function would currently return a status word with CMPL set, the callback is scheduled
immediately.
If you are using a NI-488.2M (native 32-bit) driver then the following mask bits are valid:
At the board level, you can specify any of the status word bits that can be specified in the
waitMask parameter to the ibwait function for a board, other than ERR. This includes
SRQI, END, CMPL, TIMO, CIC, and others.
At the device level, you can specify any of the status word bits that can be specified in the
waitMask parameter to the ibwait function for a device, other than ERR. This includes
RQS, END, CMPL, and TIMO.
If you are using a NI-488.2 driver (Windows 3.1 or compatibility driver for Windows 95), then
the only following mask bits are valid:
SRQI or CMPL but not both.
SRQI, RQS, and Auto Serial Polling
If you want to install a callback for the SRQI (board-level) event, Auto Serial Polling must be
disabled. You can disable Auto Serial Polling with the following function call:
ibconfig (boardIndex, IbcAUTOPOLL, 0);
If you want to install a callback for the RQS (device-level) event, Auto Serial Polling must be
enabled for the board. You can enable Auto Serial Polling with the following function call:
ibconfig (boardIndex, IbcAUTOPOLL, 1);
4-16
Chapter 4
GPIB/GPIB-488.2 Library
CallbackFunction
The callback function must have the following form.
void CallbackFunctionName (int boardOrDevice, int mask, void *callbackData);
The mask and callbackData parameters are the same values that were passed to
ibInstallCallback.
If invoked because of an SRQI or RQS condition, the callback function should call the ibrsp
function to read the status byte. For an SRQI (board-level) condition, calling the ibrsp
function is necessary to cause the requesting device to turn off the SRQ line.
char statusByte;
ibrsp (device, &statusByte);
The ibcnt and ibcntl status variables are not updated until this call to ibwait is made.
See Also
ibnotify
ibNotify
int status = ibnotify (int boardOrDevice, int eventMask,
GpibNotifyCallback_t callbackFunction, void *callbackData);
Note: This function is available only on Windows 95 and NT. On UNIX, use the ibsgnl
function.
Purpose
This function allows you to install an asynchronous callback function for a specified board or
device. If you want to install a synchronous callback, use the ibInstallCallback function
instead.
The callback function is called when any of the GPIB events specified in the eventMask
parameter have occurred on the specified board or device. Asynchronous callbacks can be called
at any time while your program is running. You do not have to allow the system to process
events. Because of this, you are restricted in what you can do in the callback. See the
Restrictions on Operations in Asynchronous Callbacks discussion below.
4-17
GPIB/GPIB-488.2 Library
Chapter 4
Only one callback function can apply for each board or device. Each call to this function for the
same board or device supersedes the previous call.
To disable callbacks for a board or device, pass 0 for the eventMask parameter.
Parameters
Input
boardOrDevice
integer
eventMask
integer
callbackFunction
GpibNotifyCallback_t
callbackData
void pointer
integer
Return Value
status
eventMask
The conditions upon which to invoke the callback function are specified as bits in the
eventMask parameter. The bits corresponds to the bits of the ibsta status word. This value
reflects a sum of one or more events. If any one of the conditions occur, the callback is called.
If, when you install the callback, one of the bits you have set in the mask is already TRUE, the
callback is called immediately. For example, if you pass CMPL as the eventMask, and the
ibwait function would currently return a status word with CMPL set, the callback is called
immediately.
At the board level, you can specify any of the status word bits that can be specified in the
waitMask parameter to the ibwait function for a board, other than ERR. This includes SRQI,
END, CMPL, TIMO, CIC, and others.
At the device level, you can specify any of the status word bits that can be specified in the
waitMask parameter to the ibwait function for a device, other than ERR. This includes RQS,
END, CMPL, and TIMO.
LabWindows/CVI Standard Libraries
4-18
Chapter 4
GPIB/GPIB-488.2 Library
If you want to install a callback for the RQS (device-level) event, Auto Serial Polling must be
enabled for the board. You can enable Auto Serial Polling with the following function call:
ibconfig (boardIndex, IbcAUTOPOLL, 1);
CallbackFunction
The callback function must have the following form.
void __stdcall CallbackFunctionName (int boardOrDevice, int sta, int err,
long cntl, void *callbackData);
The callbackData parameter is the same callbackData value passed to
ibInstallCallback. The sta, err, and cntl parameters contain the information that you
normally obtain using the ibsta, iberr, and ibcntl global variables or the
ThreadIbsta, ThreadIberr, and ThreadIbcntl functions. The global variables and
thread status functions return undefined values within the callback function. So you must use the
sta, err and cntl parameters instead.
The value that you return from the callback function is very important. It is the event mask that is
used to rearm the callback. If you return 0, the callback is disarmed (that is, it is not called again
until you make another call to ibnotify). If you return an event mask different than the one
you originally passed to ibnotify, the new event mask is used. Normally, you want to return
the same event mask that you originally passed to ibnotify.
If you return an invalid event mask or if there is an operating system error in rearming the
callback, the callback is called with the sta set to ERR , err set to EDVR, and cntl set to
IBNOTIFY_REARM_FAILED.
Warning:
Because the callback can be called as the result of a rearming error, you should
always check the value of the sta parameter to make sure that one of the
requested events has in fact occurred.
If invoked because of an SRQI or RQS condition, the callback function should call the ibrsp
function to read the status byte. For an SRQI (board-level) condition, calling the ibrsp
function is necessary to cause to requesting device to turn off the SRQ line.
char statusByte;
ibrsp (device, &statusByte);
4-19
GPIB/GPIB-488.2 Library
Chapter 4
The ibcnt and ibcntl status variables are not updated until this call to ibwait is made.
Restrictions on Operations in Asynchronous Callbacks
Callbacks installed with ibnotify can be called at any time while your program is running.
You do not have to allow the system to process events. Because of this, you are restricted in what
you can do in the callback. You can do the following:
Call the User Interface Library PostDeferredCall function, which schedules a different
callback function to be called synchronously.
Manipulate global variables, but only if you know that the callback has not been called at a
point when the main part of your program is modifying or interrogating the same global
variables.
Call ANSI C functions such as strcpy and sprintf, which affect only the arguments
passed in (that is, have no side effects). You cannot call printf or file I/O functions.
If you need to perform operations that fall outside these restrictions, do the following.
1.
2.
See Also
ibInstallCallback
4-20
Chapter 4
GPIB/GPIB-488.2 Library
OpenDev
int bd = OpenDev (char *deviceName, char *instrumentPrefix);
Purpose
Opens a GPIB device.
Parameters
Input
deviceName
string
Must be null-terminated.
instrumentPrefix
string
Must be null-terminated.
integer
Return Value
bd
Return Codes
-1
Parameter Discussion
deviceName is a string specifying a device name that appears in the IBCONF device table. If
deviceName is not "", OpenDev acts identically to ibfind. If deviceName is "", OpenDev
acts identically to ibdev. OpenDev uses the first available unopened device.
instrumentPrefix is a string that specifies the instrument prefix associated with the instrument
module. The instrument prefix must be identical to the prefix entered when creating the function
tree for the instrument module. If the instrument module has no prefix or if OpenDev is not
being used in an instrument module, pass the string "" for instrumentPrefix.
Using This Function
This function attempts to find an unused device in the GPIB handler's device table and open it. If
successful, OpenDev returns a device descriptor. Otherwise, it returns a negative number.
4-21
GPIB/GPIB-488.2 Library
Chapter 4
ThreadIbcnt
int threadSpecificCount = ThreadIbcnt (void);
Note: This function is available only under Windows 95 and NT.
This function returns the value of the thread-specific ibcnt variable for the current thread.
The global variables ibsta, iberr, ibcnt, and ibcntl are maintained on a process-specific
(rather than thread-specific) basis. If you are calling GPIB functions in more than one thread, the
values in these global variables may not always be reliable.
Status variables analogous to ibsta, iberr, ibcnt, and ibcntl are maintained for each
thread. This function returns the value of the thread-specific ibcnt variable.
If you are not using multiple threads, the value returned by this function is identical to the value
of the ibcnt global variable.
Parameters
none
Return Value
threadSpecificCount
See Also
ThreadIbsta, ThreadIberr, ThreadIbcntl.
ThreadIbcntl
long threadSpecificCount = ThreadIbcntl (void);
Note: This function is available only under Windows 95 and NT.
This function returns the value of the thread-specific ibcntl variable for the current thread.
The global variables ibsta, iberr, ibcnt, and ibcntl are maintained on a process-specific
(rather than thread-specific) basis. If you are calling GPIB functions in more than one thread, the
values in these global variables may not always be reliable.
Status variables analogous to ibsta, iberr, ibcnt, and ibcntl are maintained for each
thread. This function returns the value of the thread-specific ibcntl variable.
4-22
Chapter 4
GPIB/GPIB-488.2 Library
If you are not using multiple threads, the value returned by this function is identical to the value
of the ibcntl global variable.
Parameters
none
Return Value
threadSpecificCount long
integer
See Also
ThreadIbsta, ThreadIberr, ThreadIbcnt.
ThreadIberr
int threadSpecificError = ThreadIberr (void);
Note: This function is available only under Windows 95 and NT.
This function returns the value of the thread-specific iberr variable for the current thread.
The global variables ibsta, iberr, ibcnt, and ibcntl are maintained on a process-specific
(rather than thread-specific) basis. If you are calling GPIB functions in more than one thread, the
values in these global variables may not always be reliable.
Status variables analogous to ibsta, iberr, ibcnt, and ibcntl are maintained for each
thread. This function returns the value of the thread-specific iberr variable.
If you are not using multiple threads, the value returned by this function is identical to the value
of the iberr global variable.
Parameters
none
Return Value
threadSpecificError
integer
The most recent GPIB error code for the current thread of
execution. The value is meaningful only when
ThreadIbsta returns a value with the ERR bit set.
4-23
GPIB/GPIB-488.2 Library
Chapter 4
Return Codes
Defined
Constant
Value
Description
EDVR
ECIC
ENOL
EADR
EARG
ESAC
EABO
ENEB
EDMA
EOIP
10
ECAP
11
Unsupported feature.
EFSO
12
EBUS
14
ESTB
15
ESRQ
16
ETAB
20
ELCK
21
ELNK
200
The GPIB library was not linked. Dummy functions were linked instead.
EDLL
201
EFNF
203
EGLB
205
ENNI
206
EMTX
207
Unable to acquire Mutex for loading DLL. The MS Windows error code
is returned by ThreadIbcntl.
EMSG
210
ECTB
211
4-24
Chapter 4
GPIB/GPIB-488.2 Library
See Also
ThreadIbsta, ThreadIbcnt, ThreadIbcntl.
ThreadIbsta
int threadSpecificStatus = ThreadIbsta (void);
Note: This function is available only under Windows 95 and NT.
This function returns the value of the thread-specific ibsta variable for the current thread.
The global variables ibsta, iberr, ibcnt, and ibcntl are maintained on a process-specific
(rather than thread-specific) basis. If you are calling GPIB functions in more than one thread, the
values in these global variables may not always be reliable.
Status variables analogous to ibsta, iberr, ibcnt, and ibcntl are maintained for each
thread. This function returns the value of the thread-specific ibsta variable.
If you are not using multiple threads, the value returned by this function is identical to the value
of the ibsta global variable.
Parameters
none
Return Value
threadSpecificStatus
integer
4-25
GPIB/GPIB-488.2 Library
Chapter 4
Return Codes
The return value is a sum of the following bits.
Defined
Constant
Hex Value
Condition
ERR
8000
GPIB error.
END
2000
SRQI
1000
SRQ is on.
RQS
800
CMPL
100
I/O completed.
LOK
80
REM
40
CIC
20
GPIB-PC is Controller-In-Charge.
ATN
10
Attention is asserted.
TACS
GPIB-PC is Talker.
LACS
GPIB-PC is Listener.
DTAS
DCAS
See Also
ThreadIberr, ThreadIbcnt, ThreadIbcntl
4-26
Chapter 5
RS-232 Library
This chapter describes the functions in the LabWindows/CVI RS-232 Library. The RS-232
Library Function Overview section contains general information about the RS-232 Library
functions and panels. The RS-232 Library Function Reference section contains an alphabetical
list of function descriptions.
In order to use the RS-232 Library on UNIX, your UNIX kernel must support asynchronous I/O
functions (for example, aioread and aiowrite). You can enable this by building your
UNIX kernel as Generic instead of Generic Small.
OpenComConfig
CloseCom
OpenCom
ComRd
ComRdTerm
ComRdByte
(continues)
5-1
RS-232 Library
Chapter 5
ComToFile
ComWrt
ComWrtByte
ComFromFile
XModemSend
XModemReceive
XModemConfig
SetComTime
SetXMode
SetCTSMode
FlushInQ
FlushOutQ
ComBreak
ComSetEscape
GetComStat
GetInQLen
GetOutQLen
ReturnRS232Err
GetRS232ErrorString
InstallComCallback
The Open/Close function panels open, close and configure a com port.
The Input/Output function panels read from and write to a com port.
The XModem function panels transfer files using the XModem protocol.
The Control function panels set the time-out limit, set communication modes, flush the I/O
queues, and send the break signal.
The Status function panels return the com port status and the length of the I/O queues.
The Callbacks function panel installs callback functions for COM events.
The online help with each panel contains specific information about operating each function
panel.
5-2
Chapter 5
RS-232 Library
Using RS-485
You can use all of the functions in the RS-232 Library with the National Instruments RS-485
AT-Serial board. The ComSetEscape function allows you to control the transceiver mode of
the board.
Troubleshooting
Establishing communication between two RS-232 devices can be difficult because of the many
different possible configurations. When using this library, you must know the device
requirements, such as baud rate, parity, number of data bits, and number of stop bits. Basically,
these configurations must match between the two parties of communication.
If you encounter difficulty in establishing initial communication with the device, refer to an
elementary RS-232 communications handbook for information about cable requirements and
general RS-232 communication. Refer also to the section RS-232 Cable Information later in this
chapter.
5-3
RS-232 Library
Chapter 5
All functions, except the Open and Close functions, require the com port to be opened with
OpenCom or OpenComConfig.
If the program writes data to the output queue and then immediately closes the com port, the data
in the queue may be lost if it has not had time to be sent over the port. To guarantee that all bytes
were written before closing the port, monitor the length of the output queue with the
GetOutQLen function. When the output queue length becomes zero, it is safe to close the port.
If the XModemReceive function fails to complete properly, verify that the input queue length
is greater than or equal to the packet size. Refer to the functions OpenComConfig and
XModemConfig.
If the receiver appears to lose data transmitted by the sender, the input queue of the receiver may
be overflowing. This means that the input queue of the receiver is not emptied as quickly as data
is coming in. You can solve this problem using handshaking, provided both devices offer the
same handshaking support. Refer to the Handshaking section of this chapter for further
information.
If an XModem file transfer with a large packet size and a low baud rate fails, you might need to
increase the wait period. Ten seconds is sufficient for most transfers.
Meaning
TxDTransmit Data *
RxDReceive Data
RTSRequest to Send *
CTSClear to Send
20
Common
The items with an asterisk (*) indicate the lines that the PC drives, and all other items indicate
the lines the PC monitors.
5-4
Chapter 5
RS-232 Library
All serial devices are either of the type Data Communication Equipment (DCE) or Data
Transmission Equipment (DTE). The PC is of type DTE. The difference between the two
devices is in the meaning assigned to the pins. A DCE device reverses the meaning of pins 2 and
3, 4 and 5, and 6 and 20. In the simplest scenario, a DTE device is attached to a DCE device,
such as a modem. Therefore, the cable required for a PC (or DTE) to talk to a device that is a
DCE is shown in Table 5-3.
Table 5-3. DTE to DCE Cable Configuration
(PC)
TxD*
RxD
RTS*
CTS
DSR
DTR*
common
(Device)
3_______________ 3
4_______________ 4
TxD*
5_______________ 5
6_______________ 6
RTS*
20 ______________20
7_______________ 7
DSR*
RxD
CTS
DTR
common
You need a different cable for the PC to talk to a DTE device, because both devices transmit data
over pin 2. The cable to connect a PC to a DTE is called a null modem cable. A null modem
cable must be built as shown in Table 5-4.
Table 5-4. PC to DTE Cable Configuration
(PC)
TxD*
RxD
RTS*
CTS
DSR
DTR*
common
(Device)
3_______________ 2
4_______________ 5
TxD*
5_______________ 4
6_______________20
RTS*
20 ______________ 6
7_______________ 7
RxD
CTS
DTR
DSR*
common
For further information on the meaning of DTE and DCE, refer to a reference book on RS-232
communication.
In the simplest case, a serial cable needs lines 2, 3, and 7 for basic communication to take place.
Hardware handshaking and modem control can require other lines, depending on your
5-5
RS-232 Library
Chapter 5
application. Refer to the Hardware Handshaking section later in this chapter for more
information about using the lines 4, 5, 6, and 20.
Another area that requires special attention is the gender of the connectors of your serial cable.
The serial cable plugs into sockets in the PC and the serial device just as a lamp cord plugs into a
wall socket. Both the connector and the socket can be male, with pins (like a lamp plug), or
female, with holes (like an outlet). If your serial cable connector and PC socket are the same
gender, you cannot plug the cable into the socket. You can change this by attaching a small
device called a gender changer to your cable. One type of gender changer converts a female
connector to a male connector and the other type converts a male connector to a female
connector.
The size of the connector on your serial cable can also differ from the size of the socket. Most
serial ports require a 25-pin connector. However, some serial ports require a 9-pin connector.
To resolve this incompatibility, you must either change the connector on your serial cable or
attach a small device that converts from a 25-pin connector to a 9-pin connector.
Handshaking
A common error condition in RS-232 communications is that the receiver appears to lose data
transmitted by the sender. This condition typically results from the input queue of the receiver
not being emptied quickly enough.
Handshaking prevents overflow of the input queue that occurs when the receiver is unable to
empty its input queue as quickly as the sender is able to fill it. The RS-232 Library has two types
of handshaking: software handshaking and hardware handshaking. You should enable one or the
other if you want to ensure that your application program synchronizes its data transfers with
other serial devices that perform handshaking.
Software Handshaking
The SetXMode function enables software handshaking. You can use software handshaking
when you are transferring ASCII data or text and your serial device uses software handshaking.
The RS-232 Library performs software handshaking by sending and monitoring incoming data
for special data bytes (XON and XOFF, or decimal 17 and 19). These bytes indicate whether the
receiver is ready to receive data.
You must not enable software handshaking when transmitting binary data because the special
XON/XOFF characters can occur as part of the data stream and are mistaken as control codes.
However, you can enable hardware handshaking regardless of the type of data transferred.
No special cable configuration is required to perform software handshaking.
5-6
Chapter 5
RS-232 Library
Hardware Handshaking
The SetCTSMode function enables hardware handshaking. For hardware handshaking to work,
two conditions must exist. First, the serial devices must follow the same or similar hardware
handshake protocols (they must use the same lines for the handshake and assign the same
meanings to those lines). Second, the serial cable connecting the two devices must include the
lines required to support the protocol. Because no single well-defined hardware handshake
protocol exists, resolve any differences between the LabWindows/CVI hardware handshake
protocol and the one your device uses.
Most serial devices primarily rely on the CTS and RTS lines to perform hardware handshaking,
and the DTR line is used to signal its online presence to the other device. Some serial devices
also may use the DTR line for hardware handshaking similarly to the CTS line. The
SetCTSMode function has two different modes to handle either case.
This SetCTSMode function employs the following line behaviors for each mode.
Note: Under UNIX, changes to the DTR line have no effect on the communication port.
LWRS_HWHANDSHAKE_OFF
The RTS and DTR lines are raised when opening the port and lowered when closing the port.
Data is sent out the port regardless of the status of CTS.
Note: Under Windows, the SetComEscape function can be used to change the value of
the RTS and DTR lines.
LWRS_HWHANDSHAKE_CTS_RTS
If the input queue of the port is nearly full, the library lowers RTS.
If the input queue of the port is nearly empty, the library raises RTS.
The RS-232 library must detect that its CTS line is high before sending data out the port.
LWRS_HWHANDSHAKE_CTS_RTS_DTR
5-7
RS-232 Library
Chapter 5
If the input queue of the port is nearly full, the library lowers RTS and DTR.
If the input queue of the port is nearly empty, the library raises RTS and DTR.
The RS-232 library must detect that its CTS line is high before sending data out the port.
CloseCom
int result = CloseCom (int COMPort);
Purpose
Closes a COM port.
Parameter
Input
COMPort
integer
integer
Return Value
result
5-8
Chapter 5
RS-232 Library
Parameter Discussion
The function does nothing if the port numbers are invalid (port is not open or parameter value is
not in the range 1 through 32).
ComBreak
int result = ComBreak (int COMPort, int breakTimeMsec);
Purpose
Generates a break signal.
Parameters
Input
COMPort
integer
breakTimeMsec
integer
integer
Return Value
result
ComFromFile
int nbytes = ComFromFile (int COMPort, int fileHandle, int count,
int terminationByte);
Purpose
Reads from the specified file and writes to output queue of the specified COM port.
5-9
RS-232 Library
Chapter 5
Parameters
Input
COMPort
integer
fileHandle
integer
count
integer
terminationByte
integer
integer
Return Value
nbytes
<0
Parameter Discussion
Reads count bytes from the file unless it encounters terminationByte, reaches EOF, or
encounters an error. The function returns the number of bytes successfully written to the output
queue. The function returns immediately after placing all bytes in the output queue, not when
bytes have all been sent out the com port.
If count is zero, the function terminates on terminationByte, EOF, or error.
If terminationByte is -1, it is ignored, and the function terminates on count bytes written, EOF,
or error. If terminationByte is not -1, reading from the file stops when terminationByte is
encountered. It does not write terminationByte to the output queue. If terminationByte is CR
or LF, then the function treats CR-LF and LF-CR combinations just as ComRdTerm does.
If both count and terminationByte are disabled, the function terminates on EOF or error.
Using This Function
To guarantee that all bytes were removed from the output queue before closing the port, call
GetOutQLen to determine the number of bytes remaining in the output queue. If you close the
port before every byte has been sent, you lose the bytes remaining in the queue.
The function returns a negative error code if the output queue remains full for the duration of the
time-out period, the file handle is bad, a read error occurs, the port is not open, or the COMPort
is invalid.
5-10
Chapter 5
RS-232 Library
ComRd
int nbytes = ComRd (int COMPort, char buffer[], int count);
Purpose
Reads count bytes from input queue of the specified port and stores them in buffer. Returns
either on time-out or when count bytes have been read. Returns an integer value indicating the
number of bytes read from queue.
Parameters
Input
Output
COMPort
integer
count
integer
buffer
string
integer
Return Value
nbytes
5-11
RS-232 Library
Chapter 5
ComRdByte
int byte = ComRdByte (int COMPort);
Purpose
Reads a byte from the input queue of the specified port. Returns an integer whose low-order byte
contains the byte read. Returns either on time-out, when the byte is read, or when an error occurs.
If an error or a time-out occurs, ComRdByte returns a negative error code. See Table 5-6. This is
the only case in which the high-order byte of the return value is non-zero.
Parameter
Input
COMPort
integer
integer
Return Value
byte
<0
Error.
ComRdTerm
int nbytes = ComRdTerm (int COMPort, char buffer[], int count,
int terminationByte);
Purpose
Reads from input queue until terminationByte occurs in buffer, count is met, or a time-out
occurs. Returns integer value indicating number of bytes read from queue.
5-12
Chapter 5
RS-232 Library
Parameters
Input
Output
COMPort
integer
count
integer
terminationByte
integer
buffer
string
integer
Return Value
nbytes
If terminationByte = CR, and if the character immediately following CR is LF, discard the
LF in addition to the CR.
If terminationByte = LF, and if the character immediately following LF is CR, discard the
CR in addition to the LF.
Only the bytes placed in buffer are included in the return count. If CR or LF is discarded
because it follows an LF or CR, it is not counted toward satisfying the count.
The function returns an error if the port is not open or parameter values are invalid.
5-13
RS-232 Library
Chapter 5
ComSetEscape
int result = ComSetEscape (int COMPort, int escapeCode);
Purpose
Directs the specified com port to carry out an extended function such as clearing or setting the
RTS signal line or setting the transceiver mode for RS-485. The extended functions are defined
by the serial device driver.
Not all device drives support all escape codes. Unknown System Error (-1) is returned when the
device driver does not support a particular escape code.
Note: This function is supported in the MS Windows version of LabWindows/CVI only.
Parameters
Input
COMPort
escapeCode
Return Value
result
integer
Parameter Discussion
The following values can be used for escape code.
CLRDTRClears the DTR (data-terminal-ready) signal.
CLRRTSClears the RTS (request-to-send) signal.
GETMAXCOMReturns the maximum com port identifier supported by the system. This value
ranges from 0x00 to 0x7F, such that 0x00 corresponds to COM1, 0x01 to COM2, 0x02 to
COM3, and so on.
SETDTRSends the DTR (data-terminal-ready) signal.
SETRTSSends the RTS (request-to-send) signal.
SETXOFFCauses the port to act as if an XOFF character has been received.
SETXONCauses the port to act as if an XON character has been received.
5-14
Chapter 5
RS-232 Library
The following values may be used only with the RS-485 serial driver developed by National
Instruments:
WIRE_4Sets the transceiver to Four Wire Mode.
WIRE_2_ECHOSets the transceiver to Two Wire DTR controlled with echo mode.
WIRE_2_CTRLSets the transceiver to Two Wire DTR controlled without echo.
WIRE_2_AUTOSets the transceiver to Two Wire auto TXRDY controlled mode.
ComToFile
int nbytes = ComToFile (int COMPort, int fileHandle, int count,
int terminationByte);
Purpose
Reads from input queue of specified com port and write data to file specified by fileHandle.
Returns number of bytes successfully written to file. Bytes are read from input queue until count
is satisfied, terminationByte is encountered, or an error occurs, whichever occurs first.
Parameters
Input
COMPort
integer
fileHandle
integer
count
integer
terminationByte
integer
integer
Return Value
nbytes
Parameter Discussion
If count is zero, the function ignores it and terminates on terminationByte or error.
If terminationByte is -1, the function ignores it and terminates on count bytes read or an error.
If terminationByte is valid, the function stops when it encounters terminationByte.
terminationByte is removed from the input queue and is not written to the file. If
terminationByte is CR or LF, then CR-LF and LF-CR combinations are treated just as they are
5-15
RS-232 Library
Chapter 5
for ComRdTerm. If both count and terminationByte are disabled, the function terminates on
error (which can include a time-out).
Using This Function
The function returns an error if the output queue remains full for the duration of the time-out
period, the file handle is bad, a read error occurs, the port is not open, or the COMPort is
invalid.
ComWrt
int nbytes = ComWrt (int COMPort, char buffer[], int count);
Purpose
Writes count bytes to the output queue of the specified port. Returns an integer value indicating
the number of bytes placed in the queue. Returns immediately without waiting for the bytes to
be sent out of the serial port.
Parameters
Input
COMPort
integer
buffer
string
count
integer
integer
Return Value
nbytes
<0
5-16
Chapter 5
RS-232 Library
the port, call GetOutQLen. GetOutQLen returns the number of bytes remaining in the output
queue.
The function returns an error if the port is not open or parameter values are invalid.
Example
/*
/*
if
/*
or
char buf[100];
Fmt(buf,"%s","Hello, World!");
if (ComWrt (2, buf, 13) != 13)
/* Operation was unsuccessful */;
ComWrtByte
int status = ComWrtByte (int COMPort, int byte);
Purpose
Writes a byte to the output queue of the specified port. The byte written is the low-order byte of
the integer. Returns a 1 to indicate the operation is successful, or a negative error code to indicate
the operation has failed. Returns immediately without waiting for the byte to be transmitted out
through the serial port.
Parameters
Input
COMPort
integer
byte
integer
integer
Return Value
status
<0
5-17
RS-232 Library
Chapter 5
Parameter Discussion
This function times out if the output queue has not been updated in the specified time-out period.
This can occur if the output queue is full and no further data can be sent because XON/XOFF is
enabled and the device has sent an XOFF character without sending the follow-on XON
character. It can also occur if Hardware Handshaking is enabled and the Clear To Send (CTS)
line is not asserted.
Bytes are sent from the output queue to the serial device under interrupt control without program
intervention. If you close the port before all bytes have been sent, you lose the bytes remaining in
the queue. To guarantee that all bytes have been removed from the output queue before closing
the port, call GetOutQLen. GetOutQLen returns the number of bytes remaining in the output
queue.
The function returns an error if the port is not open or parameter values are invalid.
FlushInQ
int status = FlushInQ (int COMPort);
Purpose
Removes all characters from the input queue of the specified port.
Parameter
Input
COMPort
integer
integer
Return Value
status
5-18
Chapter 5
RS-232 Library
FlushOutQ
int status = FlushOutQ (int COMPort);
Purpose
Removes all characters from the output queue of the specified port.
Parameter
Input
COMPort
integer
integer
Return Value
status
GetComStat
int status = GetComStat (int COMPort);
Purpose
Returns information about the status of the specified COM port. COM port conditions are
accumulated until you call GetComStat.
Parameter
Input
COMPort
integer
integer
Return Value
status
<0
5-19
RS-232 Library
Chapter 5
Mnemonic
Description
0001
INPUT LOST
0002
0010
PARITY
0020
OVERRUN
0040
FRAMING
0080
BREAK
1000
REMOTE XOFF
4000
LOCAL XOFF
Notice the ambiguity in this status information. If an error occurs on the indicated port, the
application program knows that one or more bytes are invalid. The program cannot know from
the status word which byte read since the last call to GetComStat is invalid.
The function returns a negative error code if the port is not open or if COMPort is invalid.
GetInQLen
int len = GetInQLen (int COMPort);
Purpose
Returns the number of characters in the input queue of the specified port. This function does not
change the input queue.
5-20
Chapter 5
RS-232 Library
Parameter
Input
COMPort
integer
integer
Return Value
len
Parameter Discussion
The function returns an error if the port is not open or if COMPort is invalid.
GetOutQLen
int len = GetOutQLen (int COMPort);
Purpose
Returns the number of characters in the output queue of the specified port.
Parameter
Input
COMPort
integer
integer
Return Value
len
5-21
RS-232 Library
Chapter 5
GetRS232ErrorString
char *message = GetRS232ErrorString (int errorNum)
Purpose
Converts the error number returned by an RS-232 Library function into a meaningful error
message.
Parameters
Input
errorNum
integer
string
Explanation of error.
Return Value
message
InstallComCallback
int status = InstallComCallback (int COMPort, int eventMask, int notifyCount,
int eventCharacter, ComCallbackPtr callbackPtr,
void *callbackData);
Note: This function is available only in the Windows version of LabWindows/CVI.
Purpose
This function allows you to install a callback function for a particular COM port. The callback
function is called whenever any of the events specified in the eventMask parameter occur on the
COM port and you allow the system to process events. The system can process events in the
following situations.
You have called RunUserInterface and none of your callback functions is currently
executing, or
Only one callback function can apply for each COM port. Each call to this function for the same
COM port supersedes the previous call.
To disable callbacks for a board or device, pass 0 for the eventMask and/or callbackFunction
parameters.
5-22
Chapter 5
RS-232 Library
Note: The callback function may receive more than one event at a time. When using this
function at higher baud rates, some LWRS_RXCHAR events may be missed. It is
recommended to use LWRS_RECEIVE or LWRS_RXFLAG instead.
Note: Once the LWRS_RECEIVE event occurs, it is not triggered again until the input queue
falls below, and then rises back above, notifyCount bytes.
Example
notifyCount = 50; /* Wait for at least 50 bytes in queue */
eventChar
= 13; /* Wait for LF */
eventMask
= LWRS_RXFLAG | LWRS_TXEMPTY | LWRS_RECEIVE;
InstallComCallback (comport, eventMask, notifyCount,
eventChar, ComCallback, NULL);
...
/* Callback Function */
void ComCallback(int portNo, int evnetMask, void *data)
{
if (eventMask & LWRS_RXFLAG)
printf("Received specified character\n");
if (eventMask & LWRS_TXEMPTY)
printf("Transmit queue now empty\n");
if (eventMask & LWRS_RECEIVE)
printf("50 or more bytes in input queue\n");
}
Parameters
Input
COMPort
integer
eventMask
integer
notifyCount
integer
eventCharacter
integer
callbackPtr
ComCallbackPtr
callbackData
void *
5-23
RS-232 Library
Chapter 5
Return Value
integer
status
Parameter Discussion
The callback function must have the following form.
void CallbackFunctionName (int COMPort, int eventMask, void *callbackData);
The eventMask and callbackData parameters are the same values that were passed to
InstallComCallback.
The events are specified using bits in the eventMask parameter. You can specify multiple event
bits in the eventMask parameter. The valid event bits are listed in the table below.
Bit
Hex Value
Constant Name
0x0001
LWRS_RXCHAR
0x0002
LWRS_RXFLAG
0x0004
LWRS_TXEMPTY
0x0008
LWRS_CTS
0x0010
LWRS_DSR
0x0020
LWRS_RLSD
0x0040
BREAK received.
LWRS_BREAK
0x0080
LWRS_ERR
0x0100
LWRS_RING
15
0x8000
LWRS_RECEIVE
5-24
Chapter 5
RS-232 Library
Description
LWRS_RXCHAR
LWRS_RXFLAG
LWRS_TXEMPTY
LWRS_CTS
LWRS_DSR
LWRS_RLSD
LWRS_BREAK
LWRS_ERR
LWRS_RING
LWRS_RECEIVE
OpenCom
int result = OpenCom (int COMPort, char deviceName[]);
Purpose
Opens a com port.
Parameter
Input
COMPort
integer
deviceName
string
5-25
RS-232 Library
Chapter 5
Return Value
integer
result
Parameter Discussion
deviceName is the name of the com port in the ASCII string. For example, COM1 for com port 1
on Microsoft Windows using COMM.DRV, and /dev/ttya for com port 1 on UNIX using the
Zilog 8530 SCC serial comm driver.
If you pass a NULL pointer or an empty string for deviceName, the library uses the following
device names depending on the COM port number you have specified.
Port Number
deviceName on Windows
deviceName on UNIX
COM1
/dev/ttya
COM2
/dev/ttyb
COM3
/dev/ttys1
COM4
/dev/ttys2
and so on
Using This Function
OpenCom uses 512 bytes of the buffer for the input queue, 512 bytes for the output. The
function assumes the default baud rate, parity, stop bits, data bits, port address, and handshake
mode established through the com port configuration of the operating system. The time-out for
I/O operations is 5 seconds. Refer to the functions SetXMode, SetCTSMode, and
SetComTime if you want to change these defaults.
OpenComConfig
int result = OpenComConfig (int COMPort, char deviceName[], long baudRate,
int parity, int dataBits, int stopBits,
int inputQueueSize, int outputQueueSize);
Purpose
Opens a com port, and sets port parameters as specified. If inputQueueSize or
outputQueueSize is between 1 and 29, it is forced to 30.
5-26
Chapter 5
RS-232 Library
Parameters
Input
COMPort
integer
deviceName
string
baudRate
long
parity
integer
dataBits
integer
stopBits
integer
Either 1 or 2.
inputQueueSize
integer
outputQueueSize
integer
Return Value
integer
result
Parameter Discussion
deviceName is the name of the com port in the ASCII string. For example, COM1 for com port 1
on Microsoft Windows using COMM.DRV, and /dev/ttya for com port 1 on UNIX using the
Zilog 8530 SCC serial comm driver.
If you pass a NULL pointer or an empty string for deviceName, the library uses the following
device names depending on the COM port number you have specified.
Port Number
deviceName on Windows
deviceName on UNIX
COM1
/dev/ttya
COM2
/dev/ttyb
COM3
/dev/ttys1
COM4
/dev/ttys2
and so on
5-27
RS-232 Library
Chapter 5
Under UNIX, the inputQueueSize and outputQueueSize parameters are ignored. The serial
driver determines the queue size.
Under Windows, if you specify 0 for inputQueueSize or outputQueueSize, 512 is used. If you
specify a value between 0 and 30, 30 is used. On Windows 95 and NT, there is no maximum
limitation on the queue size. On Windows 3.1, the maximum queue size is 65535. However,
some serial drivers have a maximum of 32767 and give undefined behavior when you use a
larger queue size. It is recommended that you use a queue size no greater than 32767.
Under Windows 3.1, the baudRate value may be from 0 to 0xffff. Values below 0xff00 are
interpreted by the comm driver literally. Values from 0xff00 to 0xffff are codes defined by
the particular comm driver to represent rates higher than 0xfeff.
Under Windows 95 and NT, all baudRate values are interpreted literally by the comm driver.
Using This Function
The function disables XON/XOFF mode, and CTS hardware handshaking. The default time-out
for I/O operations is 5 seconds. Refer to the functions SetXMode, SetCTSMode, and
SetComTime if you want to change these defaults.
If the specified port is already open, OpenComConfig closes the port (see CloseCom) then
opens it again.
ReturnRS232Err
int status = ReturnRS232Err (void);
Purpose
Returns the value of rs232err.
Parameters
None
Return Value
status
integer
5-28
Chapter 5
RS-232 Library
SetComTime
int result = SetComTime (int COMPort, double timeoutSeconds);
Purpose
Sets time-out limit for input/output operations.
Parameters
Input
COMPort
integer
timeoutSeconds
double-precision
integer
Return Value
result
5-29
RS-232 Library
Chapter 5
SetCTSMode
int result = SetCTSMode (int COMPort, int mode);
Purpose
Enables or disables hardware handshaking as described in the Hardware Handshaking section of
the RS-232 Library Function Overview.
Parameters
Input
COMPort
integer
mode
integer
0 to disable hardware
handshaking, non-zero to enable
hardware handshaking. See
discussion below.
integer
Return Value
result
Parameter Discussion
The following are the valid values for mode.
0LWRS_HWHANDSHAKE_OFFHardware handshaking is disabled. The CTS line is ignored.
The RTS and DTR lines are raised the entire time the port is open.
1LWRS_HWHANDSHAKE_CTS_RTS_DTRHardware handshaking is enabled. The CTS line
is monitored. Both the RTS and DTR lines are used for handshaking.
2LWRS_HWHANDSHAKE_CTS_RTSHardware handshaking is enabled. The CTS line is
monitored. The RTS is used for handshaking. The DTR line is raised the entire time the port is
open.
Using This Function
By default, hardware handshaking is not used.
The function returns an error if the port is not open or parameter values are invalid.
5-30
Chapter 5
RS-232 Library
SetXMode
int result = SetXMode (int COMPort, int mode);
Purpose
Enables or disables software handshaking by enabling or disabling XON/XOFF sensitivity on
transmission and reception of data.
Parameters
Input
COMPort
integer
mode
integer
integer
Return Value
result
XModemConfig
int result = XModemConfig (int COMPort, double startDelay,
int maximum#ofRetries, double waitPeriod,
int packetSize);
Purpose
Sets the XModem configuration parameters for the specified com port.
5-31
RS-232 Library
Chapter 5
Parameters
Input
COMPort
startDelay
integer
double-precision
maximum#ofRetries
waitPeriod
integer
double-precision
packetSize
integer
integer
Return Value
result
(Less than zero)
(Zero)
Success.
Parameter Discussion
XModemSend and XModemReceive use the baud rate, and the input/output queue sizes
specified by OpenComConfig. But they ignore the data bits, the parity and the stop bits
settings of OpenComConfig, and always use 8 bits, no parity, and one stop bit. Instead of using
the time-out value defined by the SetComTime function, XModem functions use a 1 second
time-out between data bytes.
A zero input for any parameter except COMPort sets that parameter to its default value.
startDelay sets the timing for the initial connection between the two communication parties.
When a LabWindows/CVI program assumes the role of receiver, startDelay specifies the
interval (in seconds) during which to send the initial negative acknowledgment character to the
transmitter. That character is sent every startDelay seconds, up to maximum#ofRetries times.
When a LabWindows/CVI program assumes the role of transmitter, startDelay specifies the
interval (in seconds) during which the transmitter waits for the initial negative acknowledgment.
The transmitter waits up to (startDelay*maximum#ofRetries) seconds. The default value of
startDelay is 10.0.
maximum#ofRetries sets the maximum number of times the transmitter retries sending a packet
to the receiver on the occurrence of an error condition. The default value of
maximum#ofRetries is 10.
waitPeriod sets the period of time between the transfers of two packets. When a
LabWindows/CVI program assumes the role of transmitter, it waits for up to waitPeriod seconds
5-32
Chapter 5
RS-232 Library
for an acknowledgment before it re-sends the current packet. When LabWindows/CVI plays the
role of receiver, it waits for up to waitPeriod seconds for the next packet after it sends out an
acknowledgment for the current packet. If it does not receive the next packet within delayPeriod
seconds, it re-sends the acknowledgment, and waits again, up to maximum#ofRetries times. The
default value of waitPeriod is 10.0.
packetSize sets the packet size in bytes. Its value must be less than or equal to the input and
queue sizes. The standard XModem protocol defines packet sizes to be 128 or 1024. If you are
using any other size, make sure the two communication parties understand each other. The
default value of packetSize is 128.
Using This Function
For transfers with a large packet size and a low baud rate, a large delay period is recommended.
XModemReceive
int result = XModemReceive (int COMPort, char fileName[]);
Purpose
Receives packets of information over the com port specified by COMPort and writes the packets
to the specified file.
Parameters
Input
COMPort
integer
fileName
string
integer
Return Value
result
<0
Failure.
Success.
5-33
RS-232 Library
Chapter 5
XModemSend
int result = XModemSend (int COMPort, char fileName[]);
Purpose
Reads data from fileName file and sends it in packets over the com port specified by COMPort.
Parameters
Input
COMPort
integer
fileName
string
5-34
Chapter 5
RS-232 Library
Return Value
result
integer
<0
Failure.
Success.
5-35
RS-232 Library
Chapter 5
Error Conditions
If an error condition occurs during a call to any of the functions in the LabWindows/CVI RS-232
Library, the function returns an error code and the global variable rs232err contains that error
code. This code is a non-zero value that specifies the type of error that occurred. The currently
defined error codes and their meanings are given in Table 5-6.
Table 5-6. RS-232 Library Error Codes
Code
Error Message
-1
-2
-3
-4
-5
-6
-7
-11
-13
Invalid parameter.
-14
-24
Invalid parity.
-34
-44
-90
-91
-94
-97
-99
-104
-114
-124
-151
-152
-257
5-36
Chapter 5
RS-232 Library
-259
-260
-261
-262
-263
-264
-265
-269
-300
-301
-302
-303
-304
-305
-402
-503
-504
-505
-506
-507
-508
CRC error.
The value of rs232err is zero if the most recently called RS-232 function completed
successfully. Errors above 200 occur only on XModem function calls. Errors 261 through 265
are recorded when the maximum number of retries has been exhausted in trying to receive an
XModem function packet.
5-37
Chapter 6
DDE Library
This chapter describes the functions in the LabWindows/CVI DDE (Dynamic Data Exchange)
Library. The DDE Library Function Overview section contains general information about the
DDE Library functions and panels. The DDE Library Function Reference section contains an
alphabetical list of function descriptions. This library is available for LabWindows/CVI for
Microsoft Windows only.
RegisterDDEServer
ServerDDEWrite
AdviseDDEDataReady
BroadcastDDEDataReady
UnregisterDDEServer
ClientDDEExecute
ClientDDERead
ClientDDEWrite
ConnectToDDEServer
SetUpDDEHotLink
SetUpDDEWarmLink
TerminateDDELink
DisconnectFromDDEServer
GetDDEErrorString
6-1
DDE Library
Chapter 6
6-2
Chapter 6
DDE Library
DDE callback functions used in a program that acts as a DDE server can be triggered in a
number of ways from client applications. Whenever a client application attempts to connect to
your server program or requests information from your program, the callback function in your
program is executed to process the request. The parameter prototypes for the DDE callback
functions in LabWindows/CVI are defined below:
int CallbackFunction (int handle, char *topicName,
char *itemName, int xType, int dataFmt,
int dataSize, void *dataPtr,
void *callbackData);
Parameters
Input
Note:
handle
topicName
itemName
The data item within the server application that triggers the
callback. Exception: When xType is DDE_EXECUTE,
itemName represents the command string from the client
program.
xtype
dataFmt
dataSize
dataPtr
callbackData
The value of the dataSize parameter is greater than or equal to the actual size of
the data. It is recommended that you encode size information in your data.
Return Value
The callback function should return 1 to indicate success or 0 to indicate failure or rejection of
the requested action.
Transaction Types
All of the DDE transaction types (xType) that can trigger a callback function are listed in
Table 6-2.
6-3
DDE Library
Chapter 6
Server
Client
When ?
DDE_DISCONNECT
DDE_DATAREADY
DDE_REQUESTDATA
DDE_ADVISELOOP
DDE_ADVISESTOP
DDE_EXECUTE
DDE Links
Whenever a client program needs to be informed of changes to the value of a particular data item
in the server application, a DDE data link is required. You can establish a DDE data link in
LabWindows/CVI by calling the SetUpDDEWarmLink or SetUpDDEHotLink functions.
Whenever the data value changes, the client callback function is triggered, and the data is
available in the dataPtr parameter.
Within one client-server connection, there can be multiple data links, each applying to a different
data item. For example, you can establish a link between your LabWindows/CVI program and a
particular cell in Excel. The data item to which the link applies is specified in the itemName
parameter in the call to SetUpDDEWarmLink or SetUpDDEHotLink functions.
As defined in Windows, warm and hot links differ in that under a warm link the client is merely
alerted when the data value changes, whereas under a hot link the data is actually sent.
LabWindows/CVI makes no distinction between warm links and hot links. In both cases, your
client application receives the data through the client callback function when the data value
changes. (If a warm link is in effect, LabWindows/CVI requests and receives the data from the
server before the callback function is called.) The SetUpDDEWarmLink and
SetUpDDEHotLink functions are provided because some DDE server applications offer only
one type of link.
6-4
Chapter 6
DDE Library
6-5
DDE Library
Chapter 6
conversationHandle
unsigned integer
itemName
string
dataFormat
unsigned integer
dataPointer
void pointer
dataSize
unsigned integer
timeout
unsigned integer
Timeout in ms.
integer
Return Value
status
6-6
Chapter 6
DDE Library
Parameter Discussion
dataFormat must be a valid data format recognized by Microsoft Windows. The following are
the valid data formats supported by Microsoft Windows:
CF_TEXT
CF_PALETTE
CF_BITMAP
CF_PENDATA
CF_METAFILEPICT
CF_RIFF
CF_SYLK
CF_WAVE
CF_DIF
CF_OWNERDISPLAY
CF_TIFF
CF_DSPTEXT
CF_OEMTEXT
CF_DSPBITMAP
CF_DIB
CF_DSPMETAFILEPICT
The Microsoft Windows 3.x Programmer's Reference contains an in-depth discussion of DDE
programming and meaning of each data format type.
Using This Function
This function allows your program, acting as a DDE server, to send data to a client that has set
up a hot or warm link.
When a hot or warm link is set up, your server callback function receives a DDE_ADVISELOOP
transaction type (xType) for a particular data object (identified by itemName). When the hot or
warm link is terminated, your server callback function receives a DDE_ADVISESTOP
transaction type for the data object.
During the period when the hot or warm link is in effect, your server program is responsible for
notifying the client whenever the value of the data object changes. When the data object's value
changes, you can call this function, AdviseDDEDataReady, or
BroadcastDDEDataReady.
AdviseDDEDataReady differs from BroadcastDDEDataReady in that you specify a
particular conversation with a client. AdviseDDEDataReady sends the data only to the
specified client, even if other clients have hot or warm links to the same item.
AdviseDDEDataReady sends the data without invoking your server callback function.
However, if there are other clients with warm links to the same item, they are all notified that
new data is available. If they request the new data, your server callback function is invoked with
the DDE_REQUESTDATA message. If you do not want to send the data to those other clients,
you must write your server callback function so that it does not call ServerDDEWrite in this
case.
If you pass NULL (0) as the dataPointer and 0 as the dataSize, no data is sent to the specified
client. Instead, all clients with warm links to the item are notified. If they request the new data,
your server callback function is invoked with the DDE_REQUESTDATA message, and you can
use the ServerDDEWrite function to send the data in response.
National Instruments Corporation
6-7
DDE Library
Chapter 6
If successful, this function returns the number of bytes sent. Otherwise, this function returns a
negative error code. See the help for the status control for the error code values.
Note: Your program should not call AdviseDDEDataReady in a tight loop because the
iterations will compete with user interface events for the CPU time. You should use
this function sparingly, and only when the value of the hot- or warm-linked data object
changes. In cases when large data objects are to be returned from the server, your
program should only call AdviseDDEDataReady when the user interface is not
busy.
See Also
RegisterDDEServer, SetUpDDEHotLink, SetUpDDEWarmLink,
BroadcastDDEDataReady
BroadcastDDEDataReady
int status = BroadcastDDEDataReady (char serverName[], char itemName[],
char topicName[], unsigned int dataFormat,
void *dataPointer, unsigned int dataSize)
Purpose
Called by a server to send, to send data to all clients that have set up hot or warm links on the
specified topic and item.
Parameters
Input
serverName
string
topicName
string
itemName
string
dataFormat
unsigned
integer
dataPointer
void pointer
dataSize
unsigned
integer
integer
Return Value
status
6-8
Chapter 6
DDE Library
Parameter Discussion
serverName, topicName, and itemName must be strings of length from 1 to 255. They are used
without regard to case.
Using this Function
This function allows your program, acting as a DDE server, to send data to all clients that have
set up hot or warm links on the specified topic and item.
When a hot or warm link is set up, your server callback function receives a DDE_ADVISELOOP
transaction type (xType) for a particular data object (identified by itemName). When the hot or
warm link is terminated, your server callback function receives a DDE_ADVISESTOP
transaction type for the data object.
During the period when the hot or warm link is in effect, your server program is responsible for
notifying the client whenever the value of the data object changes. When the data object's value
changes, your server program should call either of the following functions,
BroadcastDDEDataReady or AdviseDDEDataReady.
BroadcastDDEDataReady differs from AdviseDDEDataReady in that it is not restricted
to a particular client. BroadcastDDEDataReady sends the data automatically to all clients
with hot links to the item. BroadcastDDEDataReady notifies all clients with warm links to
the item. For each warm-linked client that requests the data, your server callback function is
invoked with the DDE_REQUESTDATA message. You must call ServerDDEWrite in the
callback to send the data.
When successful, this function returns the number of bytes sent. Otherwise, this function returns
a negative error code. Consult the table at the end of this chapter to see the error code values.
Note: Your program should not call this function within a tight loop, because it will compete
with user interface events for the CPU time. This function should be used sparingly,
and only when the value of the hot or warm linked data object changes. In cases when
large data objects are to be returned from the server, it should only be called when the
user interface is not busy.
See Also
RegisterDDEServer, SetUpDDEHotLink, SetUpDDEWarmLink,
AdviseDDEDataReady,
ClientDDEExecute
int status = ClientDDEExecute (unsigned int conversationHandle,
char commandString[], unsigned int timeout);
6-9
DDE Library
Chapter 6
Purpose
Called by client to send a command to be executed by a DDE server application.
Parameters
Input
commandString
string
Command to be executed by
the server application.
timeout
unsigned integer
Timeout in ms.
integer
Return Value
status
Parameter Discussion
The commandString represents a valid command sequence for the server application to execute.
Refer to the command function reference manual for the application to which you are connecting
for more information on the commands supported.
See Also
ConnectToDDEServer, ClientDDERead, ClientDDEWrite
ClientDDERead
int status = ClientDDERead (unsigned int conversationHandle, char itemName[],
unsigned int dataFormat, void *dataBuffer,
unsigned int dataSize, unsigned int timeout);
Purpose
Called by client to read data from a DDE server application.
Parameters
Input
conversationHandle
unsigned integer
itemName
string
6-10
Chapter 6
Output
DDE Library
dataFormat
unsigned integer
dataSize
unsigned integer
timeout
unsigned integer
Timeout in ms.
dataBuffer
void pointer
integer
Return Value
status
Parameter Discussion
dataFormat must be a valid data format recognized by Microsoft Windows. The following are
the valid data formats supported by Microsoft Windows:
CF_TEXT
CF_PALETTE
CF_BITMAP
CF_PENDATA
CF_METAFILEPICT
CF_RIFF
CF_SYLK
CF_WAVE
CF_DIF
CF_OWNERDISPLAY
CF_TIFF
CF_DSPTEXT
CF_OEMTEXT
CF_DSPBITMAP
CF_DIB
CF_DSPMETAFILEPICT
Refer to Microsoft programmers' documention for Windows 3.x for an in-depth discussion of
DDE programming and meaning of each data format type.
status returns a positive number representing the number of bytes that were successfully read. A
negative number corresponds to the error code.
See Also
ConnectToDDEServer, ClientDDEWrite
ClientDDEWrite
int status = ClientDDEWrite (unsigned int conversationHandle, char itemName[],
unsigned int dataFormat, void *dataPointer,
unsigned int dataSize, unsigned int timeout);
National Instruments Corporation
6-11
DDE Library
Chapter 6
Purpose
Called by client to write data to a DDE server application.
Parameters
Input
conversationHandle
unsigned integer
itemName
string
dataFormat
unsigned integer
dataPointer
void pointer
dataSize
unsigned integer
timeout
unsigned integer
Timeout in ms.
integer
Return Value
status
Parameter Discussion
dataFormat must be a valid data format recognized by Microsoft Windows. The following are
the valid data formats supported by Microsoft Windows:
CF_TEXT
CF_PALETTE
CF_BITMAP
CF_PENDATA
CF_METAFILEPICT
CF_RIFF
CF_SYLK
CF_WAVE
CF_DIF
CF_OWNERDISPLAY
CF_TIFF
CF_DSPTEXT
CF_OEMTEXT
CF_DSPBITMAP
CF_DIB
CF_DSPMETAFILEPICT
Refer to Microsoft programmers' documention for Windows 3.x for an in-depth discussion of
DDE programming and meaning of each data format type.
status returns a positive number representing the number of bytes that were successfully read. A
negative number corresponds to the error code.
6-12
Chapter 6
DDE Library
See Also
ConnectToDDEServer, ClientDDERead
ConnectToDDEServer
int status = ConnectToDDEServer (unsigned int *conversationHandle,
char serverName[], char topicName[],
ddeFuncPtr clientCallbackFunction,
void *callbackData);
Purpose
Establishes a connection (conversation) between your program and a named server on a given
topic name.
Parameters
Input
serverName
string
topicName
string
callbackData
void pointer
User-defined data.
conversationHandle
unsigned integer
integer
Return Value
status
Parameter Discussion
The conversationHandle returns an integer value that uniquely represents a conversation
between a server and a client.
serverName and topicName must be strings of length from 1 to 255. They are used without
regard to case.
Each server application defines its own set of valid topic names. Refer to the command function
reference manual for the server application. A client and a server can have multiple connections
as long as they are under different topic names.
6-13
DDE Library
Chapter 6
clientCallbackFunction defines a callback function through which all messages from the server
will be routed.
The callback function must be of the following form:
int (*ddeFuncPtr) (int handle, char *topicName, char *itemName,
int xType, int dataFmt, int dataSize,
void*dataPtr, void *callbackData);
The xType (transaction type) parameter specifies the type of message received from the server.
The clientCallbackFunction can receive only two transaction types: DDE_DISCONNECT and
DDE_DATAREADY.
DDE_DISCONNECTReceived when a server is requesting the termination of a connection, or
when Windows terminates the connection due to an internal error.
DDE_DATAREADYReceived when you have already set up a hot or warm link by calling
SetUpDDEHotLink or SetUpDDEWarmLink, and the server notifies you that new data is
available. (If the server program uses the LabWindows/CVI DDE Library, it notifies you by
calling AdviseDDEDataReady or BroadcastDDEDataReady.) The data is received in
the callback in the dataPtr parameter. The topicName, itemName, dataFmt, dataSize, and
dataPtr parameters contain significant data. The itemName can specify an object to which the
data refers. For example, in Excel, the item name specifies a cell. The dataFmt is one of the
Windows-defined data types, for example, CF_TEXT. The dataSize specifies the number of
bytes in the data pointed to by dataPtr.
Note: The dataSize value is the value LabWindows/CVI receives from Microsoft Windows.
This value can be larger than the actual number of bytes written by the client.
Note: The callback function should return TRUE if the message can be processed
successfully. Otherwise, it should return FALSE. The callback function should be
short and return as soon as possible.
callbackData is a four-byte value that will be passed to the callback function each time it is
called for this client.
You can define the meaning of the callback data. For example, you can use the callback data as a
pointer to a data object that you need to access in the callback function. In this way, you would
not need to declare the data object as a global variable.
If you do not want to use the callback data, you can pass zero.
Note: In the case of DDE_DISCONNECT, the value of callbackData is undefined.
See Also
DisconnectFromDDEServer, RegisterDDEServer
6-14
Chapter 6
DDE Library
DisconnectFromDDEServer
int status = DisconnectFromDDEServer (unsigned int conversationHandle);
Purpose
Disconnects your client program from a server application.
Parameters
Input
conversationHandle
unsigned integer
integer
Return Value
status
Note: This function ends a conversation between a client and server corresponding to the
conversationHandle that was passed. Remember that there can be more than one
conversation between a client and a server.
See Also
ConnectToDDEServer, RegisterDDEServer
GetDDEErrorString
char *message = GetDDEErrorString (int errorNum)
Purpose
Converts the error number returned by a DDE Library function into a meaningful error message.
Parameters
Input
errorNum
integer
6-15
Status returned by a
DDE function.
DDE Library
Chapter 6
Return Value
string
message
Explanation of error.
RegisterDDEServer
int status = RegisterDDEServer (char serverName[],
ddeFuncPtr serverCallbackFunction,
void *callbackData);
Purpose
Registers your program as a valid DDE server, allowing other Windows applications to connect
to it for interprocess communication.
Parameters
Input
serverName
string
void pointer
Return Value
status
integer
Parameter Discussion
serverName must be a string of length from 1 to 255. It is used without regard to case.
The serverCallbackFunction is the name of the callback function that will be invoked to
process client requests.
The callback function must be of the following form:
int (*ddeFuncPtr) (int handle, char *topicName, char *itemName,
int xType, int dataFmt, int dataSize,
void *dataPtr, void *callbackData);
The xType (transaction type) parameter specifies the type of request received from the client.
The following transaction types are supported:
DDE_CONNECT
6-16
Chapter 6
DDE Library
DDE_DISCONNECT
DDE_DATAREADY
DDE_REQUEST
DDE_ADVISELOOP
DDE_ADVISESTOP
DDE_EXECUTE
DDE_CONNECTThis transaction type is received when a client is requesting a connection.
The topicName parameter specifies the connection topic. The set of valid topic names is defined
by the server and can be used in different ways. For example, Excel uses the topic name to
specify the file on which the client requests to operate. A client can have multiple connections to
the same server as long as there is a different topic name for each connection.
DDE_DISCONNECTReceived when a client is requesting the termination of a connection, or
when Windows terminates the connection due to an internal error.
DDE_DATAREADYReceived when the client has sent data via DDE to the server. The
topicName, itemName, dataFmt, dataSize, and dataPtr parameters contain significant data.
The itemName can specify an object to which the data refers. For example, in Excel, the item
name specifies a cell. The dataFmt is one of the Windows-defined data types, for example,
CF_TEXT. The dataSize specifies the number of bytes in the data pointed to by dataPtr.
Note: The dataSize value is the value LabWindows/CVI receives from Microsoft Windows.
This value can be larger than the actual number of bytes written by the client.
DDE_REQUESTReceived when the client is requesting that data be sent to it via DDE. The
itemName can specify an object to which the data refers. For example, in Excel, the item name
specifies a cell. The dataFmt is one of the Windows-defined data types, for example,
CF_TEXT.
DDE_ADVISELOOPReceived when the client is requesting a hot or warm link (advisory loop)
on a specific item. When a hot or warm link is in effect, the server is supposed to notify the
client whenever the specified item changes value. The server notifies the client of the change in
value by calling the function AdviseDDEDataReady or BroadcastDDEDataReady. The
itemName and dataFmt parameters contain significant values. The itemName can specify an
object to which the data item refers. For example, in Excel, the item name specifies a cell. The
dataFmt is one of the Windows-defined data types, for example, CF_TEXT.
DDE_ADVISESTOPReceived when the client is requesting the termination of an advisory
loop. The itemName contains the same value that was used to set up the advisory loop.
DDE_EXECUTEReceived when the client requests the execution of a command. The
itemName parameter contains the command string. The set of valid command strings is defined
by the server. For example, Excel uses "[Save()]" to save a file.
Using This Function
6-17
DDE Library
Chapter 6
This function registers your program as a DDE server with the specified name. Clients
attempting to connect to your program must use the specified name. Thereafter, all requests by
the client will be routed through the specified serverCallbackFunction.
You can register your program as a DDE server multiple times as long as you specify different
server names.
Note: The callback function should return TRUE if the request is successful else return
FALSE. The callback function should be short and should return as soon as possible.
callbackData is a four-byte value that will be passed to the callback function each time it is
called for this server.
You can define the meaning of the callback data. The following are examples of how the
callback data can be used:
1. You can register your program as a DDE server multiple times under different names. For
instance, you can use the same callback function for all of the server instances by using the
callback data to differentiate between them.
2. You can use the callback data to point to a data object that you need to access in the callback
function. In this way, you would not need to declare the data object as a global variable.
If you do not want to use the callback data, you can pass zero.
Note: In the case of DDE_DISCONNECT, the value of callbackData is undefined.
See Also
ConnectToDDEServer, UnregisterDDEServer
6-18
Chapter 6
DDE Library
ServerDDEWrite
int status = ServerDDEWrite (unsigned int conversationHandle, char itemName[],
unsigned int dataFormat, void *dataPointer,
unsigned int dataSize, unsigned int timeout);
Purpose
Writes data to a DDE client application when it requests data.
Parameters
Input
conversationHandle
unsigned integer
itemName
string
dataFormat
unsigned integer
dataPointer
void pointer
dataSize
unsigned integer
timeout
unsigned integer
Timeout in ms.
integer
Return Value
status
Parameter Discussion
dataFormat must be a valid data format recognized by Microsoft Windows. The following are
the valid data formats supported by Microsoft Windows:
CF_TEXT
CF_PALETTE
CF_BITMAP
CF_PENDATA
CF_METAFILEPICT
CF_RIFF
CF_SYLK
CF_WAVE
CF_DIF
CF_OWNERDISPLAY
CF_TIFF
CF_DSPTEXT
CF_OEMTEXT
CF_DSPBITMAP
CF_DIB
CF_DSPMETAFILEPICT
6-19
DDE Library
Chapter 6
Refer to Microsoft programmers' documention for Windows 3.x for an in-depth discussion of
DDE programming and meaning of each data format type.
Using This Function
This function allows your program, acting as a DDE server, to send data to a client. You should
call this function only when your serverCallbackFunction receives transaction type (xType) of
DDE_REQUESTDATA.
If you call the function at any other time, the data is stored until the client requests data. If you
call the function multiple times on the same conversation before the client requests the data, each
new data set is appended to the buffer containing the stored data.
If the client has set up a hot or warm link and you need to send data other than in response to a
DDE_REQUESTDATA transaction, use the AdviseDDEDataReady or
BroadcastDDEDataReady function.
If successful, this function returns the number of bytes written. Otherwise, this function returns a
negative error code.
See Also
RegisterDDEServer, AdviseDDEDataReady
SetUpDDEHotLink
int status = SetUpDDEHotLink (unsigned int conversationHandle, itemName[],
unsigned int dataFormat,
unsigned int timeout);
Purpose
Sets up a hot link (advisory loop) between the client and the server. The function returns zero for
success and a negative error code for failure.
Parameters
Input conversationHandle
unsigned integer
itemName
string
dataFormat
unsigned integer
timeout
unsigned integer
Timeout in ms.
6-20
Chapter 6
DDE Library
Return Value
integer
status
Parameter Discussion
The itemName represents the information in the server application where the DDE link is
established. For example, the item name could represent an Excel range of cells by using the
range description R1C1:R10C10.
Note: To the client, LabWindows/CVI does not distinguish between a hot link and a warm
link. For both types of links, the clientCallbackFunction is called with a transaction
type of DDE_DATAREADY when the data item is changed at the server site, and the new
data is available in the dataPtr parameter of the callback function. LabWindows/CVI
has two different functions for setting up a warm link or hot link in case some
applications only accept one or the other kind of link.
See Also
RegisterDDEServer, SetUpDDEWarmLink
SetUpDDEWarmLink
int status = SetUpDDEWarmLink (unsigned int conversationHandle,
char itemName[], unsigned int dataFormat,
unsigned int timeout);
Purpose
Sets up a warm link (advisory loop) between the client and the server. The function returns zero
for success and a negative error code for failure.
Parameters
Input
timeout
Return Value
status
integer
6-21
DDE Library
Chapter 6
Parameter Discussion
The itemName represents the information in the server application where the DDE link is
established. For example, the item name could represent an Excel range of cells by using the
range description R1C1:R10C10.
Note: To the client, LabWindows/CVI does not distinguish between a hot link and a warm
link. For both types of links, the clientCallbackFunction is called with a transaction
type of DDE_DATAREADY when the data item is changed at the server site, and the new
data is available in the dataPtr parameter of the callback function. LabWindows/CVI
has two different functions for setting up a warm link or hot link in case some
applications only accept one or the other kind of link.
See Also
RegisterDDEServer, SetUpDDEHotLink
TerminateDDELink
int status = TerminateDDELink (unsigned int conversationHandle,
char itemName[], unsigned int dataFormat,
unsigned int timeout);
Purpose
Lets your program, acting as a DDE client, terminate an advisory link, previously set up with the
server either through SetUpDDEWarmLink or SetUpDDEHotLink.
This function returns zero for success or a negative error code for failure.
Parameters
Input conversationHandle unsigned integer Uniquely identifies the conversation.
string
Uniquely identifies the output item; for
itemName
example, system.
dataFormat
timeout
Return Value
status
integer
6-22
Chapter 6
DDE Library
UnregisterDDEServer
int status = UnregisterDDEServer (char serverName[]);
Purpose
Unregisters your application program as a DDE server.
Parameters
Input
serverName
string
integer
Return Value
status
See Also
RegisterDDEServer
Error Conditions
If an error condition occurs during a call to any of the functions in the LabWindows/CVI DDE
Library, the status return value contains the error code. This code is a non-zero value that
specifies the type of error that occurred. Error code return values are negative numbers. The
currently defined error codes and their associated meanings are shown in Table 6-3.
6-23
DDE Library
Chapter 6
Error Message
kDDE_NoError
-kDDE_UnableToRegisterService
-kDDE_ExistingServer
-kDDE_FailedToConnect
-kDDE_ServerNotRegistered
-kDDE_TooManyConversations
-kDDE_ReadFailed
-kDDE_WriteFailed
-kDDE_ExecutionFailed
-kDDE_InvalidParameter
-kDDE_OutOfMemory
-kDDE_TimeOutErr
-kDDE_NoConnectionEstablished
-kDDE_FailedToSetUpHotLink
-kDDE_FailedToSetUpWarmLink
-kDDE_GeneralIOErr
-kDDE_AdvAckTimeOut
-kDDE_Busy
-kDDE_DataAckTimeOut
-kDDE_DllNotInitialized
-kDDE_DllUsage
-kDDE_ExecAckTimeOut
-kDDE_DataMismatch
-kDDE_LowMemory
-kDDE_MemoryError
-kDDE_NotProcessed
-kDDE_NoConvEstablished
-kDDE_PokeAckTimeOut
-kDDE_PostMsgFailed
-kDDE_Reentrancy
-kDDE_ServerDied
-kDDE_SysError
-kDDE_UnadvAckTimeOut
-kDDE_UnfoundQueueId
Note: Error codes from -16 to -33 are native DDEML errors which correspond to Windows
DDE error codes starting from 0x4000.
6-24
Chapter 7
TCP Library
This chapter describes the functions in the LabWindows/CVI TCP (Transmission Control
Protocol) Library. The TCP Library Function Overview section contains general information
about the TCP Library functions and panels. The TCP Library Function Reference section
contains an alphabetical list of function descriptions.
In order to use this library in Microsoft Windows, a version of WINSOCK.DLL has to be present.
The DLL comes with the program that drives the network card.
RegisterTCPServer
ServerTCPRead
ServerTCPWrite
UnregisterTCPServer
DisconnectTCPClient
ConnectToTCPServer
ClientTCPRead
ClientTCPWrite
DisconnectFromTCPServer
GetTCPErrorString
7-1
TCP Library
Chapter 7
7-2
Chapter 7
TCP Library
program is invoked to process the request. The parameter prototypes for the TCP callback
functions in LabWindows/CVI are defined below:
int CallbackFunction (int handle, int xType, int errCode,
void *callbackData);
where
handle represents the conversation handle
xType represents the transaction type (see table below)
errCode for TCP_DISCONNECT, is negative if the connection is being terminated due to an
error
callbackData is a user-defined data value.
All of the TCP transaction types (xType) that can trigger a callback function are listed in
Table 7-2.
Table 7-2. TCP Transaction Types (xType)
xType
TCP_CONNECT
Server
Client
When ?
TCP_DISCONNECT
TCP_DATAREADY
7-3
TCP Library
Chapter 7
Parameters
Input
conversationHandle
unsigned integer
dataBuffer
void pointer
dataSize
unsigned integer
timeout
unsigned integer
Timeout in ms.
integer
Return Value
status
See Also
ConnectToTCPServer, ClientTCPWrite
ClientTCPWrite
int status = ClientTCPWrite (unsigned int conversationHandle, void *dataPointer,
int dataSize, unsigned int timeout);
Purpose
Writes data to a TCP server application.
Parameters
Input
conversationHandle
unsigned integer
dataPointer
void pointer
dataSize
unsigned integer
timeout
unsigned integer
Timeout in ms.
7-4
Chapter 7
TCP Library
Return Value
integer
status
See Also
ConnectToTCPServer, ClientTCPRead
ConnectToTCPServer
int status = ConnectToTCPServer (unsigned int *conversationHandle,
unsigned int portNumber,
char serverHostName[],
tcpFuncPtr clientCallbackFunction,
void *callbackData, unsigned int timeout);
Purpose
Establishes a conversation between your program and a pre-existing server. Your program
becomes a client.
Parameters
Input
portNumber
unsigned integer
serverHostName
character array
Output
clientCallbackFunction
TCP function
pointer
callbackData
void pointer
User-defined data.
timeout
unsigned integer
Timeout in ms.
conversationHandle
unsigned integer
7-5
TCP Library
Chapter 7
Return Value
status
integer
Parameter Discussion
clientCallbackFunction is the name of the function called to process messages to your program
as a TCP client.
The callback function must be of the following form:
int (*tcpFuncPtr) (int handle, int xType, int errCode, void *callbackData);
The xType (transaction type) parameter specifies the type of message received from the server.
The client callback function can receive the following transaction types.
TCP_DISCONNECT
TCP_DATAREADY
The errCode parameter is used only when the transaction type is TCP_DISCONNECT.
The following describes each transaction type.
TCP_DISCONNECTReceived when a server is requesting the termination of a connection, or
when a connection is being terminated due to an error. If the connection is terminated due to an
error, the errCode parameter contains a negative error code. Refer to Table 7-3 for the list of
error codes.
TCP_DATATREADYReceived when the server has sent data via TCP to the client. Your
program, acting as the client, should call ClientTCPRead to obtain the data.
The client callback function should return TRUE if the message can be processed successfully.
Otherwise, the function should return FALSE.
Note: The callback function should be short and should return as soon as possible.
callbackData is a four-byte value that will be passed to the callback function each time it is
called for this client.
You should define the meaning of the callback data. One way to use the callbackData is as a
pointer to a data object that you need to access in the callback function. In this way, you would
not need to declare the data object as a global variable.
If you do not want to use the callbackData, you can pass zero.
7-6
Chapter 7
TCP Library
See Also
RegisterTCPServer, DisconnectFromTCPServer
DisconnectFromTCPServer
int status = DisconnectFromTCPServer (unsigned int conversationHandle);
Purpose
Disconnects your client program from a server application.
Parameters
Input
Return Value
integer
status
Note: This function terminates a connection identified by the conversation handle passed.
There can be more than one conversation between a client and a server.
See Also
ConnectToTCPServer, RegisterTCPServer
DisconnectTCPClient
int status = DisconnectTCPClient (unsigned int conversationHandle);
Purpose
Called by a TCP server to terminate a connection with a client. (Be aware that there can be more
than one conversation between a server and a client.)
Parameters
Input
conversationHandle
unsigned integer
integer
Return Value
status
7-7
TCP Library
Chapter 7
See Also
RegisterTCPServer
GetTCPErrorString
char *message = GetTCPErrorString (int errorNum)
Purpose
Converts the error number returned by a TCP Library function into a meaningful error message.
Parameters
Input
errorNum
integer
string
Explanation of error.
Return Value
message
RegisterTCPServer
int status = RegisterTCPServer (unsigned int portNumber,
tcpFuncPtr serverCallbackFunction,
void *callbackData);
Purpose
Registers your program as a valid TCP server and allows other applications to connect to it for
network communication.
Parameters
Input
portNumber
unsigned integer
void pointer
7-8
Chapter 7
TCP Library
Return Value
status
integer
Parameter Discussion
serverCallbackFunction is the name of the function to be called to process client requests.
The callback function must be of the following form:
int (*tcpFuncPtr) (int handle, int xType, int errCode,
void *callbackData)
The xType parameter specifies the type of message received from the server. The server
callback function can receive the following transaction types.
TCP_CONNECT
TCP_DISCONNECT
TCP_DATAREADY
The errCode parameter is used only when the transaction type is TCP_DISCONNECT.
The following describes each transaction type.
TCP_CONNECTThe transaction type is received when a client is requesting a connection.
TCP_DISCONNECTReceived when a client is requesting the termination of a connection, or
when a connection is being terminated due to an error. If the connection is terminated due to an
error, the errCode parameter contains a negative error code. Refer to Table 7-3 for the list of
error codes.
TCP_DATATREADYReceived when the client has sent data via TCP to the server. Your
program, acting as the server, should call ServerTCPRead to obtain the data.
The server callback function should return TRUE if the request is successful. Otherwise, the
function should return FALSE.
Note: Server callback should be short and should return as soon as possible.
callbackData is a four-byte value that will be passed to the callback function each time it is
called for this server.
7-9
TCP Library
Chapter 7
It is up to you to define the meaning of the callback data. The following are examples of how the
callback data can be used:
You can register your program as a TCP server multiple times under different port numbers.
You could use the same callback function for all of the server instances by using the callback
data to differentiate between them.
You can use the callback data to point to a data object that you need to access in the callback
function. In this way, you would not need to declare the data object as a global variable.
If you do not want to use the callback data, you can pass zero.
See Also
ConnectToTCPServer, UnregisterTCPServer
ServerTCPRead
int status = ServerTCPRead (unsigned int conversationHandle, void *dataBuffer,
unsigned int dataSize, unsigned int timeout);
Purpose
Reads data from a TCP client application.
Parameters
Input
conversationHandle
unsigned integer
dataBuffer
void pointer
dataSize
unsigned integer
timeout
unsigned integer
Timeout in ms.
integer
Return Value
status
See Also
RegisterTCPServer, ServerTCPWrite
7-10
Chapter 7
TCP Library
ServerTCPWrite
int status = ServerTCPWrite (unsigned int conversationHandle, void *dataPointer,
unsigned int dataSize, unsigned int timeout);
Purpose
Writes data to a TCP client application.
Parameters
Input
dataPointer
void pointer
dataSize
unsigned integer
timeout
unsigned integer
Timeout in ms.
integer
Return Value
status
See Also
RegisterTCPServer, ServerTCPRead
UnregisterTCPServer
int status = UnregisterTCPServer (unsigned int portNumber);
Purpose
Unregisters your server application program as a TCP server.
Parameters
Input
portNumber
7-11
TCP Library
Chapter 7
Return Value
integer
status
See Also
RegisterTCPServer
Error Conditions
If an error condition occurs during a call to any of the functions in the LabWindows/CVI TCP
Library, the status return value contains the error code. This code is a non-zero value that
specifies the type of error that occurred. Error code return values are negative numbers. The
currently defined error codes and their associated meanings are shown in Table 7-3.
Table 7-3. TCP Library Error Codes
Code
0
Error Message
kTCP_NoError
-1
-kTCP_UnableToRegisterService
-2
-kTCP_UnableToEstablishConnection
-3
-kTCP_ExistingServer
-4
-kTCP_FailedToConnect
-5
-kTCP_ServerNotRegistered
-6
-kTCP_TooManyConnections
-7
-kTCP_ReadFailed
-8
-kTCP_WriteFailed
-9
-kTCP_InvalidParameter
-10
-kTCP_OutOfMemory
-11
-kTCP_TimeOutErr
-12
-kTCP_NoConnectionEstablished
-13
-kTCP_GeneralIOErr
-14
-kTCP_ConnectionClosed
-15
-kTCP_UnableToLoadWinsockDLL
-16
-kTCP_IncorrectWinsockDLLVersion
-17
-kTCP_NetworkSubsystemNotReady
-18
-kTCP_ConnectionsStillOpen
7-12
Chapter 8
Utility Library
This chapter describes the functions in the LabWindows/CVI Utility Library. The Utility
Library contains functions that do not fit into any of the other LabWindows/CVI libraries. The
Utility Library Function Panels section contains general information about the Utility Library
functions and panels. The Utility Library Function Reference section contains an alphabetical
list of function descriptions.
Timer
Delay
SyncWait
DateStr
TimeStr
GetSystemDate
SetSystemDate
GetSystemTime
SetSystemTime
KeyHit
GetKey
(continues)
8-1
Utility Library
Chapter 8
DeleteFile
RenameFile
CopyFile
GetFileSize
GetFileDate
SetFileDate
GetFileTime
SetFileTime
GetFileAttrs
SetFileAttrs
GetFirstFile
GetNextFile
MakePathname
SplitPath
GetDir
GetProjectDir
GetModuleDir
GetFullPathFromProject
SetDir
MakeDir
DeleteDir
GetDrive
SetDrive
LoadExternalModule
LoadExternalModuleEx
RunExternalModule
GetExternalModuleAddr
UnloadExternalModule
ReleaseExternalModule
inp
inpw
outp
outpw
(continues)
8-2
Chapter 8
Utility Library
Cls
GetStdioWindowOptions
SetStdioWindowOptions
GetStdioWindowPosition
SetStdioWindowPosition
GetStdioWindowSize
SetStdioWindowSize
GetStdioWindowVisibility
SetStdioWindowVisibility
GetStdioPort
SetStdioPort
SetBreakOnLibraryErrors
GetBreakOnLibraryErrors
SetBreakOnProtectionErrors
GetBreakOnProtectionErrors
DisableBreakOnLibraryErrors
EnableBreakOnLibraryErrors
DisableInterrupts
EnableInterrupts
GetInterruptState
ReadFromPhysicalMemory
ReadFromPhysicalMemoryEx
WriteToPhysicalMemory
WriteToPhysicalMemoryEx
SetPersistentVariable
GetPersistentVariable
DisableTaskSwitching
EnableTaskSwitching
(continues)
8-3
Utility Library
Chapter 8
LaunchExecutable
LaunchExecutableEx
ExecutableHasTerminated
TerminateExecutable
RetireExecutableHandle
SystemHelp
GetCVIVersion
GetCurrentPlatform
InStandaloneExecutable
InitCVIRTE
CloseCVIRTE
CVILowLevelSupportDriverLoaded
Beep
Breakpoint
RoundRealToNearestInteger
TruncateRealNumber
GetWindowDisplaySetting
Timer/Wait functions use the system timer, including functions that wait on a timed basis.
Date/Time functions return the date or time in ASCII or integer formats, and set the date or
time.
External Modules functions load, execute, and unload files that contain compiled C object
modules.
Port I/O functions read and write data from I/O ports (Supported only under Microsoft
Windows).
8-4
Chapter 8
Utility Library
Run-Time Error Reporting functions enable and disable the feature which breaks execution
when a LabWindows/CVI library function returns an error code.
Physical Memory Access functions read and write data from and to physical memory
addresses. (Supported only under Microsoft Windows).
Persistent Variable functions store and retrieve an integer value across multiple builds and
executions of a project in the LabWindows/CVI development environment.
Task Switching functions control whether a user can switch to another task under Microsoft
Windows.
Launching Executables functions start another executable, check whether it is still running,
and terminate it.
Miscellaneous functions perform a variety of operations that do not fit into any of the other
function classes.
The online help with each panel contains specific information about operating each function
panel.
Beep
void Beep (void);
Purpose
Sounds the speaker.
Parameters
None
Return Value
None
8-5
Utility Library
Chapter 8
Breakpoint
void Breakpoint (void);
Purpose
During execution of a program, a call to Breakpoint suspends program operation. While the
program is suspended, you can inspect or modify variables, and use many other features of the
LabWindows/CVI interactive program.
Calling Breakpoint with the debugging level set to None, or from a compiled module, has no
effect.
Parameters
None
Return Value
None
CloseCVIRTE
void CloseCVIRTE (void)
Purpose
This function releases memory in the LabWindows/CVI Run-Time Engine that was allocated by
InitCVIRTE for a particular DLL.
If you call InitCVIRTE from DllMain, you also should call CloseCVIRTE from
DllMain. You should call it in response to the DLL_PROCESS_DETACH message after your
other detach code.
Parameters
None
Return Value
None
8-6
Chapter 8
Utility Library
Cls
void Cls (void);
Purpose
In the LabWindows/CVI environment, this function clears the Standard I/O window.
Parameters
None
Return Value
None
CopyFile
int result = CopyFile (char sourceFileName[], char targetFileName[]);
Purpose
Copies the contents of an existing file to another file.
Parameters
Input
sourceFileName
string
File to copy.
targetFileName
string
integer
Return Value
result
Return Codes
0
Success.
-1
-3
-4
-5
-6
Access denied.
-7
-8
Disk is full.
8-7
Utility Library
Chapter 8
Parameter Discussion
sourceFileName and targetFileName may contain wildcard characters ? and *. If
sourceFileName has wildcards, all matching files are copied. If targetFileName has wildcards,
it will be matched to sourceFileName. If the target file is a directory, the existing file (or group
of files) will be copied into the directory.
sourceFileName may also be the empty string (""), in which case the file found by the most
recent call to GetFirstFile or GetNextFile is copied.
CVILowLevelSupportDriverLoaded
int loaded = CVILowLevelSupportDriverLoaded (void);
Note: This function is available only in the Windows 95 and NT version of
LabWindows/CVI.
Purpose
This function returns an indication of whether the LabWindows/CVI low-level support driver
was loaded at startup. The following Utility Library functions require the LabWindows/CVI lowlevel driver to be loaded at startup.
Function
inp
inpw
Windows NT
outp
Windows NT
outpw
Windows NT
ReadFromPhysicalMemory
Windows 95 and NT
Windows 95 and NT
DisableInterrupts
Windows 95
EnableInterrupts
Windows 95
DisableTaskSwitching
Windows 95
Most of these functions do not return an error if the low-level support driver is not loaded. To
make sure your calls to these functions can execute correctly, call
CVILowLevelSupportDriverLoaded at the beginning of your program.
8-8
Chapter 8
Utility Library
Return Value
loaded
integer
Return Codes
1
DateStr
char *s = DateStr (void);
Purpose
Returns a 10-character string in the form MM-DD-YYYY, where MM is the month, DD is the day,
and YYYY is the year.
Parameters
None
Return Value
10-character string
Delay
void Delay (double numberofSeconds);
Purpose
Waits the number of seconds indicated by numberofSeconds. The resolution on Windows is
normally 1 millisecond. However, if the following line appears in the CVI section of your
WIN.INI file, the resolution is 55 milliseconds.
useDefaultTimer = True
The resolution on Sun Solaris is 1 millisecond.
8-9
Utility Library
Chapter 8
Parameter
Input
numberofSeconds
double-precision
Return Value
None
DeleteDir
int result = DeleteDir (char directoryName[]);
Purpose
Deletes an existing directory.
Parameters
Input
directoryName
String.
Return Value
integer
result
Result of operation.
Return Codes
0
Success.
-1
-3
-4
-6
-7
DeleteFile
int result = DeleteFile (char fileName[]);
Purpose
Deletes an existing file from disk.
8-10
Chapter 8
Utility Library
Parameter
Input
fileName
string
File to delete.
integer
Return Value
result
Return Codes
0
Success.
-1
-3
-4
-5
-6
Access denied.
-7
Parameter Discussion
fileName may contain wildcard characters ? and * in which case all matching files are
deleted.
fileName may also be the empty string ("") in which case the file found by the most recent call
to GetFirstFile or GetNextFile is deleted.
DisableBreakOnLibraryErrors
void DisableBreakOnLibraryErrors (void);
Purpose
If debugging is enabled (if the debugging level in the Run Options dialog box of the Options
menu in the Project window is set to Standard or Extended), this function directs
LabWindows/CVI not to display a run-time error dialog box when a National Instruments library
function reports an error. If debugging is disabled, this function has no effect.
8-11
Utility Library
Chapter 8
DisableInterrupts
void DisableInterrupts (void);
Purpose
Under Windows 3.1 and Windows 95, this function uses the CLI instruction to turn off all
maskable 80x86 interrupts. On UNIX, this function uses sigblock to block all blockable
signals.
Note: For you to be able to use this function under Windows 95, the LabWindows/CVI lowlevel support driver must be loaded.
Note: Under Windows NT, the EnableInterrupts and DisableInterrupts
functions have no effect. Interrupts are always enabled while your program is running
at the user (as opposed to the kernel) level.
Parameter
None
Return Value
None
DisableTaskSwitching
void DisableTaskSwitching (void);
Note: This function is available only on the Windows versions of LabWindows/CVI.
Purpose
This function prevents the end-user from using one of the following Windows features to switch
another task.
8-12
Chapter 8
Utility Library
The <Alt-Tab>, <Alt-Esc>, or <Ctrl-Esc> key combination under Windows 3.1 or Windows 95.
This function affects the behavior of these keys only while LabWindows/CVI or a
LabWindows/CVI Standalone Executable is the active application under Microsoft Windows.
This function has no effect in Windows NT. See the Alternatives in Windows NT section for
instructions on how to achieve the desired effect.
Note: To use this function on Windows 95, the LabWindows/CVI low-level support driver
must be loaded.
Disabling the Task List
DisableTaskSwitching does not prevent the user from clicking on the desktop to get the
task list in Windows 3.1, or clicking on the task bar in Windows 95. You can prevent the user
from clicking on the desktop by forcing your window to cover the entire screen.
Forcing Window to Cover Entire Screen
You can force your window to cover the entire screen by making the following calls to functions
in the User Interface Library.
SetPanelAttribute
SetPanelAttribute
SetPanelAttribute
SetPanelAttribute
SetPanelAttribute
SetPanelAttribute
(panel,
(panel,
(panel,
(panel,
(panel,
(panel,
ATTR_SIZABLE, FALSE);
ATTR_CAN_MINIMIZE, FALSE);
ATTR_CAN_MAXIMIZE, FALSE);
ATTR_SYSTEM_MENU_VISIBLE, FALSE);
ATTR_MOVABLE, FALSE);
ATTR_WINDOW_ZOOM, VAL_MAXIMIZE);
In these calls, panel is the panel handle for your top-level window. These calls will work in
Windows 3.1, Windows 95, and Windows NT.
Alternatives in Windows 3.1
Under Windows 3.1, you can prevent the end-user accessing the task list by disabling the Task
Manager. Change a line in your system.ini [boot] section from
taskman.exe = taskman.exe
to
taskman.exe =
Forcing your window to cover the entire screen or disabling the Task Manager does not prevent
the user from task switching using the <Alt-Tab> and <Alt-Esc> key combinations. You must
also call DisableTaskSwitching to disable the <Alt-Tab> and <Alt-Esc> key
combinations. As an alternative to calling DisableTaskSwitching, you can arrange for
8-13
Utility Library
Chapter 8
your standalone application to be brought up in place of the Program Manager when Windows
boots. You can do this by changing the following line in your system.ini [boot] section.
shell = progman.exe
to
shell = <full-path-of-your-executable>
Alternatives in Windows 95
Under Windows 95, you can arrange for your standalone application to appear in place of the
desktop when Windows boots.
You can do this by changing the following line in your system.ini [boot] section.
shell = Explorer.exe
to
shell = <full-path-of-your-executable>
Alternatives in Windows NT
Under Windows NT, you can achieve the same results as DisableTaskSwitching by
arranging for your LabWindows/CVI application to be brought up in place of the Program
Manager and by disabling the Task Manager. You can do this by making following changes to
the registry entry for the key name,
KEY_LOCAL_MACHINE\Software\Microsoft\CurrentVersion\Winlogon
Change the value for SHELL to the pathname of your application executable.
Add a value with the name TASKMAN. Set the data to an empty string.
You can prevent these user actions from interfering with event processing by doing all of the
following.
Call DisableTaskSwitching (or use the alternative for Windows NT mentioned in this
section).
8-14
Chapter 8
Utility Library
If you use any of the built-in pop-ups in the User Interface Library, make the following calls.
SetSystemPopupsAttribute (ATTR_MOVABLE, 0);
SetSystemPopupsAttribute (ATTR_SYSTEM_MENU_VISIBLE, 0);
An alternative approach is available on Windows 95 and NT. You can enable timer control
callbacks while <Alt-Tab> is pressed, while the system menu is pulled down, or (in some cases)
while a window is being moved or sized. You can do this by using the following function call.
SetSystemAttribute (ATTR_ALLOW_UNSAFE_TIMER_EVENTS, 1);
This alternative is incomplete and can be unsafe. See the discussion on Unsafe Timer Events in
the Using the System Attributes section of Chapter 3, Programming with the User Interface
Library, of the LabWindows/CVI User Interface Reference Manual.
EnableBreakOnLibraryErrors
void EnableBreakOnLibraryErrors (void);
Purpose
If debugging is enabled (if the debugging level in the Run Options dialog box of the Options
menu in the Project window is set to Standard or Extended), this function directs
LabWindows/CVI to display a run-time error dialog box when a National Instruments library
function reports an error. If debugging is disabled, this function has no effect.
In general, you should check the Break on Library Errors check box in the Run Options dialog
box of the Options menu in the Project window to enable this feature. However, you can use this
function in conjunction with DisableBreakOnLibraryErrors to temporarily suppress the
Break on Library Errors feature around a segment of code. It does not affect the state of the
Break on Library Errors check box.
Note: This function has been superseded by SetBreakOnLibraryErrors.
EnableInterrupts
void EnableInterrupts (void);
Under Windows 3.1 and Windows 95, this function uses the STI instruction to turn on all
maskable 80x86 interrupts. On UNIX, this function reverses the effect of the last call to
DisableInterrupts. It restores the signal processing state to the condition prior to the
DisableInterrupts call.
8-15
Utility Library
Chapter 8
Note: For you to be able to use this function under Windows 95, the LabWindows/CVI lowlevel support driver must be loaded.
Note: Under Windows NT, the EnableInterrupts and DisableInterrupts
functions have no effect. Interrupts are always enabled while your program is running
at the user (as opposed to the kernel) level.
Parameter
None
Return Value
None
EnableTaskSwitching
void EnableTaskSwitching (void);
Note: This function is available only on the Windows versions of LabWindows/CVI.
Purpose
This function lets the user switch to another task by using the <Alt-Tab>, <Alt-Esc>, and
<Ctrl-Esc> key combinations, as well as the Switch-To item in the Control/System menu. This
function only affects the behavior of these keys while LabWindows/CVI or a LabWindows/CVI
standalone executable is the active application.
ExecutableHasTerminated
int status = ExecutableHasTerminated (int executableHandle);
Purpose
Determines whether an application started with LaunchExecutableEx has terminated.
Parameters
Input executableHandle
8-16
Chapter 8
Utility Library
Return Value
integer Result of operation.
status
Return Codes
-1
Handle is invalid.
Note: If you launch another LabWindows/CVI executable under Windows 3.x, the launched
executable process will terminate itself after launching the new copy of the
CVI Run-time Engine. If you use ExecutableHasTerminated, the return value
will always be 1 because the process identification for the second Run-time Engine
cannot be tracked. See LaunchExecutableEx for more information.
GetBreakOnLibraryErrors
int state = GetBreakOnLibraryErrors (void);
Purpose
This function returns the state of the Break on library errors option. It returns a 1 if the Break
on library errors option is enabled, or a 0 if it is disabled.
The state of the Break on Library errors option can be changed interactively using the Run
Options command in the Options menu of the Project window. The state of the Break on
Library errors option can also be changed programmatically using
SetBreakOnLibraryErrors, or the EnableBreakOnLibraryErrors and
DisableBreakOnLibraryErrors functions.
If debugging is disabled, this function always returns 0.
Return Value
state
integer
Return Codes
1
8-17
Utility Library
Chapter 8
GetBreakOnProtectionErrors
int state = GetBreakOnProtectionErrors (void);
Purpose
This function returns the state of the break on protection errors feature. It returns a 1 if the
option is enabled, or a 0 if it is disabled. If debugging is disabled, this function always returns 0.
For more information on the feature, see the documentation for
SetBreakOnProtectionErrors.
Return Value
state
integer
Return Codes
1
GetCVIVersion
int versionNum = GetCVIVersion (void);
Purpose
This function returns the version of LabWindows/CVI you are running. In a standalone
executable, this tells you which version of the LabWindows/CVI run-time libraries you are
using.
The value is in the form Nnn, where the N.nn is the version number that shows in the About
LabWindows/CVI dialog box.
For example, for LabWindows/CVI version 4.0, GetCVIVersion returns 400. For version 4.1,
it would return 410. The values will always increase with each new version of
LabWindows/CVI.
The return value of GetCVIVersion should not be confused with the predefined macro
_CVI_, which specifies the version of LabWindows/CVI in which the source file is compiled.
Return Value
versionNum
integer
8-18
Chapter 8
Utility Library
Return Codes
Nnn
GetCurrentPlatform
int platformCode = GetCurrentPlatform (void);
Purpose
This function returns a code representing the operating system under which a project or
standalone executable is running.
The return value of GetCurrentPlatform should not be confused with the predefined
macros such as _NI_mswin_, _NI_unix_, and others, which specify the platform on which
the project is compiled.
This function is useful when you have a program that can run on multiple operating systems but
must take different actions on the different systems. For example, the same standalone
executable can run on both Windows 95 and Windows NT. If the program needs to behave
differently on the two platforms, you can use GetCurrentPlatform to determine the
platform at run-time.
Return Value
platformCode
integer
Return Codes
kPlatformWin16
Windows 3.1
kPlatformWin95
Windows 95
kPlatformWinnt
Windows NT
kPlatformSunos4
Sun Solaris 1
kPlatformSunos5
Sun Solaris 2
kPlatformHPUX9
HP-UX 9.x
kPlatformHPUX10
HP-UX 10.x
8-19
Utility Library
Chapter 8
GetDir
int result = GetDir (char currentDirectory[]);
Purpose
Gets the current working directory on the default drive.
Parameter
Output
currentDirectory
string
Current directory.
integer
Result of operation.
Return Value
result
Return Codes
0
Success.
-3
-4
Parameter Discussion
currentDirectory must be at least MAX_PATHNAME_LEN bytes long.
GetDrive
int result = GetDrive (int *currentDriveNumber, int *numberofDrives);
Note: This function is available only on the Windows versions of LabWindows/CVI.
Purpose
Gets the current default drive number and the total number of logical drives in the system.
Parameters
Output
currentDriveNumber
integer
numberofDrives
integer
8-20
Chapter 8
Utility Library
Return Value
integer
result
Result of operation.
Return Codes
0
Success.
-1
-3
-4
-6
Access denied.
Parameter Discussion
The mapping between the drive number and the logical drive letter is 0 = A, 1 = B, and so on.
The total number of logical drives includes floppy-disk drives, hard-disk drives, RAM disks, and
networked drives.
GetExternalModuleAddr
void *address = GetExternalModuleAddr (char name[], int moduleID, int *status);
Purpose
Obtains the address of an identifier in a module that was loaded using
LoadExternalModule.
Parameters
Input
name
moduleID
string
integer
Name of identifier.
ID of loaded module.
Output
status
integer
void pointer
Return Value
address
8-21
Utility Library
Chapter 8
Return Codes
0
Success.
-1
Out of memory.
-4
-5
Undefined references.
-8
-9
-10
-25
Parameter Discussion
moduleID is the value LoadExternalModule returns.
name is the name of the identifier whose address is obtained from the external module. The
identifier must be a variable or function name defined globally in the external module.
status is zero if the function is a success, or a negative error code if it fails.
If GetExternalModuleAddr succeeds, it returns the address of the variable or function in
the module. If the function fails, it returns NULL.
Example
void (*funcPtr) (char buf[], double dval, int *ival);
int module_id;
int status;
char buf[100];
double dval;
int ival;
char *pathname;
char *funcname;
pathname = "EXTMOD.OBJ";
funcname = "my_function";
module_id = LoadExternalModule (pathname);
if (module_id < 0)
FmtOut ("Unable to load %s\n", pathname);
else
{
funcPtr = GetExternalModuleAddr (module_id, funcname, &status);
if (funcPtr == NULL)
FmtOut ("Could not get address of %s\n", funcname);
else
(*funcPtr) (buf, dval, &ival);
}
8-22
Chapter 8
Utility Library
GetFileAttrs
int result = GetFileAttrs (char fileName[], int *read-only, int *system, int *hidden,
int *archive);
Note: Only available on the Windows version of LabWindows/CVI.
Purpose
Gets the following attributes of a file:
Read-Only
System
Hidden
Archive
The read-only attribute makes it impossible to write to the file or create a file with the same
name.
The system attribute and hidden attribute both prevent the file from appearing in a directory list
and exclude it from normal searches.
The archive attribute is set whenever you modify the file, and cleared by the DOS BACKUP
command.
Parameters
Input
fileName
string
Output
read-only
integer
system
integer
System attribute.
hidden
integer
Hidden attribute.
archive
integer
Archive attribute.
integer
Result of operation.
Return Value
result
Return Codes
0
Success.
-1
8-23
Utility Library
Chapter 8
Parameter Discussion
Each attribute parameter will contain one of the following values:
0attribute is not set
1attribute is set
fileName may be the empty string (""), in which case the attributes of the file found by the most
recent call to GetFirstFile or GetNextFile are returned.
Example
/* get the attributes of WAVEFORM.DAT */
int read_only,system,hidden,archive;
GetFileAttrs ("waveform.dat",&read_only,&system,&hidden,&archive);
if (read_only)
FmtOut("WAVEFORM.DAT is a read-only file!");
GetFileDate
int result = GetFileDate (char fileName[], int *month, int *day, int *year);
Purpose
Gets the date of a file.
Parameters
Input
fileName
string
Output
month
integer
Month (1 to 12).
day
integer
year
integer
Year (19802099).
integer
Result of operation.
Return Value
result
8-24
Chapter 8
Utility Library
Return Codes
0
Success.
-1
-3
-4
-5
-6
Access denied.
Parameter Discussion
fileName may be the empty string (""), in which case the date of the file found by the most
recent call to GetFirstFile or GetNextFile is returned (Windows only).
Example
/* get the date of WAVEFORM.DAT */
int month, day, year;
GetFileDate ("waveform.dat",&month,&day,&year);
GetFileSize
int result = GetFileSize (char fileName[], long *fileSize);
Purpose
Returns the size of a file.
Parameters
Input
fileName
string
Name of file.
Output
fileSize
long
integer
Result of operation.
Return Value
result
8-25
Utility Library
Chapter 8
Return Codes
0
Success.
-1
-3
-4
-5
-6
Access denied.
Parameter Discussion
fileName may be the empty string (""), in which case the size of the file found by the most
recent call to GetFirstFile or GetNextFile is returned (Windows only).
Example
long size;
if (GetFileSize ("waveform.dat",&size) == 0)
FmtOut("The size of WAVEFORM.DAT is %i[b4]",size);
GetFileTime
int result = GetFileTime (char fileName[], int *hours, int *minutes, int *seconds);
Purpose
Gets the time of a file.
Parameters
Input
fileName
string
Output
hours
integer
Hours (0 to 23).
minutes
integer
Minutes (0 to 59).
seconds
integer
integer
Result of operation.
Return Value
result
8-26
Chapter 8
Utility Library
Return Codes
0
Success.
-1
-3
-4
-5
-6
Access denied.
Parameter Discussion
fileName may be the empty string (""), in which case the time of the file found by the most
recent call to GetFirstFile or GetNextFile is returned (Windows only).
Example
/* get the time of WAVEFORM.DAT */
int hours,minutes,seconds;
GetFileTime ("waveform.dat",&hours,&minutes,&seconds);
GetFirstFile
int result = GetFirstFile (char searchPath[], int normal, int read-only, int system,
int hidden, int archive, int directory, char fileName[]);
Purpose
Starts a search for files with specified attributes and returns the first matching file. If you select
multiple attributes, a match occurs on the first file for which one or more of the specified
attributes are set and which matches the pattern in the searchPath parameter. The search
attributes are:
Normal
Read-only
System
Hidden
Archive
Directory
Under UNIX, only the directory attribute is honored. If you pass 1 for the directory attribute,
only directories match. If you pass 0 for the directory attribute, only non-directories match.
8-27
Utility Library
Chapter 8
Under Windows, all of the attributes are honored. The normal attribute specifies files with no
other attributes set or with only the archive bit set. The archive attribute specifies files that have
been modified because they were last backed up using the DOS BACKUP command. The readonly attribute specifies files that are protected from being modified or overwritten. The system
and hidden attributes specify files which normally do not appear in a directory listing. The
directory attribute specifies directories.
If you pass 1 only for the normal attribute, any file that is not read-only, not a system file, not
hidden, and not a directory can match. A normal files archive bit may be either on or off. The
normal attribute is the only attribute that requires other attributes not to be set. For example, if
you use the read-only attribute, any read-only file can match regardless of its other attributes.
This holds true for the system, hidden, directory, and archive attributes.
If you use more than one attribute, the effect is additive. For example, if you use the read-only
and directory attributes, all read-only files and all directories can match. If you use the normal
and read-only attributes, all normal files and all read-only files can match.
Parameters
Input
Output
searchPath
string
Path to search.
normal
integer
Normal attribute.
read-only
integer
Read-only attribute.
system
integer
System attribute.
hidden
integer
Hidden attribute.
archive
integer
Archive attribute.
directory
integer
Directory attribute.
fileName
string
integer
Result of search.
Return Value
result
Return Codes
0
Success.
-1
-3
-4
-5
-6
Access denied.
8-28
Chapter 8
Utility Library
Parameter Discussion
searchPath may contain the wildcard characters '*' and '?'.
Each attribute parameter can have one of the following values:
0 do not search for files with the attribute
1 search for files with the attribute
fileName contains the basename and extension of the first matching file and must be at least
MAX_FILENAME_LEN characters in length.
GetFullPathFromProject
int result = GetFullPathFromProject (char fileName[], char fullPathName[]);
Purpose
Gets the full pathname for the specified file, if the file is in the currently loaded project.
Parameters
Input
fileName
string
Output
fullPathName
string
integer
Result of operation.
Return value
result
Return codes
0
-1
Success.
File was not found in project.
Parameter Discussion
fileName is the name of a file that is in the currently loaded project. The name must be a simple
file name and should not contain any directory paths. For example, file.c is a simple file
name, whereas dir\file.c is not.
fullPathName must be at least MAX_PATHNAME_LEN bytes long.
8-29
Utility Library
Chapter 8
GetInterruptState
int interruptstate = GetInterruptState (void);
Note: This function is available only on the Windows versions of LabWindows/CVI.
Purpose
This function returns the state of the interrupt bit of the 80x86 CPU status flag.
On Windows NT, this function always returns 1. Interrupts are always enabled while your
program is running at the user (as opposed to the kernel) level.
Return Value
interrupt state
integer
GetKey
int k = GetKey (void);
Purpose
Waits for the user to press a key and returns the key code as an integer value.
Note: This function only detects keystrokes in the Standard I/O window. It does not detect
keystrokes in windows created with the User Interface Library or in the console
window in a Windows Console Application.
8-30
Chapter 8
Utility Library
Parameters
None
Return Value
integer
Key code.
Return Value
<b>
'b'
<Ctrl-b>
(VAL_MENUKEY_MODIFIER | 'B')
<F4>
VAL_F4_VKEY
<Shift-F4>
(VAL_SHIFT_MODIFIER | VAL_F4_VKEY)
Note: This function returns -1 if you are running on UNIX and have done one of the
following.
Selected Use hosts systems standard Input/Output in the dialog box brought up
by selecting Options Environment in the Project window; or
Example
/* Give the user a chance to quit the program */
int k;
FmtOut ("Enter 'q' to quit, any other key to continue ");
k = GetKey ();
if ((k == 0x0051) || (k == 0x0071))
/* q or Q */
exit (0);
GetModuleDir
int result = GetModuleDir (char directoryName[], void *moduleHandle);
Note: This function is available only in the Windows 95 and NT versions of
LabWindows/CVI.
8-31
Utility Library
Chapter 8
Purpose
This function obtains the name of the directory of the specified DLL module.
This function is useful when a DLL and its related files are distributed to multiple users who may
place them in different directories. If your DLL needs to access a file that is in the same directory
as the DLL, you can use the GetModuleDir and MakePathname functions to construct the
full pathname.
If the specified module handle is zero, then this function returns the same result as
GetProjectDir.
Parameter List
Output directoryPathname
string
Directory of module.
Input
void
pointer
moduleHandle
Parameter Discussion
directoryPathname must be at least MAX_PATHNAME_LEN bytes long.
If you want to obtain the directory name of the DLL in which the call to GetModuleDir
resides, then pass __CVIUserHInst as the moduleHandle. You can pass any valid Windows
module handle. If you pass 0 for the moduleHandle, this function obtains the directory of the
project or standalone executable.
Return Value
integer
result
Return Codes
0
Success.
-1
-2
-3
Out of memory.
-4
8-32
Chapter 8
Utility Library
GetNextFile
int result = GetNextFile (char fileName[]);
Purpose
Gets the next file found in the search starting with GetFirstFile.
Parameters
Output
fileName
string
integer
Result of search.
Return Value
result
Return Codes
0
Success.
-1
-2
Parameter Discussion
fileName will contain the basename and extension of the next matching file and must be at least
MAX_FILENAME_LEN characters in length.
GetPersistentVariable
void GetPersistentVariable (int *value);
Purpose
Returns the value set by SetPersistentVariable. However, if you unloaded the project
since you last called SetPersistentVariable, zero is returned.
In a standalone executable, zero is returned if you have not called SetPersistentVariable
since the start of execution.
Parameters
Output
value
8-33
Utility Library
Chapter 8
GetProjectDir
int result = GetProjectDir (char directoryName[]);
Purpose
Gets the name of the directory containing the currently loaded project file.
Parameters
Output
directoryName
string
Directory of project.
integer
Result of operation.
Return value
result
Return codes
0
-1
Success.
Current project has no pathname (it is untitled).
Parameter Discussion
directoryName must be at least MAX_PATHNAME_LEN bytes long.
Using This Function
This function is useful when a project and its related files are distributed to multiple users who
may place them in a different directory on each machine. If your program needs to access a file
that is in the same directory as the project, you can use GetProjectDir and
MakePathname to construct the full pathname.
Example
char *fileName;
char projectDir[MAX_PATHNAME_LEN];
char fullPath[MAX_PATHNAME_LEN];
fileName = "myfile";
if (GetProjectDir (projectDir) < 0)
FmtOut ("Project is untitled\n");
else
MakePathname (projectDir, fileName, fullPath);
8-34
Chapter 8
Utility Library
GetStdioPort
void GetStdioPort (int *stdioPort);
Purpose
Gets a value indicating the current destination for data written to the standard output (and the
source of data read from the standard input.)
The Standard I/O port can be either the CVI Standard Input/Output window or the standard
Input/Output of the host system.
This function is valid only on the UNIX version.
Parameters
Output
stdioPort
integer
GetStdioWindowOptions
void GetStdioWindowOptions (int *maxNumLines, int *bringToFrontWhenModified,
int *showLineNumbers);
Purpose
Gets the current value of the following Standard Input/Output window options:
Maximum Number of Lines
Bring To Front When Modified
Show Line Numbers
8-35
Utility Library
Chapter 8
Parameters
Output
maxNumLines
integer
bringToFrontWhenModified integer
showLineNumbers
integer
Parameter Discussion
If you do not want to obtain any of these values, you can pass NULL.
GetStdioWindowPosition
void GetStdioWindowPosition (int *top, int *left);
Purpose
Gets the current position, in pixels, of the client area of the Standard Input/Output window
relative to the upper left corner of the screen. The client area begins under the title bar and to the
right of the frame.
8-36
Chapter 8
Utility Library
Parameters
Output
top
integer
left
integer
GetStdioWindowSize
void GetStdioWindowSize (int *height, int *width);
Purpose
Gets the height and width, in pixels, of the client area of the Standard Input/Output window. The
client area excludes the frame and the title bar.
Parameters
Output
height
integer
width
integer
GetStdioWindowVisibility
void GetStdioWindowVisibility (int *visible);
Purpose
Indicates whether the Standard Input/Output window is currently visible. If the window has been
made into an icon, it is considered to be not visible. If the window cannot be seen merely
because its position is off the screen it is considered to be visible.
8-37
Utility Library
Chapter 8
Parameters
Output
visible
integer
GetSystemDate
int status = GetSystemDate (int *month, int *day, int *year);
Note: This function is only available on the Windows version of LabWindows/CVI.
Purpose
Obtains the system date in numeric format.
Parameters
Output
month
integer
Month (112).
day
integer
year
integer
integer
Success or failure.
Return Value
status
Return Codes
0
-1
Success.
Failure reported by operating system.
8-38
Chapter 8
Utility Library
GetSystemTime
int status = GetSystemTime(int *hours, int *minutes, int *seconds);
Note: This function is only available on the Windows version of LabWindows/CVI.
Purpose
Obtains the system time in numeric format.
Parameters
Output
hours
integer
Hours (023).
minutes
integer
Minutes (059).
seconds
integer
Seconds (059).
integer
Success or failure.
Return Value
status
Return Codes
0
-1
Success.
Failure reported by operating system.
GetWindowDisplaySetting
void GetWindowDisplaySetting (int *visible, int *zoomState);
Note: This function is only available on the Windows version of LabWindows/CVI.
Purpose
Indicates how the user of your application wants the initial application window to be displayed.
The values returned by this function reflect the display options set for the program in Program
Manager and other MS Windows shells.
8-39
Utility Library
Chapter 8
Parameters
Output
visible
integer
0, if window is to be hidden;
1, if window is to be displayed.
zoomState
integer
ATTR_NO_ZOOMnormal
display;
ATTR_MINIMIZE
ATTR_MAXIMIZE.
Return Value
None
Example
If you want to honor the users display options, put the following code where you display your
initial panel.
int showWindow, zoomState;
GetWindowDisplaySetting (&showWindow, &zoomState);
/* load panel or create panel) */
if (showWindow){
SetPanelAttribute (panel, ATTR_WINDOW_ZOOM, zoomState);
SetPanelAttribute (panel, ATTR_VISIBLE, 1);
}
InitCVIRTE
int status = InitCVIRTE (void *hInstance, char *argv[], void *reserved);
Purpose
This function performs initialization of the CVI Run-Time Engine. It is needed only in
executables or DLLs that are linked using an external compiler. Otherwise, it is harmless.
Note: In LabWindows/CVI version 4.0.1, this function was expanded from one to three
parameters. Executables and DLLs created with the one-parameter version of the
function will continue to work properly.
8-40
Chapter 8
Utility Library
Parameters
Input
hInstance
void
pointer
argv
string
array
reserved
void
pointer
integer
1 indicates success.
0 indicates failure (probably out of memory).
Return Value
status
8-41
Utility Library
Chapter 8
Note: The prototypes for InitCVIRTE and CloseCVIRTE are in cvirte.h, which is
included by utility.h.
inp
char byteRead = inp (int portNumber);
Note: This function is available only on the Windows versions of LabWindows/CVI.
Purpose
Reads a byte from a port.
Note: For you to be able to use this function under Windows NT, the LabWindows/CVI lowlevel support driver must be loaded.
Parameters
Input
portNumber
integer
The port.
char
Return Value
byteRead
inpw
short wordRead = inpw (int portNumber);
Note: This function is available only on the Windows versions of LabWindows/CVI.
Purpose
Reads a word from a port.
Note: For you to be able to use this function under Windows NT, the LabWindows/CVI lowlevel support driver must be loaded.
8-42
Chapter 8
Utility Library
Parameters
Input
portNumber
integer
The port.
short
Return Value
wordRead
InStandaloneExecutable
int standalone = InStandaloneExecutable(void);
Purpose
Returns a non-zero value if your program is running as a standalone executable. If your program
is running in the LabWindows/CVI development environment, a zero is returned.
Return Value
standalone
integer
KeyHit
int result = KeyHit (void);
Purpose
Indicates whether the user has pressed a key on the keyboard.
Note: This function only detects keystrokes in the Standard I/O window. It does not detect
keystrokes in windows created with the User Interface Library or in the console
window in a Windows Console Application.
Parameters
None
Return Value
result
integer
8-43
Utility Library
Chapter 8
Return Codes
0
Selected Use hosts systems standard Input/Output in the dialog box brought up
by selecting Options Environment in the Project window; or
Called SetStdioPort to set the port to HOST_SYSTEM_STDIO.
Example
/* flush any pending keystrokes */
while (KeyHit())
GetKey();
/* perform loop indefinitely until the user presses key */
while (!KeyHit()) {
}
LaunchExecutable
int result = LaunchExecutable (char fileName[]);
Purpose
Starts running a program and returns without waiting for it to exit. The program must be an
actual executable; that is, you cannot launch commands intrinsic to a command interpreter.
Under Microsoft Windows the executable can be either an DOS or Windows executable,
including *.exe, *.com, *.bat, and *.pif files.
If you need to execute a command built into command.com such as copy, dir, and others,
you can call LaunchExecutable with the command
command.com /C DosCommand args, where DosCommand is the shell command you
would like executed. For example, the following command string would copy file.tmp from
the temp directory to the tmp directory:
command.com /C copy c:\\temp\\file.tmp c:\\tmp
8-44
Chapter 8
Utility Library
Refer to your DOS documentation for further help with command.com. DOS executables
(.exe, .com, and .bat files) use the settings in _default.pif (in your Windows
directory) when they are running. You can change their priority, display options, and more by
editing _default.pif or by creating another .pif file. Refer to your Microsoft Windows
documentation for help on creating and editing .pif files.
Parameter
Input
fileName
string
integer
Result of operation.
Return Value
result
Return Codes Under UNIX
0
-1
The system-imposed limit on the total number of processes under execution or the
total number of processes per user would be exceeded. This limit is determined
when the system is generated.
-2
-3
-4
Search permission is denied for a directory listed in the path prefix of the new
process image file, or the new process image file denies execution permission, or
the new process image file is not a regular file.
-5
The length of the path or file, or an element of the environment variable PATH
prefixed to a file exceeds {PATH_MAX}, or a pathname component is longer than
{NAME_MAX} while {_POSIX_NO_TRUNC} is in effect for that file (see man
page for pathconf(2V)).
-6
One or more components of the pathname of the new process image file do not
exist.
-7
A component of the path prefix of the new process image file is not a directory.
-8
The number of bytes used by the new process image's argument list and
environment list is greater than {ARG_MAX} bytes (see man page for
sysconf(2V)).
The new process image file has the appropriate access permission, but is not in the
proper format.
-9
8-45
Utility Library
Chapter 8
-1
System was out of memory, executable file was corrupt, or relocations were invalid.
-3
-4
-6
Attempt was made to dynamically link to a task, or there was a sharing or networkprotection error.
-7
-9
-11
-12
Executable file was invalid. Either it was not a Windows application or there was an
error in the .EXE image.
-13
-14
-15
-16
Attempt was made to load a real-mode application (developed for an earlier version of
Windows).
-17
Attempt was made to load a second instance of an executable file containing multiple
data segments that were not marked read-only.
-20
Attempt was made to load a compressed executable file. The file must be
decompressed before it can be loaded.
-21
Dynamic-link library (DLL) file was invalid. One of the DLLs required to run this
application was corrupt.
Application requires Microsoft Windows 32-bit extensions.
-22
Parameter Discussion
fileName is the program to be run.
If the program is not in one of the directories specified in the PATH environment variable, you
must specify the full path. The path can include arguments to be passed to the program.
Under Microsoft Windows, if the program is a .pif, .bat, or .com file, the extension must be
included in the path name.
For example, under Microsoft Windows the following command string launches the Edit
program with the file file.dat.
c:\\dos\\edit.com c:\\file.dat
8-46
Chapter 8
Utility Library
LaunchExecutableEx
int result = LaunchExecutableEx (char *fileName, int windowState, int *handle);
Purpose
LaunchExecutableEx performs the same operation as LaunchExecutable with the
following extended features:
Under Windows, you can specify how the Windows application displays.
This function returns a handle to the executable that can show whether the executable is still
running and also terminate the executable.
Parameters
Input
fileName
string
windowState
integer
integer
integer
Result of operation.
Output handle
Return Value
result
Return Codes
0
Success.
(non-zero value)
Parameter Discussion
The following values are valid for windowState:
LE_HIDE
LE_SHOWNORMAL
LE_SHOWMINIMIZED
LE_SHOWMAXIMIZED
LE_SHOWNA
LE_SHOWMINNOACTIVE
8-47
Utility Library
Chapter 8
c:\test\myapp.exe
The pathname of the Run-Time Engine might not be c:\cvi\cvirt4.exe. You can
determine the pathname of the Run-Time Engine by looking at the [cvirt4] section in
win.ini. (If the runtime executable was made with a different version of CVI, look in the
[cvirtnn] section for that version.)
If you need to pass arguments to your application, create a file containing the arguments and pass
the pathname of that file as the second argument to the Run-Time Engine. For example:
c:\cvi\cvirt4.exe
c:\test\myapp.exe
myargs
The file containing the arguments must be in the same directory as the executable. The first three
characters in the file containing the arguments must be CVI in uppercase, as in the following
example:
CVI
arg1
arg2
arg3
The Run-Time Engine deletes the file containing the arguments after reading it.
8-48
Chapter 8
Utility Library
LoadExternalModule
int module_id = LoadExternalModule (char pathName[]);
Purpose
Loads a file containing one or more object modules.
Parameter
Input
pathName
string
integer
Return Value
module_id
Return Codes
-1
Out of memory.
-2
-4
-6
-7
-8
-11
-12
-13
-14
-15
-16
-17
-18
-19
-20
A function in the DLL header file was not found in the DLL.
(continues)
8-49
Utility Library
Chapter 8
-22
-23
Could not load the DLL header file (out of memory or the file is corrupted).
-24
-25
-26
-27
-28
Parameter Discussion
This function loads an external object module file. The file need not be listed in your project nor
loaded as an instrument module.
Under Windows 3.1, the file may be an object file (.obj), a library file (.lib), or a
dynamically linked library (.dll). Object and library modules must be compiled with the
Watcom C compiler for Windows or the LabWindows/CVI compiler.
Under Windows 95 and NT, the file may be an object file (.obj), a library file (.lib), or a
DLL import library (.lib). You cannot load a DLL directly. Object and library modules can be
compiled in LabWindows/CVI or an external compiler.
In UNIX, the file may be an object file (.o) or a statically linked library (.a).
All files must conform to the rules for loadable compiled modules in the LabWindows/CVI
Programmer Reference Manual.
By loading external object modules, you can execute code that is not in your project and not in a
loaded instrument module. You can load the external modules only when needed and unload
them when they are no longer needed.
After a module has been loaded, you can execute its code in one of two ways:
8-50
Chapter 8
Utility Library
You can call RunExternalModule. This requires that the module contain a function with
a pre-defined name and prototype. The function serves as the entry point to the module. See
RunExternalModule for more information.
LoadExternalModule can also be used on a source file (.c) that is part of the current
project or a source file that has been loaded as the program for an instrument module. This
allows you to develop your module in source code form and test it using the LabWindows/CVI
debugging capabilities. After you have finished testing your module and compiled it into an
external object or library file, you need to make no modifications to your application source code
other than to change the pathname in the call to LoadExternalModule.
Avoid calling LoadExternalModule on a file in the project when you plan to link your
program in an external compiler. The LabWindows/CVI Utility library does not know the
locations of symbols in executables or DLLs linked in external compilers. You can provide this
information by using the Other Symbols section of the External Compiler Support dialog box
(in the Build menu of the LabWindows/CVI Project window) to create an object module
containing a table of symbols you want to find using GetExternalModuleAddr. If you use
this method, you should pass the empty string ("") to LoadExternalModule for the module
pathname.
If successful, LoadExternalModule returns an integer module ID which can later be passed
to RunExternalModule, GetExternalModuleAddr, and UnloadExternalModule.
If unsuccessful, LoadExternalModule returns a negative error code.
Resolving External References from Object and Static Library Files on Windows 95/NT
There is an important difference between loading an object or static library module and loading a
DLL via an import library. DLLs are prelinked, that is, when an DLL is loaded, no external
references need to be resolved. Object and static library modules, on the other hand, do have
external references that need to be resolved. LoadExternalModule resolves them using
symbols defined in the project or in object, static library, or import library modules that have
already been loaded using LoadExternalModule. This is true even when you call
LoadExternalModule from a DLL. LoadExternalModule does not use symbols in a
DLL to resolve external references unless those symbols have been exported in the import
library.
When you load an object or library module from a DLL, you may want external references to be
resolved through global symbols in the DLL that have not been exported in the import library. If
this is your intention, you must call LoadExternalModuleEx rather than
LoadExternalModule.
Using This Function
pathname may be a relative or absolute pathname. If it is a simple file name (such as
module.obj), LoadExternalModule attempts to find the file as follows.
1. It first looks for the file in the project list.
2. It then looks for the file in the directory that contains the currently loaded project.
8-51
Utility Library
Chapter 8
3. If the file has not been found and its extension is .dll, LoadExternalModule searches
for the file in the directories specified in the Windows LoadLibrary call.
If it is a relative pathname with one or more directory paths (such as dir\module.obj),
LoadExternalModule creates an absolute pathname by appending the relative pathname to
the directory that contains the currently loaded project.
If the pathname is for a DLL import library, LoadExternalModule finds the DLL using the
DLL name embedded in the import library and the standard Windows DLL search algorithm.
Example
void (*funcPtr) (char buf[], double dval, int *ival);
int module_id;
int status;
char buf[100];
double dval;
int ival;
char *pathname;
char *funcname;
pathname = "EXTMOD.OBJ";
funcname = "my_function";
module_id = LoadExternalModule (pathname);
if (module_id < 0)
FmtOut ("Unable to load %s\n", pathname);
else
{
funcPtr = GetExternalModuleAddr (module_id, funcname, &status);
if (funcPtr == NULL)
FmtOut ("Could not get address of %s\n", funcname);
else
(*funcPtr) (buf, dval, &ival);
}
LoadExternalModuleEx
int moduleId = LoadExternalModuleEx (char pathName[],
void *callingModuleHandle);
Purpose
LoadExternalModuleEx loads a file containing one or more object modules. It is similar to
LoadExternalModule, except that, on Windows 95 and NT, external references in object
and library modules loaded from a DLL can be resolved using DLL symbols that are not
exported. On platforms other than Windows 95 and NT, LoadExternalModuleEx works
exactly like LoadExternalModule.
8-52
Chapter 8
Utility Library
Parameters
Input
pathName
string
callingModuleHandle
void
pointer
integer
Return Value
moduleId
Return Codes
Same as the return codes for LoadExternalModule.
Using this Function
Refer to the function help for LoadExternalModule for detailed information on that
function.
When you call LoadExternalModule on an object or library module, external references
need to be resolved. They are resolved using symbols defined in the project or in object, library,
or DLL import library modules that have already been loaded using LoadExternalModule
(or LoadExternalModuleEx). This is true even if you call LoadExternalModule from
a DLL.
You may want to load an object or library module from a DLL and have the module link back to
symbols that you defined in (but did not export from) the DLL. You can do this using
LoadExternalModuleEx. You must specify the module handle of the DLL as the
callingModuleHandle parameter. You can do so by using the LabWindows/CVI pre-defined
variable __CVIUserHInst.
LoadExternalModuleEx first searches the global DLL symbols to resolve external
references. Any remaining unresolved references are resolved by searching the symbols defined
in the project or in object, library, or import library modules that have already been loaded using
LoadExternalModule (or LoadExternalModuleEx).
LoadExternalModuleEx expects the DLL to contain a table of symbols that can be used to
resolve references. If you create the DLL in LabWindows/CVI, the table is included
automatically. If you create the DLL using an external compiler, you must arrange for this table
to be included in the DLL. You can do this by creating an include file that includes all of the
symbols that need to be in this table. You can then use the External Compiler Support
8-53
Utility Library
Chapter 8
command in the Build menu of the Project Window to create an object file containing the table.
You must include this object file in the external compiler project you use to create the DLL.
LoadExternalModuleEx acts identically to LoadExternalModule if either,
you pass __CVIUserHInst for callingModuleHandle, but you are calling the function
from a file that is in the project or your executable, rather than in a DLL, or
You cannot load the same external module using two different calling module handles. The
function reports an error if you attempt to load the an external module when it is already loaded
under a different module handle.
MakeDir
int result = MakeDir (char directoryName[]);
Purpose
Creates a new directory based on the specified directory name.
Note: You can create only one directory at a time.
Parameters
Input
directoryName
string
integer
Result of operation.
Return Value
result
Return Codes
0
Success.
-1
-3
-4
-5
-6
Access denied.
-8
Disk is full.
-9
8-54
Chapter 8
Utility Library
Example
/* make a new directory named \DATA\WAVEFORM on drive C /*
/* assuming that C:\DATA does not exist
*/
MakeDir ("C:\\DATA");
MakeDir ("C:\\DATA\\WAVEFORM");
MakePathname
void MakePathname (char directoryName[], char fileName[], char pathName[]);
Purpose
Constructs a path name from a directory path and a filename. The subroutine ensures that the
directory path and the filename are separated by a backslash.
Parameters
Input
Output
directoryName
string
Directory path.
fileName
string
pathName
string
Path name.
Return Value
None
Parameter Discussion
pathName must be at least MAX_PATHNAME_LEN bytes long. If the pathName constructed
from directoryName and fileName exceeds that size, an empty string is returned in pathName.
Example
char dirname[MAX_PATHNAME_LEN];
char pathname[MAX_PATHNAME_LEN];
GetProjectDir (dirname);
MakePathname (dirname, "FILE.DAT", pathname);
8-55
Utility Library
Chapter 8
outp
char byteWritten = outp(int portNumber, char byteToWrite);
Note: This function is available only on the Windows versions of LabWindows/CVI.
Purpose
Writes a byte to a port.
Note: For you to be able to use this function under Windows NT, the LabWindows/CVI lowlevel support driver must be loaded.
Parameters
Input
portNumber
integer
The port.
byteToWrite
char
char
Return Value
byteWritten
outpw
short wordWritten = outpw (short portNumber, int wordToWrite);
Note: This function is available only on the Windows versions of LabWindows/CVI.
Purpose
Writes a word to a port.
Note: For you to be able to use this function under Windows NT, the LabWindows/CVI lowlevel support driver must be loaded.
Parameters
Input
portNumber
integer
The port.
wordToWrite
short
Return Value
wordWritten
short
8-56
Chapter 8
Utility Library
ReadFromPhysicalMemory
int status = ReadFromPhysicalMemory (unsigned int physicalAddress,
void *destinationBuffer,
unsigned int numberOfBytes);
Note: This function is available only on the Windows versions of LabWindows/CVI.
Purpose
Copies the contents of a region of physical memory into destinationBuffer. The function does
not check whether the memory actually exists. If the memory does not exist, the success value is
returned but no data is read.
Note: For you to be able to use this function under Windows 95 or NT, the LabWindows/CVI
low-level support driver must be loaded.
Parameters
Input
physicalAddress
unsigned integer
destinationBuffer
void pointer
numberOfBytes
unsigned integer
integer
Return Value
status
Return Codes
1
Success.
8-57
Utility Library
Chapter 8
ReadFromPhysicalMemoryEx
int status = ReadFromPhysicalMemoryEx (unsigned int physicalAddress,
void *destinationBuffer,
unsigned int numberOfBytes,
int bytesAtATime);
Note: This function is available only in the Windows version of LabWindows/CVI.
Purpose
This function copies the contents of a region of physical memory into the specified buffer. It can
copy the data in units of 1, 2, or 4 bytes at a time.
The function does not check whether the memory actually exists. If the memory does not exist,
the success value is returned but no data is read.
Note: For you to be able to use this function under Windows 95 or NT, the LabWindows/CVI
low-level support driver must be loaded.
Parameters
Input
physicalAddress
unsigned
integer
destinationBuffer
void pointer
numberOfBytes
unsigned
integer
bytesAtATime
integer
integer
Return Value
status
Return Codes
1
Success.
Parameter Discussion
numberOfBytes must be a multiple of bytesAtATime.
8-58
Chapter 8
Utility Library
ReleaseExternalModule
int status = ReleaseExternalModule (int moduleID);
Purpose
Decreases the reference count for a module loaded using LoadExternalModule.
When LoadExternalModule is called successfully on a module, that module's reference
count is incremented by one. When you call ReleaseExternalModule, its reference count
is decremented by one.
If the reference count is decreased to zero, then the module ID is invalidated and you cannot
access the module through GetExternalModuleAddr or RunExternalModule. If, in
addition, the module file is not in the project and not loaded as an instrument, the external
module is removed from memory.
If you want to unload the module regardless of the reference count, call
UnloadExternalModule rather than ReleaseExternalModule. Use
ReleaseExternalModule when multiple calls may have been made to
LoadExternalModule on the same module and you do not want to unload the module in
case it is still being used by other parts of the application.
Parameter
Input
moduleID
integer
integer
Return Value
status
Return Codes
>0
Success, but the module was not unloaded. The value indicates the number of
remaining references.
-5
-9
8-59
Utility Library
Chapter 8
RenameFile
int result = RenameFile (char existingFileName[], char newFileName[]);
Purpose
Renames an existing file.
Parameters
Input
existingFileName
string
newFileName
string
integer
Return Value
result
Return Codes
0
Success.
-1
-3
-4
-5
-6
Access denied.
-7
-8
Disk is full.
-9
Parameter Discussion
existingFileName and newFileName may contain DOS wildcard characters ? and *. If
existingFileName has wildcards, all matching files are renamed. If newFileName has
wildcards, it will be matched to existingFileName.
existingFileName may be the empty string (""), in which case the file found by the most recent
call to GetFirstFile or GetNextFile is renamed.
Under Microsoft Windows, if the arguments to RenameFile specify files on different disk
drives, RenameFile copies the source to the target and then deletes the source file.
8-60
Chapter 8
Utility Library
Under UNIX, if the arguments to RenameFile specify files on different file systems,
RenameFile copies the source to the target and then deletes the source file.
RetireExecutableHandle
int status = RetireExecutableHandle (int executableHandle);
Purpose
Informs the Utility Library that you no longer intend to use the handle acquired from
LaunchExecutableEx. When you call this function the Utility Library can reuse the
memory allocated to keep track of the state of the executable.
Under UNIX, if the process has terminated, the system removes the process from the list of
processes. This keeps the system from reaching the limit on the total number of processes under
execution by a single user which the system imposes.
Parameters
Input
executableHandle
integer
integer
Result of operation.
Return Value
status
RoundRealToNearestInteger
long n = RoundRealToNearestInteger (double inputRealNumber);
Purpose
Rounds its floating-point argument and returns the result as a long integer. A value with a
fractional part of exactly 0.5 is rounded to the nearest even number. This function is encountered
in translations.
Parameter
Input
inputRealNumber
Double-precision.
8-61
Utility Library
Chapter 8
Return Value
long
Example
long n;
n = round
n = round
n = round
n = round
n = round
n = round
n = round
n = round
(1.2);
(1.8);
(1.5);
(0.5);
(-1.2);
(-1.8);
(-1.5);
(-0.5);
/*
/*
/*
/*
/*
/*
/*
/*
result:
result:
result:
result:
result:
result:
result:
result:
1L
2L
2L
0L
-1L
-2L
-2L
0L
*/
*/
*/
*/
*/
*/
*/
*/
RunExternalModule
int result = RunExternalModule (int moduleID, char *buffer);
Purpose
Calls the pre-defined entry point function in an external module (see LoadExternalModule).
Parameters
Input
moduleID
integer
ID of loaded module.
buffer
string
Parameter buffer.
integer
Return Value
result
Return Codes
0
Success.
-1
Out of memory.
-3
-4
-5
Undefined references.
-8
-9
8-62
Chapter 8
Utility Library
Parameter Discussion
moduleID is the value LoadExternalModule returns. buffer is a character array in
which you can pass information to and from the module.
RunExternalModule requires that the module define the following function:
void _xxx_entry_point (char [])
where xxx is the base name of the file, in lowercase. For example, if the pathname of the
file is as follows:
C:\LW\PROGRAMS\TEST01.OBJ
Example
int module_id;
int status;
char *pathname;
pathname = "EXTMOD.OBJ";
module_id = LoadExternalModule (pathname);
if (module_id <0)
FmtOut ("Unable to load %s\n", pathname);
else {
RunExternalModule (module_id, "");
UnloadExternalModule (module_id);
}
SetBreakOnLibraryErrors
int oldState = SetBreakOnLibraryErrors (int newState);
Purpose
When debugging is enabled and a National Instruments library function reports an error,
LabWindows/CVI can display a runtime error dialog box and suspend execution. You can use
this function to enable or disable this feature.
In general, it is best to use the Break on library errors checkbox in the Run Options command
of the Project window to enable or disable this feature. You should use this function only when
you want the temporarily disable the Break on library errors feature around a segment of code.
This function does not affect the state of the Break on library errors checkbox in the Run
Options command of the Project window.
8-63
Utility Library
Chapter 8
If debugging is disabled, this function has no effect. Run-time errors are never reported when
debugging is disabled.
Parameters
Input
newState
integer
integer
Return Value
oldState
Return Codes
1
Example
int oldValue;
oldValue = SetBreakOnLibraryErrors (0);
/* function calls that may legitimately return errors */
SetBreakOnLibraryErrors (oldValue);
SetBreakOnProtectionErrors
int oldState = SetBreakOnProtectionErrors (int newState);
Purpose
If debugging is enabled, LabWindows/CVI uses information it gathers from compiling your
source code to make extensive run-time checks to protect your program. When it encounters a
protection error at run-time, LabWindows/CVI displays a dialog box and suspends execution.
Examples of protection errors are
An attempt is made in source code to read or write beyond the end of an array.
A function call is made in source code in which an array is smaller than is expected by the
function.
8-64
Chapter 8
Utility Library
You can use this function to prevent LabWindows/CVI from displaying the dialog box and
suspending execution when it encounters a protection error. In general, it is better not to disable
the break on protection errors feature. Nevertheless, you may want to disable it temporarily
around a line of code for which LabWindows/CVI is erroneously reporting a protection error.
If debugging is disabled, this function has no effect. Run-time errors are not reported when
debugging is disabled.
Note: If an invalid memory access generates a processor exception, LabWindows/CVI reports
the error and terminates your program regardless of the debugging level or the state of
the break on protection errors feature.
Parameters
Input
newState
integer
integer
Return Value
oldState
Return Codes
1
Example
int oldValue;
oldValue = SetBreakOnProtectionErrors (0);
/* the statement that erroneously reports an error */
SetBreakOnProtectionErrors (oldValue);
8-65
Utility Library
Chapter 8
SetDir
int result = SetDir (char directoryName[]);
Purpose
Sets the current working directory to the specified directory. Under Windows 3.1, this function
can change the current working directory on any drive, however it does not change the default
drive. To change the default drive, use the SetDrive function.
Parameters
Input
directoryName
string
integer
Result of operation.
Return Value
result
Return Codes
0
Success.
-1
Parameter Discussion
Under Windows 3.1, directoryName must not contain a drive letter.
SetDrive
int result = SetDrive (int driveNumber);
Note: This function is available only on the Windows versions of LabWindows/CVI.
Purpose
Sets the current default drive.
Parameters
Input
driveNumber
integer
8-66
Chapter 8
Utility Library
Return Value
integer
result
Result of operation.
Return Codes
0
Success.
-1
SetFileAttrs
int result = SetFileAttrs (char fileName[], int read-only, int system, int hidden,
int archive);
Note: This function is available only on the Windows versions of LabWindows/CVI.
Purpose
Sets the read-only, system, hidden and archive attributes of a file.
The read-only attribute protects a file from being overwritten and prevents the creation of a file
with the same name.
The system attribute and hidden attribute both prevent the file from appearing in a directory list
and exclude it from normal searches.
The archive attribute is set whenever the file is modified, and cleared by the DOS BACKUP
command.
Parameters
Input
fileName
read-only
string
integer
system
integer
System attribute.
hidden
integer
Hidden attribute.
archive
integer
Archive attribute.
8-67
Utility Library
Chapter 8
Return Value
result
return value
Result of operation.
Return Codes
0
-1
Success.
One of the following errors occurred:
File not found.
Attribute cannot be changed.
Parameter Discussion
Each attribute parameter can have one of the following values:
0clears the attribute
1sets the attribute
-1leaves the attribute unchanged
fileName may be the empty string (""), in which case the attributes of the file found by the most
recent call to GetFirstFile or GetNextFile are set.
SetFileDate
int status = SetFileDate (char fileName[], int month, int day, int year);
Purpose
Sets the date of a file.
8-68
Chapter 8
Utility Library
Parameters
Input
fileName
string
month
integer
Month (1 to 12)
1 January
2 February
3 March
4 April
5 May
6 June
7 July
8 August
9 September
10 October
11 November
12 December
day
integer
year
integer
Year (19802099)
integer
Result of operation.
Return Value
status
Return Codes
0
Success.
-1
-3
-4
-5
-6
Access denied.
Parameter Discussion
fileName may be the empty string (""), in which case the date of the file found by the most
recent call to GetFirstFile or GetNextFile is set.
8-69
Utility Library
Chapter 8
SetFileTime
int result = SetFileTime (char fileName[], int hours, int minutes, int seconds);
Purpose
Sets the time of a file.
Parameters
Input
fileName
string
hours
integer
Hours (0 to 23).
minutes
integer
Minutes (0 to 59).
seconds
integer
integer
Result of operation.
Return Value
result
Return Codes
0
Success.
-1
-3
-4
-5
-6
Access denied.
Parameter Discussion
fileName may be the empty string (""), in which case the time of the file found by the most
recent call to GetFirstFile or GetNextFile is set.
seconds value must be entered in increments of 2.
8-70
Chapter 8
Utility Library
SetPersistentVariable
void SetPersistentVariable (int value);
Purpose
Lets you store an integer value across multiple builds and executions of your project in the
LabWindows/CVI development environment. When you unload a project or load a new project,
the value is reset to zero.
This function is useful when your program performs an action (such as setting up your
instruments) that takes a long time and that you do not want to be repeated each time you re-run
your program. Global variables in your program are reinitialized to zero each time you run your
project. Thus, they cannot be used to indicate that you have already taken the action once.
To get around this problem, LabWindows/CVI maintains an integer variable across multiple
builds and executions of your project. This function sets the value of that variable. To retrieve
the variable value, call GetPersistentVariable().
Parameters
Input
value
integer
SetStdioPort
int status = SetStdioPort (int stdioPort);
Purpose
Sets the current destination for data written to the standard output (and the source of data read
from standard input).
You can specify either the CVI Standard Input/Output window or the standard input/output of
the host system.
Note: This function is valid only on the UNIX version of LabWindows/CVI.
8-71
Utility Library
Chapter 8
Parameters
Input
stdioPort
integer
CVI_STDIO_WINDOW (0) =
the CVI Standard Input/Output
window.
HOST_SYSTEM_STDIO (1) =
the host system's standard
output.
integer
Return Value
status
Return Codes
0
-2
Success.
Destination was not a valid range.
Parameter Discussion
In a standalone executable, the default value for stdioPort is CVI_STDIO_WINDOW.
In the CVI Development System, the default value for stdioPort is the current state of the Use
host system's standard input/output option in the dialog box brought up by the Environment
command in the Options menu of the Project window. The value that you set using this function
is reflected the next time you bring up the environment dialog.
SetStdioWindowOptions
int status = SetStdioWindowOptions (int maxNumLines,
int bringToFrontWhenModified,
int showLineNumbers);
Purpose
Sets the current value of the following Standard Input/Output window options:
Maximum Number of Lines
Bring To Front When Modified
Show Line Numbers
8-72
Chapter 8
Utility Library
Parameters
Input
maxNumLines
integer
bringToFrontWhenModified
integer
showLineNumbers
integer
Return Value
status
integer
Return Codes
0
-1
Success.
Maximum number of lines is not within the valid
range.
Parameter Discussion
maxNumLinesIn an executable, the default value is 10000. In the CVI Development System,
the default value is the value set in the dialog box brought up by the Environment command in
the Options menu of the Project window. The value that you set using this function is reflected
the next time you bring up the Environment dialog box.
bringToFrontWhenModifiedIn an executable, the default value is 1 ("bring to front when
modified"). In the CVI Development System, the default value is the current state of the "Bring
Standard Input/Output window to front whenever modified" option in the dialog box brought up
by the Environment command in the Options menu of the Project window. The value that you
set using this function is reflected the next time you bring up the Environment dialog box.
8-73
Utility Library
Chapter 8
showLineNumbersIn an executable, the default value is 0 ("do not show line numbers"). In
the CVI Development System, the default value is the current state of the Line Numbers option
in the View menu of the Standard Input/Output Window. The value that you set using this
function is reflected the next time you bring up the View menu.
SetStdioWindowPosition
int status = SetStdioWindowPosition (int top, int left);
Purpose
Sets the current position, in pixels, of the client area of the Standard Input/Output window
relative to the upper left corner of the screen. The client area begins under the title bar and to the
right of the frame.
Parameters
Input
top
integer
left
integer
Return Value
status
integer
Return Codes
0
-1
Success.
top is not within the valid range.
-2
8-74
Chapter 8
Utility Library
Parameter Discussion
To vertically center the Standard Input/Output window client area within the area of the screen,
pass VAL_AUTO_CENTER as the top parameter.
To horizontally center the Standard Input/Output window client area within the area of the
screen, pass VAL_AUTO_CENTER as the left parameter.
SetStdioWindowSize
int status = SetStdioWindowSize (int height, int width);
Purpose
Sets the height and width, in pixels, of the client area of the Standard Input/Output window. The
client area excludes the frame and the title bar.
Parameters
Input
height
integer
width
integer
Return Value
status
integer
Return Codes
0
-1
Success.
height is not within the valid range.
-2
8-75
Utility Library
Chapter 8
SetStdioWindowVisibility
void SetStdioWindowVisibility (int visible);
Purpose
Either brings to the front or hides the Standard Input/Output window.
Parameters
Input
visible
integer
SetSystemDate
int status = SetSystemDate (int month, int day, int year);
Note: This function is only available on the Windows version of LabWindows/CVI. Under
Windows NT, you must have system administrator status to use this function.
Purpose
Sets the system date.
Parameters
Input
month
integer
Month (112).
day
integer
year
integer
integer
Success or failure.
Return Value
status
Return Codes
0
Success.
-1
8-76
Chapter 8
Utility Library
SetSystemTime
int status = SetSystemTime(int hours, int minutes, int seconds);
Note: This function is only available on the Windows version of LabWindows/CVI. Under
Windows NT, you must have system administrator status to use this function.
Purpose
Sets the system time.
Parameters
Input
hours
integer
Hours (023).
minutes
integer
Minutes (059).
seconds
integer
integer
Success or failure.
Return Value
status
Return Codes
0
-1
Success.
Failure reported by operating system, probably due to
an invalid parameter.
SplitPath
void SplitPath (char pathName[], char driveName[], char directoryName[],
char fileName[]);
Purpose
Splits a path name into the drive name, the directory name, and the file name.
8-77
Utility Library
Chapter 8
Parameters
Input
pathName
string
Output
driveName
string
Drive name.
directoryName
string
fileName
string
Return Value
None
Parameter Discussion
The driveName, directoryName, and fileName parameters can each be NULL. If not NULL,
they must be buffers of the following size or greater.
drive name
directory name
file name
MAX_DRIVENAME_LEN
MAX_DIRNAME_LEN
MAX_FILENAME_LEN
On operating systems without drive names (such as UNIX), driveName will always be filled in
with the empty string.
Example
char pathName[MAX_PATHNAME_LEN];
char driveName[MAX_DRIVENAME_LEN];
char dirName[MAX_DIRNAME_LEN];
char fileName[MAX_FILENAME_LEN];
SplitPath (pathName, driveName, dirName, fileName);
/*
If pathName contains
c:\cvi\samples\apps\update.c
then
c:
driveName contains
\cvi\samples\apps\
dirName contains
update.c
fileName contains
If pathName is
\\computer\share\dirname\foo.c
then
drive name is
""
directory name is
" \\computer\share\dirname\"
file name is
"foo.c"
*/
8-78
Chapter 8
Utility Library
SyncWait
void SyncWait (double beginTime, double interval);
Purpose
Waits until the number of seconds indicated by interval have elapsed since beginTime.
Parameters
Input
beginTime
interval
double-precision
double-precision
Parameter Discussion
beginTime must be a value returned by the Timer function.
The resolution on Windows is normally 1 millisecond. However, if the following line appears
in the CVI section of your WIN.INI file, the resolution is 55 milliseconds.
useDefaultTimer = True
The resolution on Sun Solaris is 1 millisecond.
Return Value
None
SystemHelp
int status = SystemHelp (char helpFile[], unsigned int command,
unsigned long additionalLongData,
char additionalStringData[]);
Note: This function is available only on the Windows versions of LabWindows/CVI.
Purpose
Starts Windows Help (WINHELP.EXE) and passes optional data indicating the nature of the help
requested by the application. The application specifies the path of the help file that the
application is to display.
For information about creating help files, see the Microsoft Windows Programming
Documentation (not included with LabWindows/CVI).
8-79
Utility Library
Chapter 8
Parameters
Input
helpFile
string
command
unsigned integer
additionalLongData
unsigned long
integer
additionalStringData
string
integer
Return Value
status
Parameter Discussion
helpFile contains a filename that may be followed by an angle bracket (<) and the name of a
secondary window if the topic is to be displayed in a secondary window rather than in the
primary window. The name of the secondary window must have been defined in the [WINDOWS]
section of the Help Project (.HPJ) file.
command can be one of the following values:
HELP_COMMANDExecute a Help Macro. In this case, additionalStringData is the Help
macro to be executed.
HELP_CONTENTSDisplays the Help contents topic as defined by the Contents option in the
[OPTIONS] section of the .HPJ file.
HELP_CONTEXTDisplay Help for a particular topic identified by a context number that has
been defined in the [MAP] section of the .HPJ file. In this case, additionalLongData is the
context number of the topic.
HELP_CONTEXTNOFOCUSDisplay Help for a particular topic identified by a context number
that has been defined in the [MAP] section of the .HPJ file. Help does not change the focus to
the window displaying the topic.
8-80
Chapter 8
Utility Library
8-81
Utility Library
Chapter 8
TerminateExecutable
int status = TerminateExecutable (int executableHandle);
Purpose
Attempts to terminate an executable if it has not already terminated.
Under Windows the system terminates an executable by sending close messages to each window
in the application. If the application does not honor the close messages, then the application does
not terminate. The TerminateExecutable function gives up control for a limited period to
give the application an opportunity to process the close messages. This period should be
sufficient for all applications. When you need to allow more time, your program can call the
ProcessSystemEvents function in a loop, as shown in the following example.
Example
#define TIME_LIMIT 5.0 /* number of seconds */
double startTime;
startTime = Timer ();
TerminateExecutable (handle);
while (!ExecutableHasTerminated(handle)
&& (Timer()-startTime > TIME_LIMIT))
ProcessSystemEvents();
Under UNIX, you can allow more time by sending the SIGKILL message to the process. The
SIGKILL message cannot be blocked, caught, or ignored, and therefore should always succeed.
Parameters
Input
executableHandle
integer
Return Value
status
integer
Result of operation.
Return Codes
-1
Handle is invalid.
Handle is invalid.
8-82
Chapter 8
Utility Library
Timer
double t = Timer (void);
Purpose
Returns the number of seconds that have elapsed since the first call to Timer, Delay, or
SyncWait or the first operation on a timer control. The value is never reset to zero except
when you restart your program. The resolution on Windows is normally 1 millisecond.
However, if the following line appears in the CVI section of your WIN.INI file, the
resolution is 55 milliseconds.
useDefaultTimer = True
double-precision
TimeStr
char *s = TimeStr (void);
Purpose
Returns an 8-character string in the form HH:MM:SS, where HH is the hour, MM is in minutes,
and SS is in seconds.
Parameters
None
Return Value
s
8-character string
8-83
Utility Library
Chapter 8
TruncateRealNumber
double y = TruncateRealNumber (double inputRealNumber);
Purpose
Truncates the fractional part of inputRealNumber and returns the result as a real number.
Parameters
Input
inputRealNumber
double-precision.
Return Value
double-precision
Value of inputRealNumber
without its fractional part.
UnloadExternalModule
int status_id = UnloadExternalModule (int moduleID);
Purpose
Unloads an external module file loaded via LoadExternalModule.
Parameter
Output
moduleID
integer
ID of loaded module.
integer
Return Value
status_id
Return Codes
0
-9
Success.
Failure due to invalid module_id.
Parameter Discussion
moduleID is the value returned by LoadExternalModule, or -1. If -1 is used, all
external modules are unloaded.
LabWindows/CVI Standard Libraries
8-84
Chapter 8
Utility Library
Example
int module_id;
int status;
char *pathname'
pathname = "PROG.OBJ";
module_id = LoadExternalModule (pathname);
if (module_id <0)
FmtOut ("Unable to load %s\n", pathname);
else {
RunExternalModule (module_id, "");
UnloadExternalModule (module_id);
}
WriteToPhysicalMemory
int status = WriteToPhysicalMemory (unsigned int physicalAddress,
void *sourceBuffer,
unsigned int numberOfBytes);
Note: This function is available only on the Windows versions of LabWindows/CVI.
Purpose
Copies the contents of destinationBuffer into a region of physical memory. The function does
not check whether the memory actually exists. If the memory does not exist, the success value is
returned but no data is read.
Note: For you to be able to use this function under Windows 95 or NT, the LabWindows/CVI
low-level support driver must be loaded.
Parameters
Input
physicalAddress
unsigned integer
sourceBuffer
void pointer
numberOfBytes
unsigned integer
8-85
Utility Library
Chapter 8
Return Value
status
integer
Return Codes
1
0
Success.
Failure reported by the operating system, or low-level
support driver not loaded.
WriteToPhysicalMemoryEx
int status = WriteToPhysicalMemoryEx (unsigned int physicalAddress,
void *sourceBuffer,
unsigned int numberOfBytes,
int bytesAtATime);
Note: This function is available only in the Windows version of LabWindows/CVI.
Purpose
This function copies the contents of the specified buffer to a region of physical memory. It can
copy the data in units of 1, 2, or 4 bytes at a time.
The function does not check whether the memory actually exists. If the memory does not exist,
success is returned but no data is written.
Note: For you to be able to use this function on Windows 95 or NT, the LabWindows/CVI
low-level support driver must be loaded.
Parameters
Input
physicalAddress
unsigned
integer
sourceBuffer
void pointer
numberOfBytes
unsigned
integer
bytesAtATime
integer
8-86
Chapter 8
Utility Library
Return Value
integer
status
Return Codes
1
Success.
Parameter Discussion
numberOfBytes must be a multiple of bytesAtATime.
8-87
Chapter 9
X Property Library
_____________________________________________________________________________
This chapter describes the functions in the Lab/Windows CVI X Property Library. The X
Property Library contains functions that read and write properties to and from X Windows. The
X Property Library Overview section contains general information about the X Property Library
functions and panels. The X Property Library Function Reference section contains an
alphabetical list of function descriptions.
These functions provide a mechanism for communication among X clients. This library provides
capabilities similar to those available in the TCP library, but differs from the TCP library in the
following significant ways.
It works between any X clients that are connected to the same display, and does not require
any particular underlying communication protocol such as TCP.
It provides a method for sharing data among X clients without explicit point-to-point
connections between them.
The X Property Library Overview section contains general information about the X Property
Library. The X Property Library Function Reference section alphabetically lists function names,
with descriptions.
9-1
X Property Library
Chapter 9
ConnectToXDisplay
DisconnectFromXDisplay
CreateXPropType
GetXPropTypeName
GetXPropTypeSize
GetXPropTypeUnit
DestroyXPropType
CreateXProperty
GetXPropertyName
GetXPropertyType
DestroyXProperty
GetXWindowPropertyItem
PutXWindowPropertyItem
GetXWindowPropertyValue
PutXWindowPropertyValue
RemoveXWindowProperty
InstallXPropertyCallback
UninstallXPropertyCallback
GetXPropErrorString
X Interclient Communication
X applications often use X properties to communicate with each other. Properties are essentially
tagged data associated with a window. Applications communicate by reading and writing
properties to and from windows. In addition, an X application can request that the X server
notify it whenever a specific property value changes on a window.
The X applications that need to communicate with each other must first connect to the same X
display. Then they must agree upon the names and types of properties as well as the X window
IDs that they use to transfer the data. Although it is a simple matter to agree upon the names and
types of properties in advance, the window IDs cannot be known in advance because they are
different for each invocation of the program. There must be a mechanism for transferring the
window IDs from one client to another. A client usually accomplishes this by placing a property
that contains the window ID on the root window, which is a window that all clients can access.
The window ID refers to the window containing the data for transfer to other clients. The other
clients read this property from the root window to determine where the data is stored.
9-2
Chapter 9
X Property Library
With the LabWindows/CVI X Property Library functions, you can connect to X displays and
obtain the root window ID, read and write properties on windows, and monitor when specific
properties change.
Name
"WINDOW"
"INTEGER"
"STRING"
Size/Unit
sizeof(WindowX)
sizeof(int)
sizeof(char)
9-3
X Property Library
Chapter 9
not delete it, the property remains there indefinitely. Second, because there is only one root
window, there may be conflicts when multiple applications attempt to access the same properties.
To overcome those disadvantages, LabWindows/CVI provides a hidden window. Before it runs
your program, LabWindows/CVI creates a window that never displays. The X window ID for
this window is available in the X Property Library from the global variable
CVIXHiddenWindow. This window ID is always available to your program for reading and
writing properties. When your program terminates, LabWindows/CVI removes the window and
all of its properties.
Error Codes
PropLibXErrType is the data type of all return values in the X Property Library functions.
PropLibXErrType is an enumerated (enum) type containing descriptive constant names and
numeric values for the errors. PropLibXErrType and its enumerated values are all integers.
All error values are negative numbers.
The following table lists all the enumerated constant names and their corresponding numeric
values. Detailed descriptions of these error types appear in the function descriptions in the
following section.
9-4
Chapter 9
X Property Library
Value
Description
InvalidParamXErr
-1
InvalidDisplayXErr
-2
InvalidWindowXErr
-3
InvalidPropertyXErr
-4
InvalidPropTypeXErr
-5
TooManyConnectionsXErr -6
CannotConnectXErr
-7
DupPropertyXErr
-8
9-5
X Property Library
Chapter 9
-9
PropertyInUseXErr
-10
PropTypeInUseXErr
-11
TypeMismatchXErr
-12
UnitMismatchXErr
-13
InvalidIndexXErr
-14
SizeMismatchXErr
-15
OverflowXErr
-16
InvalidCallbackXErr
-17
MissingPropertyXErr
-18
InsuffMemXErr
-19
GeneralXErr
-20
BrokenConnectionXErr
-21
9-6
Chapter 9
X Property Library
ConnectToXDisplay
PropLibXErrType status = ConnectToXDisplay (const char *displayName,
DisplayPtrX *display,
WindowX *rootWindow);
Purpose
Connect to a remote X server.
Use this function to access an X server on a remote computer. This function returns a display
pointer and the root window, which you can use to read and write properties on the root window
of the remote X server.
If you want to communicate only with applications using the same display as your application,
you do not need this function. Instead, use the global variables CVIXDisplay and
CVIXRootWindow, which contain the display and root window of the X server used by
LabWindows/CVI.
9-7
X Property Library
Chapter 9
Parameters
Input
displayName
Output display
rootWindow
string
DisplayPtrX
(passed by
reference)
WindowX
(passed by
reference)
Return Values
The return value indicates the success or failure status of the function call. A negative value
indicates an error. status values are shown in the following table.
NoXErr
InvalidParamXErr
TooManyConnectionsXErr
CannotConnectXErr
Parameter Discussion
Valid values for displayName include any valid arguments to the Xlib function
XOpenDisplay. The format is hostname:server or hostname:server.screen,
where:
hostname specifies the name of the host computer on which the display is physically
connected.
server specifies the number of the server on its host computer (usually 0).
screen specifies the number of the default screen on the server (usually 0).
9-8
Chapter 9
X Property Library
See Also
Refer to the Xlib Programming Manual or to XlibC Language X Interface, MIT X Consortium
Standard for more information about the XOpenDisplay and DefaultRootWindow
functions.
_____________________________________________________________________________
CreateXProperty
PropLibXErrType status = CreateXProperty (const char *propertyName,
PropTypeHandleX propertyType,
PropertyHandleX *property);
Purpose
Create X property information.
Use this function to define the attributes of the properties that you read and write on X windows.
You must create properties with this function before you can access them on X windows.
Each property has a unique name and a type (created by CreateXPropType) that you cannot
change except by destroying the property and recreating it.
Note: You can create a maximum of 256 different properties.
Parameters
Input
propertyName string
propertyType
Output property
PropTypeHandleX
PropertyHandleX
(passed by reference)
9-9
X Property Library
Chapter 9
Return Values
The return value indicates the success or failure status of the function call. A negative value
indicates an error. The following table shows status values.
NoXErr
InvalidParamXErr
InvalidPropTypeXErr
DupPropertyXErr
InsuffMemXErr
Parameter Discussion
propertyType is added with the property the first time you write a property to a window. When
you access a property on a window on which the property already exists, its type must match this
value for the access to succeed.
See Also
Refer to the Xlib Programming Manual or to XlibC Language X Interface, MIT X Consortium
Standard for more information about the XInternAtom function.
_____________________________________________________________________________
CreateXPropType
PropLibXErrType status = CreateXPropType (const char *typeName,
unsigned int size, unsigned int unit,
PropTypeHandleX *propertyType);
Purpose
Creates X property type. You can use this function to define the attributes of the properties that
you read and write on X windows. You must create property types with this function before you
can create properties.
Each property type has a unique name and set of attributes that cannot be changed except by
destroying the property and recreating it.
9-10
Chapter 9
X Property Library
There are three predefined property types that you do not need to create using this function.
These types, listed below, are useful for defining properties to store window IDs, integers and
strings.
Property Type
WINDOW_X_PROP_TYPE
INTEGER_X_PROP_TYPE
STRING_X_PROP_TYPE
Name
"WINDOW"
"INTEGER"
"STRING"
Size/Unit
sizeof(WindowX)
sizeof(int)
sizeof(char)
typeName
string
size
unsigned integer
unit
unsigned integer
PropTypeHandleX
(passed by reference)
Output propertyType
Return Values
The return value indicates the success or failure status of the function call. A negative value
indicates an error. status values are shown in the following table.
NoXErr
InvalidParamXErr
DupPropTypeXErr
InsuffMemXErr
9-11
X Property Library
Chapter 9
Parameter Discussion
Usually, you can use the expression sizeof(TYPE) for the size parameter, where TYPE is the
C data type (char, int, and others) used to store the property value. This value must be a
multiple of the unit argument.
unit specifies how the X server should view the property item (as an array of 1-byte, 2-byte or
4-byte objects) and is necessary to perform simple byte-swapping between different types of
computers. See the notes near the end of this function description.
If the property item consists of a single object, such as an integer or a character, the unit should
be just the size of the object. An exception is the double type, for which the default unit
should be 4 bytes.
If the property item is a structure or array containing a number of smaller objects, then the unit
should be the number of bytes in the smaller objects.
Note: If you are communicating with a remote X server on a computer that has different
byte-ordering than your application, the unit specified is used to perform the byte
swapping. However, byte swapping cannot be properly performed for structures
containing different size members or for double type. For these special cases, use a
unit of 1 and then explicitly perform byte swapping where needed.
Note: The LabWindows/CVI X Property Library specifies units in the number of BYTES as
opposed to BITS. Thus, the "format" values of 8, 16 and 32 used by Xlib functions
correspond to units of 1, 2 and 4, respectively in the functions of the LabWindows/CVI
X Property Library.
See Also
Refer to the Xlib Programming Manual or to XlibC Language X Interface, MIT X Consortium
Standard for more information about the XInternAtom function.
DestroyXProperty
PropLibXErrType status = DestroyXProperty (PropertyHandleX property);
Purpose
Destroys X property information. You can use this function when you no longer need to access a
property. This function frees memory allocated by CreateXProperty. The property handle
cannot be used after this function is called.
All property information is destroyed when the program terminates.
Note: It is not possible to destroy properties for which callbacks are installed.
9-12
Chapter 9
X Property Library
Parameter
Input
property
PropertyHandleX
Return Values
The return value indicates the success or failure status of the function call. A negative value
indicates an error. The following table shows status values.
NoXErr
InvalidPropertyXErr
PropertyInUseXErr
_____________________________________________________________________________
DestroyXPropType
PropLibXErrType status = DestroyXPropType (PropTypeHandleX propertyType);
Purpose
Destroys X property type. You can use this function when you no longer need a property type.
This function frees memory that was allocated by CreateXPropType. The property type
cannot be used after this function is called.
All property types are destroyed when the program terminates.
Note: It is not possible to destroy property types if there are properties that use them.
Parameter
Input
propertyType
9-13
X Property Library
Chapter 9
Return Values
The return value indicates the success or failure status of the function call. A negative value
indicates an error. The following table shows status values.
NoXErr
InvalidPropTypeXErr
PropTypeInUseXErr
DisconnectFromXDisplay
PropLibXErrType status = DisconnectFromXDisplay (DisplayPtrX display);
Purpose
Disconnects from a remote X server. You can use this function to end access to a remote
X server you connected using ConnectToXDisplay. After this function is called, you can no
longer access the remote X server.
Parameter
Input
display
DisplayPtrX
Return Values
The return value indicates the success or failure status of the function call. A negative value
indicates an error. The following table shows status values.
NoXErr
InvalidParamXErr
InvalidDisplayXErr
9-14
Chapter 9
X Property Library
See Also
Refer to the Xlib Programming Manual or to XlibC Language X Interface, MIT X Consortium
Standard for more information about the XCloseDisplay function.
GetXPropErrorString
char *message = GetXPropErrorString (PropLibXErrType errorNum)
Purpose
Converts the error number returned by an X Property Library function into a meaningful error
message.
Parameters
Input
errorNum
Return Value
string
message
Explanation of error.
____________________________________________________________________________________________
GetXPropertyName
PropLibXErrType status = GetXPropertyName (PropertyHandleX property,
char **propertyName);
Purpose
Gets a property name. This function returns a pointer to the name associated with the property
handle.
Parameters
Input
property
Output propertyName
9-15
X Property Library
Warning:
Chapter 9
Return Values
The return value indicates the success or failure status of the function call. A negative value
indicates an error. The following table shows status values.
NoXErr
InvalidParamXErr
InvalidPropertyXErr
_____________________________________________________________________________
GetXPropertyType
PropLibXErrType status = GetXPropertyType (PropertyHandleX property,
PropTypeHandleX *propertyType);
Purpose
Gets the type of a property.
This function returns a pointer to the type associated with the property handle.
Parameters
Input
property
Output propertyType
9-16
Chapter 9
X Property Library
Return Values
The return value indicates the success or failure status of the function call. A negative value
indicates an error. The following table shows status values.
NoXErr
InvalidParamXErr
InvalidPropertyXErr
GetXPropTypeName
PropLibXErrType status = GetXPropTypeName (PropTypeHandleX propertyType,
char **typeName);
Purpose
Gets a property type name. This function returns the name associated with the property type.
Parameters
Input
propertyType
Output typeName
InvalidParamXErr
InvalidPropTypeXErr
9-17
X Property Library
Chapter 9
See Also
CreateXPropType
GetXPropTypeSize
PropLibXErrType status = GetXPropTypeSize (PropTypeHandleX propertyType,
unsigned int *size);
Purpose
Gets a property type size. This function returns the size associated with the property type. The
size is the number of bytes in a single property item.
Parameters
Input
propertyType
Output size
Return Values
The return value indicates the success or failure status of the function call. A negative value
indicates an error. The following table shows status values.
NoXErr
InvalidParamXErr
InvalidPropTypeXErr
See Also
CreateXPropType
9-18
Chapter 9
X Property Library
GetXPropTypeUnit
PropLibXErrType status = GetXPropTypeUnit (PropTypeHandleX propertyType,
unsigned int *unit);
Purpose
Get a property type unit.
This function returns the unit associated with the property type. The unit is the number of bytes
(1, 2, or 4) in the basic objects that make up a property item.
Parameters
Input
propertyType
Output unit
PropTypeHandleX
unsigned integer
(passed by
reference)
Return Values
The return value indicates the success or failure status of the function call. A negative value
indicates an error. The following table shows status values.
NoXErr
InvalidParamXErr
-1
InvalidPropTypeXErr -5
See Also
CreateXPropType
9-19
X Property Library
Chapter 9
GetXWindowPropertyItem
PropLibXErrType status = GetXWindowPropertyItem (DisplayPtrX display,
WindowX window,
PropertyHandleX property,
void *propertyItem);
Purpose
Get a single property item from a window.
This function obtains the value of the specified property on the window and copies a single item
into the supplied buffer. When there are more than one item in the property value, this function
obtains only the first one. This function does not change the property value.
If the property does not exist on the window, this function reports the
MissingPropertyXErr error.
Use the function GetXWindowPropertyValue to get multiple property items.
Parameters
Input
display
DisplayPtrX
window
WindowX
property
PropertyHandleX
generic pointer
Output propertyItem
9-20
Chapter 9
X Property Library
Return Values
The return value indicates the success or failure status of the function call. A negative value
indicates an error. The following table shows status values.
NoXErr
InvalidParamXErr
-1
InvalidDisplayXErr
-2
InvalidWindowXErr
-3
InvalidPropertyXErr
-4
TypeMismatchXErr
UnitMismatchXErr
SizeMismatchXErr
MissingPropertyXErr
InsuffMemXErr
GeneralXErr
BrokenConnectionXErr -21 The connection to the X server was broken. This occurs if
the remote server terminated.
Parameter Discussion
display must either be the predefined value CVIXDisplay or be the value returned by
ConnectToXDisplay. Use CVIXDisplay if the window is on the same display used by
LabWindows/CVI.
For the window parameter, use CVIXRootWindow to access the default root window of the
display used by LabWindows/CVI. Use CVIXHiddenWindow to access the hidden window
associated with your application.
propertyItem must point to an object of the same size as the property item. You can get the size
of the property item by calling the function GetXPropertySize.
9-21
X Property Library
Chapter 9
See Also
Refer to the Xlib Programming Manual or to XlibC Language X Interface, MIT X Consortium
Standard for more information about the XGetWindowProperty function.
GetXWindowPropertyValue
PropLibXErrType status = GetXWindowPropertyValue (DisplayPtrX display,
WindowX window, PropertyHandleX property,
unsigned int index, unsigned int numberofItemsRequested,
int delete, unsigned int *numberofItemsReturned,
unsigned int *numberOfItemsRemaining,
void *propertyValue);
Purpose
Get the value of a property on a window.
This function obtains the value of the specified property on the window and copies it into the
supplied buffer.
Note: If the property does not exist on the window, this function does NOT report an error.
Instead, the number of items returned is set to 0.
9-22
Chapter 9
X Property Library
Parameters
Input
display
DisplayPtrX
window
WindowX
property
index
unsigned integer
numberofItemsRequested
unsigned integer
delete
integer
Output numberofItemsReturned
unsigned integer
Number of property items that
(passed by reference) were obtained from the window.
generic pointer
9-23
X Property Library
Chapter 9
Return Values
The return value indicates the success or failure status of the function call. A negative value
indicates an error. The following table shows status values.
NoXErr
InvalidParamXErr
-1
InvalidDisplayXErr
-2
InvalidWindowXErr
-3
InvalidPropertyError -4
TypeMismatchXErr
UnitMismatchXErr
InvalidIndexXErr
SizeMismatchXErr
InsuffMemXErr
GeneralXErr
BrokenConnectionXErr -21 The connection to the X server was broken. This occurs if
the remote server terminated.
Parameter Discussion
display must either be the predefined value CVIXDisplay or be the value returned by
ConnectToXDisplay. Use CVIXDisplay if the window is on the same display used by
LabWindows/CVI.
For the window parameter, use CVIXRootWindow to access the default root window of the
display used by LabWindows/CVI. Use CVIXHiddenWindow to access the hidden window
associated with your application.
numberofItemsReturned will be less than or equal to the number of property items requested.
If the property does not exist on the window or there is no property value, this value will be 0.
You must check this value to determine if any property items were read.
9-24
Chapter 9
X Property Library
See Also
Refer to the Xlib Programming Manual or to XlibC Language X Interface, MIT X Consortium
Standard for more information about the XGetWindowProperty function.
InstallXPropertyCallback
PropLibXErrType status = InstallXPropertyCallback (DisplayPtrX display,
const WindowX windowList[],
unsigned int numberofWindows,
const PropertyHandleX propertyList[], unsigned
int numberofProperties,
const void *callbackData, PropertyCallbackTypeX
*callbackFunction);
Purpose
Install a property callback function.
The specified function is called whenever one of the specified properties on one of the specified
windows changes in any way. If more than one function is installed for the same property, the
functions are called in the reverse order in which they were installed.
If the function is already installed as a callback function, the list of windows and properties that
are associated with that function are replaced with those specified by the new installation.
Parameters
DisplayPtrX
windowList
const WindowX []
numberofWindows
unsigned integer
propertyList
const
PropertyCallbackTypeX []
An array of handles to
properties for which the
callback is called.
Input display
(continues)
9-25
X Property Library
Chapter 9
Parameters (Continued)
numberofProperties
unsigned integer
callbackData
generic pointer
callbackFunction
PropertyCallbackTypeX *
Return Values
The return value indicates the success or failure status of the function call. A negative value
indicates an error. The following table shows status values.
Table 9-4. Status Values for InstallXPropertyCallback
NoXErr
InvalidParamXErr
InvalidDisplayXErr
InvalidWindowXErr
InvalidPropertyXErr
InsuffMemXErr
BrokenConnectionXErr -21 The connection to the X server was broken. This occurs if
the remote server terminated.
Parameter Discussion
display must either be the predefined value CVIXDisplay or be the value returned by
ConnectToXDisplay. Use CVIXDisplay if the window is on the same display used by
LabWindows/CVI.
To specify a single window, named win, pass the expression &win for the windowList
parameter and pass 1 for the numberOfWindows. Use &CVIXRootWindow to access the
9-26
Chapter 9
X Property Library
PutXWindowPropertyItem
PropLibXErrType status = PutXWindowPropertyItem (DisplayPtrX display,
WindowX window, PropertyHandleX property,
void *propertyItem);
Purpose
This function stores the supplied property item with the specified property on the window. Any
existing property value is replaced by this value.
To store multiple property items, use the function PutXWindowPropertyValue.
Parameters
Input
display
DisplayPtrX
window
WindowX
property
9-27
X Property Library
Chapter 9
Return Values
The return value indicates the success or failure status of the function call. A negative value
indicates an error. The following table shows status values.
NoXErr
InvalidParamXErr
InvalidDisplayXErr
InvalidWindowXErr
InvalidPropertyXErr
InsuffMemXErr
GeneralXErr
BrokenConnectionXErr -21 The connection to the X server was broken. This occurs if
the remote server terminated.
Parameter Discussion
display must either be the predefined value CVIXDisplay or be the value returned by
ConnectToXDisplay. Use CVIXDisplay if the window is on the same display used by
LabWindows/CVI.
For the window parameter, use CVIXRootWindow to access the default root window of the
display used by LabWindows/CVI. Use CVIXHiddenWindow to access the hidden window
associated with your application.
See Also
Refer to the Xlib Programming Manual or to XlibC Language X Interface, MIT X Consortium
Standard for more information about the XChangeProperty function.
_____________________________________________________________________________
9-28
Chapter 9
X Property Library
PutXWindowPropertyValue
PropLibXErrType status = PutXWindowPropertyValue (DisplayPtrX display,
WindowX window, PropertyHandleX property,
unsigned int numberofItems, int mode,
void *propertyValue);
Purpose
This function stores the supplied value with the property on the window.
To store a single property item, you can use the function PutXWindowPropertyItem.
Parameters
Input
display
DisplayPtrX
window
WindowX
property
PropertyHandleX
numberofItems
unsigned integer
mode
integer
propertyValue
generic pointer
9-29
X Property Library
Chapter 9
Return Values
The return value indicates the success or failure status of the function call. A negative value
indicates an error. The following table shows status values.
NoXErr
InvalidParamXErr
InvalidDisplayXErr
InvalidWindowXErr
InvalidPropertyXErr
TypeMismatchXErr
UnitMismatchXErr
OverflowXErr
InsuffMemXErr
GeneralXErr
BrokenConnectionXErr -21 The connection to the X server was broken. This occurs if
the remote server terminated.
Parameter Discussion
display must either be the predefined value CVIXDisplay or be the value returned by
ConnectToXDisplay. Use CVIXDisplay if the window is on the same display used by
LabWindows/CVI.
For the window parameter, use CVIXRootWindow to access the default root window of the
display used by LabWindows/CVI. Use CVIXHiddenWindow to access the hidden window
associated with your application.
9-30
Chapter 9
X Property Library
RemoveXWindowProperty
PropLibXErrType status = RemoveXWindowProperty (DisplayPtrX display,
WindowX window,
PropertyHandleX property);
Purpose
Remove the property from a window.
This function deletes the property value and removes the property from the window.
Parameters
Input
display
DisplayPtrX
window
WindowX
property
9-31
X Property Library
Chapter 9
Return Values
The return value indicates the success or failure status of the function call. A negative value
indicates an error. The following table shows status values.
NoXErr
InvalidParamXErr
InvalidDisplayXErr
InvalidWindowXErr
InvalidPropertyXErr
InsuffMemXErr
BrokenConnectionXErr -21 The connection to the X server was broken. This occurs if
the remote server terminated.
Parameter Discussion
display must either be the predefined value CVIXDisplay or be the value returned by
ConnectToXDisplay. Use CVIXDisplay if the window is on the same display used by
LabWindows/CVI.
For the window parameter, use CVIXRootWindow to access the default root window of the
display used by LabWindows/CVI. Use CVIXHiddenWindow to access the hidden window
associated with your application.
See Also
Refer to the Xlib Programming Manual or to XlibC Language X Interface, MIT X Consortium
Standard for more information about the XDeleteProperty function.
9-32
Chapter 9
X Property Library
UninstallXPropertyCallback
PropLibXErrType status = UninstallXPropertyCallback
(PropertyCallbackTypeX *callbackFunction);
Purpose
Uninstall a property callback function.
After a callback function is uninstalled, it is no longer called when properties change. All
property callback functions are automatically uninstalled when the program terminates.
Note: Although you cannot selectively uninstall certain properties or windows associated
with a callback function, you can reinstall a callback function with a new set of
windows and properties using InstallXPropertyCallback.
Parameters
Input callbackFunction PropertyCallbackTypeX* The function that was installed with
InstallXPropertyCallback.
Return Values
The return value indicates the success or failure status of the function call. A negative value
indicates an error. The following table shows status values.
NoXErr
InvalidCallbackXErr
_____________________________________________________________________________
9-33
Chapter 10
Easy I/O for DAQ Library
This chapter describes the functions in the Easy I/O for DAQ Library. The Easy I/O for DAQ
Library Function Overview section contains general information about the functions, and
guidelines and restrictions you should know when using the Easy I/O for DAQ Library. The Easy
I/O for DAQ Library Function Reference section contains an alphabetical list of function
descriptions.
10-1
Chapter 10
The Easy I/O for DAQ functions are device independent which means that you can use the same
function on a Lab series board, an MIO board, an EISA-A2000 or SCXI module.
AISampleChannel
AISampleChannels
AIAcquireWaveforms
AIAcquireTriggeredWaveforms
AIStartAcquisition
AICheckAcquisition
AIReadAcquisition
AIClearAcquisition
PlotLastAIWaveformsPopup
AOUpdateChannel
AOUpdateChannels
AOGenerateWaveforms
AOCheckWaveforms
AOClearWaveforms
(continues)
10-2
Chapter 10
ReadFromDigitalLine
ReadFromDigitalPort
WriteToDigitalLine
WriteToDigitalPort
CounterMeasureFrequency
CounterEventOrTimeConfig
ContinuousPulseGenConfig
DelayedPulseGenConfig
FrequencyDividerConfig
PulseWidthOrPeriodMeasConfig
CounterStart
CounterRead
CounterStop
ICounterControl
GetDAQErrorString
GetNumChannels
GetChannelIndices
GetChannelNameFromIndex
GetAILimitsOfChannel
GroupByChannel
SetEasyIOMultitaskingMode
The Analog Input function class contains all of the functions that perform A/D conversions.
The Asynchronous Acquisition function class contains all of the functions that perform
asynchronous (background) A/D conversions.
The Analog Output function class contains all of the functions that perform D/A
conversions.
The Digital Input/Output function class contains all of the functions that perform digital
input and output operations.
The Counter/Timer function class contains all of the functions that perform counting and
timing operations.
The Miscellaneous function class contains functions that do not fit into the other categories,
but are useful when writing programs using the Easy I/O for DAQ Library.
10-3
Chapter 10
Device Numbers
The first parameter to most of the Easy I/O for DAQ functions is the device number of the DAQ
device you want to use for the given operation. After you have followed the installation and
configuration instructions in Chapter 1, Introduction to NI-DAQ, of the NI-DAQ User Manual
for PC Compatibles, the configuration utility displays the device number for each device you
have installed in the system. You can use the configuration utility to verify your device numbers.
You can use multiple DAQ devices in one application; to do so, simply pass the appropriate
device number to each function.
If you are using an MIO board, NEC-AI-16E-4, or NEC-AI-16XE-50, list the channels in
the order in which they are to be read, as in the following example:
"0,2,5"
"0:3"
To sample a single AMUX-64T channel, you must also specify the number of the AMUX64T board, as in the following example:
"AM1!3" /* samples channel 3 on AMUX-64T board 1
"AM4!8" /* samples channel 8 on AMUX-64T board 4
10-4
*/
*/
Chapter 10
SCXI channel ranges cannot cross module boundaries. SCXI channel ranges must always
increase in channel number.
The following examples of the SCXI channel syntax introduce the special SCXI channels:
"OB0!SCx!MDy!MTEMP"
/* The temperature sensor configured in MTEMP mode
on the multiplexed module in slot y of the chassis with ID x. */
"OB1!SCx!MDy!DTEMP"
/* The temperature sensor configured in DTEMP mode
on the parallel module in slot y of the chassis with ID x. */
"OB0!SCx!MDy!CALGND" /* (SCXI-1100 and SCXI-1122 only) The grounded
amplifier of the module in slot y of the chassis with ID x. */
"OB0!SCx!MDy!SHUNT0" /* (SCXI-1121, SCXI-1122 and SCXI-1321 only) Channel
0 of the module in slot y of the chassis with ID x, with the shunt resistor
applied. */
"OB0!SCx!MDy!SHUNT0:3" /* (SCXI-1121, SCXI-1122 and SCXI-1321 only) Channel
0 through 3 of the module in slot y of the chassis with ID x, with the
shunt resistors applied at each channel. */
10-5
Chapter 10
Command Strings
You can use command strings within the Channel String to set per-channel limits and an
interchannel sample rate. For example,
"cmd hi 10.0 low -10.0; 7:4; cmd hi 5.0 low -5.0; 3:0"
specifies that channels 7 through 4 should be scanned with limits of +/- 10.0 volts and
channels 3 through 0 should be scanned with limits of +/- 5.0 volts. As you view the
Channel String from left to right, when a high/low limit command is encountered, those limits
are assigned to the following channels until the next high/low limit command is encountered.
The High Limit and Low Limit parameters to AISampleChannels are the initial high/low
limits. These parameters can be thought of as the left-most high/low limit command.
The following Channel String,
"cmd interChannelRate 1000.0; 0:3"
specifies that channels 0 through 3 should be sampled at 1000.0 Hz, in other words, there should
be 1/1000.0 = 1ms of delay between each channel. If you do not set an interchannel sample rate,
the channels are sampled as fast as possible for your hardware to achieve pseudo simultaneous
scanning.
The syntax for the command string can be described using the following guide:
;|<LF> means you may use either ; or <LF> to separate command strings from channel
strings
The syntax for the initial command string that appears before any channels are specified is:
"cmd [interChannelRate <number>[!]] [hi <number> [!]low <number>[!]];|<LF>"
The syntax for command strings that appear after any channels are specified is:
";|<LF> cmd hi <number>[!] low <number>[!] ;|<LF>"
10-6
Chapter 10
If you are using a DAQ device without SCXI, list the channels to be driven, as in the
following example:
"0,2,5"
"0:3"
If you are using SCXI, you can address SCXI channels when you attach one or more SCXI
chassis to a plug-in data acquisition board.
SCXI channel ranges cannot cross module boundaries. SCXI channel ranges must always
increase in channel number.
Valid Counters
DAQ-STC Devices
0 and 1
1, 2, and 5
PC-TIO-10
1 through 10
EISA-A2000
10-7
Chapter 10
AIAcquireTriggeredWaveforms
short error = AIAcquireTriggeredWaveforms (short device, char channelString[],
long numberOfScans,
double scansPerSecond,
double highLimitVolts,
double lowLimitVolts,
double *actualScanRate,
unsigned short triggerType,
unsigned short edgeSlope,
double triggerLevelV,
char triggerSource[],
long pretriggerScans,
double timeLimitsec,
short fillMode, double waveforms[]);
Purpose
This function performs a timed acquisition of voltage data from the analog channels specified in
the channelString. The acquisition does not start until the trigger conditions are satisfied.
If you have an E Series DAQ device, you can select Equivalent Time Sampling for the Trigger
Type to sample repetitive waveforms at up to 20 MHz. See the help for the Trigger Type
parameter for details.
10-8
Chapter 10
Parameters
Input
Output
device
short integer
channelString
string
numberOfScans
long integer
scansPerSecond
double
highLimitVolts
double
lowLimitVolts
double
triggerType
unsigned
short integer
edgeSlope
unsigned
short integer
triggerLevelV
double
triggerSource
string
pretriggerScans
long integer
timeLimitsec
double
fillMode
short integer
actualScanRate
double
waveforms
double array
short integer
Return Value
error
10-9
Chapter 10
Parameter Discussion
channelString is the analog input channels that are to be sampled. Refer to the Channel String
for Analog Input Functions subsection of the Easy I/O for DAQ Library Function Overview
section of this chapter for the syntax of this string.
triggerType is the trigger type. The trigger types are:
Hardware Analog Trigger:
Digital Trigger A:
Digital Triggers A & B:
Scan Clock Gating:
Software Analog Trigger:
Equivalent Time Sampling
HW_ANALOG_TRIGGER
DIGITAL_TRIGGER_A
DIGITAL_TRIGGER_AB
SCAN_CLOCK_GATING
SW_ANALOG_TRIGGER
ETS_TRIGGER
If you choose Hardware or Software Analog Trigger, data is retrieved after the analog
triggering parameters have been satisfied. Be sure that the Trigger Source is one of the
channels listed in the channel string. Hardware triggering is more accurate than software
triggering, but it is not available on all boards.
If you choose Scan Clock Gating, an external signal gates the scan clock on and off. If the
scan clock gate becomes FALSE, the current scan completes, and the scan clock ceases
operation. When the scan clock gate becomes TRUE, the scan clock immediately begins
operation again.
If you choose Equivalent Time Sampling: This is a mode in which the Equivalent Time
Sampling technique is used on an E Series DAQ device to achieve an effective acquisition
rate of up to 20 MHz.
The signal that is being measured must be a periodic waveform.
The trigger conditions must be satisfied or this function times out.
Equivalent Time Sampling is the process of taking A/D conversions from a periodic
waveform at special points in time such that when the A/D conversions are placed sideby-side, they represent the original waveform as if it had been sampled at a high
frequency.
10-10
Chapter 10
For example, if the A/D conversions (represented by x's) on the waveform shown below are
placed side-by-side, they represent one cycle of the waveform.
_
_
_
x
_
_
_
/ \
/ \
x \
/ \
/ x
/ \
/ \
/
\
x
\
/
\
/
\
/
\
/
x
/
\
x
\_/
\_/
\_/
\_/
\_/
\_/
x_/
x
x x
x
x
x
x
10-11
Chapter 10
When the A/D conversions are placed side-by-side, they represent the original waveform as if it
had been sampled at a high frequency.
x
x x
x
x
x
x
edgeSlope specifies whether the trigger occurs when the trigger signal voltage is leading
(POSITIVE_SLOPE) or trailing (NEGATIVE_SLOPE).
triggerLevelV the voltage at which the trigger is to occur. triggerLevelV is valid only when the
Trigger Type is hardware or software analog trigger.
triggerSource specifies which channel is the trigger source. triggerSource must be one of the
channels listed in the channelString. Or if you pass "" or NUL, the first channel in the
channelString is used as the triggerSource. triggerSource is valid only when the Trigger Type
is hardware or software analog trigger.
timeLimitsec is the maximum length of time in seconds to wait for the data. If the time you set
expires, the function returns a timeout error (timeOutErr = -10800).
Other Values:
-2.0 disables the time limit.
Warning:
This setting leaves your computer in a suspended state until the trigger
condition occurs.
-1.0 (default) lets the function calculate the timeout based on the acquisition rate and number
of scans requested.
fillMode specifies whether the waveforms array is grouped by channels or grouped by scans.
Consider the following examples:
If you scan channels A through C and Number of Scans is 5, then the possible fill modes are:
GROUP_BY_CHANNEL
A1 A2 A3 A4 A5 B1 B2 B3 B4 B5 C1 C2 C3 C4 C5
\----------/
\----------/
\----------/
or
GROUP_BY_SCAN
A1 B1 C1 A2 B2 C2 A3 B3 C3 A4 B4 C4 A5 B5 C5
\----/
\----/
\----/
\----/
\----/
If you are to pass the array to a graph, you should acquire the data grouped by channel.
If you are to pass the array to a strip chart, you should acquire the data grouped by scan.
You can also acquire the data grouped by scan and later reorder it to be grouped by channel
using the GroupByChannel function.
10-12
Chapter 10
waveforms is an array containing the voltages acquired on the channels specified in the
channelString. The acquired voltages are placed into the array in the order specified by
fillMode. This array must be declared as large as:
(number of channels) * (numberOfScans)
You can determine the number of channels using the GetNumChannels function.
AIAcquireWaveforms
short error = AIAcquireWaveforms (short device, char channelString[],
long numberOfScans, double scansPerSecond,
double highLimitVolts, double lowLimitVolts,
double *actualScanRate, short fillMode,
double waveforms[]);
Purpose
This function performs a timed acquisition of voltage data from the analog channels specified in
the channelString.
Parameters
Input
Output
device
short
integer
channelString
string
numberOfScans
long
integer
scansPerSecond
double
highLimitVolts
double
lowLimitVolts
double
fillMode
short
integer
actualScanRate
double
The actual scan rate may differ slightly from the scan
rate you specified, given the limitations of your
particular DAQ device.
waveforms
double
array
10-13
Chapter 10
Return Value
error
short
integer
Parameter Discussion
channelString is the analog input channels that are to be sampled. Refer to the Channel String
for Analog Input Functions subsection of the Easy I/O for DAQ Library Function Overview
section of this chapter for the syntax of this string.
fillMode specifies whether the waveforms array is grouped by channels or grouped by scans.
Consider the following examples:
If you scan channels A through C and Number of Scans is 5, then the possible fill modes are:
GROUP_BY_CHANNEL
A1 A2 A3 A4 A5 B1 B2 B3 B4 B5 C1 C2 C3 C4 C5
\----------/
\----------/
\----------/
or
GROUP_BY_SCAN
A1 B1 C1 A2 B2 C2 A3 B3 C3 A4 B4 C4 A5 B5 C5
\----/
\----/
\----/
\----/
\----/
If you are to pass the array to a graph, you should acquire the data grouped by channel.
If you are to pass the array to a strip chart, you should acquire the data grouped by scan.
You can also acquire the data grouped by scan and later reorder it to be grouped by channel
using the GroupByChannel function.
waveforms is an array containing the voltages acquired on the channels specified in the
channelString. The acquired voltages is placed into the array in the order specified by fillMode.
This array must be declared as large as:
(number of channels) * (numberOfScans)
You can determine number of channels using the function GetNumChannels.
10-14
Chapter 10
AICheckAcquisition
short error = AICheckAcquisition (unsigned long taskID,
unsigned long *scanBacklog);
Purpose
This function can be used to determine the backlog of scans that have been acquired into the
circular buffer but have not been read using AIReadAcquisition.
If AIReadAcquisition is called with read mode set to LATEST_MODE, scanBacklog is
reset to zero.
Parameters
Input
taskID
unsigned
long integer
Output
scanBacklog
unsigned
long integer
Return Value
short integer
error
AIClearAcquisition
short error = AIClearAcquisition (unsigned long taskID);
Purpose
This function clears the current asynchronous acquisition that was started by
AIStartAcquisition.
Parameters
Input
unsigned
long integer
taskID
Return Value
error
short integer
10-15
Chapter 10
AIReadAcquisition
short error = AIReadAcquisition (unsigned long taskID, long scanstoRead,
unsigned short readMode,
unsigned long *scanBacklog,
short fillMode, double waveforms[]);
Purpose
This function reads the specified number of scans from the internal circular buffer established by
AIStartAcquisition.
If the specified number of scans is not available in the buffer, the function waits until the scans
are available. You can call AICheckAcquisition before calling AIReadAcquisition to
determine how many scans are available.
Parameters
Input
Output
taskID
unsigned long
integer
scanstoRead
long integer
readMode
unsigned
short integer
fillMode
short integer
scanBacklog
unsigned long
integer
waveforms
double array
short integer
Return Value
error
Parameter Discussion
readMode specifies whether scans are read from the circular buffer in CONSECUTIVE_MODE or
LATEST_MODE. In CONSECUTIVE_MODE scans are read from the internal circular buffer
starting from the last scan that was read. Using this mode, you are guaranteed that you will not
lose data unless an error occurs. In LATEST_MODE the most recently acquired n scans are read
10-16
Chapter 10
AISampleChannel
short error = AISampleChannel (short device, char singleChannel[],
double highLimitVolts, double lowLimitVolts,
double *voltage);
Purpose
This function acquires a single voltage from a single analog input channel.
Parameters
Input
Output
device
short integer
singleChannel
string
highLimitVolts
double
lowLimitVolts
double
voltage
double
(passed by
reference)
short integer
Return Value
error
10-17
Chapter 10
Parameter Discussion
singleChannel is the analog input channel that is to be sampled. See the Channel String for
Analog Input Functions subsection of the Easy I/O for DAQ Library Function Overview section
in this chapter for the syntax of this string.
AISampleChannels
short error = AISampleChannels (short device, char channelString[],
double highLimitVolts, double lowLimitVolts,
double voltageArray[]);
Purpose
This function performs a single scan on a set of analog input channels.
Parameters
Input
device
short
integer
channelString
string
highLimitVolts
double
lowLimitVolts
double
double
array
short
integer
Output voltageArray
Return Value
error
Parameter Discussion
channelString is the analog input channels that are to be sampled. Refer to the Channel String
for Analog Input Functions subsection of the Easy I/O for DAQ Library Function Overview
section of this chapter for the syntax of this string.
voltageArray is an array containing the voltages acquired on the channels specified in the
channelString. The acquired voltages are placed into the array in the order specified in the
channelString. This array must be declared as large as the number of channels specified in the
channelString. You can use the function GetNumChannels to determine the number of
channels.
10-18
Chapter 10
AIStartAcquisition
short error = AIStartAcquisition (short device, char channelString[],
int bufferSize, double scansPerSecond,
double highLimitVolts, double lowLimitVolts,
double *actualScanRate,
unsigned long *taskID);
Purpose
This function starts a continuous asynchronous acquisition on the analog input channels specified
in the channelString. Data is acquired into an internal circular buffer. Use
AIReadAcquisition to retrieve scans from the internal buffer.
Parameters
Input
Output
device
short integer
channelString
string
bufferSize
integer
scansPerSecond
double
highLimitVolts
double
lowLimitVolts
double
actualScanRate
double
taskID
unsigned
long integer
short integer
Return Value
error
Parameter Discussion
channelString is the analog input channels that are to be sampled. Refer to the Channel String
for Analog Input Functions subsection of the Easy I/O for DAQ Library Function Overview
section of this chapter for the syntax of this string.
taskID is an identifier for the asynchronous acquisition that must be passed to
AICheckAcquisition
AIReadAcquisition
AIClearAcquisition
10-19
Chapter 10
AOClearWaveforms
short error = AOClearWaveforms (unsigned long taskID);
Purpose
This function clears the waveforms generated by AOGenerateWaveforms when you passed 0
for its Iterations parameter.
Parameters
Input
taskID
unsigned
long integer
Return Value
error
10-20
Chapter 10
AOGenerateWaveforms
short error = AOGenerateWaveforms (short device, char channelString[],
double updatesPerSecond,
int updatesPerChannel, int iterations,
double waveforms[],
unsigned long *taskID);
Purpose
This function generates a timed waveform of voltage data on the analog output channels
specified in the channelString.
Parameters
Input
Output
device
channelString
string
updatesPerSecond
double
updatesPerChannel
integer
iterations
integer
waveforms
taskID
unsigned
long integer
Return Value
error
Parameter Discussion
channelString is the analog output channels to which the voltages are applied. Refer to the
Channel String for Analog Output Functions subsection of the Easy I/O for DAQ Library
Function Overview section of this chapter for the syntax of this string.
10-21
Chapter 10
updatesPerChannel is the number of D/A conversions that compose a waveform for a particular
channel. If updatesPerChannel is 10, then each waveform is composed of 10 elements from the
waveforms array.
iterations is the number of waveform iterations that are performed before the operation is
complete. If you pass 0, the waveform(s) are generated continuously and you need to call
AOClearWaveforms to clear waveform generation.
waveforms is the array containing the voltages to be applied to the channels specified in the
channelString. The voltages are applied to the analog output channels in the order specified in
the channelString. For example, if the channelString is
"0:3,5",
the array should contain the voltages in the following order:
waveforms[0]
waveforms[1]
waveforms[2]
waveforms[3]
waveforms[4]
waveforms[5]
waveforms[6]
waveforms[7]
waveforms[8]
waveforms[9]
.
.
.
waveforms[n-5]
waveforms[n-4]
waveforms[n-3]
waveforms[n-2]
waveforms[n-1]
/*
/*
/*
/*
/*
/*
/*
/*
/*
/*
the
the
the
the
the
the
the
the
the
the
1st
1st
1st
1st
1st
2nd
2nd
2nd
2nd
2nd
/*
/*
/*
/*
/*
the
the
the
the
the
last
last
last
last
last
update
update
update
update
update
update
update
update
update
update
update
update
update
update
update
on
on
on
on
on
on
on
on
on
on
on
on
on
on
on
channel
channel
channel
channel
channel
channel
channel
channel
channel
channel
channel
channel
channel
channel
channel
0
1
2
3
5
0
1
2
3
5
*/
*/
*/
*/
*/
*/
*/
*/
*/
*/
0
1
2
3
5
*/
*/
*/
*/
*/
AOUpdateChannel
short error = AOUpdateChannel (short device, char singleChannel[],
double voltage);
Purpose
This function applies a specified voltage to a single analog output channel.
10-22
Chapter 10
Parameters
Input
device
short integer
singleChannel
string
voltage
double
short integer
Return Value
error
Parameter Discussion
singleChannel is the analog output channel to which the voltage are applied. Refer to the
Channel String for Analog Output Functions subsection of the Easy I/O for DAQ Library
Function Overview section of this chapter for the syntax of this string.
AOUpdateChannels
short AOUpdateChannels (short device, char channelString[],
double voltageArray[]);
Purpose
This function applies specified voltages to the analog output channel specified in the
channelString.
Parameters
Input
device
short integer
channelString
string
voltageArray
double array
short integer
Return Value
error
10-23
Chapter 10
Parameter Discussion
channelString is the analog output channels to which the voltages are applied. Refer to the
Channel String for Analog Output Functions subsection of the Easy I/O for DAQ Library
Function Overview section of this chapter for the syntax of this string.
voltageArray is the voltages that are applied to the specified analog output channels. This array
should contain the voltages to be applied to the analog output channels in the order that is
specified in the channelString. For example, if the channelString contains:
"0,1,3"
then
voltage[0] = 1.2;
voltage[1] = 2.4;
voltage[2] = 3.6;
ContinuousPulseGenConfig
short error = ContinuousPulseGenConfig (short device, char counter[],
double frequency, double dutyCycle,
unsigned short gateMode,
unsigned short pulsePolarity,
double *actualFrequency,
double *actualDutyCycle,
unsigned long *taskID);
Purpose
Configures a counter to generate a continuous TTL pulse train on its OUT pin.
The signal is created by repeatedly decrementing the counter twice, first for the delay to the pulse
(phase 1), then for the pulse itself (phase 2). The function selects the highest resolution timebase
to achieve the desired characteristics.
You can also call the CounterStart function to gate or trigger the operation with a signal on
the counter's GATE pin.
10-24
Chapter 10
Parameters
Input
Output
device
short
integer
counter
string
frequency
double
dutyCycle
double
gateMode
unsigned
short
integer
pulsePolarity
unsigned
short
integer
actualFrequency
double
actualDutyCycle
double
taskID
unsigned
long
integer
short
integer
Return Value
error
Parameter Discussion
counter is the counter to be used for the counting operation. The valid counters are shown in
Table 10-2, which is found in the Valid Counters for the Counter/Timer Functions subsection of
the Easy I/O for DAQ Library Function Overview section of this chapter.
dutyCycle is the desired ratio of the duration of the pulse phase (phase 2) to the period (phase 1
+ phase 2). The default of 0.5 generates a square wave.
If dutyCycle = 0.0, the function computes the closest achievable duty cycle using a
minimum pulse phase (phase 2) of three timebase cycles.
If dutyCycle = 1.0, the function computes the achievable duty cycle using a minimum delay
phase (phase 1) of three timebase cycles.
10-25
Chapter 10
gateMode specifies how the signal on the counter's GATE pin is used. The options are:
POSITIVE_POLARITYthe delay (phase 1) is a low TTL level and the pulse (phase 2) is a
high level.
NEGATIVE_POLARITYthe delay (phase 1) is a high TTL level and the pulse (phase 2) is
a low level.
CounterEventOrTimeConfig
short error = CounterEventOrTimeConfig (short device, char counter[],
unsigned short counterSize,
double sourceTimebase,
unsigned short countLimitAction,
short sourceEdge,
unsigned short gateMode,
unsigned long *taskID);
Purpose
Configures one or two counters to count edges in the signal on the specified counter's SOURCE
pin or the number of cycles of a specified internal timebase signal.
When you use this function with the internal timebase and in conjunction with CounterStart
and CounterRead your program can make more precise timing measurements than with the
Timer function.
You can also call the CounterStart function to gate or trigger the operation with a signal on
the counter's GATE pin.
10-26
Chapter 10
Parameters
Input
Output
device
short
integer
counter
string
counterSize
unsigned
short
integer
sourceTimebase
double
countLimitAction
unsigned
short
integer
sourceEdge
short
integer
gateMode
unsigned
short
integer
taskID
unsigned
long
integer
short
integer
Return Value
error
Parameter Discussion
counter is the counter to be used for the counting operation. The valid counters are shown in
Table 10-2, which is found in the Valid Counters for the Counter/Timer Functions subsection of
the Easy I/O for DAQ Library Function Overview section of this chapter.
counterSize determines the size of the counter used to perform the operation.
10-27
Chapter 10
If you use TWO_COUNTERS, counter+1 is cascaded with the specified counter. Counter+1 is
defined as shown in Table 10-3.
Table 10-3. Definition of Am 9513: Counter +1
counter
counter+1
10
10
sourceTimebase determines whether the counter uses its SOURCE pin or an internal timebase
as its signal source. Pass USE_COUNTER_SOURCE to count TTL edges at counters SOURCE
pin, or pass a valid internal timebase frequency to count the TTL edges of an internal clock.
Valid internal timebase frequencies are:
1000000
100000
10000
1000
100
20000000
100000
(Am9513)
(Am9513)
(Am9513)
(Am9513)
(Am9513)
(DAQ-STC)
(DAQ-STC)
countLimitAction is the action to take when the counter reaches terminal count. The parameter
accepts the following attributes:
COUNT_UNTIL_TCcount until terminal count, and set the overflow status when it is
reached. This mode is not available on the DAQ-STC.
10-28
Chapter 10
sourceEdge is the edge of the counter source or timebase signal on which it increments, and this
parameter accepts the following attributes:
COUNT_ON_RISING_EDGE
COUNT_ON_FALLING_EDGE
gateMode specifies how the signal on the counter's GATE pin is used. The options are:
CounterMeasureFrequency
short error = CounterMeasureFrequency (short device, char counter[],
unsigned short counterSize,
double gateWidthSampleTimeinSec,
double maxDelayBeforeGateSec,
unsigned short counterMinus1GateMode,
double *actualGateWidthSec,
short *overflow, short *valid,
short *timeout, double *frequency);
Purpose
Measures the frequency of a TTL signal on the specified counter's SOURCE pin by counting
rising edges of the signal during a specified period of time. In addition to this connection, you
must also wire the counter's GATE pin to the OUT pin of counter-1. For a specified Counter,
Counter-1 and Counter+1 are defined as shown in Table 10-4.
10-29
Chapter 10
counter
counter+1
10
10
10
counter-1
counter
counter+1
DAQ-STC
This function is useful for relatively high frequency signals when many cycles of the signal occur
during the timing period. Use the PulseWidthOrPeriodMeasConfig function for
relatively low frequency signals. Keep in mind that
period = 1/frequency
This function configures the specified counter and counter+1 (optional) as event counters to
count rising edges of the signal on counter's SOURCE pin. The function also configures
counter-1 to generate a minimum-delayed pulse to gate the event counter, starts the event
counter and then the gate counter, waits the expected gate period, and then reads the gate
counter until its output state is low. Next the function reads the event counter and computes the
signal frequency (number of events/actual gate pulse width) and stops the counters. You can
optionally gate or trigger the operation with a signal on counter-1's GATE pin.
10-30
Chapter 10
Parameters
Input
Output
device
short
integer
counter
string
counterSize
unsigned
short
integer
gateWidthSampleTimeinSec double
maxDelayBeforeGateSec
double
counterMinus1GateMode
unsigned
short
integer
actualGateWidthSec
double
overflow
short
integer
valid
short
integer
timeout
short
integer
frequency
double
10-31
Chapter 10
Return Value
short
integer
error
Parameter Discussion
counter is the counter to be used for the counting operation. The valid counters are shown in
Table 10-2, which is found in the Valid Counters for the Counter/Timer Functions subsection of
the Easy I/O for DAQ Library Function Overview section of this chapter.
counterSize determines the size of the counter used to perform the operation.
If you use TWO_COUNTERS, counter+1 is cascaded with the specified counter. counter+1 is
defined as shown in Table 10-3 in the function description for
CounterEventOrTimeConfig.
counterMinus1GateMode is the gate mode for counter-1. The possible values are:
UNGATED_SOFTWARE_START
COUNT_WHILE_GATE_HIGH
COUNT_WHILE_GATE_LOW
START_COUNTING_ON_RISING_EDGE
counter-1 is used to gate counter so that rising edges are counted over a precise sample time.
For a specified counter, counter-1 is defined as shown in Table 10-4.
CounterRead
short error = CounterRead
Purpose
Reads the counter identified by taskID.
10-32
Chapter 10
Parameters
Input
taskID
unsigned long
integer
Output
overflow
short integer
count
long integer
short integer
Return Value
error
Parameter Discussion
overflow indicates whether the counter rolled over past its terminal count. If overflow is 1, the
value of count is inaccurate.
CounterStart
short error = CounterStart (unsigned long taskID);
Purpose
Starts the counter identified by taskID.
Parameters
Input
taskID
unsigned
long integer
short integer
Return Value
error
10-33
Chapter 10
CounterStop
short error = CounterStop (unsigned long taskID);
Purpose
Stops a count operation immediately.
Parameters
Input
taskID
unsigned
long integer
Return Value
error
DelayedPulseGenConfig
short error = DelayedPulseGenConfig (short device, char counter[],
double pulseDelay, double pulseWidth,
unsigned short timebaseSource,
unsigned short gateMode,
unsigned short pulsePolarity,
double *actualDelay,
double *actualPulseWidth,
unsigned long *taskID);
Purpose
Configures a counter to generate a delayed TTL pulse or triggered pulse train on its OUT pin.
The signal is created by decrementing the counter twice, first for the delay to the pulse (phase 1),
then for the pulse itself (phase 2). The function selects the highest resolution timebase to achieve
the desired characteristics.
You can also call the CounterStart function to gate or trigger the operation with a signal on
the counter's GATE pin.
10-34
Chapter 10
Parameters
Input
Output
device
short integer
counter
string
pulseDelay
double
pulseWidth
double
timebaseSource
unsigned short
integer
gateMode
unsigned short
integer
pulsePolarity
unsigned short
integer
actualDelay
double
actualPulseWidth
double
taskID
unsigned long
integer
short integer
Return Value
error
Parameter Discussion
counter is the counter to be used for the counting operation. The valid counters are shown in
Table 10-2, which is found in the Valid Counters for the Counter/Timer Functions subsection of
the Easy I/O for DAQ Library Function Overview section of this chapter.
pulseDelay is the desired duration of the delay (phase 1) before the pulse. This parameter accepts
the following attributes:
If pulseDelay = 0.0 and timebaseSource is internal, the function selects a minimum delay of
three cycles of the timebase used.
10-35
Chapter 10
pulseWidth is the desired duration of the pulse (phase 2) after the delay
If pulseDelay = 0.0 and timebaseSource is internal, the function selects a minimum delay of
three cycles of the timebase used.
timebaseSource is the signal that causes the counter to count. This parameter accepts the
following attributes:
USE_COUNTER_SOURCEThe signal on the counter's SOURCE pin is used and the units
of pulse delay and width are cycles of that signal.
gateMode specifies how the signal on the counter's GATE pin is used. This parameter accepts
the following attributes:
pulsePolarity is the polarity of phase 2 of each cycle. This parameter accepts the following
attributes:
POSITIVE_POLARITYthe delay (phase 1) is a low TTL level and the pulse (phase 2) is a
high level.
NEGATIVE_POLARITYthe delay (phase 1) is a high TTL level and the pulse (phase 2) is
a low level.
10-36
Chapter 10
FrequencyDividerConfig
short error = FrequencyDividerConfig (short device, char counter[],
double sourceTimebase,
double timebaseDivisor,
unsigned short gateMode,
unsigned short outputBehavior,
short sourceEdge, unsigned long *taskID);
Purpose
This function configures the specified counter to count the number of signal transitions on its
SOURCE pin or on an internal timebase signal, and to strobe or toggle the signal on its OUT pin.
To divide an external TTL signal, connect it to counter's SOURCE pin, and set the
sourceTimebase parameter to USE_COUNTER_SOURCE.
To divide an internal timebase signal, set the sourceTimebase parameter to a desired valid
frequency.
Set the timebaseDivisor to the desired value. For a value of N and a pulsed output, an output
pulse equal to the period of the source or timebase signal appears on counter's OUT pin once
each N cycles of that signal. For a toggled output, the output toggles after each N cycles. The
toggled output frequency is thus half that of the pulsed output, in other words,
pulsedFrequency = sourceFrequency/N
and
toggledFrequency = sourceFrequency/(2*N)
thus, if N=3, the OUT pin would generate pulses as follows:
_
_
_
_
_
_
_
_
_
_
_
_
_| |_| |_| |_| |_| |_| |_| |_| |_| |_| |_| |_| |
___
___
___
___
pulsed _|
|_______|
|_______|
|_______|
|______
___________
___________
toggled _|
|___________|
|_________
source
10-37
Chapter 10
Parameters
Input
Output
device
short integer
counter
string
sourceTimebase
double
timebaseDivisor
double
gateMode
unsigned
short integer
outputBehavior
unsigned
short integer
sourceEdge
short integer
taskID
unsigned
long integer
Return Value
short integer Refer to error codes in Table 10-5.
error
Parameter Discussion
counter is the counter to be used for the counting operation. The valid counters are shown in
Table 10-2, which is found in the Valid Counters for the Counter/Timer Functions subsection of
the Easy I/O for DAQ Library Function Overview section of this chapter.
sourceTimebase determines whether the counter uses its SOURCE pin or an internal timebase
as its signal source. Pass USE_COUNTER_SOURCE to count TTL edges at counters SOURCE
pin, or pass a valid internal timebase frequency to count the TTL edges of an internal clock.
Valid internal timebase frequencies are:
1000000
100000
10000
1000
100
20000000
100000
(Am9513)
(Am9513)
(Am9513)
(Am9513)
(Am9513)
(DAQ-STC)
(DAQ-STC)
10-38
Chapter 10
timebaseDivisor is the source frequency divisor. For example, if the source signal is 1000 Hz,
the timebaseDivisor is 10, and the output is pulsed, the frequency of the counter's OUT signal is
100 Hz. If the output is toggled, the frequency is 50 Hz.
gateMode specifies how the signal on the counter's GATE pin is used. This parameter accepts
the following attributes:
outputBehavior is the behavior of the output signal when counter reaches terminal count. This
parameter accepts the following attributes:
For a Timebase Divisor of N and a pulsed output, an output pulse equal to the period of the
source or timebase signal appears on counter's OUT pin once each N cycles of that signal For a
toggled output, the output toggles after each N cycles. The toggled output frequency is thus half
that of the pulsed output, in other words,
pulsedFrequency = sourceFrequency/ N
and
toggledFrequency = sourceFrequency/(2*N)
thus, if N =3, the OUT pin would generate pulses as follows:
_
_
_
_
_
_
_
_
_
_
_
_
_| |_| |_| |_| |_| |_| |_| |_| |_| |_| |_| |_| |
___
___
___
___
HIGH_PULSE _|
|_______|
|_______|
|_______|
|______
___________
___________
HIGH_TOGGLE _|
|___________|
|_________
source
10-39
Chapter 10
GetAILimitsOfChannel
short error = GetAILimitsOfChannel (short device, char channelString[],
char singleChannel[],
double initialHighLimitVolts,
double initialLowLimitVolts,
double *highLimitVolts,
double *lowLimitVolts);
Purpose
Returns the high and low limits for a particular channel in the channel string.
Parameters
Input
Output
device
short
integer
channelString
string
singleChannel
string
initialHighLimitVolts
double
initialLowLimitVolts
double
highLimitVolts
double
lowLimitVolts
double
short
integer
Return Value
error
Parameter Discussion
channelString is the analog input channels that are to be sampled. Refer to the Channel String
for Analog Input Functions subsection of the Easy I/O for DAQ Library Function Overview
section of this chapter for the syntax of this string.
singleChannel is a single channel of the channel string. For example, if the channel string is
"0:3,5"
a single channel could be
"2" or "5" and so on.
10-40
Chapter 10
initialHighLimitVolts specifies the maximum voltage that is measured for all channels in the
channel string listed before a command string that specifies a new high limit. For the following
channel string:
"0,1; cmd hi 10.0 low -10.0; 2,3"
If initialHighLimitVolts is 5.0, channels "0" and "1" have a high limit of 5.0 and channels
"2" and "3" have a high limit of 10.0.
initialLowLimitVolts is the minimum voltage that is measured for all channels in the channel
string listed before a command string that specifies a new low limit. For the following channel
string:
"0,1; cmd hi 10.0 low -10.0; 2,3"
If the initialLowLimitVolts is -5.0, channels "0" and "1" have a low limit of -5.0 and channels
"2" and "3" have a low limit of -10.0.
GetChannelIndices
short error = GetChannelIndices (short device, char channelString[],
char channelSubString[], short channelType,
long channelIndices[]);
Purpose
Determines the indices of the channels in the channelSubString. For example, if the
channelString is
"1:6"
10-41
Chapter 10
Parameters
Input
Output
device
channelString
string
channelSubString
string
channelType
channelIndices
long integer
array
Return Value
error
Parameter Discussion
channelString is the analog channels that are to be sampled. Refer to the Channel String for
Analog Input Functions subsection of the Easy I/O for DAQ Library Function Overview section
of this chapter for the syntax of this string.
channelSubString is a sub-string of the channelString. For example, if the channelString is
"0:3,5"
GetChannelNameFromIndex
short error = GetChannelNameFromIndex (short device, char channelString[],
long index, short channelType,
char channelName[]);
Purpose
Determines the name of the particular channel in the channelString indicated by index.
10-42
Chapter 10
Parameters
Input
Output
device
short integer
channelString
string
index
long integer
channelType
short integer
channelName
string
short integer
Return Value
error
Parameter Discussion
channelString is the analog channels that are to be sampled. Refer to the Channel String for
Analog Input Functions or Channel String for Analog Output Functions subsection of the Easy
I/O for DAQ Library Function Overview section of this chapter for the syntax of this string.
channelName returns the name of the particular channel in the channelString indicated by
index. This string should be declared to have MAX_CHANNEL_NAME_LENGTH bytes.
GetDAQErrorString
char *errorString = GetDAQErrorString (short errorNumber);
Purpose
This function returns a string containing the description for the numeric error code.
Parameters
Input
errorNumber
short
integer
string
Return Value
errorString
10-43
Chapter 10
GetNumChannels
short error = GetNumChannels (short device, char channelString[],
short channelType,
unsigned long *numberOfChannels);
Purpose
Determines the number of channels contained in the channelString.
You need to know the number of channels in the channelString so that you can interpret (for
analog input) or build (for analog output) waveform arrays correctly.
Parameters
Input
Output
device
short
integer
channelString
string
channelType
short
integer
numberOfChannels
unsigned
long integer
short
integer
Return Value
error
Parameter Discussion
channelString is the analog channels that are to be sampled. Refer to the Channel String for
Analog Input Functions or Channel String for Analog Output Functions subsection of the Easy
I/O for DAQ Library Function Overview section of this chapter for the syntax of this string.
GroupByChannel
short error = GroupByChannel (float array[], long numberOfScans,
unsigned long numberOfChannels);
Purpose
This function can be used to reorder an array of data from "grouped by scan" mode into "grouped
by channel" mode.
10-44
Chapter 10
If you acquire data in "grouped by scan" mode, you need to reorder the array into "grouped by
channel" mode before it can be passed to graph plotting functions, analysis functions, and others.
See the description of the fillMode parameter of AIAcquireWaveforms for an explanation of
"grouped by scan" versus "grouped by channel".
Parameters
Input/ array
Output
double
array
Input
numberOfScans
long integer
numberOfChannels
unsigned
long integer
short integer
Return Value
error
ICounterControl
short error = ICounterControl (short device, short counter, short controlCode,
unsigned short count, short binaryorBCD,
short outputState, unsigned short *readValue);
Purpose
Controls counters on devices that use the 8253 timer chip (Lab boards, SCXI-1200,
DAQPad-1200, PC-LPM-16, DAQCard 700).
10-45
Chapter 10
Parameters
Input
Output
device
short integer
counter
short integer
controlCode
short integer
count
unsigned
short integer
binaryorBCD
short integer
outputState
short integer
readValue
unsigned
short integer
short integer
Return Value
error
Parameter Discussion
controlCode determines the counter's operating mode. This parameter accepts the following
attributes:
0: I_TOGGLE_ON_TCcounter's output becomes low after the mode set operation and the
counter decrements from count to 0 while the gate is high. The output toggles from low to
high once the counter reaches 0.
2: I_RATE_GENERATORcounter's output becomes low for one period of the clock input.
The count indicates the period between output pulses.
10-46
Chapter 10
6: I_READread the counter and return the value in the readValue parameter.
count is the period between output pulses. This parameter accepts the following attributes:
Note: 0 is equivalent to 65,535 in binary counter operation and 10,000 in BCD counter
operation.
PlotLastAIWaveformsPopup
short error = PlotLastAIWaveformsPopup (short device, double waveformsBuffer[]);
Purpose
This function plots the last AI waveform that was acquired. It is intended for demonstration
purposes.
Data must be grouped by channel before it is passed to this function:
Either use the GROUP_BY_CHANNEL as the fillMode parameter when acquiring the data or call
GroupByChannel before calling this function.
Parameters
Input
device
short integer
waveformsBuffer
double array
short integer
Return Value
error
10-47
Chapter 10
PulseWidthOrPeriodMeasConfig
short error = PulseWidthOrPeriodMeasConfig (short device, char counter[],
unsigned short typeOfMeasurement,
double sourceTimebase,
unsigned long *taskID);
Purpose
Configures the specified counter to measure the pulse width or period of a TTL signal connected
to its GATE pin. The measurement is done by counting the number of cycles of the specified
timebase between the appropriate starting and ending events.
Connect the signal you want to measure to the counter's GATE pin.
To measure with an internal timebase, set sourceTimebase to the desired frequency.
To measure with an external timebase, connect that signal to counter's SOURCE pin and set the
sourceTimebase parameter to USE_COUNTER_SOURCE.
Call CounterStart to start the measurement. Then call CounterRead to read the value. A
valid count value is greater than 3 without overflow.
Parameters
Input
device
short
integer
counter
string
typeOfMeasurement unsigned
short
integer
Output
sourceTimebase
double
taskID
unsigned
The reference number assigned for the counter
long integer reserved for this operation. You pass taskID
to CounterStart, CounterRead, and
CounterStop.
Return Value
error
10-48
Chapter 10
Parameter Discussion
typeOfMeasurement identifies the type of pulse width or period measurement to make. This
parameter accepts the following attributes:
sourceTimebase determines whether the counter uses its SOURCE pin or an internal timebase
as its signal source. Pass USE_COUNTER_SOURCE to count TTL edges at counters SOURCE
pin, or pass a valid internal timebase frequency to count the TTL edges of an internal clock.
Valid internal timebase frequencies are:
1000000
100000
10000
1000
100
20000000
100000
(Am9513)
(Am9513)
(Am9513)
(Am9513)
(Am9513)
(DAQ-STC)
(DAQ-STC)
ReadFromDigitalLine
short error = ReadFromDigitalLine (short device, char portNumber[], short line,
short portWidth, long configure,
unsigned long *lineState);
Purpose
Reads the logical state of a digital line on a port that you configure as input.
10-49
Chapter 10
Parameters
Input
Output
device
short integer
portNumber
string
line
short integer
portWidth
short integer
configure
long integer
lineState
unsigned
long integer
Return Value
error
Parameter Discussion
portNumber specifies the digital port this function configures.
portWidth is the total width in bits of the port. For example, you can combine two 4-bit ports
into an 8-bit port on an MIO (non E-Series) board by setting portWidth to 8.
When portWidth is greater than the physical port width of a digital port, the following
restrictions apply. The portWidth must be an integral multiple of the physical port width,
and the port numbers in the combined port must begin with the port named by portNumber
and must increase consecutively. For example, if portNumber is 3 and portWidth is
24(bits), LabWindows/CVI uses ports 3, 4, and 5.
10-50
Chapter 10
The portWidth for the 8255-based digital I/O ports (including all digital ports on Lab
boards, SCXI-1200, DAQPad-1200, DAQCard-1200, DIO-24, DIO-32F, DIO-96, and
AT-MIO-16DE-10/AT-MIO-16D ports 2, 3 and 4) should be at least 8.
When this function is called in a loop, it can be optimized by only configuring the digital port
on the first iteration.
When you configure a digital I/O port that is part of an 8255 PPI (including all digital ports
on Lab boards, SCXI-1200, DAQPad-1200, DAQCard-1200, DIO-24, DIO-32F, DIO-96,
and AT-MIO-16DE-10/AT-MIO-16D ports 2, 3 and 4), the 8255 PPI goes through a
configuration phase, where all the ports within the same PPI chip get reset to logic low,
regardless of the data direction. The data directions on other ports, however, are maintained.
ReadFromDigitalPort
short error = ReadFromDigitalPort (short device, char portNumber[],
short portWidth, long configure,
unsigned long *pattern);
Purpose
Reads a digital port that you configure for input.
Parameters
Input
Output
device
short integer
portNumber
string
line
short integer
portWidth
short integer
configure
long integer
pattern
unsigned
long integer
10-51
Chapter 10
Return Value
error
short integer
Parameter Discussion
portNumber specifies the digital port this function configures.
A portNumber value of 0 signifies port 0, a portNumber of 1 signifies port 1, and so on. If you
use an SCXI-1160, SCXI-1161, SCXI-1162, or SCXI-1163 module, use the
"SCx!MDy!0"
syntax, where x is the chassis ID and y is the module device number, to specify the port on a
module.
portWidth is the total width in bits of the port. For example, you can combine two 4-bit ports
into an 8-bit port on an MIO (non E-Series) board by setting portWidth to 8.
When portWidth is greater than the physical port width of a digital port, the following
restrictions apply. The portWidth must be an integral multiple of the physical port width,
and the port numbers in the combined port must begin with the port named by portNumber
and must increase consecutively. For example, if portNumber is 3 and portWidth is
24(bits), LabWindows/CVI uses ports 3, 4, and 5.
The portWidth for the 8255-based digital I/O ports (including all digital ports on Lab
boards, SCXI-1200, DAQPad-1200, DAQCard-1200, DIO-24, DIO-32F, DIO-96, and
AT-MIO-16DE-10/AT-MIO-16D ports 2, 3 and 4) should be at least 8.
When this function is called in a loop, it can be optimized by only configuring the digital port
on the first iteration.
When you configure a digital I/O port that is part of an 8255 PPI (including all digital ports
on Lab boards, SCXI-1200, DAQPad-1200, DAQCard-1200, DIO-24, DIO-32F, DIO-96,
and AT-MIO-16DE-10/AT-MIO-16D ports 2, 3 and 4), the 8255 PPI goes through a
configuration phase, where all the ports within the same PPI chip get reset to logic low,
regardless of the data direction. The data directions on other ports, however, are maintained.
10-52
Chapter 10
SetEasyIOMultitaskingMode
void SetEasyIOMultitaskingMode (int multitaskingMode);
Purpose
By default, if you call the non-timed Easy I/O for DAQ functions repetitively, these functions do
not reconfigure the hardware unless you change the parameters to the functions. Thus, the
performance of these functions is improved by only reconfiguring the hardware when necessary.
However, if you run multiple data acquisition programs simultaneously, any non-timed Easy I/O
for DAQ functions will not know when the hardware has been reconfigured by another
application accessing the same DAQ device, and the functions will run incorrectly.
To get around this problem, you can force these functions to always reconfigure the hardware by
setting the multitasking mode to MULTITASKING_AWARE.
You should set the multitasking mode to MULTITASK_AWARE if your program calls the nontimed Easy I/O for DAQ functions and you expect another data acquisition program to be
accessing the same board while your program is running. In this mode, the Easy I/O for DAQ
functions always reconfigure the hardware on each invocation, which means they will not be
adversely affected by other applications but they will not be optimized for speed.
You should set the multitasking mode to MULTITASK_UNAWARE if you know there will not be
another program accessing the same DAQ device while your program is running.
Parameters
Input
multitaskingMode
integer
Return Value
None.
WriteToDigitalLine
short error = WriteToDigitalLine (short device, char portNumber[], short line,
short portWidth, long configure,
unsigned long lineState);
Purpose
Sets the output logic state of a digital line on a digital port.
10-53
Chapter 10
Parameters
Input
device
short integer
portNumber
string
line
short integer
portWidth
short integer
configure
long integer
lineState
unsigned long
integer
short integer
Return Value
error
Parameter Discussion
portNumber specifies the digital port this function configures.
A portNumber value of 0 signifies port 0, a portNumber of 1 signifies port 1, and so on. If you
use an SCXI-1160, SCXI-1161, SCXI-1162, or SCXI-1163 module, use the
"SCx!MDy!0"
syntax, where x is the chassis ID and y is the module device number, to specify the port on a
module.
portWidth is the total width in bits of the port. For example, you can combine two 4-bit ports
into an 8-bit port on an MIO (non E-Series) board by setting portWidth to 8.
When portWidth is greater than the physical port width of a digital port, the following
restrictions apply. The portWidth must be an integral multiple of the physical port width,
and the port numbers in the combined port must begin with the port named by portNumber
and must increase consecutively. For example, if portNumber is 3 and portWidth is
24(bits), LabWindows/CVI uses ports 3, 4, and 5.
10-54
Chapter 10
The portWidth for the 8255-based digital I/O ports (including all digital ports on Lab
boards, SCXI-1200, DAQPad-1200, DAQCard-1200, DIO-24, DIO-32F, DIO-96, and
AT-MIO-16DE-10/AT-MIO-16D ports 2, 3 and 4) should be at least 8.
When this function is called in a loop, it can be optimized by only configuring the digital port
on the first iteration.
When you configure a digital I/O port that is part of an 8255 PPI (including all digital ports
on Lab boards, SCXI-1200, DAQPad-1200, DAQCard-1200, DIO-24, DIO-32F, DIO-96,
and AT-MIO-16DE-10/AT-MIO-16D ports 2, 3 and 4), the 8255 PPI goes through a
configuration phase, where all the ports within the same PPI chip get reset to logic low,
regardless of the data direction. The data directions on other ports, however, are maintained.
WriteToDigitalPort
device
short integer
portNumber
string
portWidth
short integer
configure
long integer
pattern
unsigned
long integer
10-55
Chapter 10
Return Value
error
short integer
Parameter Discussion
portNumber specifies the digital port this function configures.
A portNumber value of 0 signifies port 0, a portNumber of 1 signifies port 1, and so on. If you
use an SCXI-1160, SCXI-1161, SCXI-1162, or SCXI-1163 module, use the
"SCx!MDy!0"
syntax, where x is the chassis ID and y is the module device number, to specify the port on a
module.
portWidth is the total width in bits of the port. For example, you can combine two 4-bit ports
into an 8-bit port on an MIO (non E-Series) board by setting portWidth to 8.
When portWidth is greater than the physical port width of a digital port, the following
restrictions apply. The portWidth must be an integral multiple of the physical port width,
and the port numbers in the combined port must begin with the port named by portNumber
and must increase consecutively. For example, if portNumber is 3 and portWidth is
24(bits), LabWindows/CVI uses ports 3, 4, and 5.
The portWidth for the 8255-based digital I/O ports (including all digital ports on Lab
boards, SCXI-1200, DAQPad-1200, DAQCard-1200, DIO-24, DIO-32F, DIO-96, and
AT-MIO-16DE-10/AT-MIO-16D ports 2, 3 and 4) should be at least 8.
When this function is called in a loop, it can be optimized by only configuring the digital port
on the first iteration.
When you configure a digital I/O port that is part of an 8255 PPI (including all digital ports
on Lab boards, SCXI-1200, DAQPad-1200, DAQCard-1200, DIO-24, DIO-32F, DIO-96,
and AT-MIO-16DE-10/AT-MIO-16D ports 2, 3 and 4), the 8255 PPI goes through a
configuration phase, where all the ports within the same PPI chip get reset to logic low,
regardless of the data direction. The data directions on other ports, however, are maintained.
10-56
Chapter 10
Error Conditions
All of the functions in the Easy I/O for DAQ Library return an error code. A negative number
indicates that an error occurred. If the return value is positive, it has the same description as if it
were negative, but it is considered a warning.
Table 10-5. Easy I/O for DAQ Error Codes
0
Success.
-10001 syntaxErr An error was detected in the input string; the arrangement or ordering of
the characters in the string is not consistent with the expected ordering.
-10002 semanticsErr An error was detected in the input string; the syntax of the string is
correct, but certain values specified in the string are inconsistent with other values
specified in the string.
-10003 invalidValueErr The value of a numeric parameter is invalid.
-10004 valueConflictErr The value of a numeric parameter is inconsistent with another
parameter, and the combination is therefore invalid.
-10005 badDeviceErr The device parameter is invalid.
-10006 badLineErr The line parameter is invalid.
-10007 badChanErr A channel is out of range for the device type or input configuration, the
combination of channels is invalid, or you must reverse the scan order so that
channel 0 is last.
-10008 badGroupErr The group parameter is invalid.
-10009 badCounterErr The counter parameter is invalid.
-10010 badCountErr The count parameter is too small or too large for the specified counter.
-10011 badIntervalErr The interval parameter is too small or too large for the associated
counter or I/O channel.
-10012 badRangeErr The analog input or analog output voltage range is invalid for the
specified channel.
-10013 badErrorCodeErr The driver returned an unrecognized or unlisted error code.
-10014 groupTooLargeErr The group size is too large for the device.
-10015 badTimeLimitErr The time limit parameter is invalid.
-10016 badReadCountErr The read count parameter is invalid.
-10017 badReadModeErr The read mode parameter is invalid.
-10018 badReadOffsetErr The offset is unreachable.
(continues)
10-57
Chapter 10
10-58
Chapter 10
10-59
Chapter 10
10-60
Chapter 10
10-61
Chapter 10
10-62
Chapter 10
10-63
Chapter 10
10-64
Chapter 10
10-65
Chapter 10
10-66
Appendix A
Customer Communication
For your convenience, this appendix contains forms to help you gather the information necessary
to help us solve technical problems you might have as well as a form you can use to comment on
the product documentation. Filling out a copy of the Technical Support Form before contacting
National Instruments helps us help you better and faster.
National Instruments provides comprehensive technical assistance around the world. In the U.S.
and Canada, applications engineers are available Monday through Friday from 8:00 a.m. to
6:00 p.m. (central time). In other countries, contact the nearest branch office. You may fax
questions to us at any time.
Electronic Services
Bulletin Board Support
National Instruments has BBS and FTP sites dedicated for 24-hour support with a collection of
files and documents to answer most common customer questions. From these sites, you can also
download the latest instrument drivers, updates, and example programs. For recorded
instructions on how to use the bulletin board and FTP services and for BBS automated
information, call (512) 795-6990. You can access these services at:
France: 1 48 65 15 59
Up to 9,600 baud, 8 data bits, 1 stop bit, no parity
FaxBack Support
FaxBack is a 24-hour information retrieval system containing a library of documents on a wide
range of technical information. You can access FaxBack from a touch-tone telephone at the
following number: (512) 418-1111.
A-1
Customer Communication
Appendix A
FTP Support
To access our FTP site, log on to our Internet host, ftp.natinst.com, as anonymous and use your
Internet address, such as joesmith@anywhere.com, as your password. The support files and
documents are located in the /support directories.
gpib.support@natinst.com
daq.support@natinst.com
vxi.support@natinst.com
lv.support@natinst.com
lw.support@natinst.com
hiq.support@natinst.com
visa.support@natinst.com
lookout.support@natinst.com
Telephone
Australia
Austria
Belgium
Canada (Ontario)
Canada (Quebec)
Denmark
Finland
France
Germany
Hong Kong
Italy
Japan
Korea
Mexico
Netherlands
Norway
Singapore
Spain
Sweden
Switzerland
Taiwan
U.K.
Fax
03 9 879 9422
0662 45 79 90 0
02 757 00 20
519 622 9310
514 694 8521
45 76 26 00
90 527 2321
1 48 14 24 24
089 741 31 30
2645 3186
02 413091
03 5472 2970
02 596 7456
95 800 010 0793
0348 433466
32 84 84 00
2265886
91 640 0085
08 730 49 70
056 200 51 51
02 377 1200
01635 523545
03 9 879 9179
0662 45 79 90 19
02 757 03 11
514 694 4399
45 76 26 02
90 502 2930
1 48 14 24 14
089 714 60 35
2686 8505
02 41309215
03 5472 2977
02 596 7455
5 520 3282
0348 430673
32 84 86 00
2265887
91 640 0533
08 730 43 70
056 200 51 55
02 737 4644
01635 523154
A-2
Phone
Computer brand
Model
Mouse
MHz
yes
no
RAM
)
Processor
MB
Windows NT 3.1,
Display adapter
Brand
Instruments used
National Instruments hardware product model
Revision
Configuration
National Instruments software product
Configuration
The problem is
Windows NT 3.5,
Version
Other Products
Computer Make and Model _____________________________________________________________________
Microprocessor _______________________________________________________________________________
Clock Frequency ______________________________________________________________________________
Type of Video Board Installed ___________________________________________________________________
Operating System _____________________________________________________________________________
Operating System Version ______________________________________________________________________
Operating System Mode ________________________________________________________________________
Programming Language ________________________________________________________________________
Programming Language Version _________________________________________________________________
Other Boards in System ________________________________________________________________________
Base I/O Address of Other Boards ________________________________________________________________
DMA Channels of Other Boards _________________________________________________________________
Interrupt Level of Other Boards __________________________________________________________________
Edition Date:
July 1996
Part Number:
320682C-01
Phone
Glossary
Prefix
Meaning
Value
n-
nano-
10
micro-
10
m-
milli-
10
k-
kilo-
10
M-
mega-
10
-9
-6
-3
3
6
Numbers/Symbols
1D
One-dimensional.
2D
Two-dimensional.
A
A
Analog input.
A/D
Analog-to-digital.
AC
Alternating current.
ADC A/D
converter
ADC resolution
analog trigger
G-1
Glossary
AO
Analog output.
asynchronous
automatic serial
B
B
Bytes.
background
acquisition
bipolar
A signal range that includes both positive and negative values (for
example, -5 V to +5 V).
block-mode
A high-speed data transfer in which the address of the data is sent followed
by a specified number of back-to-back data words.
C
CodeBuilder
cold-junction
compensation
conversion time
The time required, in an analog input or output system, from the moment a
channel is interrogated (such as with a read instruction) to the moment that
accurate data is available.
counter/timer
coupling
G-2
Glossary
D
D/A
Digital-to-analog.
DAC D/A
converter
Data acquisition
DC
Direct current.
device
differential input
digital port
See port.
DIO
Digital I/O.
E
external trigger
A voltage pulse from an external source that triggers an event such as A/D
conversion.
F
FIFO
A first-in first-out memory buffer; the first data stored is the first data sent
to the acceptor.
format string
G-3
Glossary
G
G gain
gender
gender changer
GPIB
group
H
handshaking
Prevents overflow of the input queue that occurs when the receiver is
unable to empty its input queue as quickly as the sender is able to fill it.
The RS-232 Library has two types of handshakingsoftware handshaking,
and hardware handshaking. You should enable one or the other if you want
to ensure that your application program synchronizes its data transfers with
other serial devices that perform handshaking.
Hz
Hertz.
I
I/O
Input/output.
ID
Identification.
IEEE
in.
Inches.
Instrument Library
interrupt
A computer signal indicating that the CPU should suspend its current task
to service a designated activity.
G-4
Glossary
K
KB
Kilobytes of memory.
kS
1,000 samples.
ksamples
1,000 samples.
L
LSB
M
manual scaling
MB
Megabytes of memory.
MIO
Multifunction I/O.
ms
Milliseconds.
mux
N
NI-488 functions
NI-488.2 routines
P
port
postriggering
G-5
Glossary
pretriggering
The technique used on a DAQ board to keep a continuous buffer filled with
data, so that when the trigger conditions are met, the sample includes the
data leading up to the trigger condition.
pts
Points.
R
resolution
RTD
S
s
Seconds.
S/s
Samples per second; used to express the rate at which a DAQ board
samples an analog signal.
Sample-and-Hold
(S/H)
SCXI
self-calibrating
Single-Ended (SE)
Inputs
software trigger
standard libraries
STC System
Timing Controller.
synchronous
G-6
Glossary
T
TC
Terminal count.
throughput rate
transfer rate
U
unipolar
V
V
Volts.
VDC
X
Xmodem functions
Allow you to transfer files using a data transfer protocol. The protocol uses
a generally accepted technique for performing serial file transfers with
error-checking. Files are sent in packets that contain data from the files
plus error-checking and synchronization information.
G-7
Index
Numbers/Symbols
1D array functions. See one-dimensional
array operation functions.
1D complex operation functions. See onedimensional complex operation functions.
2D array functions. See two-dimensional
array operation functions.
* (asterisks) in format specifiers
formatting functions, 2-39
scanning functions, 2-48
A
Abs1D function, 3-4 to 3-5
accessing physical memory. See physical
memory access functions.
accessing window properties. See window
properties, accessing.
Add1D function, 3-5
Add2D function, 3-5 to 3-6
AdviseDDEDataReady function, 6-6 to 6-8
AIAcquireTriggeredWaveforms function,
10-8 to 10-13
AIAcquireWaveforms function, 10-13
to 10-14
AICheckAcquisition function, 10-15
AIClearAcquisition function, 10-15
AIReadAcquisition function, 10-16 to 10-17
AISampleChannel function, 10-17 to 10-18
AISampleChannels function, 10-18
AIStartAcquisition function, 10-19
analog input functions. See also Easy I/O for
DAQ Library.
AIAcquireTriggeredWaveforms, 10-8
to 10-13
AIAcquireWaveforms, 10-33 to 10-34
AISampleChannel, 10-17 to 10-18
AISampleChannels, 10-18
Channel String, 10-4 to 10-5
I-1
Index
I-2
Add1D, 3-5
Add2D, 3-5 to 3-6
Div1D, 3-16 to 3-17
Div2D, 3-17 to 3-18
LinEv1D, 3-21
LinEv2D, 3-22
MaxMin1D, 3-24
MaxMin2D, 3-24 to 3-25
Mul1D, 3-26 to 3-27
Mul2D, 3-27
Neg1D, 3-28
Sub1D, 3-30 to 3-31
Sub2D, 3-31
Subset1D, 3-32
array utility functions
Clear1D, 3-6 to 3-7
Copy1D, 3-7
Set1D, 3-28
ArrayToFile function, 2-4 to 2-6
asterisks (*) in format specifiers
formatting functions, 2-39
scanning functions, 2-48
asynchronous acquisition functions
AICheckAcquisition, 10-15
AIClearAcquisition, 10-15
AIReadAcquisition, 10-16 to 10-17
AIStartAcquisition, 10-19
PlotLastAIWaveformsPopup, 10-47
asynchronous callbacks
notification of SRQ and other GPIB
events, 4-12
restrictions with ibNotify function, 4-20
automatic serial polling
compatibility, 4-8
hardware interrupts, 4-8 to 4-9
purpose and use, 4-7 to 4-8
RQS events
ibInstallCallback function, 4-17
ibNotify function, 4-19
SRQI events
ibInstallCallback function, 4-17
ibNotify function, 4-19
Index
B
Beep function, 8-5
board control functions, GPIB, 4-7
board control functions, GPIB Library, 4-3
break on library error functions
DisableBreakOnLibraryErrors, 8-11
to 8-12
EnableBreakOnLibraryErrors, 8-15
GetBreakOnLibraryErrors, 8-17
GetBreakOnProtectionErrors, 8-18
SetBreakOnLibraryErrors, 8-63 to 8-64
SetBreakOnProtectionErrors, 8-64
to 8-65
Breakpoint function, 8-6
BroadcastDDEDataReady function, 6-8
to 6-9
bus control functions, GPIB Library, 4-3
byte count variable (ibcntl), 4-6
C
C locale, 1-2 to 1-5
information values (table), 1-3
LC_COLLATE, 1-5
LC_CTYPE, 1-4 to 1-5
LC_MONETARY, 1-4
LC_NUMERIC, 1-4
LC_TIME, 1-5
cables. See RS-232 cables.
callback functions
DDE Library functions, 6-2 to 6-4
DDE transaction types (table), 6-4
example using Excel, 6-5 to 6-6
parameter prototypes (table), 6-3
GPIB/GPIB-488.2 Libraries
function tree, 4-3
ibInstallCallback, 4-12, 4-14 to 4-17
ibNotify, 4-12, 4-17 to 4-20
Windows NT and Windows 95
asynchronous callbacks, 4-12
driver version requirements, 4-12
ibInstallCallback, 4-14 to 4-17
ibNotify function, 4-17 to 4-20
synchronous callbacks, 4-12
I-3
RS-232 Library
function tree, 5-2
InstallComCallback, 5-22 to 5-25
TCP Library functions
overview, 7-2 to 7-3
TCP transaction types (table), 7-3
X Property Library functions
InstallXPropertyCallback, 9-4, 9-25
to 9-27
overview, 9-4
UninstallXPropertyCallback, 9-4, 9-33
character processing, ANSI C, 1-5
classes, ANSI C Library, 1-1 to 1-2
clear functions, GPIB-488.2 Library, 4-3
Clear1D function, 3-6 to 3-7
ClientDDEExecute function, 6-10
ClientDDERead function, 6-10 to 6-11
ClientDDEWrite function, 6-12 to 6-13
clients and servers
DDE Library functions, 6-2
TCP Library functions, 7-2
ClientTCPRead function, 7-3 to 7-4
ClientTCPWrite function, 7-4 to 7-5
close functions
GPIB and GPIB-488.2 Libraries, 4-2
RS-232 Library, 5-1
CloseCom function, 5-8 to 5-9
CloseCVIRTE function, 8-6
CloseDev function, 4-6 to 4-7, 4-13
CloseFile function, 2-7
CloseInstrDevs function, 4-14
Cls function, 8-7
ComBreak function, 5-9
ComFromFile function, 5-3, 5-9 to 5-10
communications functions. See RS-232
Library functions.
CompareBytes function, 2-7 to 2-8
CompareStrings function, 2-8 to 2-9
complex operation functions
CxAdd, 3-7 to 3-8
CxAdd1D, 3-8 to 3-9
CxDiv, 3-9
CxDiv1D, 3-10
CxLinEv1D, 3-11
CxMul, 3-12
CxMul1D, 3-12 to 3-13
LabWindows/CVI Standard Libraries
Index
I-4
ContinuousPulseGenConfig, 10-24
to 10-26
CounterEventOrTimeConfig, 10-26
to 10-29
CounterMeasureFrequency, 10-29 to
10-32
CounterRead, 10-32 to 10-33
CounterStart, 10-33
CounterStop, 10-34
DelayedPulseGenConfig, 10-34 to 10-36
FrequencyDividerConfig, 10-37 to 10-39
ICounterControl, 10-45 to 10-47
PulseWidthOrPeriodMeasConfig, 10-48
to 10-49
valid counters (table), 10-7
CreateXProperty function, 9-3, 9-9 to 9-10
CreateXPropType function, 9-3, 9-10
to 9-12
customer communication, xx, Appendix-1
CVILowLevelSupportDriverLoaded
function, 8-8 to 8-9
CVIXDisplay global variable, 9-3
CVIXHiddenWindow global variable, 9-4
CVIXRootWindow variable, 9-3
CxAdd function, 3-7 to 3-8
CxAdd1D function, 3-8 to 3-9
CxDiv function, 3-9
CxDiv1D function, 3-10
CxLinEv1D function, 3-11
CxMul function, 3-12
CxMul1D function, 3-12 to 3-13
CxRecip function, 3-13 to 3-14
CxSub function, 3-14
CxSub1D function, 3-15
D
data acquisition functions. See Easy I/O for
DAQ Library.
data formatting functions. See formatting
functions; scanning functions; status
functions.
DateStr function, 8-9
date/time functions
ANSI C Library, 1-6 to 1-7
Index
DateStr, 8-9
GetSystemDate, 8-38
GetSystemTime, 8-39
SetSystemDate, 8-76
SetSystemTime, 8-77
TimeStr, 8-83
DCE device, 5-5
DDE Library functions
callback function, 6-2 to 6-4
functions capable of trigger callback
function (table), 6-4
parameter prototypes (table), 6-3
clients and servers, 6-2
connecting to DDE server, 6-2
DDE data links, 6-4
error conditions, 6-23 to 6-24
function reference
AdviseDDEDataReady, 6-6 to 6-8
BroadcastDDEDataReady, 6-8 to 6-9
ClientDDEExecute, 6-10
ClientDDERead, 6-10 to 6-11
ClientDDEWrite, 6-12 to 6-13
ConnectToDDEServer, 6-2, 6-13
to 6-15
DisconnectFromDDEServer, 6-15
GetDDEErrorString, 6-15 to 6-16
RegisterDDEServer, 6-2, 6-16
to 6-18
ServerDDEWrite, 6-19 to 6-20
SetUpDDEHotLink, 6-2, 6-4, 6-20
to 6-21
SetUpDDEWarmLink, 6-2, 6-4, 6-21
to 6-22
TerminateDDELink, 6-22
UnregisterDDEServer, 6-23
function tree (table), 6-1
Microsoft Excel example, 6-5 to 6-6
DDE transaction types (table), 6-4
Delay function, 8-9 to 8-10
DelayedPulseGenConfig function, 10-34
to 10-36
DeleteDir function, 8-10
DeleteFile function, 8-10 to 8-11
DestroyXProperty function, 9-12 to 9-13
DestroyXPropType function, 9-13 to 9-14
Determinant function, 3-16
National Instruments Corporation
I-5
Index
E
Easy I/O for DAQ Library
advantages, 10-1 to 10-2
calls to Data Acquisition Library
(note), 10-1
Channel String
analog input functions, 10-4 to 10-5
analog output functions, 10-7
classes, 10-3
command strings, 10-6
device numbers, 10-4
error conditions (table), 10-57 to 10-66
function reference
AIAcquireTriggeredWaveforms,
10-8 to 10-13
AIAcquireWaveforms, 10-33
to 10-34
AICheckAcquisition, 10-15
AIClearAcquisition, 10-15
AIReadAcquisition, 10-16 to 10-17
AISampleChannel, 10-17 to 10-18
AISampleChannels, 10-18
AIStartAcquisition, 10-19
AOClearWaveforms, 10-20
AOGenerateWaveforms, 10-21
to 10-22
AOUpdateChannel, 10-22 to 10-23
AOUpdateChannels, 10-23 to 10-24
ContinuousPulseGenConfig, 10-24
to 10-26
I-6
CounterEventOrTimeConfig, 10-26
to 10-29
CounterMeasureFrequency, 10-29
to 10-32
CounterRead, 10-32 to 10-33
CounterStart, 10-33
CounterStop, 10-34
DelayedPulseGenConfig, 10-34
to 10-36
FrequencyDividerConfig, 10-37
to 10-39
GetAILimitsOfChannel, 10-40 to
10-41
GetChannelIndices, 10-41 to 10-42
GetChannelNameFromIndex, 10-42
to 10-43
GetDAQErrorString, 10-43 to 10-44
GetNumChannels, 10-44
GroupByChannel, 10-44 to 10-45
ICounterControl, 10-45 to 10-47
PlotLastAIWaveformsPopup, 10-47
PulseWidthOrPeriodMeasConfig,
10-48 to 10-49
ReadFromDigitalLine, 10-49
to 10-51
ReadFromDigitalPort, 10-51
to 10-52
SetEasyIOMultitaskingMode, 10-53
WriteToDigitalLine, 10-53 to 10-55
WriteToDigitalPort, 10-55 to 10-56
function tree, 10-2 to 10-3
limitations, 10-2
overview, 10-1
valid counters for counter/timer
functions (table), 10-7
EnableBreakOnLibraryErrors function, 8-15
EnableInterrupts function, 8-15 to 8-16
EnableTaskSwitching function, 8-16
END message, GPIB, 4-9
end-of-string (EOS) character, GPIB, 4-9
end-or-identify (EOI) signal, GPIB, 4-9
errno global variable, set by file I/O
functions, 1-6
error codes
control functions, 1-8
X Property Library, 9-4 to 9-6
National Instruments Corporation
Index
error conditions
Analysis Library functions, 3-37
DDE Library functions, 6-23 to 6-24
Easy I/O for DAQ Library, 10-57
to 10-66
RS-232 Library functions, 5-36 to 5-37
TCP Library functions, 7-12
Error control, GPIB, 4-6
Error (iberr) global variable, 4-6, 4-11
error reporting
Analysis Library functions, 3-4
RS-232 Library functions, 5-3
error-related functions. See also status
functions.
DisableBreakOnLibraryErrors, 8-11
to 8-12
EnableBreakOnLibraryErrors, 8-15
GetAnalysisErrorString, 3-19
GetBreakOnLibraryErrors, 8-17
GetBreakOnProtectionErrors, 8-18
GetDDEErrorString, 6-15 to 6-16
GetFmtErrNdx, 2-18
GetRS232ErrorString, 5-22
GetTCPErrorString, 7-8
GetXPropErrorString, 9-15
ReturnRS232Err, 5-28
SetBreakOnLibraryErrors, 8-63 to 8-64
SetBreakOnProtectionErrors, 8-64
to 8-65
example programs. See formatting function
programming examples; scanning function
programming examples.
ExecutableHasTerminated function, 8-16
to 8-17
executables, launching. See standalone
executables, launching.
extended character sets, 1-2
external module utility functions
GetExternalModuleAddr, 8-21 to 8-22
LoadExternalModule, 8-49 to 8-52
LoadExternalModuleEx, 8-52 to 8-54
ReleaseExternalModule, 8-59
RunExternalModule, 8-62 to 8-63
UnloadExternalModule, 8-84 to 8-85
I-7
F
fax technical support, Appendix-1
fdopen function, ANSI C Library, 1-9
to 1-10
file I/O functions
CloseFile, 2-7
errno global variable, 1-6
GetFileInfo, 2-17
OpenFile, 2-20 to 2-22
ReadFile, 2-22 to 2-23
SetFilePtr, 2-26 to 2-28
WriteFile, 2-29 to 2-30
file utility functions
CopyFile, 8-7 to 8-8
DeleteFile, 8-10 to 8-11
GetFileAttrs, 8-23 to 8-24
GetFileDate, 8-24 to 8-25
GetFileSize, 8-25 to 8-26
GetFileTime, 8-26 to 8-27
GetFirstFile, 8-27 to 8-29
GetNextFile, 8-33
RenameFile, 8-60 to 8-61
SetFileAttrs, 8-67 to 8-68
SetFileDate, 8-68 to 8-69
SetFileTime, 8-70
SplitPath, 8-77 to 8-78
FileToArray function, 2-11 to 2-12
FillBytes function, 2-13
FindPattern function, 2-13 to 2-14
floating-point modifiers (%f)
formatting functions, 2-37 to 2-38
scanning functions, 2-45 to 2-46
FlushInQ function, 5-18
FlushOutQ function, 5-19
Fmt, FmtFile, and FmtOut functions. See
formatting function programming
examples; formatting functions.
format codes
formatting functions, 2-34 to 2-35
scanning functions, 2-42 to 2-43
format string
formatting functions, 2-33 to 2-35
examples, 2-33 to 2-34
form of, 2-34
format codes, 2-34 to 2-35
LabWindows/CVI Standard Libraries
Index
I-8
Index
G
gender changer, 5-6
GetAILimitsOfChannel function, 10-40
to 10-41
GetAnalysisErrorString function, 3-19
GetBreakOnLibraryErrors function, 8-17
GetBreakOnProtectionErrors function, 8-18
GetChannelIndices function, 10-41 to 10-42
GetChannelNameFromIndex function, 10-42
to 10-43
GetComStat function, 5-19 to 5-20
GetCurrentPlatform function, 8-19
GetCVIVersion function, 8-18 to 8-19
GetDAQErrorString function, 10-43
to 10-44
GetDDEErrorString function, 6-15 to 6-16
GetDir function, 8-20
GetDrive function, 8-20 to 8-21
GetExternalModuleAddr function, 8-21
to 8-22
GetFileAttrs function, 8-23 to 8-24
GetFileDate function, 8-24 to 8-25
GetFileInfo function, 2-17
GetFileSize function, 8-25 to 8-26
GetFileTime function, 8-26 to 8-27
GetFirstFile function, 8-27 to 8-29
GetFmtErrNdx function, 2-18
GetFmtIOError function, 2-18 to 2-19
GetFmtIOErrorString function, 2-19
GetFullPathFromProject function, 8-29
to 8-30
GetInQLen function, 5-20 to 5-21
GetInterruptState function, 8-30
GetKey function, 8-30 to 8-31
GetModuleDir function, 8-31 to 8-32
GetNextFile function, 8-33
GetNumChannels function, 10-44
GetOutQLen function, 5-4, 5-21
I-9
Index
H
handshaking for RS-232 communications,
5-6 to 5-8
hardware handshaking, 5-7 to 5-8
software handshaking, 5-6
hardware handshaking, 5-7 to 5-8
hardware interrupts and autopolling, 4-8
to 4-9
help, starting. See SystemHelp function.
hidden window for providing X window
IDs, 9-3 to 9-4
Histogram function, 3-19 to 3-20
I
I/O functions. See also Easy I/O for DAQ
Library; Formatting and I/O Library
functions; Standard Input/Output window
functions.
GPIB Library, 4-2
low-level GPIB/GPIB-488.2 I/O
functions, 4-4
I-10
Index
K
keyboard utility functions
GetKey, 8-30 to 8-31
KeyHit, 8-43 to 8-44
L
LaunchExecutable function, 8-44 to 8-46
LaunchExecutableEx function, 8-47 to 8-48
launching executables. See standalone
executables, launching.
LC_COLLATE locale, 1-5
LC_CTYPE locale, 1-4 to 1-5
LC_MONETARY locale, 1-4
LC_NUMERIC locale, 1-4
LC_TIME locale, 1-5
LinEv1D function, 3-21
LinEv2D function, 3-22
literals in format string
formatting functions, 2-40
scanning functions, 2-48 to 2-49
LoadExternalModule function, 8-49 to 8-52
LoadExternalModuleEx function, 8-52
to 8-54
local functions, GPIB-488.2 Library, 4-4
locale. See C locale.
low-level I/O functions
ANSI C Library, 1-2
GPIB-488.2 Library, 4-4
M
MakeDir function, 8-54 to 8-55
MakePathname function, 8-55
managing property information. See
property information, managing.
manual. See documentation.
mathematical functions, ANSI C, 1-6
I-11
Index
ReadFromPhysicalMemory, 8-57
ReadFromPhysicalMemoryEx, 8-58
WriteToPhysicalMemory, 8-85 to 8-86
WriteToPhysicalMemoryEx, 8-86
to 8-87
PlotLastAIWaveformsPopup
function, 10-47
port I/O utility functions
inp, 8-42
inpw, 8-42 to 8-43
outp, 8-56
outpw, 8-56
properties. See also X Property Library
functions.
definition, 9-2
handles and types, 9-3
property events, handling
GetXPropErrorString, 9-15
InstallXPropertyCallback, 9-4, 9-25
to 9-27
UninstallXPropertyCallback, 9-4, 9-33
property information, managing
CreateXProperty, 9-3, 9-9 to 9-10
DestroyXProperty, 9-12 to 9-13
GetXPropertyName, 9-15 to 9-16
GetXPropertyType, 9-16 to 9-17
property types, managing
CreateXPropType, 9-3, 9-10 to 9-12
DestroyXPropType, 9-13 to 9-14
GetXPropTypeName, 9-17 to 9-18
GetXPropTypeSize, 9-18
GetXPropTypeUnit, 9-19
PulseWidthOrPeriodMeasConfig function,
10-48 to 10-49
PutXWindowPropertyItem function, 9-27
to 9-28
PutXWindowPropertyValue function, 9-29
to 9-31
O
one-dimensional array operation functions
Abs1D, 3-4 to 3-5
Add1D, 3-5
Div1D, 3-16 to 3-17
LinEv1D, 3-21
MaxMin1D, 3-24
Mul1D, 3-26 to 3-27
Neg1D, 3-28
Sub1D, 3-30 to 3-31
Subset1D, 3-32
one-dimensional complex operation
functions
CxAdd1D, 3-8 to 3-9
CxDiv1D, 3-10
CxLinEv1D, 3-11
CxMul1D, 3-12 to 3-13
CxSub1D, 3-15
ToPolar1D, 3-33 to 3-34
ToRect1D, 3-35
open functions
GPIB Library, 4-2
RS-232 Library, 5-1
OpenCom function, 5-4, 5-25 to 5-26
OpenComConfig function, 5-4, 5-26 to 5-28
OpenDev function, 4-6, 4-20
OpenFile function, 2-20 to 2-22
outp function, 8-56
outpw function, 8-56
P
parallel poll functions, GPIB-488.2
Library, 4-4
persistent variable functions
GetPersistentVariable, 8-33 to 8-34
SetPersistentVariable, 8-71
I-12
Index
R
read termination, GPIB, 4-9
ReadFile function, 2-22 to 2-23
ReadFromDigitalLine function, 10-49
to 10-51
ReadFromDigitalPort function, 10-51
to 10-52
ReadFromPhysicalMemory function, 8-57
ReadFromPhysicalMemoryEx
function, 8-58
ReadLine function, 2-23 to 2-24
RegisterDDEServer function, 6-2, 6-16
to 6-18
RegisterTCPServer function, 7-2, 7-8
to 7-10
ReleaseExternalModule function, 8-59
remote functions, GPIB-488.2 Library, 4-4
remote hosts
ConnectToXDisplay function, 9-3, 9-7
to 9-9
DisConnectFromXDisplay, 9-14 to 9-15
RemoveXWindowProperty function, 9-31
to 9-32
RenameFile function, 8-60 to 8-61
ResetDevs function no longer supported
(note), 4-13
RetireExecutableHandle function, 8-61
ReturnRS232Err function, 5-28
RoundRealToNearestInteger function, 8-61
to 8-62
RQS events, and auto serial polling
ibInstallCallback function, 4-17
ibNotify function, 4-19
RS-232 cables, 5-4 to 5-6
DTE to DCE cable configuration
(table), 5-5
gender of connectors, 5-6
PC cable configuration (table), 5-4
PC to DTE cable configuration
(table), 5-5
RS-232 Library functions
error conditions, 5-36 to 5-37
function panels
classes and subclasses, 5-2
function tree (table), 5-1 to 5-2
National Instruments Corporation
I-13
function reference
CloseCom, 5-8 to 5-9
ComBreak, 5-9
ComFromFile, 5-3, 5-9 to 5-10
ComRd, 5-11
ComRdByte, 5-12
ComRdTerm, 5-12 to 5-13
ComSetEscape, 5-14 to 5-15
ComToFile, 5-3, 5-15 to 5-16
ComWrt, 5-16 to 5-17
ComWrtByte, 5-17 to 5-18
FlushInQ, 5-18
FlushOutQ, 5-19
GetComStat, 5-19 to 5-20
GetInQLen, 5-20 to 5-21
GetOutQLen, 5-4, 5-21
GetRS232ErrorString, 5-22
InstallComCallback, 5-22 to 5-25
OpenCom, 5-4, 5-25 to 5-26
OpenComConfig, 5-4, 5-26 to 5-28
ReturnRS232Err, 5-28
SetComTime, 5-29
SetCTSMode, 5-7, 5-30
SetXMode, 5-31
XModemConfig, 5-4, 5-31 to 5-33
XModemReceive, 5-3, 5-4, 5-33
to 5-34
XModemSend, 5-34 to 5-35
handshaking, 5-6 to 5-8
reporting errors, 5-3
RS-232 cables, 5-4 to 5-6
troubleshooting, 5-3 to 5-4
XModem file transfer functions, 5-3
rs232err global variable, 5-3
RS-485 AT-Serial board, 5-3
RunExternalModule function, 8-62 to 8-63
Index
S
scanning function programming examples
ASCII file to two integers with error
checking, 2-68
ASCII file with comma separated
numbers to real array, with number of
elements at beginning of file, 2-68
to 2-69
binary file to integer array, assuming
fixed number of elements, 2-69
binary file to real array
assuming fixed number of
elements, 2-69
assuming variable number of
elements, 2-69 to 2-70
integer array containing 1-byte integers
to real array, 2-66 to 2-67
integer array to real array, 2-66
with byte swapping, 2-66
list of examples, 2-49 to 2-50
reading integer from standard input, 2-70
reading line from standard input, 2-71
reading string from standard input, 2-70
to 2-71
scanning strings that are not NULterminated, 2-65 to 2-66
string containing binary integers to
integer array, 2-67
string containing IEEE-format real
number to real variable, 2-67 to 2-68
string to integer, 2-59 to 2-60
string to integer and real, 2-61
string to integer and string, 2-63
string to long integer, 2-60
string to real, 2-60 to 2-61
after finding semicolon in
string, 2-64
after finding substring in string, 2-64
skipping over non-numeric
characters, 2-63
string to string, 2-62
string with comma-separated ASCII
numbers to real array, 2-65
I-14
Index
I-15
statistics functions
Histogram, 3-19 to 3-20
Mean, 3-25 to 3-26
Sort, 3-29
StdDev, 3-29 to 3-30
Status control, GPIB, 4-6
status functions. See also error-related
functions.
Formatting and I/O Library functions
GetFmtErrNdx, 2-18
GetFmtIOError, 2-18 to 2-19
GetFmtIOErrorString, 2-19
NumFmtdBytes, 2-20
RS-232 library
GetComStat, 5-19 to 5-20
GetInQLen, 5-20 to 5-21
GetOutQLen, 5-4, 5-21
GetRS232ErrorString, 5-22
ReturnRS232Err, 5-28
thread-specific, GPIB Library
ThreadIbcnt, 4-22
ThreadIbcntl function, 4-22 to 4-23
ThreadIberr, 4-23 to 4-25
ThreadIbsta, 4-25 to 4-26
Status Word (ibsta) global variable, 4-6, 4-10
StdDev function, 3-29 to 3-30
string manipulation functions
CompareBytes, 2-7 to 2-8
CompareStrings, 2-8 to 2-9
CopyBytes, 2-9 to 2-10
CopyString, 2-10
definition, 2-3
FillBytes, 2-13
FindPattern, 2-13 to 2-14
ReadLine, 2-23 to 2-24
StringLength, 2-28
StringLowerCase, 2-28 to 2-29
StringUpperCase, 2-29
WriteLine, 2-30 to 2-31
string modifiers (%s)
formatting functions, 2-38 to 2-39
scanning functions, 2-46 to 2-48
string processing, ANSI C, 1-5
Sub1D function, 3-30 to 3-31
Sub2D function, 3-31
Subset1D function, 3-32
LabWindows/CVI Standard Libraries
Index
T
task switching functions
DisableTaskSwitching, 8-12 to 8-15
EnableTaskSwitching, 8-16
TCP Library functions
callback function, 7-2 to 7-3
clients and servers, 7-2
error conditions, 7-12
function reference
ClientTCPRead, 7-3 to 7-4
ClientTCPWrite, 7-4 to 7-5
ConnectToTCPServer, 7-5 to 7-7
DisconnectFromTCPServer, 7-7
to 7-8
DisconnectTCPClient, 7-7
GetTCPErrorString, 7-8
RegisterTCPServer, 7-2, 7-8 to 7-10
ServerTCPRead, 7-10
ServerTCPWrite, 7-11
UnregisterTCPServer, 7-11 to 7-12
function tree (table), 7-1
technical support, Appendix-1
TerminateDDELink function, 6-22
TerminateExecutable function, 8-82
thread-specific status functions
ThreadIbcnt, 4-22
ThreadIbcntl function, 4-22 to 4-23
ThreadIberr, 4-23 to 4-25
ThreadIbsta, 4-25
time/date functions
ANSI C Library, 1-6 to 1-7
DateStr, 8-9
GetSystemDate, 8-38
GetSystemTime, 8-39
SetSystemDate, 8-76
SetSystemTime, 8-77
TimeStr, 8-83
timeouts, GPIB, 4-9
I-16
U
UninstallXPropertyCallback
function, 9-4, 9-33
UnloadExternalModule function, 8-84
to 8-85
UnregisterDDEServer function, 6-23
UnregisterTCPServer function, 7-11 to 7-12
Utility Library functions
function panels
classes and subclasses, 8-4 to 8-5
function tree (table), 8-1 to 8-4
function reference
Beep, 8-5
Breakpoint, 8-6
CloseCVIRTE, 8-6
Cls, 8-7
CopyFile, 8-7 to 8-8
CVILowLevelSupportDriverLoaded,
8-8 to 8-9
DateStr, 8-9
Delay, 8-9 to 8-10
Index
DeleteDir, 8-10
DeleteFile, 8-10 to 8-11
DisableBreakOnLibraryErrors, 8-11
to 8-12
DisableInterrupts, 8-12
DisableTaskSwitching, 8-12 to 8-15
EnableBreakOnLibraryErrors, 8-15
EnableInterrupts, 8-15 to 8-16
EnableTaskSwitching, 8-16
ExecutableHasTerminated, 8-16
to 8-17
GetBreakOnLibraryErrors, 8-17
GetBreakOnProtectionErrors, 8-18
GetCurrentPlatform, 8-19
GetCVIVersion, 8-18 to 8-19
GetDir, 8-20
GetDrive, 8-20 to 8-21
GetExternalModuleAddr, 8-21
to 8-22
GetFileAttrs, 8-23 to 8-24
GetFileDate, 8-24 to 8-25
GetFileSize, 8-25 to 8-26
GetFileTime, 8-26 to 8-27
GetFirstFile, 8-27 to 8-29
GetFullPathFromProject, 8-29
to 8-30
GetInterruptState, 8-30
GetKey, 8-30 to 8-31
GetModuleDir, 8-31 to 8-32
GetNextFile, 8-33
GetPersistentVariable, 8-33 to 8-34
GetProjectDir, 8-34
GetStdioPort, 8-35
GetStdioWindowOptions, 8-35
to 8-36
GetStdioWindowPosition, 8-36
to 8-37
GetStdioWindowSize, 8-37
GetStdioWindowVisibility,
8-37 to 8-38
GetSystemDate, 8-38
GetSystemTime, 8-39
GetWindowDisplaySetting, 8-39
to 8-40
InitCVIRTE, 8-40 to 8-42
inp, 8-42
National Instruments Corporation
I-17
Index
TruncateRealNumber, 8-84
UnloadExternalModule, 8-84 to 8-85
WriteToPhysicalMemory, 8-85
to 8-86
WriteToPhysicalMemoryEx, 8-86
to 8-87
V
va_arg() macro, 1-2
variable argument functions,
LabWindows/CVI support of, 1-2
vector and matrix algebra functions
Determinant, 3-16
DotProduct, 3-18
InvMatrix, 3-20 to 3-21
MatrixMul, 3-23
Transpose, 3-36
void HandlePropertyNotifyEvent
function, 9-7
void_InitXPropertyLib function, 9-7
W
wait utility functions. See timer/wait utility
functions.
window functions, standard input/output.
See Standard Input/Output window
functions.
window properties, accessing
GetXWindowPropertyItem, 9-20 to 9-22
GetXWindowPropertyValue, 9-22
to 9-25
PutXWindowPropertyItem, 9-27 to 9-28
PutXWindowPropertyValue, 9-29
to 9-31
RemoveXWindowProperty, 9-31 to 9-32
Windows 95 GPIB support, 4-10 to 4-11
compatibility driver, 4-11
native 32-bit driver, 4-10
Windows NT and GPIB driver, 4-11
limitations on transfer size, 4-11
multithreading, 4-11
I-18
Index
PutXWindowPropertyValue, 9-29
to 9-31
RemoveXWindowProperty, 9-31
to 9-32
UninstallXPropertyCallback, 9-4, 9-33
void HandlePropertyNotifyEvent, 9-7
void_InitXPropertyLib, 9-7
function tree (table), 9-2
hidden window, 9-3
overview, 9-1
property handles and types, 9-3 to 9-4
predefined property types (table), 9-3
using outside of LabWindows/CVI, 9-7
X interclient communication, 9-2 to 9-3
XModem file transfer functions
purpose and use, 5-3
XModemConfig, 5-4, 5-31 to 5-33
XModemReceive, 5-3, 5-4, 5-33 to 5-34
XModemSend, 5-3, 5-34 to 5-35
I-19